-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
314 lines (248 loc) Β· 8.88 KB
/
api.py
File metadata and controls
314 lines (248 loc) Β· 8.88 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""
FinAgent Investment Agent - FastAPI Server
Multi-Agent AI ν¬μ μλ¬Έ μμ€ν
REST API
"""
import asyncio
import uuid
from typing import Optional, Dict, Any, List
from datetime import datetime
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from dotenv import load_dotenv
from langgraph.graph import StateGraph, START, END
from langchain_core.messages import HumanMessage, AIMessage
from langgraph.checkpoint.memory import MemorySaver
from utils.state import AgentState
from condition.guardrail import GuardrailNode
from condition.condition import ConditionNode
from user_chat.node import UserProfileChatNode
from retriever.node import RetrieverNode
from debate.node import DebateNode
from finance.node import FinanceNode
from utils.db import get_supabase_client
load_dotenv()
# FastAPI μ± μ΄κΈ°ν
app = FastAPI(
title="FinAgent Investment Agent API",
description="Multi-Agent AI κΈ°λ° ν¬μ μλ¬Έ μμ€ν
",
version="1.0.0"
)
# CORS μ€μ
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# μ μ λ³μ: LangGraph μ± λ° μΈμ
κ΄λ¦¬
financial_agent = None
active_sessions: Dict[str, Dict[str, Any]] = {}
# ===== Pydantic Models =====
class ChatRequest(BaseModel):
"""μ±ν
μμ² λͺ¨λΈ"""
user_id: str = Field(..., description="μ¬μ©μ κ³ μ ID")
message: str = Field(..., description="μ¬μ©μ λ©μμ§")
session_id: Optional[str] = Field(None, description="μΈμ
ID (μμΌλ©΄ μλ‘ μμ±)")
class ChatResponse(BaseModel):
"""μ±ν
μλ΅ λͺ¨λΈ"""
session_id: str
user_id: str
message: str
response: str
node_executed: Optional[str] = None
debate_history: Optional[List[str]] = None
timestamp: str
class ProfileResponse(BaseModel):
"""νλ‘ν μ‘°ν μλ΅"""
user_id: str
profile: Dict[str, Any]
timestamp: str
class HealthResponse(BaseModel):
"""ν¬μ€μ²΄ν¬ μλ΅"""
status: str
timestamp: str
agent_ready: bool
# ===== Helper Functions =====
def create_financial_agent():
"""LangGraph κΈ°λ° Financial Agent μμ±"""
memory = MemorySaver()
workflow = StateGraph(AgentState)
workflow.add_node("guardrail", GuardrailNode().run)
workflow.add_node("condition", ConditionNode().run)
workflow.add_node("user_chat", UserProfileChatNode().run)
workflow.add_node("retriever", RetrieverNode().run)
workflow.add_node("debate", DebateNode().run)
workflow.add_node("finance", FinanceNode().run)
workflow.add_edge(START, "guardrail")
def check_safety(state: AgentState):
result = state.get("guardrail_result", {})
return "condition" if result.get("is_allowed", True) else END
workflow.add_conditional_edges(
"guardrail",
check_safety,
{"condition": "condition", END: END}
)
return workflow.compile(checkpointer=memory)
async def load_user_profile(user_id: str) -> Dict[str, Any]:
"""Supabaseμμ μ¬μ©μ νλ‘ν λ‘λ"""
supabase = get_supabase_client()
if not supabase:
return {}
try:
res = supabase.table("user_profile").select("*").eq("external_user_key", user_id).execute()
if res.data:
return res.data[0]
except Exception as e:
print(f"Error loading profile for {user_id}: {e}")
return {}
# ===== Startup & Shutdown =====
@app.on_event("startup")
async def startup_event():
"""μλ² μμ μ Agent μ΄κΈ°ν"""
global financial_agent
print("π Initializing FinAgent...")
financial_agent = create_financial_agent()
print("β
FinAgent ready!")
@app.on_event("shutdown")
async def shutdown_event():
"""μλ² μ’
λ£ μ μ 리 μμ
"""
global active_sessions
active_sessions.clear()
print("π FinAgent shutdown complete.")
# ===== API Endpoints =====
@app.get("/", response_model=HealthResponse)
async def root():
"""λ£¨νΈ μλν¬μΈνΈ"""
return HealthResponse(
status="running",
timestamp=datetime.now().isoformat(),
agent_ready=financial_agent is not None
)
@app.get("/health", response_model=HealthResponse)
async def health_check():
"""ν¬μ€μ²΄ν¬ μλν¬μΈνΈ"""
return HealthResponse(
status="healthy",
timestamp=datetime.now().isoformat(),
agent_ready=financial_agent is not None
)
@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
"""
μ±ν
μλν¬μΈνΈ
- μ¬μ©μ λ©μμ§λ₯Ό λ°μ LangGraph Agentλ₯Ό μ€ν
- μΈμ
λ³λ‘ λν νμ€ν 리 κ΄λ¦¬
- Debate λ‘κ·Έ ν¬ν¨ κ°λ₯
"""
if not financial_agent:
raise HTTPException(status_code=500, detail="Agent not initialized")
# μΈμ
ID μμ± λλ κΈ°μ‘΄ μΈμ
μ¬μ©
session_id = request.session_id or str(uuid.uuid4())
# μΈμ
μ΄κΈ°ν
if session_id not in active_sessions:
profile = await load_user_profile(request.user_id)
active_sessions[session_id] = {
"user_id": request.user_id,
"profile": profile,
"first_run": True
}
session = active_sessions[session_id]
config = {"configurable": {"thread_id": session_id}}
# μ
λ ₯ μν ꡬμ±
input_state = {
"messages": [HumanMessage(content=request.message)],
"user_id": request.user_id
}
if session.get("first_run"):
input_state["user_profile"] = session["profile"]
input_state["collected_data"] = {}
session["first_run"] = False
# Agent μ€ν
response_text = ""
last_node = None
debate_history = None
try:
async for event in financial_agent.astream(input_state, config=config):
for node_name, state_update in event.items():
if state_update is None:
continue
last_node = node_name
# Debate νμ€ν 리 μΆμΆ
if node_name == "debate":
collected = state_update.get("collected_data", {})
debate_history = collected.get("debate_history", [])
# μ΅μ’
λ©μμ§ μΆμΆ
if "messages" in state_update:
last_msg = state_update["messages"][-1]
if isinstance(last_msg, AIMessage) and last_msg.content:
response_text = last_msg.content
except Exception as e:
raise HTTPException(status_code=500, detail=f"Agent execution failed: {str(e)}")
return ChatResponse(
session_id=session_id,
user_id=request.user_id,
message=request.message,
response=response_text or "No response generated",
node_executed=last_node,
debate_history=debate_history,
timestamp=datetime.now().isoformat()
)
@app.get("/profile/{user_id}", response_model=ProfileResponse)
async def get_profile(user_id: str):
"""μ¬μ©μ νλ‘ν μ‘°ν"""
profile = await load_user_profile(user_id)
if not profile:
raise HTTPException(status_code=404, detail=f"Profile not found for user: {user_id}")
return ProfileResponse(
user_id=user_id,
profile=profile,
timestamp=datetime.now().isoformat()
)
@app.post("/profile/{user_id}")
async def update_profile(user_id: str, profile_data: Dict[str, Any]):
"""
μ¬μ©μ νλ‘ν μ
λ°μ΄νΈ (Supabase)
"""
supabase = get_supabase_client()
if not supabase:
raise HTTPException(status_code=500, detail="Supabase client not available")
try:
# Upsert μν
profile_data["external_user_key"] = user_id
res = supabase.table("user_profile").upsert(profile_data).execute()
return {
"status": "success",
"user_id": user_id,
"updated_profile": res.data[0] if res.data else profile_data,
"timestamp": datetime.now().isoformat()
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Profile update failed: {str(e)}")
@app.delete("/session/{session_id}")
async def delete_session(session_id: str):
"""μΈμ
μμ (λ©λͺ¨λ¦¬ μ 리)"""
if session_id in active_sessions:
del active_sessions[session_id]
return {"status": "deleted", "session_id": session_id}
else:
raise HTTPException(status_code=404, detail="Session not found")
@app.get("/sessions")
async def list_sessions():
"""νμ± μΈμ
λͺ©λ‘ μ‘°ν"""
return {
"active_sessions": list(active_sessions.keys()),
"count": len(active_sessions),
"timestamp": datetime.now().isoformat()
}
# ===== μ€ν (κ°λ° λͺ¨λ) =====
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"api:app",
host="0.0.0.0",
port=8000,
reload=True,
log_level="info"
)