Sub topic 7
Providing the LLM Client with Depends
This chapter assumes you can write a basic FastAPI route and a Pydantic model. It also assumes you understand async/await and know the earlier chapters' StreamingResponse endpoint. Here you will look at one line of that endpoint, client: AsyncOpenAI = Depends(get_client), and see why it is there, how it behaves, and which mistakes it prevents.
Why the endpoint does not create its own client
The simplest way to call a model is to construct the client inside the route:
@app.post("/chat")
async def chat(body: ChatRequest):
client = AsyncOpenAI() # created on every request
...This works in a demo and causes three problems in a real service.
- Connection reuse is lost. An async client holds an HTTP connection pool. A new client per request pays for a new TCP and TLS handshake each time. Abandoned pools also leave sockets open until garbage collection closes them.
- Tests need the network. The route calls the real provider, so a test needs an API key, costs money, and returns different text on each run.
- Configuration is scattered. Every route that calls the model repeats the construction code and the settings behind it.
Dependency injection fixes all three. The route declares what it needs, and FastAPI supplies it. The route does not know how the object was built or where it came from.
How Depends works
Depends(get_client) tells FastAPI to call get_client before your route function runs and pass the return value as the parameter. FastAPI does this for every request. Dependencies can have their own dependencies, and FastAPI resolves them in order.
flowchart LRThe diagram below shows the flow for a normal request and for a test.
Note that FastAPI also validates body: ChatRequest before the route runs. If the body is invalid, the client dependency may already have been resolved, but the route never starts.
A shared client with lru_cache
The endpoint from the previous chapter uses this factory:
from functools import lru_cache
from openai import AsyncOpenAI
@lru_cache
def get_client() -> AsyncOpenAI:
return AsyncOpenAI()lru_cache on a function with no arguments stores the first return value and returns it on every later call. All requests then share one client and one connection pool. AsyncOpenAI() reads OPENAI_API_KEY from the environment, so the factory needs no arguments.
You can check the sharing without a real model. This script is complete and runnable with fastapi and httpx installed:
from functools import lru_cache
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
class Client:
pass
@lru_cache
def get_client() -> Client:
print("creating client")
return Client()
@app.get("/id")
def show_id(client: Client = Depends(get_client)):
return {"id": id(client)}
with TestClient(app) as http:
first = http.get("/id").json()
second = http.get("/id").json()
print(first == second)The output is creating client once, then True. The factory ran one time and both requests received the same object.
Gotchas with lru_cache
- The first call is lazy. The client is built on the first request, not at startup. A missing
OPENAI_API_KEYmakesAsyncOpenAI()raise, and the first user gets a 500 error. An exception is not cached, so every request retries and fails until you fix the environment. - Concurrent first calls can build two clients. FastAPI runs a plain
defdependency in a thread pool.lru_cachedoes not hold a lock while the function runs, so two simultaneous first requests may both construct a client. One result wins the cache and the other is discarded. This is harmless for a client object, but do not use this pattern for anything with side effects. - The cache is per process. With four worker processes you get four clients. This is normal and usually what you want.
- The client is never closed. The pool is released when the process exits. That is acceptable for many services. If you need a clean shutdown, use the lifespan approach below.
Making it explicit with lifespan
If you want startup validation and a clean close, create the client in the application's lifespan and store it on app.state. The dependency then reads it back from the request:
from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI, Request
from openai import AsyncOpenAI
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.llm = AsyncOpenAI()
yield
await app.state.llm.close()
app = FastAPI(lifespan=lifespan)
def get_client(request: Request) -> AsyncOpenAI:
return request.app.state.llm
@app.get("/ping")
async def ping(client: AsyncOpenAI = Depends(get_client)):
return {"client_ready": client is not None}Construction now happens before the server accepts traffic, so a missing key stops the startup instead of failing a user request. The close() call after yield runs at shutdown.
Both options give the route the same Depends(get_client) line, so you can switch between them without touching the route.
| Approach | Built when | Closed cleanly | Failure on bad config | Extra code |
|---|---|---|---|---|
| Client inside the route | Every request | No | Per request | None, but wasteful |
| `lru_cache` factory | First request | No | First request | Minimal |
| Lifespan and `app.state` | Startup | Yes | At startup | A lifespan function |
Cleaner signatures with Annotated
Repeating Depends(get_client) in every route is noisy. FastAPI supports Annotated, which lets you name the dependency once:
from typing import Annotated
from fastapi import Depends
from openai import AsyncOpenAI
LLMClient = Annotated[AsyncOpenAI, Depends(get_client)]
@app.post("/chat")
async def chat(body: ChatRequest, client: LLMClient):
...The type and the source of the value stay together. If you later rename or replace get_client, you change one line.
Passing the client into the generator
Look at how the streaming endpoint uses the injected value:
return StreamingResponse(
token_events(client, body.prompt),
media_type="text/event-stream",
)The route resolves client and passes it to the generator as an argument. The generator does not call get_client() itself. This keeps the generator a plain function of its inputs, which makes it easy to run with a fake client. It also avoids a subtle problem. The generator body runs while the response is being sent, after the route function has returned. Anything you resolve there is outside FastAPI's normal dependency handling.
Other things worth injecting
The same pattern applies to anything the route should not build itself. A common second dependency is settings, such as the model name:
import os
from functools import lru_cache
from pydantic import BaseModel
class Settings(BaseModel):
model: str
@lru_cache
def get_settings() -> Settings:
return Settings(model=os.environ.get("LLM_MODEL", "gpt-4o-mini"))A route can then declare settings: Settings = Depends(get_settings) and pass settings.model to the generator. A test can override the model name without editing environment variables. Do this only when you have a real need to vary the value. The endpoint in this tutorial reads LLM_MODEL directly, and that is fine for a single setting.
Overriding a dependency
The reason the pattern pays off is app.dependency_overrides, a dictionary that maps an original dependency to a replacement. The testing chapter covers it in full. The core idea is short:
app.dependency_overrides[get_client] = lambda: FakeClient()Two rules matter for correctness.
- The key must be the exact function object used in
Depends. If you writeDepends(get_client)in the route and override a different function with the same name, nothing changes and the real client is called. - Clear overrides when the test ends. The dictionary lives on the app object. A leftover override leaks into other tests. Call
app.dependency_overrides.clear()in afinallyblock or a fixture teardown.
The replacement receives its own arguments through the same Depends machinery, so a lambda with no parameters is enough for a fake with no dependencies.
Common errors
- Using the
lru_cachekey by mistake. Adding parameters to a cached factory makes FastAPI see them as request parameters. Keep cached factories argument-free, or read configuration from the environment inside them. - Awaiting the dependency.
get_clientreturns the client, not a coroutine. Writingawait get_client()raises aTypeError. A dependency can beasync def, but then FastAPI awaits it for you. - Closing a shared client per request. Using
async with AsyncOpenAI() as clientinside a route closes the pool when the block ends. That is fine for a per-request client. With a shared client, one request would close the pool for every other request. - Assuming one client means one connection. The client manages a pool. Concurrent streams each hold a connection from it for the whole length of their response, so very high concurrency can need pool limits. The last chapter returns to limits.
Exercise
A teammate changes getclient to `def getclient(apikey: str) -> AsyncOpenAI: return AsyncOpenAI(apikey=apikey) and keeps Depends(getclient)` in the route. What happens when a request arrives, and how would you fix it so the key still comes from the environment?
Show answer
FastAPI treats api_key as a request parameter, because it is a plain str argument with no default. It looks for api_key in the query string, finds nothing, and returns a 422 validation error before the route runs. The fix is to remove the parameter and read the key from the environment, as AsyncOpenAI() already does. Alternatively, add a second dependency such as get_settings and declare settings: Settings = Depends(get_settings) in get_client, so the key comes from a dependency and not from the request.
Exercise
You switch from the lru_cache factory to the lifespan version. Name one failure that now appears earlier, and one thing the old version never did that the new one does.
Show answer
A missing or invalid API setup now fails at startup, when AsyncOpenAI() is constructed in the lifespan function, instead of on the first user request. The new version also closes the client with await app.state.llm.close() at shutdown, which releases the connection pool. The lru_cache version never closed it.