Skip to content
Visual explainer 3h 30m to learn 5 steps

Serve the knowledge agent behind a typed FastAPI endpoint

Expose the assistant through an authenticated FastAPI endpoint with request IDs, source IDs, deadlines, cancellation and safe errors.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.

Topic 22 of 34

In short

A service contract says exactly what the API accepts, what it returns and how it fails. For the knowledge assistant that means a typed FastAPI endpoint that authenticates the caller, attaches a request ID, returns an answer or status with source IDs, enforces a deadline, stops work when cancelled and never leaks internal errors.

Explained simply

So far the assistant runs as Python functions. To let other systems use it, you put it behind an HTTP API. A service contract is the promise that API makes: what a request looks like, what a response looks like, and what happens when something goes wrong.

FastAPI makes the contract concrete. You describe the request and response with Pydantic models, and FastAPI checks incoming data against them, rejects bad input with a 422 error, and publishes interactive documentation at /docs automatically.

The caller proves who they are with a token in the Authorization header. The endpoint checks it and works out which documents that caller may see. Every request gets a request ID, which appears in the response and in the logs, so a support person can find exactly what happened.

Two more rules finish the contract. Each request has a deadline, after which the work stops and the caller gets a clear timeout response. And error messages are safe: a code, a short message and the request ID, never a stack trace, SQL or prompt text.

Press Play on a diagram to walk through it one step at a time.

SequenceOne request through the assistant API
Client
FastAPI endpoint
Agent
Retrieval
  1. 1POST /v1/ask with bearer token
    Client to FastAPI endpoint: POST /v1/ask with bearer token
  2. 2Verified scope, request ID, deadline
    FastAPI endpoint to Agent: Verified scope, request ID, deadline
  3. 3Search within scope
    Agent to Retrieval: Search within scope
  4. 4Chunks with IDs
    Retrieval to Agent: Chunks with IDs
  5. 5Answer, status, source IDs
    Agent to FastAPI endpoint: Answer, status, source IDs
  6. 6200 JSON with X-Request-ID
    FastAPI endpoint to Client: 200 JSON with X-Request-ID
CompareOutcomes the contract defines
Success
  • 200 with status answered
  • Answer text and source IDs
  • Request ID echoed
Valid non-answer
  • 200 with status abstained or escalated
  • Reason code, no source IDs
  • Not treated as an error
Error
  • 401 bad token, 422 bad input
  • 504 deadline exceeded
  • Safe message and request ID only
MapMapping failures to status codes
POST /v1/ask outcome
  • 200 OK
    • answered with source_ids
    • clarify with a question
    • abstained or escalated with reason
  • 401
    • Missing or invalid token
  • 422
    • Body fails Pydantic validation
  • 503
    • Model or database unavailable
  • 504
    • Request deadline exceeded

In depth

Hands-on setup: prerequisites and running it

You need Python 3.11 or later (for asyncio.timeout), FastAPI with its standard extras, and your agent code from earlier modules running against the deterministic model stub. No paid service is needed. Install with pip install "fastapi[standard]" in a virtual environment, put the app in main.py and start it with fastapi dev main.py. Open http://127.0.0.1:8000/docs to see the generated OpenAPI page.

The expected evidence: /docs lists POST /v1/ask with your AskRequest and AskResponse schemas; a call without a token returns 401; a call with an empty question returns 422; a call with the test token returns 200 with a request_id and status. Cleanup is simply stopping the server with Ctrl+C and deactivating the virtual environment. Use only test tokens such as test-token-staff, never real credentials.

  • Python 3.11+, fastapi[standard], the model stub
  • fastapi dev main.py, then open /docs
  • Expect 401, 422 and 200 for the three test calls
  • Test tokens only; nothing to tear down but the process

Authentication and trusted identity

Authentication answers "who is calling?" In FastAPI you write it as a dependency: a function that reads the Authorization header, verifies the token and returns a Caller object with a user ID and a set of scopes. The endpoint declares it with Depends, so it runs before any agent code. FastAPI's HTTPBearer helper reads a bearer token for you. In production you would verify a signed token from your identity provider; for the lab, a dictionary of test tokens is fine.

The key rule is that the Caller object is the only source of identity. The request body has no user_id or scope field, and nothing the model outputs can change the caller. The agent receives the Caller and passes its scopes to every retrieval and tool call.

  • Dependency returns a typed Caller
  • Missing or bad token: 401 with WWW-Authenticate
  • No identity fields in the request body
  • Scopes flow from Caller to every tool call

Request IDs and response shape

Generate a request ID at the edge, for example a UUID4, or accept a well-formed X-Request-ID header from a trusted gateway. Put it in the response body and in an X-Request-ID response header, and include it in every log line and trace span for that request. A small middleware does this for all routes.

The response always has the same shape: request_id, status, answer, source_ids and reason. Status is one of answered, clarify, abstained or escalated. Source IDs are the validated chunk or document IDs from the permitted evidence set, so a client can show citations without seeing internal scores or lineage. Keep internal fields, such as lineage and token counts, in your logs, not in the response.

LayersWhat runs on each request, outside in
  1. 1
    Request ID middleware

    Assigns ID, adds response header

  2. 2
    Validation

    Pydantic checks the body; 422 on failure

  3. 3
    Auth dependency

    Verifies token, returns Caller; 401 on failure

  4. 4
    Endpoint

    Starts the agent with a deadline

  5. 5
    Agent and tools

    Use Caller scopes for every call

Deadlines and cancellation

A deadline is a total time budget for the request, for example 20 seconds. Wrap the agent call in asyncio.timeout so that, when time runs out, Python cancels the running task and raises TimeoutError, which you map to a 504 response with the code deadline_exceeded. Pass the remaining time down to tools too, so a slow search does not use the whole budget.

Cancellation covers the case where the client goes away. Starlette, which FastAPI is built on, lets you check await request.is_disconnected(). A common pattern is a small watcher task that polls it and cancels the agent task when the client has gone, so you stop paying for model calls nobody will read. Agent code must let asyncio.CancelledError propagate after any cleanup rather than swallowing it.

  • Total deadline per request; remaining time passed to tools
  • TimeoutError maps to 504 deadline_exceeded
  • Watch request.is_disconnected() and cancel the agent task
  • Never swallow CancelledError

User-safe errors

Define a small set of error codes and map every failure to one: unauthenticated (401), invalid_request (422), deadline_exceeded (504), upstream_unavailable (503) and internal_error (500). Register exception handlers so every error body has the same shape: code, message and request_id. The message is short and generic, such as "The assistant could not finish in time."

The full exception, with stack trace, goes to server logs tagged with the request ID. Never put exception text in the response: it can contain file paths, SQL, environment details or parts of the prompt and retrieved documents. Also remember that abstained and escalated are not errors; they are normal 200 responses.

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Define request and response models~40m
  2. 2
    Authenticate the caller~40m
  3. 3
    Attach request IDs~40m
  4. 4
    Enforce deadlines and cancellation~40m
  5. 5
    Return user-safe errors~40m

Key points

  • Pydantic request and response models make the contract explicit and generate OpenAPI docs.
  • Identity comes from a verified token, never from a field in the request body.
  • Every response and log line carries the same request ID so support can trace it.
  • Abstaining or escalating is a normal 200 response with a reason, not an error.
  • Error bodies contain a code, a short safe message and the request ID; no stack traces.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from typing import Literal
from pydantic import BaseModel, Field

class AskRequest(BaseModel):
    question: str = Field(min_length=3, max_length=2000)
    session_id: str | None = None

class AskResponse(BaseModel):
    request_id: str
    status: Literal['answered', 'clarify', 'abstained', 'escalated']
    answer: str | None = None
    source_ids: list[str] = []
    reason: str | None = None

Typed request and response models; the caller's identity is not a field.

A minimal authenticated endpoint with a deadline

The dependency turns a bearer token into the caller's scopes. The endpoint runs the agent inside asyncio.timeout and maps a timeout to a safe 504. run_agent is your existing agent function; TOKENS holds test tokens only.

python
import asyncio, uuid
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBearer
app, bearer = FastAPI(), HTTPBearer()
TOKENS = {'test-token-staff': {'staff'}}  # test tokens only
def caller_scopes(cred=Depends(bearer)) -> set[str]:
    if cred.credentials not in TOKENS:
        raise HTTPException(401, 'unauthenticated', {'WWW-Authenticate': 'Bearer'})
    return TOKENS[cred.credentials]
@app.post('/v1/ask', response_model=AskResponse)
async def ask(body: AskRequest, scopes: set[str] = Depends(caller_scopes)):
    rid = str(uuid.uuid4())
    try:
        async with asyncio.timeout(20): return await run_agent(body.question, scopes, rid)
    except TimeoutError: raise HTTPException(504, {'code': 'deadline_exceeded', 'request_id': rid})

Testing the contract with TestClient

Contract tests check the edges, not the answer quality. With the model stub, each test is fast and deterministic. The expected evidence is three passing tests: 401 without a token, 422 for a too-short question, and 200 with a request_id and an allowed status for a valid call.

python
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)
AUTH = {'Authorization': 'Bearer test-token-staff'}

def test_contract():
    assert client.post('/v1/ask', json={'question': 'hi there'}).status_code == 401
    assert client.post('/v1/ask', json={'question': 'x'}, headers=AUTH).status_code == 422
    r = client.post('/v1/ask', json={'question': 'Expense deadline?'}, headers=AUTH)
    assert r.status_code == 200
    assert r.json()['status'] in {'answered', 'clarify', 'abstained', 'escalated'}
    assert r.json()['request_id']

Quick reference

  • pip install "fastapi[standard]"; run with fastapi dev main.py; docs at /docs
  • Identity comes from a Depends() auth dependency, never from the request body
  • Every response and log line carries the same request ID
  • Status values: answered, clarify, abstained, escalated; all are HTTP 200
  • async with asyncio.timeout(seconds) needs Python 3.11+; TimeoutError maps to 504
  • await request.is_disconnected() tells you the client has gone
  • Error body: code, short message, request_id; details only in server logs

Common mistakes

  • Accepting a user_id field in the body and trusting it for permission checks.
  • Returning raw exception text, which can leak file paths, SQL or prompt contents.
  • Letting the agent keep running after the deadline or after the client has gone.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Where should the endpoint learn which document scopes the caller has?

Question 2

2The assistant abstains because no permitted evidence exists. Which HTTP status fits the contract?

Question 3

3What happens when the code inside async with asyncio.timeout(20) runs longer than 20 seconds?

Question 4

4Which error body is user-safe?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write AskRequest and AskResponse Pydantic models. The question must be 3 to 2000 characters, and status must be one of answered, clarify, abstained or escalated.

  2. Exercise 2medium

    Add middleware that assigns a UUID4 request ID to every request, stores it on request.state and returns it in an X-Request-ID header.

  3. Exercise 3hard

    Make the endpoint stop the agent when the client disconnects. Start the agent as a task, poll request.is_disconnected() every 0.5 seconds, and cancel the task if the client has gone. Show in a log line that the run was cancelled.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need OAuth to follow this topic?
No. A dictionary of test bearer tokens is enough to practise the contract locally. In production you would verify signed tokens from your identity provider in the same dependency.
Why not return the lineage and scores to the client?
They are internal details that can change and may reveal how retrieval works. Return source IDs for citations and keep lineage in logs and traces.
Should I stream the answer instead?
Streaming improves perceived speed, but you can only validate citations once the draft is complete. Many teams stream status updates and send the validated answer at the end.
What status code should a deadline timeout use?
504 Gateway Timeout is a common choice when the service gave up waiting on its own work or dependencies. Whatever you choose, document it in the contract and keep it consistent.

Go deeper

ShareXLinkedInWhatsApp