|
| 1 | +import uvicorn |
| 2 | +import asyncio |
| 3 | +from fastapi import FastAPI, Request |
| 4 | +from fastapi.responses import HTMLResponse, StreamingResponse |
| 5 | +from fastapi.templating import Jinja2Templates |
| 6 | +from pydantic import BaseModel |
| 7 | +from loguru import logger as _logger |
| 8 | +from app.agent.manus import Manus |
| 9 | +from app.logger import logger |
| 10 | + |
| 11 | +app = FastAPI() |
| 12 | +agent = Manus() |
| 13 | +log_queue = asyncio.Queue() # using `asyncio.Queue` prevents blocking |
| 14 | +templates = Jinja2Templates(directory="templates") |
| 15 | + |
| 16 | +# Log Interceptor: Asynchronously store logs in the queue |
| 17 | +async def log_intercept(message: str): |
| 18 | + message = message.strip() |
| 19 | + if message: |
| 20 | + await log_queue.put(message) |
| 21 | + |
| 22 | +# Append log interceptor to `loguru` without affecting existing log handling |
| 23 | +_logger.add(lambda msg: asyncio.create_task(log_intercept(msg)), format="{message}") |
| 24 | + |
| 25 | +# Asynchronous log stream using `async for` for efficient real-time streaming |
| 26 | +async def log_stream(): |
| 27 | + while True: |
| 28 | + message = await log_queue.get() # ✅ Waits for new log messages |
| 29 | + yield f"data: {message}\n\n" |
| 30 | + |
| 31 | +@app.get("/logs") |
| 32 | +async def stream_logs(): |
| 33 | + """Frontend can access the real-time log stream via `/logs`""" |
| 34 | + return StreamingResponse(log_stream(), media_type="text/event-stream") |
| 35 | + |
| 36 | +@app.get("/", response_class=HTMLResponse) |
| 37 | +async def index(request: Request): |
| 38 | + return templates.TemplateResponse("web.html", {"request": request}) |
| 39 | + |
| 40 | +class PromptRequest(BaseModel): |
| 41 | + prompt: str |
| 42 | + |
| 43 | +@app.post("/run") |
| 44 | +async def run(request: PromptRequest): |
| 45 | + logger.warning("Processing your request...") |
| 46 | + result = await agent.run(request.prompt) # ✅ Ensures `agent.run()` executes asynchronously |
| 47 | + return {"result": result} |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info") |
0 commit comments