AI Hints
Home›LangChain Tutorial›Serving and the Project Plan
LangChain · Lesson 97 of 120

Serving with FastAPI

An API for your chain.

⏱ 2 min read▶ Video at 1:50:33🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

So far, our chains run in a script. A website or a phone app can't call a script. They call a web API. FastAPI is a popular Python framework for building one, in a few lines.

Serving with FastAPI
From the video: Serving with FastAPI
  • Scripts aren't reachable
  • Apps call web APIs
  • FastAPI makes one

An ask endpoint

FastAPI turns Python functions into web endpoints. The question class describes the J SON body we expect. The ask endpoint receives it, calls the model, and returns J SON. To test it without starting a server, we use FastAPI's test client, which sends a real request to the app. Run it. We get status two hundred, and a J SON answer.

app.pypython
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
from langchain.chat_models import init_chat_model

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
app = FastAPI()

class Question(BaseModel):
    text: str

@app.post("/ask")
def ask(q: Question):
    return {"answer": model.invoke(q.text).text}

client = TestClient(app)   # calls the app without a real server
r = client.post("/ask", json={"text": "Name one Dickens novel. Title only."})
print(r.status_code, r.json())
Output
200 {'answer': 'Great Expectations'}

Running it for real

To serve it for real, run the app with uvicorn, a fast Python web server. Then any website or app can send a post request to slash ask. In production, add the timeout, rate limits, and fallbacks from the last section, and an API key, so only your apps can call it.

keyvalue
Runuvicorn app:app
CallPOST /ask with JSON
Addtimeouts, fallbacks
Protectan API key

Summary

FastAPI turns your chain into a web API. Define a request class and an endpoint, and test it with the test client. Next, streaming the answer over HTTP.

Key takeaways
  • FastAPI()
  • @app.post('/ask')
  • TestClient
Next up: Streaming over HTTP — text as it arrives