Repository navigation
Expand file tree
/
Copy pathquery.py
More file actions
350 lines (295 loc) · 12.4 KB
/
Copy pathquery.py
File metadata and controls
350 lines (295 loc) · 12.4 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
from typing import List, Optional, Dict, Any, AsyncGenerator
import json
from backend.core.runner import generate_answer, generate_answer_stream
from backend.core.agents import create_main_agent, create_news_chat_agent
from backend.security.filters import check_openai_moderation
from backend.core.chat import chat_history_manager, MessageRole
from backend.core.tools.visual import get_image_datas, clear_image_datas
from backend.shared.logger import get_logger
from backend.core.tools.finance import get_chart_datas, clear_chart_datas
from backend.core.tools.file_tools import get_generated_files, clear_generated_files
from backend.utils.news import format_news_context
from backend.shared.constants import set_selected_files, set_original_user_query
logger = get_logger("QUERY_PIPELINE")
async def run_orchestration(
query: str,
web_search_enabled: bool,
use_spdrag: bool = False,
session_id: Optional[str] = None,
selected_files: Optional[List[str]] = None,
) -> Dict[str, Any]:
# Clear previous attachments at the start of each new query
clear_image_datas()
clear_chart_datas()
clear_generated_files()
# Set global selected files for RAG queries
set_selected_files(selected_files)
# Set global original user query for RAG queries
set_original_user_query(query)
# Add user message to chat history
chat_history_manager.add_message(session_id, MessageRole.USER, query)
# Reduce history if too long
session = chat_history_manager.get_session(session_id)
if session and len(session.messages) > 30:
chat_history_manager.reduce_history(session, target_messages=20)
# 1. Input moderation (OpenAI moderation)
input_moderation = check_openai_moderation(query)
if input_moderation["flagged"]:
response_message = f"Your query contains inappropriate content: {input_moderation['violations']}"
# Add assistant response to chat history
chat_history_manager.add_message(
session_id, MessageRole.ASSISTANT, response_message
)
return {
"response": response_message,
"images": [],
"charts": [],
"generatedFiles": [],
}
logger.info(
"query orchestration: use_spdrag=%s web_search=%s",
use_spdrag,
web_search_enabled,
)
agent = create_main_agent(
web_search_enabled=web_search_enabled,
use_spdrag=use_spdrag,
)
# Generate initial answer with structured output
final_answer, web_sources, api_sources, doc_sources = await generate_answer(
prompt=query, agent=agent, thread_id=session_id
)
# Combine document sources with web sources and API sources
all_sources = []
# Add document sources from RAG tool artifacts
for doc_source in doc_sources:
name = doc_source.get("name", "")
file_name = doc_source.get("file", "")
if name and file_name:
all_sources.append(f"{name}|doc://{file_name}")
for web_source in web_sources:
# Format as "Name|URL" for frontend to parse and display as clickable link
name = web_source.get("name", "")
url = web_source.get("url", "")
if name and url:
all_sources.append(f"{name}|{url}")
for api_source in api_sources:
# Format API sources as "API Name|description" (no URL, but frontend can handle it)
name = api_source.get("name", "")
description = api_source.get("description", "")
if name:
# Use description as a pseudo-URL for consistency, or just name
display_text = f"{name}" + (f" - {description}" if description else "")
all_sources.append(f"{display_text}|api://{name}")
# Get images, charts, and generated files and add assistant response to chat history
images = get_image_datas()
charts = get_chart_datas()
generated_files = get_generated_files()
metadata = {}
if images:
metadata["images"] = images
if charts:
metadata["charts"] = charts
if generated_files:
metadata["generatedFiles"] = generated_files
if all_sources:
metadata["sources"] = all_sources
metadata = metadata if metadata else None
chat_history_manager.add_message(
session_id, MessageRole.ASSISTANT, final_answer, metadata
)
return {
"response": final_answer,
"images": images,
"charts": charts,
"generatedFiles": generated_files,
"sources": all_sources,
}
async def run_news_chat_orchestration(
query: str,
news_context: dict,
session_id: Optional[str] = None,
) -> Dict[str, Any]:
"""
Specialized orchestration for news chat queries with news context and web search.
"""
# Handle chat history and session management
if session_id:
# Add user message to chat history
chat_history_manager.add_message(session_id, MessageRole.USER, query)
# Get conversation context
conversation_context = chat_history_manager.get_conversation_context(
session_id, max_messages=10
)
# Reduce history if too long
session = chat_history_manager.get_session(session_id)
if session and len(session.messages) > 30:
chat_history_manager.reduce_history(session, target_messages=20)
else:
conversation_context = []
# Create news context string
news_context_str = format_news_context(news_context)
# Create specialized news agent
agent = create_news_chat_agent(
news_context=news_context_str,
conversation_history=conversation_context,
)
# Generate answer
answer, web_sources, api_sources, doc_sources = await generate_answer(
prompt=query, agent=agent
)
# Combine web sources and API sources
all_sources = []
for web_source in web_sources:
name = web_source.get("name", "")
url = web_source.get("url", "")
if name and url:
all_sources.append(f"{name}|{url}")
for api_source in api_sources:
name = api_source.get("name", "")
description = api_source.get("description", "")
if name:
display_text = f"{name}" + (f" - {description}" if description else "")
all_sources.append(f"{display_text}|api://{name}")
# Get images
images = get_image_datas()
# Add assistant response to chat history
if session_id:
metadata = {"images": images} if images else None
chat_history_manager.add_message(
session_id, MessageRole.ASSISTANT, answer, metadata
)
return {"response": answer, "images": images, "session_id": session_id}
async def run_orchestration_stream(
query: str,
web_search_enabled: bool,
use_spdrag: bool = False,
session_id: Optional[str] = None,
selected_files: Optional[List[str]] = None,
) -> AsyncGenerator[str, None]:
"""
Streaming version of run_orchestration using Server-Sent Events format.
Yields SSE-formatted strings with events:
- token: text chunk from the LLM
- tool_start: tool is being called
- tool_end: tool call completed
- done: final event with sources, images, charts, files
- error: error occurred
"""
# Clear previous attachments at the start of each new query
clear_image_datas()
clear_chart_datas()
clear_generated_files()
# Set global selected files for RAG queries
set_selected_files(selected_files)
# Set global original user query for RAG queries
set_original_user_query(query)
# Add user message to chat history
chat_history_manager.add_message(session_id, MessageRole.USER, query)
# Reduce history if too long
session = chat_history_manager.get_session(session_id)
if session and len(session.messages) > 30:
chat_history_manager.reduce_history(session, target_messages=20)
# 1. Input moderation (OpenAI moderation)
input_moderation = check_openai_moderation(query)
if input_moderation["flagged"]:
response_message = f"Your query contains inappropriate content: {input_moderation['violations']}"
chat_history_manager.add_message(
session_id, MessageRole.ASSISTANT, response_message
)
yield f"data: {json.dumps({'type': 'error', 'content': response_message})}\n\n"
return
logger.info(
"stream orchestration: use_spdrag=%s web_search=%s",
use_spdrag,
web_search_enabled,
)
agent = create_main_agent(
web_search_enabled=web_search_enabled,
use_spdrag=use_spdrag,
)
# Accumulate full answer for chat history
answer = ""
all_sources = []
all_tools = [] # Track tools used during streaming
# Stream the response
async for chunk in generate_answer_stream(
prompt=query, agent=agent, thread_id=session_id
):
if chunk["type"] == "token":
answer += chunk["content"]
yield f"data: {json.dumps({'type': 'token', 'content': chunk['content']})}\n\n"
elif chunk["type"] == "tool_start":
tool_info = {
"tool_name": chunk["tool_name"],
"parent_agent": chunk.get("parent_agent"),
"query": chunk.get("query"),
}
all_tools.append(tool_info)
event_data = {
"type": "tool_start",
**tool_info,
}
yield f"data: {json.dumps(event_data)}\n\n"
elif chunk["type"] == "tool_end":
event_data = {
"type": "tool_end",
"tool_name": chunk["tool_name"],
"parent_agent": chunk.get("parent_agent"),
}
yield f"data: {json.dumps(event_data)}\n\n"
elif chunk["type"] == "spdrag_doc_start":
yield f"data: {json.dumps({'type': 'spdrag_doc_start', 'document': chunk.get('document', '')})}\n\n"
elif chunk["type"] == "spdrag_doc_end":
yield f"data: {json.dumps({'type': 'spdrag_doc_end', 'document': chunk.get('document', '')})}\n\n"
elif chunk["type"] == "spdrag_synthesis_start":
yield f"data: {json.dumps({'type': 'spdrag_synthesis_start'})}\n\n"
elif chunk["type"] == "error":
yield f"data: {json.dumps({'type': 'error', 'content': chunk['content']})}\n\n"
return
elif chunk["type"] == "done":
# Process sources
sources = chunk.get("sources", {})
web_sources = sources.get("web_sources", [])
api_sources = sources.get("api_sources", [])
doc_sources = sources.get("doc_sources", [])
# Format sources
for doc_source in doc_sources:
name = doc_source.get("name", "")
file_name = doc_source.get("file", "")
if name and file_name:
all_sources.append(f"{name}|doc://{file_name}")
for web_source in web_sources:
name = web_source.get("name", "")
url = web_source.get("url", "")
if name and url:
all_sources.append(f"{name}|{url}")
for api_source in api_sources:
name = api_source.get("name", "")
description = api_source.get("description", "")
if name:
display_text = f"{name}" + (
f" - {description}" if description else ""
)
all_sources.append(f"{display_text}|api://{name}")
# Get images, charts, and generated files
images = get_image_datas()
charts = get_chart_datas()
generated_files = get_generated_files()
# Save to chat history
metadata = {}
if images:
metadata["images"] = images
if charts:
metadata["charts"] = charts
if generated_files:
metadata["generatedFiles"] = generated_files
if all_sources:
metadata["sources"] = all_sources
if all_tools:
metadata["tools"] = all_tools
metadata = metadata if metadata else None
chat_history_manager.add_message(
session_id, MessageRole.ASSISTANT, answer, metadata
)
yield f"data: {json.dumps({'type': 'done', 'content': answer, 'images': images, 'charts': charts, 'generatedFiles': generated_files, 'sources': all_sources, 'tools': all_tools})}\n\n"