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.
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 FastAPIfrom fastapi.testclient import TestClientfrom pydantic import BaseModelfrom langchain.chat_models import init_chat_modelmodel = 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 serverr = client.post("/ask", json={"text": "Name one Dickens novel. Title only."})print(r.status_code, r.json())
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.
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.