A LangChain agent that answers technical questions about the FastAPI documentation, deployed as a container-image Lambda behind an API Gateway HTTP API. It's not a hello-world: beyond semantic search over the indexed docs, the agent has two more tools —
semantic_search— retrieves relevant passages from a Chroma index of the FastAPI docs (docs/en/docs/*.md), embedded with Voyage AI.current_datetime— returns the current UTC date/time, for freshness-of-information questions.fastapi_repo_stats— calls the live GitHub REST API for thetiangolo/fastapirepo: star count, open issue count, and the latest release version/date. This is what makes the agent's answers about "current release" or "how popular is this" genuinely live, not frozen at ingestion time.
The LLM is Claude Opus 5 via langchain-anthropic.
API Gateway HTTP API (POST /ask)
│
▼
Lambda (container image)
├─ app.py → parses the request, checks the shared-secret header
├─ agent.py → LangChain create_agent(), cached per warm container
├─ vectorstore.py → Chroma index: S3 → /tmp on cold start, cached after
├─ secrets_store.py → SSM SecureString params, cached after first read
└─ tools/ → semantic_search, current_datetime, fastapi_repo_stats
│
├─ reads → S3 (Chroma index artifact, s3:GetObject only)
├─ reads → SSM Parameter Store (SecureString: API keys, shared secret)
└─ calls → Anthropic API, Voyage AI API, GitHub REST API
The Chroma vector index is built offline by ingest/ingest.py (your
machine, not Lambda) and uploaded to S3 as a tarball. The Lambda downloads
and unpacks it into /tmp on cold start only — warm invocations reuse the
in-memory retriever via a module-level cache, so there's no S3/embedding
cost per request beyond the query's own embedding call.
Why this shape, briefly (full reasoning in the design plan):
- Chroma-on-S3 instead of pgvector/RDS — avoids putting the Lambda in a VPC and running a database server for a single-consumer demo.
- Container image instead of zip+layers —
chromadb's own dependency tree (onnxruntime,grpcio, etc.) blows past the 250MB zip+layers ceiling well before you add LangChain and the rest. - Shared-secret header instead of an API Gateway API key — HTTP API
(API Gateway v2, used here for cost/simplicity) doesn't support usage
plans/API keys natively; that's a REST-API-only feature. See
template.yamlfor the upgrade path if you need per-caller quotas later. - Secrets fetched at runtime via
ssm:GetParameter, never resolved into the Lambda's environment variables at deploy time — a decrypted{{resolve:ssm-secure:...}}value inEnvironment.Variablesis visible to anyone withlambda:GetFunctionConfiguration, a much wider audience than "whoever can decrypt via KMS".
- AWS account, not the root user for anything below — see
iam/README.mdto create a scoped deployment IAM user first. - AWS SAM CLI and Docker (container image build requires Docker).
- An Anthropic API key.
- A Voyage AI API key (free tier available).
- Optional: a GitHub fine-grained personal access token, read-only,
public repo metadata scope only.
fastapi_repo_statsworks without one — GitHub's public API allows 60 unauthenticated requests/hour, plenty for this demo — a token just raises that ceiling to 5000/hour. Skip it entirely if you don't want to set one up.
Follow iam/README.md to create a deployment IAM user scoped to this
project — do this before running any sam command.
sam build --use-container
sam deploy --guided --profile fastapi-rag-deployersam deploy --guided will prompt for stack name (fastapi-rag-agent),
region, and confirm the IAM role creation (required — it's creating the
scoped RagAgentFunctionRole from template.yaml, not granting itself
anything broader). This creates real, billable AWS resources — Lambda,
API Gateway, an S3 bucket, an ECR repository, a KMS key, an IAM role.
Nothing here runs automatically; you run this step yourself.
Note the ApiEndpoint, SecretsKmsKeyId, and ArtifactsBucketName
outputs — you'll need all three next.
Real API keys never go in the template or in git. Create them as SecureString parameters, encrypted with the KMS key the stack just created:
KMS_KEY_ID=$(aws cloudformation describe-stacks --stack-name fastapi-rag-agent \
--query "Stacks[0].Outputs[?OutputKey=='SecretsKmsKeyId'].OutputValue" --output text \
--profile fastapi-rag-deployer)
aws ssm put-parameter --name /fastapi-rag-agent/prod/anthropic_api_key \
--type SecureString --key-id "$KMS_KEY_ID" --value "sk-ant-..." \
--profile fastapi-rag-deployer
aws ssm put-parameter --name /fastapi-rag-agent/prod/voyage_api_key \
--type SecureString --key-id "$KMS_KEY_ID" --value "pa-..." \
--profile fastapi-rag-deployer
aws ssm put-parameter --name /fastapi-rag-agent/prod/api_gateway_shared_secret \
--type SecureString --key-id "$KMS_KEY_ID" --value "$(openssl rand -hex 32)" \
--profile fastapi-rag-deployer
# Optional — only if you want fastapi_repo_stats above GitHub's 60/hr
# unauthenticated limit. secrets_store.py treats a missing parameter as
# "no token" rather than an error, so this can be created at any time,
# including after the stack is already deployed and running.
aws ssm put-parameter --name /fastapi-rag-agent/prod/github_token \
--type SecureString --key-id "$KMS_KEY_ID" --value "github_pat_..." \
--profile fastapi-rag-deployerSave the generated shared secret (last command) — you'll send it as the
x-api-key header on every request.
cd ingest
python -m venv .venv && source .venv/bin/activate # or .venv\Scripts\activate on Windows
pip install -r requirements.txt
export VOYAGE_API_KEY="pa-..."
export S3_BUCKET="<ArtifactsBucketName output from step 2>"
python ingest.pyThis clones tiangolo/fastapi, chunks the markdown docs, embeds them via
Voyage AI, builds a local Chroma index, tars it, and uploads it to
s3://$S3_BUCKET/index/chroma_index.tar.gz. Note the printed tarball size
— it must comfortably fit in the Lambda's configured /tmp (2048MB by
default in template.yaml; raise EphemeralStorage.Size if needed).
S3_BUCKET is optional — omit it to stop after building ./chroma_db
locally, without touching AWS at all. That's enough to run the agent fully
locally via scripts/ask_locally.py (see Local testing below), which is
the fastest way to sanity-check the agent before deploying anything.
curl -X POST "<ApiEndpoint output from step 2>" \
-H "x-api-key: <shared secret from step 3>" \
-H "content-type: application/json" \
-d '{"question": "How do I add a path parameter in FastAPI, and what is the latest release?"}'That question deliberately exercises all three tools: semantic_search
for the "how do I" part, fastapi_repo_stats for "latest release".
Unit + agent tests (no AWS, no real API calls — everything mocked):
python -m pip install -r tests/requirements-test.txt
python -m pytestReal agent, no AWS (requires a local index from step 4 with no
S3_BUCKET set, plus real Anthropic/Voyage keys): scripts/ask_locally.py
monkeypatches secrets_store.get_secret to read plain env vars instead of
calling SSM, and points CHROMA_LOCAL_DIR straight at ingest/chroma_db
so vectorstore.py skips its S3 download step (it only downloads when
that directory doesn't already exist). Everything else — agent.py, the
three tools — runs completely unmodified, exactly as in Lambda.
export ANTHROPIC_API_KEY="sk-ant-..."
export VOYAGE_API_KEY="pa-..."
export GITHUB_TOKEN="github_pat_..." # optional; omit to skip the GitHub tool
python scripts/ask_locally.py "How do I add a path parameter in FastAPI?"Full local Lambda emulation (requires Docker; still calls real SSM/S3/
Anthropic/Voyage/GitHub unless you stub secrets_store.get_secret and
vectorstore.get_retriever yourself — useful for a true end-to-end check
after deploying the stack):
sam build --use-container
sam local start-api
curl -X POST http://localhost:3000/ask \
-H "x-api-key: <shared secret>" \
-H "content-type: application/json" \
-d '{"question": "How do I define a path parameter in FastAPI?"}'Or invoke once with the sample event:
sam local invoke RagAgentFunction --event tests/fixtures/sample_event.jsonSSLError: certificate verify failed: unable to get local issuer certificatewhen calling the Voyage or Anthropic API from Windows — Python'srequests/certifiuses its own bundled CA list instead of Windows' trusted certificate store, so it can miss a root CA that an antivirus or corporate TLS-inspection proxy installed into Windows (curl works fine in the same situation because it uses Windows' store directly). Fix:pip install pip-system-certs, which makes Python trust the OS certificate store instead.voyageai.error.RateLimitErrormentioning "you have not yet added your payment method" — Voyage AI accounts without a payment method on file are capped at 3 requests/min and 10K tokens/min. Add a payment method at dashboard.voyageai.com → Billing (the 200M free tokens for Voyage 3-series models still apply — this repo's full FastAPI corpus uses well under 1M tokens) — the higher limit kicks in within a few minutes.SimpleVoyageEmbeddings(lambda_app/voyage_embeddings.py) retries on 429s with backoff, so ingestion also eventually succeeds even without a payment method — just slowly (tens of minutes for the full corpus).PermissionErrorfromshutil.rmtreeon.git/objects/pack/*.idxwhen re-runningingest.pyon Windows — git marks packed objects read-only, which Windows refuses to delete by default. Already handled iningest.py'sclone_docs()/build_index()via anonexchook that clears the read-only flag before retrying; if you see this, you're on an older copy of the script.
- API Gateway HTTP API has a hard 30-second integration timeout (not configurable). An agentic call doing semantic_search + a GitHub lookup + synthesis, on a cold Lambda start, can plausibly exceed it — the client would see a 504 even though the Lambda (timeout: 90s) keeps running. If this becomes a real problem, the documented escape hatch is swapping the front door for a Lambda Function URL with response streaming, which isn't bound by API Gateway's ceiling.
- Container image cold starts are slower than zip (low seconds, not sub-second) — acceptable for a demo; provisioned concurrency is the (continuously-billed) fix if it isn't.
- Cost control is the shared-secret header, not cosmetic. Every
/askcall is at least one billed Claude Opus 5 call plus a Voyage embedding call. Don't skip setting a real random value in step 3. - ChromaDB's telemetry is disabled via
ANONYMIZED_TELEMETRY=False(already set intemplate.yaml) rather than viaSettings(...), which has known bugs on some chromadb versions. open_issues_and_prsin the GitHub tool's output is GitHub's own combined issues+PRs count, not issues alone — the tool's docstring and output both say so explicitly to avoid the agent misreporting it.
template.yaml SAM template (S3, KMS, IAM role, Lambda, HTTP API)
lambda_app/ Everything baked into the container image
Dockerfile
app.py Lambda handler
agent.py LangChain create_agent() construction
vectorstore.py S3 → /tmp Chroma download + cache
secrets_store.py SSM SecureString fetch + cache
voyage_embeddings.py Minimal voyageai SDK wrapper (see Troubleshooting)
tools/ semantic_search, current_datetime, fastapi_repo_stats
ingest/ Local-only: builds and uploads the Chroma index
scripts/
ask_locally.py Run the real agent against a local index, no AWS
iam/ Deploy-time least-privilege IAM policy + setup docs
tests/ pytest: unit tests (mocked) + agent wiring test (mocked)