-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
59 lines (48 loc) · 1.83 KB
/
api.py
File metadata and controls
59 lines (48 loc) · 1.83 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
# filepath: c:\Users\Mohanad Hafez\Desktop\projects\ksu\api.py
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from graph.chatbot_graph import build_graph
# Initialize FastAPI app and chatbot graph
app = FastAPI()
chatbot_graph = build_graph()
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Replace "*" with specific origins in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Define the request schema
class ChatRequest(BaseModel):
state: dict
user_message: str
import logging
# Configure logging
#logging.basicConfig(level=logging.DEBUG)
@app.post("/chat")
def chat(request: ChatRequest):
#try:
# Ensure the state has a "messages" key
if "messages" not in request.state:
request.state["messages"] = []
# Add the user's message to the state
request.state["messages"].append({"role": "user", "content": request.user_message})
# Process the state through the chatbot graph using the .stream() method
events = chatbot_graph.stream(request.state, stream_mode="values")
# Capture only the final assistant message
last_msg = None
for step in events:
last_msg = step["messages"][-1]
if last_msg:
# Add the assistant's response back into the state
request.state["messages"].append({"role": "assistant", "content": last_msg.content})
# Return the assistant's response
bot_message = last_msg.content
return {"bot_message": bot_message, "state": request.state}
else:
raise ValueError("No response generated by the chatbot.")
# except Exception as e:
# logging.exception("An error occurred while processing the chat request.")
# raise HTTPException(status_code=500, detail=str(e))