destinyebuka commited on
Commit
b7d3dbc
Β·
1 Parent(s): 18a779e
Files changed (1) hide show
  1. app/ai/routes/chat_refactored.py +27 -70
app/ai/routes/chat_refactored.py CHANGED
@@ -1,7 +1,7 @@
1
  # app/ai/routes/chat_refactored.py
2
  """
3
  AIDA Chat Endpoint - LangGraph Powered (NO AUTH)
4
- Uses proper LangGraph architecture - No JWT authentication required
5
  """
6
 
7
  from fastapi import APIRouter, HTTPException
@@ -27,11 +27,11 @@ class AskBody(BaseModel):
27
  """Request body for /ask endpoint"""
28
  message: str
29
  session_id: Optional[str] = None
30
- user_id: Optional[str] = None # Optional - will generate if not provided
31
 
32
 
33
  # ============================================================
34
- # MAIN CHAT ENDPOINT - LANGGRAPH POWERED (NO AUTH)
35
  # ============================================================
36
 
37
  @router.post("/ask", response_model=AgentResponse)
@@ -39,14 +39,7 @@ async def ask_ai(
39
  body: AskBody,
40
  ) -> AgentResponse:
41
  """
42
- Main chat endpoint using LangGraph.
43
- NO AUTHENTICATION REQUIRED - Anyone can use it.
44
-
45
- Flow:
46
- 1. Generate user_id if not provided (anonymous user)
47
- 2. Initialize state
48
- 3. Execute LangGraph
49
- 4. Return response
50
  """
51
 
52
  logger.info("πŸš€ Chat request received", message_len=len(body.message))
@@ -62,22 +55,17 @@ async def ask_ai(
62
 
63
  message = body.message.strip()
64
  session_id = body.session_id or str(uuid.uuid4())
65
-
66
- # Generate user_id if not provided (anonymous user)
67
  user_id = body.user_id or f"anonymous_{uuid.uuid4()}"
68
-
69
- # Default role for anonymous users
70
  user_role = "renter"
71
 
72
  logger.info(
73
  "User session started",
74
  user_id=user_id,
75
- user_role=user_role,
76
  session_id=session_id,
77
  )
78
 
79
  # ============================================================
80
- # STEP 2: Initialize state
81
  # ============================================================
82
 
83
  state = AgentState(
@@ -86,29 +74,26 @@ async def ask_ai(
86
  user_role=user_role,
87
  )
88
 
89
- # Add message to history
90
  state.add_message("user", message)
91
  state.last_user_message = message
92
 
93
- logger.info("State initialized", state_summary=state.get_summary())
94
 
95
  # ============================================================
96
- # STEP 3: Get LangGraph and execute
97
  # ============================================================
98
 
99
  graph = get_aida_graph()
100
 
101
- logger.info("πŸ“ Executing LangGraph")
 
 
102
 
103
- # Execute the graph
104
- # LangGraph handles all node execution and routing
105
- final_state = await graph.ainvoke({
106
- "user_id": user_id,
107
- "session_id": session_id,
108
- "user_role": user_role,
109
- "last_user_message": message,
110
- "conversation_history": state.conversation_history,
111
- })
112
 
113
  logger.info(
114
  "βœ… LangGraph execution completed",
@@ -117,7 +102,7 @@ async def ask_ai(
117
  )
118
 
119
  # ============================================================
120
- # STEP 4: Build response
121
  # ============================================================
122
 
123
  response_text = final_state.temp_data.get("response_text", "")
@@ -125,6 +110,9 @@ async def ask_ai(
125
  draft = final_state.temp_data.get("draft")
126
  draft_ui = final_state.temp_data.get("draft_ui")
127
 
 
 
 
128
  response = AgentResponse(
129
  success=final_state.last_error is None,
130
  text=response_text,
@@ -164,7 +152,7 @@ async def ask_ai(
164
  logger.error("❌ Chat endpoint error", exc_info=e)
165
  raise HTTPException(
166
  status_code=500,
167
- detail="Internal server error"
168
  )
169
 
170
 
@@ -177,16 +165,13 @@ async def health_check():
177
  """Health check for chat service"""
178
 
179
  try:
180
- # Initialize graph to test it works
181
  graph = get_aida_graph()
182
 
183
  return {
184
  "status": "healthy",
185
  "service": "AIDA Chat (LangGraph)",
186
- "architecture": "LangGraph (Industry Standard)",
187
  "version": "2.0.0",
188
- "graph_nodes": 10,
189
- "authentication": "DISABLED - Public Access",
190
  }
191
  except Exception as e:
192
  logger.error("Health check failed", exc_info=e)
@@ -197,38 +182,12 @@ async def health_check():
197
 
198
 
199
  # ============================================================
200
- # VISUALIZATION ENDPOINT (Optional - for debugging)
201
- # ============================================================
202
-
203
- @router.get("/graph/structure")
204
- async def graph_structure():
205
- """Get the graph structure as ASCII art"""
206
-
207
- try:
208
- from app.ai.agent.graph import print_graph_structure
209
- print_graph_structure()
210
-
211
- return {
212
- "status": "success",
213
- "message": "Graph structure printed to logs",
214
- }
215
- except Exception as e:
216
- logger.error("Could not get graph structure", exc_info=e)
217
- return {
218
- "status": "error",
219
- "error": str(e),
220
- }
221
-
222
-
223
- # ============================================================
224
- # HISTORY ENDPOINT (Anonymous users)
225
  # ============================================================
226
 
227
  @router.get("/history/{session_id}")
228
- async def get_history(
229
- session_id: str,
230
- ):
231
- """Get conversation history for a session (no auth required)"""
232
 
233
  try:
234
  logger.info("Retrieved history", session_id=session_id)
@@ -236,7 +195,7 @@ async def get_history(
236
  return {
237
  "success": True,
238
  "session_id": session_id,
239
- "messages": [], # TODO: Fetch from Redis
240
  }
241
 
242
  except Exception as e:
@@ -249,10 +208,8 @@ async def get_history(
249
  # ============================================================
250
 
251
  @router.post("/reset-session/{session_id}")
252
- async def reset_session(
253
- session_id: str,
254
- ):
255
- """Reset a session to fresh state (no auth required)"""
256
 
257
  try:
258
  logger.info("Session reset", session_id=session_id)
 
1
  # app/ai/routes/chat_refactored.py
2
  """
3
  AIDA Chat Endpoint - LangGraph Powered (NO AUTH)
4
+ Fixed ainvoke for proper state passing
5
  """
6
 
7
  from fastapi import APIRouter, HTTPException
 
27
  """Request body for /ask endpoint"""
28
  message: str
29
  session_id: Optional[str] = None
30
+ user_id: Optional[str] = None
31
 
32
 
33
  # ============================================================
34
+ # MAIN CHAT ENDPOINT - LANGGRAPH POWERED (FIXED)
35
  # ============================================================
36
 
37
  @router.post("/ask", response_model=AgentResponse)
 
39
  body: AskBody,
40
  ) -> AgentResponse:
41
  """
42
+ Main chat endpoint using LangGraph - FIXED VERSION
 
 
 
 
 
 
 
43
  """
44
 
45
  logger.info("πŸš€ Chat request received", message_len=len(body.message))
 
55
 
56
  message = body.message.strip()
57
  session_id = body.session_id or str(uuid.uuid4())
 
 
58
  user_id = body.user_id or f"anonymous_{uuid.uuid4()}"
 
 
59
  user_role = "renter"
60
 
61
  logger.info(
62
  "User session started",
63
  user_id=user_id,
 
64
  session_id=session_id,
65
  )
66
 
67
  # ============================================================
68
+ # STEP 2: Create AgentState (NOT a dict!)
69
  # ============================================================
70
 
71
  state = AgentState(
 
74
  user_role=user_role,
75
  )
76
 
77
+ # Add user message to history
78
  state.add_message("user", message)
79
  state.last_user_message = message
80
 
81
+ logger.info("State initialized", user_id=user_id)
82
 
83
  # ============================================================
84
+ # STEP 3: Get graph and execute with proper state
85
  # ============================================================
86
 
87
  graph = get_aida_graph()
88
 
89
+ if graph is None:
90
+ logger.error("❌ Graph is None!")
91
+ raise HTTPException(status_code=500, detail="Graph initialization failed")
92
 
93
+ logger.info("πŸ“ Executing LangGraph with state")
94
+
95
+ # βœ… FIX: Pass the AgentState object directly, not a dict
96
+ final_state = await graph.ainvoke(state)
 
 
 
 
 
97
 
98
  logger.info(
99
  "βœ… LangGraph execution completed",
 
102
  )
103
 
104
  # ============================================================
105
+ # STEP 4: Build response from final state
106
  # ============================================================
107
 
108
  response_text = final_state.temp_data.get("response_text", "")
 
110
  draft = final_state.temp_data.get("draft")
111
  draft_ui = final_state.temp_data.get("draft_ui")
112
 
113
+ if not response_text:
114
+ response_text = "I'm here to help! What would you like to do?"
115
+
116
  response = AgentResponse(
117
  success=final_state.last_error is None,
118
  text=response_text,
 
152
  logger.error("❌ Chat endpoint error", exc_info=e)
153
  raise HTTPException(
154
  status_code=500,
155
+ detail=f"Internal server error: {str(e)}"
156
  )
157
 
158
 
 
165
  """Health check for chat service"""
166
 
167
  try:
 
168
  graph = get_aida_graph()
169
 
170
  return {
171
  "status": "healthy",
172
  "service": "AIDA Chat (LangGraph)",
 
173
  "version": "2.0.0",
174
+ "graph_available": graph is not None,
 
175
  }
176
  except Exception as e:
177
  logger.error("Health check failed", exc_info=e)
 
182
 
183
 
184
  # ============================================================
185
+ # HISTORY ENDPOINT
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  # ============================================================
187
 
188
  @router.get("/history/{session_id}")
189
+ async def get_history(session_id: str):
190
+ """Get conversation history for a session"""
 
 
191
 
192
  try:
193
  logger.info("Retrieved history", session_id=session_id)
 
195
  return {
196
  "success": True,
197
  "session_id": session_id,
198
+ "messages": [],
199
  }
200
 
201
  except Exception as e:
 
208
  # ============================================================
209
 
210
  @router.post("/reset-session/{session_id}")
211
+ async def reset_session(session_id: str):
212
+ """Reset a session to fresh state"""
 
 
213
 
214
  try:
215
  logger.info("Session reset", session_id=session_id)