Sub topic 7
Providing the LLM client with Depends
This chapter assumes you can write a basic FastAPI route with a Pydantic model, and that you know what an async LLM chat client looks like. You will move client creation out of the endpoint body and into a dependency. That makes the endpoint easier to test and keeps one client alive for the whole app.
Why not create the client inside the endpoint
A simple version builds the client in the route:
@app.post("/chat")
async def chat(body: ChatRequest):
client = AsyncOpenAI() # new client on every request
...This has two problems.
- Each request builds a new client. The client owns an HTTP connection pool, so you lose connection reuse and pay setup cost every time.
- The endpoint is hard to test. The route is tied to the real client, so a test would call the real model unless you patch module internals.
What Depends does
Depends is FastAPI's dependency injection. You declare a function that returns the thing you need. You then list it as a parameter default. FastAPI calls the function for each request and passes the result into your endpoint.
The endpoint no longer decides how the client is built. It only says that it needs one.
Sharing one client with lru_cache
The dependency below returns the same client every time:
from functools import lru_cache
from openai import AsyncOpenAI
@lru_cache
def get_client() -> AsyncOpenAI:
return AsyncOpenAI()lru_cache stores the result of the first call. Later calls return that same object. AsyncOpenAI() reads the OPENAI_API_KEY environment variable, so no secret appears in code.
FastAPI still calls get_client on each request. The cache makes that call cheap and returns the shared instance.
Using the dependency in the endpoint
from fastapi import Depends, FastAPI
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
app = FastAPI()
class ChatRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
@app.post("/chat")
async def chat(body: ChatRequest, client: AsyncOpenAI = Depends(get_client)):
...The route receives client already built. The next chapter combines this with the streaming generator.
The testing benefit
FastAPI keeps a dictionary called app.dependency_overrides. Map the original dependency function to a replacement, and FastAPI calls the replacement instead:
app.dependency_overrides[get_client] = lambda: FakeClient()The endpoint code does not change. A later chapter uses this to test streaming without a real model.
Common errors
- Calling the function in
Depends. WriteDepends(get_client), notDepends(get_client()). The second form runs the function once at import time and breaks both per-request resolution and overrides. - Overriding with a different function object. The key in
dependency_overridesmust be the exact function used inDepends. A copy or a re-import under another name will not match. - Forgetting to clear overrides. Overrides persist on the app object. Call
app.dependency_overrides.clear()after each test, or later tests will use the fake. - Caching a client that depends on request data.
lru_cachesuits a client configured only from the environment. If a client needs per-user credentials, build it without the cache. - Missing API key. If
OPENAI_API_KEYis unset,AsyncOpenAI()raises when first called. Because of the cache, the failure happens on the first request, not at startup.
Exercise
A teammate writes client: AsyncOpenAI = Depends(get_client()) and finds that their test override of get_client has no effect. Why?
Show answer
get_client() is called when the module loads, so Depends receives the client object, not the function. FastAPI has no function to resolve per request, and dependency_overrides[get_client] never matches. The fix is Depends(get_client).
Exercise
Why does get_client use lru_cache, and what does the endpoint gain from receiving the client through Depends?
Show answer
lru_cache makes every request share one client and its connection pool instead of building a new one. Receiving the client through Depends lets tests replace it with a fake through dependency_overrides, without editing the endpoint.