|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import logging |
1 | 4 | from contextlib import asynccontextmanager |
2 | 5 | from os import getenv |
3 | 6 |
|
4 | 7 | from fastapi import FastAPI, HTTPException |
5 | | -from openai_responses_agent_base.agent import get_agent_closure |
| 8 | +from fastapi.responses import StreamingResponse |
| 9 | +from openai_responses_agent_base.agent import get_agent_closure, AIAgent |
6 | 10 | from pydantic import BaseModel |
7 | 11 |
|
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
8 | 14 |
|
9 | 15 | # Request/Response models |
10 | 16 | class ChatRequest(BaseModel): |
@@ -81,6 +87,75 @@ async def chat(request: ChatRequest): |
81 | 87 | ) |
82 | 88 |
|
83 | 89 |
|
| 90 | +@app.post("/stream") |
| 91 | +async def stream(request: ChatRequest): |
| 92 | + """ |
| 93 | + Streaming chat endpoint that accepts a message and returns the agent's |
| 94 | + response as Server-Sent Events (SSE). |
| 95 | +
|
| 96 | + Event types: |
| 97 | + - tool_call: tool invocation by the agent |
| 98 | + - tool_result: result returned by a tool (observation) |
| 99 | + - token: final answer text |
| 100 | + - done: signals the stream is complete |
| 101 | +
|
| 102 | + Args: |
| 103 | + request: ChatRequest containing the user message |
| 104 | + """ |
| 105 | + global get_agent |
| 106 | + |
| 107 | + if get_agent is None: |
| 108 | + raise HTTPException(status_code=503, detail="Agent not initialized") |
| 109 | + |
| 110 | + async def event_generator(): |
| 111 | + try: |
| 112 | + queue: asyncio.Queue = asyncio.Queue() |
| 113 | + |
| 114 | + def on_event(event_type: str, data: dict): |
| 115 | + queue.put_nowait((event_type, data)) |
| 116 | + |
| 117 | + def run_agent(): |
| 118 | + adapter = get_agent() |
| 119 | + agent = AIAgent( |
| 120 | + model=adapter._model_id, |
| 121 | + base_url=adapter._base_url, |
| 122 | + api_key=adapter._api_key, |
| 123 | + ) |
| 124 | + for name, func in adapter._tools: |
| 125 | + agent.register_tool(name, func) |
| 126 | + return agent.query(request.message, on_event=on_event) |
| 127 | + |
| 128 | + task = asyncio.get_event_loop().run_in_executor(None, run_agent) |
| 129 | + |
| 130 | + while not task.done(): |
| 131 | + try: |
| 132 | + event_type, data = await asyncio.wait_for(queue.get(), timeout=0.1) |
| 133 | + yield f"event: {event_type}\ndata: {json.dumps(data)}\n\n" |
| 134 | + except asyncio.TimeoutError: |
| 135 | + continue |
| 136 | + |
| 137 | + # Drain remaining events |
| 138 | + while not queue.empty(): |
| 139 | + event_type, data = queue.get_nowait() |
| 140 | + yield f"event: {event_type}\ndata: {json.dumps(data)}\n\n" |
| 141 | + |
| 142 | + answer = task.result() |
| 143 | + if answer: |
| 144 | + yield f"event: token\ndata: {json.dumps({'content': answer})}\n\n" |
| 145 | + |
| 146 | + yield "event: done\ndata: {}\n\n" |
| 147 | + |
| 148 | + except Exception: |
| 149 | + logger.exception("Error in stream event_generator") |
| 150 | + yield f"event: error\ndata: {json.dumps({'detail': 'Internal server error'})}\n\n" |
| 151 | + |
| 152 | + return StreamingResponse( |
| 153 | + event_generator(), |
| 154 | + media_type="text/event-stream", |
| 155 | + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, |
| 156 | + ) |
| 157 | + |
| 158 | + |
84 | 159 | @app.get("/health") |
85 | 160 | async def health(): |
86 | 161 | """Return service health and whether the agent has been initialized.""" |
|
0 commit comments