Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,281 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import os
|
| 3 |
-
from typing import Any, AsyncIterator
|
| 4 |
-
from uuid import UUID
|
| 5 |
-
import importlib.util
|
| 6 |
-
|
| 7 |
-
from starlette.concurrency import run_in_threadpool
|
| 8 |
-
|
| 9 |
-
from fastapi import FastAPI
|
| 10 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
-
from fastapi.responses import StreamingResponse
|
| 12 |
-
from pydantic import BaseModel, Field
|
| 13 |
-
|
| 14 |
-
from agents_workflow.main import get_supervisor
|
| 15 |
-
from backend.tts_service.router import router as tts_router
|
| 16 |
-
from backend.stt_service.router import router as stt_router
|
| 17 |
-
|
| 18 |
-
from backend.rag_routers.documents import router as documents_router
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
LAYA_ROUTER_PATH = os.path.join(os.path.dirname(__file__), "laya", "laya_router.py")
|
| 22 |
-
_laya_spec = importlib.util.spec_from_file_location("project_laya_router", LAYA_ROUTER_PATH)
|
| 23 |
-
if _laya_spec is None or _laya_spec.loader is None:
|
| 24 |
-
raise ImportError(f"Could not load Laya router from {LAYA_ROUTER_PATH}")
|
| 25 |
-
_laya_module = importlib.util.module_from_spec(_laya_spec)
|
| 26 |
-
_laya_spec.loader.exec_module(_laya_module)
|
| 27 |
-
route = _laya_module.route
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
app = FastAPI(
|
| 31 |
-
title="Aether AI Assistant API",
|
| 32 |
-
description="API for the multi-agent chatbot and document knowledge base",
|
| 33 |
-
version="1.0.0",
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
# Convenient for local development. Restrict this to your frontend origin in production.
|
| 37 |
-
app.add_middleware(
|
| 38 |
-
CORSMiddleware,
|
| 39 |
-
allow_origins=[
|
| 40 |
-
"http://127.0.0.1:8000",
|
| 41 |
-
"http://localhost:8000",
|
| 42 |
-
"http://localhost:5173",
|
| 43 |
-
"http://127.0.0.1:5173",
|
| 44 |
-
],
|
| 45 |
-
allow_credentials=True,
|
| 46 |
-
allow_methods=["*"],
|
| 47 |
-
allow_headers=["*"],
|
| 48 |
-
)
|
| 49 |
-
|
| 50 |
-
app.include_router(tts_router)
|
| 51 |
-
app.include_router(stt_router)
|
| 52 |
-
app.include_router(documents_router)
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
class ChatRequest(BaseModel):
|
| 56 |
-
message: str = Field(..., min_length=1, max_length=20_000)
|
| 57 |
-
thread_id: str = Field(default="local-demo", min_length=1, max_length=200)
|
| 58 |
-
profile_name: str = Field(default="", max_length=40)
|
| 59 |
-
knowledge_base_available: bool = False
|
| 60 |
-
knowledge_base_user_id: UUID
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
async def _run_laya(message: str) -> dict[str, Any]:
|
| 65 |
-
# Laya's router is synchronous, so do not block FastAPI's event loop.
|
| 66 |
-
result = await run_in_threadpool(route, message)
|
| 67 |
-
task = str(result["task"]).strip().lower()
|
| 68 |
-
if task not in {"simple", "complex"}:
|
| 69 |
-
raise ValueError(f"Unexpected task returned by Laya: {task}")
|
| 70 |
-
return {
|
| 71 |
-
"model": result["model"],
|
| 72 |
-
"task": task,
|
| 73 |
-
"confidence": result["confidence"],
|
| 74 |
-
}
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def sse_event(event: str, data: dict[str, Any]) -> str:
|
| 78 |
-
"""Encode one Server-Sent Event."""
|
| 79 |
-
return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False, default=str)}\n\n"
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def _content_to_text(content: Any) -> str:
|
| 83 |
-
"""Extract text from common LangChain message content formats."""
|
| 84 |
-
if isinstance(content, str):
|
| 85 |
-
return content
|
| 86 |
-
if isinstance(content, list):
|
| 87 |
-
parts = []
|
| 88 |
-
for item in content:
|
| 89 |
-
if isinstance(item, dict) and item.get("type") == "text":
|
| 90 |
-
parts.append(str(item.get("text", "")))
|
| 91 |
-
elif isinstance(item, str):
|
| 92 |
-
parts.append(item)
|
| 93 |
-
return "".join(parts)
|
| 94 |
-
return str(content) if content is not None else ""
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
@app.get("/")
|
| 98 |
-
async def root():
|
| 99 |
-
"""Report that the API is running; the React frontend runs separately."""
|
| 100 |
-
return {"status": "ok", "message": "API is live and running."}
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
@app.get("/health")
|
| 104 |
-
async def health():
|
| 105 |
-
return {"status": "ok"}
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
@app.post("/api/chat/stream")
|
| 109 |
-
async def chat_stream(request: ChatRequest):
|
| 110 |
-
"""Route with Laya, then stream supervisor/agent/tool events in one SSE response."""
|
| 111 |
-
async def generate() -> AsyncIterator[str]:
|
| 112 |
-
try:
|
| 113 |
-
routing = await _run_laya(request.message)
|
| 114 |
-
selected_model = routing["model"]
|
| 115 |
-
selected_task = routing["task"]
|
| 116 |
-
selected_supervisor = get_supervisor(
|
| 117 |
-
selected_model,
|
| 118 |
-
request.profile_name.strip(),
|
| 119 |
-
request.knowledge_base_available,
|
| 120 |
-
str(request.knowledge_base_user_id),
|
| 121 |
-
)
|
| 122 |
-
except Exception as exc:
|
| 123 |
-
yield sse_event(
|
| 124 |
-
"error",
|
| 125 |
-
{
|
| 126 |
-
"message": f"Laya routing failed: {exc}",
|
| 127 |
-
"hint": "Check that the Laya package is installed and its Router initializes correctly.",
|
| 128 |
-
},
|
| 129 |
-
)
|
| 130 |
-
return
|
| 131 |
-
|
| 132 |
-
config = {
|
| 133 |
-
"configurable": {
|
| 134 |
-
"thread_id": request.thread_id,
|
| 135 |
-
}
|
| 136 |
-
}
|
| 137 |
-
inputs = {
|
| 138 |
-
"messages": [
|
| 139 |
-
{"role": "user", "content": request.message}
|
| 140 |
-
]
|
| 141 |
-
}
|
| 142 |
-
|
| 143 |
-
# Tool outputs are deliberately buffered and sent only after the graph
|
| 144 |
-
# finishes. Status events (agent/tool names) can be shown immediately.
|
| 145 |
-
buffered_tool_results: list[dict[str, Any]] = []
|
| 146 |
-
seen_agent_starts: set[str] = set()
|
| 147 |
-
final_text_parts: list[str] = []
|
| 148 |
-
final_text_streamed = False
|
| 149 |
-
last_graph_output: dict[str, Any] | None = None
|
| 150 |
-
|
| 151 |
-
yield sse_event(
|
| 152 |
-
"routing",
|
| 153 |
-
{
|
| 154 |
-
"model": selected_model,
|
| 155 |
-
"task": selected_task,
|
| 156 |
-
"confidence": routing["confidence"],
|
| 157 |
-
"reason": (
|
| 158 |
-
"Classified as simple using Laya's task-complexity criteria."
|
| 159 |
-
if selected_task == "simple"
|
| 160 |
-
else "Classified as complex using Laya's task-complexity criteria."
|
| 161 |
-
),
|
| 162 |
-
},
|
| 163 |
-
)
|
| 164 |
-
yield sse_event("status", {"message": "Supervisor is analyzing your request."})
|
| 165 |
-
|
| 166 |
-
try:
|
| 167 |
-
async for event in selected_supervisor.astream_events(
|
| 168 |
-
inputs,
|
| 169 |
-
config=config,
|
| 170 |
-
version="v2",
|
| 171 |
-
):
|
| 172 |
-
event_type = event.get("event", "")
|
| 173 |
-
event_name = str(event.get("name", ""))
|
| 174 |
-
metadata = event.get("metadata") or {}
|
| 175 |
-
node_name = str(metadata.get("langgraph_node", ""))
|
| 176 |
-
|
| 177 |
-
# Keep the most recent graph output as a fallback if this
|
| 178 |
-
# LangGraph version does not tag supervisor token events as expected.
|
| 179 |
-
if event_type == "on_chain_end":
|
| 180 |
-
event_output = (event.get("data") or {}).get("output")
|
| 181 |
-
if isinstance(event_output, dict) and isinstance(event_output.get("messages"), list):
|
| 182 |
-
last_graph_output = event_output
|
| 183 |
-
|
| 184 |
-
# Report specialist agent starts in real time. The graph's
|
| 185 |
-
# node metadata normally contains the node/agent name.
|
| 186 |
-
if event_type == "on_chain_start":
|
| 187 |
-
possible_agent = node_name or event_name
|
| 188 |
-
known_agents = {
|
| 189 |
-
"web_search_agent",
|
| 190 |
-
"image_search_agent",
|
| 191 |
-
"news_agent",
|
| 192 |
-
"weather_agent",
|
| 193 |
-
"utility_agent",
|
| 194 |
-
"chat_agent",
|
| 195 |
-
"knowledge_base_agent",
|
| 196 |
-
}
|
| 197 |
-
if possible_agent in known_agents and possible_agent not in seen_agent_starts:
|
| 198 |
-
seen_agent_starts.add(possible_agent)
|
| 199 |
-
yield sse_event(
|
| 200 |
-
"agent",
|
| 201 |
-
{"name": possible_agent, "status": "working"},
|
| 202 |
-
)
|
| 203 |
-
|
| 204 |
-
# Report tool use immediately, but do not stream tool outputs yet.
|
| 205 |
-
if event_type == "on_tool_start":
|
| 206 |
-
tool_name = event_name or "unknown_tool"
|
| 207 |
-
yield sse_event(
|
| 208 |
-
"tool",
|
| 209 |
-
{"name": tool_name, "status": "running"},
|
| 210 |
-
)
|
| 211 |
-
|
| 212 |
-
if event_type == "on_tool_end":
|
| 213 |
-
buffered_tool_results.append(
|
| 214 |
-
{
|
| 215 |
-
"name": event_name or "unknown_tool",
|
| 216 |
-
"output": str((event.get("data") or {}).get("output", "")),
|
| 217 |
-
}
|
| 218 |
-
)
|
| 219 |
-
yield sse_event(
|
| 220 |
-
"tool",
|
| 221 |
-
{"name": event_name or "unknown_tool", "status": "finished"},
|
| 222 |
-
)
|
| 223 |
-
|
| 224 |
-
# Stream only the supervisor's model tokens, avoiding a mixture
|
| 225 |
-
# of private/intermediate specialist-agent text and final text.
|
| 226 |
-
if event_type == "on_chat_model_stream":
|
| 227 |
-
chunk = (event.get("data") or {}).get("chunk")
|
| 228 |
-
chunk_content = getattr(chunk, "content", None)
|
| 229 |
-
token_text = _content_to_text(chunk_content)
|
| 230 |
-
if token_text and node_name in {"supervisor", "supervisor_node"}:
|
| 231 |
-
final_text_streamed = True
|
| 232 |
-
final_text_parts.append(token_text)
|
| 233 |
-
yield sse_event("token", {"text": token_text})
|
| 234 |
-
|
| 235 |
-
# Some versions/configurations may not tag supervisor token events
|
| 236 |
-
# as expected. Recover the final answer from the output already
|
| 237 |
-
# observed in the event stream (do not invoke the graph a second time).
|
| 238 |
-
if not final_text_streamed and last_graph_output:
|
| 239 |
-
messages = last_graph_output.get("messages", [])
|
| 240 |
-
if messages:
|
| 241 |
-
answer = _content_to_text(getattr(messages[-1], "content", ""))
|
| 242 |
-
if answer:
|
| 243 |
-
final_text_parts = [answer]
|
| 244 |
-
yield sse_event("token", {"text": answer})
|
| 245 |
-
|
| 246 |
-
# Tool outputs are revealed only after the answer has finished.
|
| 247 |
-
for result in buffered_tool_results:
|
| 248 |
-
yield sse_event("tool_result", result)
|
| 249 |
-
|
| 250 |
-
yield sse_event(
|
| 251 |
-
"done",
|
| 252 |
-
{
|
| 253 |
-
"thread_id": request.thread_id,
|
| 254 |
-
"answer": "".join(final_text_parts),
|
| 255 |
-
},
|
| 256 |
-
)
|
| 257 |
-
|
| 258 |
-
except Exception as exc:
|
| 259 |
-
yield sse_event(
|
| 260 |
-
"error",
|
| 261 |
-
{
|
| 262 |
-
"message": str(exc),
|
| 263 |
-
"hint": "Check the Groq API key/model, tool API keys, imports, and package versions.",
|
| 264 |
-
},
|
| 265 |
-
)
|
| 266 |
-
|
| 267 |
-
return StreamingResponse(
|
| 268 |
-
generate(),
|
| 269 |
-
media_type="text/event-stream",
|
| 270 |
-
headers={
|
| 271 |
-
"Cache-Control": "no-cache",
|
| 272 |
-
"Connection": "keep-alive",
|
| 273 |
-
"X-Accel-Buffering": "no",
|
| 274 |
-
},
|
| 275 |
-
)
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
if __name__ == "__main__":
|
| 279 |
-
import uvicorn
|
| 280 |
-
|
| 281 |
-
uvicorn.run("app:app", host="127.0.0.1", port=8000, reload=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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