Repository navigation
Expand file tree
/
Copy pathcode.py
More file actions
210 lines (165 loc) · 6.71 KB
/
Copy pathcode.py
File metadata and controls
210 lines (165 loc) · 6.71 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
from typing import TypedDict, Annotated, Optional
from langgraph.graph import add_messages, StateGraph, END
from langchain_groq import ChatGroq
from langchain_core.messages import HumanMessage, AIMessageChunk, ToolMessage
from dotenv import load_dotenv
from langchain_community.tools.tavily_search import TavilySearchResults
from fastapi import FastAPI, Query
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
import json
from uuid import uuid4
from langgraph.checkpoint.memory import MemorySaver
load_dotenv()
# Initialize memory saver for checkpointing
memory = MemorySaver()
class State(TypedDict):
messages: Annotated[list, add_messages]
search_tool = TavilySearchResults(
max_results=4,
)
tools = [search_tool]
# Model setup
llm = ChatGroq(
model="qwen/qwen3-32b",
temperature=0.7,
streaming=True,
)
llm_with_tools = llm.bind_tools(tools=tools)
async def model(state: State):
result = await llm_with_tools.ainvoke(state["messages"])
return {
"messages": [result],
}
async def tools_router(state: State):
last_message = state["messages"][-1]
if(hasattr(last_message, "tool_calls") and len(last_message.tool_calls) > 0):
return "tool_node"
else:
return END
async def tool_node(state):
"""Custom tool node that handles tool calls from the LLM."""
# Get the tool calls from the last message
tool_calls = state["messages"][-1].tool_calls
# Initialize list to store tool messages
tool_messages = []
# Process each tool call
for tool_call in tool_calls:
tool_name = tool_call["name"]
tool_args = tool_call["args"]
tool_id = tool_call["id"]
# Handle the search tool
if tool_name == "tavily_search_results_json":
# Execute the search tool with the provided arguments
search_results = await search_tool.ainvoke(tool_args)
# Create a ToolMessage for this result
tool_message = ToolMessage(
content=str(search_results),
tool_call_id=tool_id,
name=tool_name
)
tool_messages.append(tool_message)
# Add the tool messages to the state
return {"messages": tool_messages}
graph_builder = StateGraph(State)
graph_builder.add_node("model", model)
graph_builder.add_node("tool_node", tool_node)
graph_builder.set_entry_point("model")
graph_builder.add_conditional_edges("model", tools_router)
graph_builder.add_edge("tool_node", "model")
graph = graph_builder.compile(checkpointer=memory)
app = FastAPI()
# Add CORS middleware with settings that match frontend requirements
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["Content-Type"],
)
def serialise_ai_message_chunk(chunk):
if isinstance(chunk, AIMessageChunk):
return chunk.content or ""
if isinstance(chunk, str):
return chunk
if isinstance(chunk, dict):
for key in ("content", "text"):
if key in chunk and chunk[key] is not None:
return chunk[key]
return ""
if chunk is None:
return ""
return str(chunk)
async def generate_chat_responses(message: str, checkpoint_id: Optional[str] = None):
is_new_conversation = checkpoint_id is None
if is_new_conversation:
# Generate new checkpoint ID for first message in conversation
new_checkpoint_id = str(uuid4())
config = {
"configurable": {
"thread_id": new_checkpoint_id
}
}
# Initialize with first message
events = graph.astream_events(
{"messages": [HumanMessage(content=message)]},
version="v2",
config=config
)
# First send the checkpoint ID
yield f"data: {{\"type\": \"checkpoint\", \"checkpoint_id\": \"{new_checkpoint_id}\"}}\n\n"
else:
config = {
"configurable": {
"thread_id": checkpoint_id
}
}
# Continue existing conversation
events = graph.astream_events(
{"messages": [HumanMessage(content=message)]},
version="v2",
config=config
)
async for event in events:
event_type = event["event"]
if event_type in {"on_chat_model_stream", "on_llm_stream", "on_model_stream"}:
chunk = event.get("data", {}).get("chunk")
if chunk is None:
continue
chunk_content = serialise_ai_message_chunk(chunk)
# Escape single quotes and newlines for safe JSON parsing
safe_content = chunk_content.replace("'", "\\'").replace("\n", "\\n")
yield f"data: {{\"type\": \"content\", \"content\": \"{safe_content}\"}}\n\n"
elif event_type == "on_chat_model_end":
# Check if there are tool calls for search
tool_calls = event["data"]["output"].tool_calls if hasattr(event["data"]["output"], "tool_calls") else []
search_calls = [call for call in tool_calls if call["name"] == "tavily_search_results_json"]
if search_calls:
# Signal that a search is starting
search_query = search_calls[0]["args"].get("query", "")
# Escape quotes and special characters
safe_query = search_query.replace('"', '\\"').replace("'", "\\'").replace("\n", "\\n")
yield f"data: {{\"type\": \"search_start\", \"query\": \"{safe_query}\"}}\n\n"
elif event_type == "on_tool_end" and event["name"] == "tavily_search_results_json":
# Search completed - send results or error
output = event["data"]["output"]
# Check if output is a list
if isinstance(output, list):
# Extract URLs from list of search results
urls = []
for item in output:
if isinstance(item, dict) and "url" in item:
urls.append(item["url"])
# Convert URLs to JSON and yield them
urls_json = json.dumps(urls)
yield f"data: {{\"type\": \"search_results\", \"urls\": {urls_json}}}\n\n"
# Send an end event
yield f"data: {{\"type\": \"end\"}}\n\n"
@app.get("/chat_stream/{message}")
async def chat_stream(message: str, checkpoint_id: Optional[str] = Query(None)):
return StreamingResponse(
generate_chat_responses(message, checkpoint_id),
media_type="text/event-stream"
)
# SSE - server-sent events