|
1 | 1 | """FastAPI application entry point.""" |
2 | 2 |
|
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from collections.abc import AsyncGenerator |
| 6 | + |
| 7 | +import agent |
3 | 8 | import fastapi |
4 | 9 | import fastapi.middleware.cors |
5 | | -from routes import chat |
| 10 | +import fastapi.responses |
| 11 | +import pydantic |
| 12 | +import storage |
6 | 13 |
|
7 | | -api = fastapi.FastAPI( |
| 14 | +import vercel_ai_sdk as ai |
| 15 | +import vercel_ai_sdk.ai_sdk_ui |
| 16 | + |
| 17 | +app = fastapi.FastAPI( |
8 | 18 | title="py-ai-fastapi-chat", |
9 | 19 | description="Chat demo using Python Vercel AI SDK", |
10 | 20 | ) |
11 | 21 |
|
12 | | -api.add_middleware( |
| 22 | +app.add_middleware( |
13 | 23 | fastapi.middleware.cors.CORSMiddleware, |
14 | 24 | allow_origins=["*"], |
15 | 25 | allow_credentials=True, |
16 | 26 | allow_methods=["*"], |
17 | 27 | allow_headers=["*"], |
18 | 28 | ) |
19 | 29 |
|
20 | | -api.include_router(chat.router) |
21 | | - |
22 | 30 |
|
23 | | -@api.get("/health") |
| 31 | +@app.get("/health") |
24 | 32 | async def health() -> dict[str, str]: |
25 | 33 | """Health check endpoint.""" |
26 | 34 | return {"status": "ok"} |
27 | 35 |
|
28 | 36 |
|
29 | | -app = fastapi.FastAPI() |
30 | | -app.mount("/api", api) |
| 37 | +file_storage = storage.FileStorage() |
| 38 | + |
| 39 | + |
| 40 | +class ChatRequest(pydantic.BaseModel): |
| 41 | + """Request body for the chat endpoint.""" |
| 42 | + |
| 43 | + messages: list[ai.ai_sdk_ui.UIMessage] |
| 44 | + session_id: str | None = None |
| 45 | + |
| 46 | + |
| 47 | +@app.post("/chat") |
| 48 | +async def chat(request: ChatRequest) -> fastapi.responses.StreamingResponse: |
| 49 | + """Handle chat requests and stream responses.""" |
| 50 | + messages = ai.ai_sdk_ui.to_messages(request.messages) |
| 51 | + session_id = request.session_id or "default" |
| 52 | + checkpoint_key = f"checkpoint:{session_id}" |
| 53 | + |
| 54 | + llm = agent.get_llm() |
| 55 | + |
| 56 | + # Checkpoints resume an *interrupted* run (e.g. a hook that needed |
| 57 | + # user input in serverless mode). Each normal chat turn is a fresh |
| 58 | + # run — the frontend carries the full message history — so we only |
| 59 | + # load a checkpoint when one was saved from a previous incomplete run. |
| 60 | + saved = await file_storage.get(checkpoint_key) |
| 61 | + checkpoint = ai.Checkpoint.model_validate(saved) if saved else None |
| 62 | + |
| 63 | + result = ai.run(agent.graph, llm, messages, agent.TOOLS, checkpoint=checkpoint) |
| 64 | + |
| 65 | + async def stream_response() -> AsyncGenerator[str]: |
| 66 | + async for chunk in ai.ai_sdk_ui.to_sse_stream(result): |
| 67 | + yield chunk |
| 68 | + |
| 69 | + # If the run completed (no pending hooks), clear the checkpoint |
| 70 | + # so the next request starts fresh. If hooks are pending, save |
| 71 | + # the checkpoint so the next request can resume from here. |
| 72 | + if result.pending_hooks: |
| 73 | + await file_storage.put(checkpoint_key, result.checkpoint.model_dump()) |
| 74 | + else: |
| 75 | + await file_storage.delete(checkpoint_key) |
| 76 | + |
| 77 | + return fastapi.responses.StreamingResponse( |
| 78 | + stream_response(), |
| 79 | + headers=ai.ai_sdk_ui.UI_MESSAGE_STREAM_HEADERS, |
| 80 | + ) |
0 commit comments