jdewitte commited on
Commit
5a8a2bf
Β·
1 Parent(s): aaa60d6

Fix endpoint issue

Browse files
Files changed (1) hide show
  1. app.py +33 -63
app.py CHANGED
@@ -497,75 +497,45 @@ async def chat_ui():
497
  @app.post("/chat", response_model=ChatOutput)
498
  async def chat_endpoint(chat_input: ChatInput) -> ChatOutput:
499
  """
500
- Chat endpoint for the web interface - calls agent directly
501
  """
502
  logger.info(f"πŸ’¬ Direct chat request: {chat_input.message[:100]}...")
503
 
504
  try:
505
- # Call the agent API directly
506
- agent_url = "https://agent.mcp.integration.ambris.com/index.php?fc=module&module=ambaiagent&controller=ajax"
507
-
508
- # Prepare the request for the agent
509
- agent_payload = {
510
- "action": "send_prompt",
511
- "prompt": chat_input.message,
512
- "context": {
513
- "history": [msg.dict() for msg in chat_input.conversation_history],
514
- "session_id": chat_input.session_id or f"hf_chat_{int(time.time())}"
515
- }
516
- }
 
 
 
 
 
 
 
 
 
 
 
 
517
 
518
- logger.info(f"πŸš€ Calling agent API: {agent_url}")
519
- logger.info(f"πŸ“¦ Agent payload: {json.dumps(agent_payload, indent=2)}")
520
-
521
- async with httpx.AsyncClient(timeout=30.0) as client:
522
- response = await client.post(
523
- agent_url,
524
- json=agent_payload,
525
- headers={
526
- "Content-Type": "application/json",
527
- "Accept": "application/json",
528
- "User-Agent": "HF-Space-Chat/1.0"
529
- }
530
- )
531
-
532
- logger.info(f"πŸ“‘ Agent response status: {response.status_code}")
533
-
534
- if response.status_code == 200:
535
- data = response.json()
536
- logger.info(f"βœ… Agent response received: {json.dumps(data, indent=2)}")
537
-
538
- # Extract the response from agent
539
- if data.get('success'):
540
- agent_response = data.get('response', 'No response provided')
541
-
542
- # Update conversation history
543
- updated_history = list(chat_input.conversation_history)
544
- updated_history.append(ChatMessage(role="user", content=chat_input.message))
545
- updated_history.append(ChatMessage(role="assistant", content=agent_response))
546
-
547
- return ChatOutput(
548
- response=agent_response,
549
- tool_used=data.get('tool_used'),
550
- conversation_history=updated_history
551
- )
552
- else:
553
- error_msg = data.get('error', 'Unknown error from agent')
554
- logger.error(f"❌ Agent returned error: {error_msg}")
555
- return ChatOutput(
556
- response=f"Sorry, I encountered an error: {error_msg}",
557
- conversation_history=list(chat_input.conversation_history)
558
- )
559
- else:
560
- logger.error(f"❌ Agent API call failed: {response.status_code} - {response.text}")
561
- return ChatOutput(
562
- response=f"Sorry, I'm unable to connect to the AI agent (HTTP {response.status_code})",
563
- conversation_history=list(chat_input.conversation_history)
564
- )
565
-
566
  except Exception as e:
567
- logger.error(f"πŸ’₯ Error calling agent API: {e}")
568
- import traceback
 
 
 
 
 
 
569
  logger.error(f"πŸ”¬ Full traceback: {traceback.format_exc()}")
570
 
571
  return ChatOutput(
 
497
  @app.post("/chat", response_model=ChatOutput)
498
  async def chat_endpoint(chat_input: ChatInput) -> ChatOutput:
499
  """
500
+ Chat endpoint for the web interface - uses MCP client
501
  """
502
  logger.info(f"πŸ’¬ Direct chat request: {chat_input.message[:100]}...")
503
 
504
  try:
505
+ # Use the MCP client to process the request
506
+ if not mcp_client:
507
+ raise HTTPException(status_code=500, detail="MCP client not initialized")
508
+
509
+ # Process the message through MCP
510
+ # For now, let's use a simple search as an example
511
+ search_result = await mcp_client.call_tool(
512
+ "search_products",
513
+ {"query": chat_input.message, "client_token": chat_input.client_token}
514
+ )
515
+
516
+ # Format the response
517
+ response_content = f"Based on your request '{chat_input.message}', here's what I found:\n\n{search_result}"
518
+
519
+ # Update conversation history
520
+ updated_history = list(chat_input.conversation_history)
521
+ updated_history.append(ChatMessage(role="user", content=chat_input.message))
522
+ updated_history.append(ChatMessage(role="assistant", content=response_content))
523
+
524
+ return ChatOutput(
525
+ response=response_content,
526
+ tool_used="search_products",
527
+ conversation_history=updated_history
528
+ )
529
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
530
  except Exception as e:
531
+ logger.error(f"❌ Chat endpoint error: {e}")
532
+ return ChatOutput(
533
+ response=f"Sorry, I encountered an error: {str(e)}",
534
+ conversation_history=list(chat_input.conversation_history)
535
+ )
536
+
537
+
538
+ # Helper function to identify tool needed based on message
539
  logger.error(f"πŸ”¬ Full traceback: {traceback.format_exc()}")
540
 
541
  return ChatOutput(