-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
139 lines (112 loc) · 3.4 KB
/
Copy pathmain.py
File metadata and controls
139 lines (112 loc) · 3.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
from __future__ import annotations
import httpx
from typing import Any
from sqlalchemy import text
from db.session import get_engine
from settings import get_settings
from pydantic import BaseModel, Field
from agent.graph import AnalyticsAgent
from datetime import datetime, timezone
from fastapi import FastAPI, HTTPException
settings = get_settings()
app = FastAPI(
title="AI Engineer Technical Assessment API",
version="1.0.0",
)
agent = AnalyticsAgent()
history: list[dict[str, Any]] = []
class ChatRequest(BaseModel):
question: str = Field(..., min_length=1, max_length=2000)
class ToolCallRecord(BaseModel):
tool: str
input: Any
output: Any
error: str | None = None
class ChatResponse(BaseModel):
answer: str
tool_calls: list[ToolCallRecord]
model: str
duration_ms: int
class HealthResponse(BaseModel):
status: str
ollama: str
database: str
mcp: str
class ToolInfo(BaseModel):
name: str
description: str
@app.on_event("startup")
async def startup_event() -> None:
try:
await agent.startup()
except Exception as exc:
print(f"Agent startup failed: {exc}")
@app.post("/chat", response_model=ChatResponse)
async def chat(payload: ChatRequest) -> ChatResponse:
try:
result = await agent.ask(payload.question)
history.append(
{
"question": payload.question,
"answer": result["answer"],
"tool_calls": result["tool_calls"],
"model": result["model"],
"duration_ms": result["duration_ms"],
"timestamp": datetime.now(timezone.utc).isoformat(),
}
)
del history[:-20]
return ChatResponse(**result)
except Exception as exc:
raise HTTPException(
status_code=503,
detail={
"error": "Agent request failed.",
"message": str(exc),
},
)
@app.get("/health", response_model=HealthResponse)
async def health() -> HealthResponse:
ollama_status = await check_ollama()
database_status = check_database()
mcp_status = await check_mcp()
overall = (
"ok"
if all(status == "ok" for status in [ollama_status, database_status, mcp_status])
else "degraded"
)
return HealthResponse(
status=overall,
ollama=ollama_status,
database=database_status,
mcp=mcp_status,
)
@app.get("/tools", response_model=list[ToolInfo])
async def tools() -> list[ToolInfo]:
return [ToolInfo(**tool) for tool in agent.list_tools()]
@app.get("/history")
async def get_history() -> list[dict[str, Any]]:
return list(reversed(history))
async def check_ollama() -> str:
try:
async with httpx.AsyncClient(timeout=2.0) as client:
response = await client.get(f"{settings.ollama_base_url}/api/tags")
return "ok" if response.status_code == 200 else "error"
except Exception:
return "error"
def check_database() -> str:
try:
engine = get_engine()
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
return "ok"
except Exception:
return "error"
async def check_mcp() -> str:
try:
if agent.list_tools():
return "ok"
await agent.startup()
return "ok" if agent.list_tools() else "error"
except Exception:
return "error"