Spaces:
Runtime error
Runtime error
Update research_agent.py
Browse files- research_agent.py +647 -569
research_agent.py
CHANGED
|
@@ -1,570 +1,648 @@
|
|
| 1 |
-
# ============================================================================
|
| 2 |
-
# research_agent.py - BACKEND
|
| 3 |
-
# ============================================================================
|
| 4 |
-
|
| 5 |
-
from typing import TypedDict, List, Literal, Annotated
|
| 6 |
-
import os
|
| 7 |
-
from dotenv import load_dotenv
|
| 8 |
-
|
| 9 |
-
from langgraph.graph import StateGraph, START, END
|
| 10 |
-
from langgraph.graph.message import add_messages
|
| 11 |
-
from langgraph.prebuilt import ToolNode
|
| 12 |
-
from langchain.tools import tool
|
| 13 |
-
from langchain_openai import ChatOpenAI
|
| 14 |
-
from langchain_core.messages import HumanMessage, SystemMessage
|
| 15 |
-
from openai import OpenAI
|
| 16 |
-
from tavily import TavilyClient
|
| 17 |
-
|
| 18 |
-
# ============================================================================
|
| 19 |
-
# CONFIGURATION & INITIALIZATION
|
| 20 |
-
# ============================================================================
|
| 21 |
-
|
| 22 |
-
# Load environment variables from .env file
|
| 23 |
-
load_dotenv()
|
| 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 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
"""
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
#
|
| 421 |
-
#
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
#
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
#
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
"
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
#
|
| 465 |
-
|
| 466 |
-
#
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
#
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
#
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
"""
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
#
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
return "", history, state
|
|
|
|
| 1 |
+
# ============================================================================
|
| 2 |
+
# research_agent.py - BACKEND
|
| 3 |
+
# ============================================================================
|
| 4 |
+
|
| 5 |
+
from typing import TypedDict, List, Literal, Annotated
|
| 6 |
+
import os
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
|
| 9 |
+
from langgraph.graph import StateGraph, START, END
|
| 10 |
+
from langgraph.graph.message import add_messages
|
| 11 |
+
from langgraph.prebuilt import ToolNode
|
| 12 |
+
from langchain.tools import tool
|
| 13 |
+
from langchain_openai import ChatOpenAI
|
| 14 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 15 |
+
from openai import OpenAI
|
| 16 |
+
from tavily import TavilyClient
|
| 17 |
+
|
| 18 |
+
# ============================================================================
|
| 19 |
+
# CONFIGURATION & INITIALIZATION
|
| 20 |
+
# ============================================================================
|
| 21 |
+
|
| 22 |
+
# Load environment variables from .env file
|
| 23 |
+
load_dotenv()
|
| 24 |
+
|
| 25 |
+
# Initialize API clients with environment variables as fallback
|
| 26 |
+
# These will be overridden by user-provided keys in process_message
|
| 27 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 28 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 29 |
+
|
| 30 |
+
# Initialize API clients with environment variables
|
| 31 |
+
# These will be re-initialized with user-provided keys when needed
|
| 32 |
+
openai_client = None
|
| 33 |
+
llm = None
|
| 34 |
+
light_llm = None
|
| 35 |
+
|
| 36 |
+
def initialize_clients(openai_key: str, tavily_key: str):
|
| 37 |
+
"""
|
| 38 |
+
Initialize API clients with provided keys.
|
| 39 |
+
This function is called from process_message with user-provided API keys.
|
| 40 |
+
"""
|
| 41 |
+
global openai_client, llm, light_llm, tool_node, llm_with_tools
|
| 42 |
+
|
| 43 |
+
if not openai_key or not tavily_key:
|
| 44 |
+
raise ValueError("Both OpenAI and Tavily API keys must be provided.")
|
| 45 |
+
|
| 46 |
+
openai_client = OpenAI(api_key=openai_key)
|
| 47 |
+
llm = ChatOpenAI(model="gpt-4o-mini", api_key=openai_key, temperature=0) # Main LLM for research and synthesis
|
| 48 |
+
light_llm = ChatOpenAI(model="gpt-4o-mini", api_key=openai_key, temperature=0) # Lighter LLM for clarification
|
| 49 |
+
|
| 50 |
+
# Initialize tool node and bind tools to LLM
|
| 51 |
+
tool_node = ToolNode(tools)
|
| 52 |
+
llm_with_tools = llm.bind_tools([rag_search, web_search], tool_choice="auto")
|
| 53 |
+
|
| 54 |
+
# Create and compile the research graph now that tool_node is ready
|
| 55 |
+
create_research_graph()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Set maximum number of research iterations to prevent infinite loops
|
| 59 |
+
# This is a default value and will be overridden by user input
|
| 60 |
+
DEFAULT_MAX_ITERATIONS = 3
|
| 61 |
+
|
| 62 |
+
# Global variable to store max iterations for research
|
| 63 |
+
MAX_ITERATIONS = DEFAULT_MAX_ITERATIONS
|
| 64 |
+
|
| 65 |
+
# Global variable to store tavily API key for use in web_search tool
|
| 66 |
+
_tavily_api_key = None
|
| 67 |
+
|
| 68 |
+
# ============================================================================
|
| 69 |
+
# VECTOR STORE SETUP
|
| 70 |
+
# ============================================================================
|
| 71 |
+
|
| 72 |
+
# Connect to pre-existing vector store containing embedded PDF documents
|
| 73 |
+
VECTOR_STORE_NAME = "yt-store"
|
| 74 |
+
store_id = None
|
| 75 |
+
|
| 76 |
+
def get_vector_store_id():
|
| 77 |
+
"""
|
| 78 |
+
Retrieve the vector store ID. This needs to be called after clients are initialized.
|
| 79 |
+
"""
|
| 80 |
+
global store_id
|
| 81 |
+
|
| 82 |
+
if not openai_client:
|
| 83 |
+
raise ValueError("OpenAI client not initialized. Call initialize_clients first.")
|
| 84 |
+
|
| 85 |
+
# Search for the vector store by name in the OpenAI account
|
| 86 |
+
for s in openai_client.vector_stores.list().data:
|
| 87 |
+
if s.name == VECTOR_STORE_NAME:
|
| 88 |
+
store_id = s.id
|
| 89 |
+
break
|
| 90 |
+
|
| 91 |
+
# Raise error if vector store is not found
|
| 92 |
+
if not store_id:
|
| 93 |
+
raise ValueError("β Vector store not found!")
|
| 94 |
+
|
| 95 |
+
print(f"β» Using vector store ID: {store_id}")
|
| 96 |
+
return store_id
|
| 97 |
+
|
| 98 |
+
# ============================================================================
|
| 99 |
+
# TOOL DEFINITIONS
|
| 100 |
+
# ============================================================================
|
| 101 |
+
|
| 102 |
+
@tool
|
| 103 |
+
def rag_search(query: str) -> str:
|
| 104 |
+
"""
|
| 105 |
+
Search INTERNAL knowledge base containing curated documents,
|
| 106 |
+
architecture guides, tutorials, and domain expertise.
|
| 107 |
+
|
| 108 |
+
Use for conceptual understanding, internal best practices,
|
| 109 |
+
and previously authored materials.
|
| 110 |
+
"""
|
| 111 |
+
print(f"π RAG Search called with query: {query}")
|
| 112 |
+
|
| 113 |
+
# Query the vector store with semantic search
|
| 114 |
+
res = openai_client.vector_stores.search(
|
| 115 |
+
vector_store_id=store_id,
|
| 116 |
+
query=query,
|
| 117 |
+
max_num_results=3, # Return top 3 most relevant chunks
|
| 118 |
+
ranking_options={"score_threshold": 0.5, "ranker": "auto"} # Filter by relevance score
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# Handle case where no results are found
|
| 122 |
+
if not res.data:
|
| 123 |
+
return "No relevant information found in internal documents."
|
| 124 |
+
|
| 125 |
+
# Extract text content from search results
|
| 126 |
+
out = []
|
| 127 |
+
for item in res.data:
|
| 128 |
+
for block in item.content or []:
|
| 129 |
+
if block.type == "text" and block.text:
|
| 130 |
+
out.append(block.text)
|
| 131 |
+
|
| 132 |
+
# Combine all text chunks with separator
|
| 133 |
+
result = "\n\n".join(out) if out else "No relevant text extracted from internal documents."
|
| 134 |
+
print(f"β
RAG Search returned {len(out)} chunks")
|
| 135 |
+
return result
|
| 136 |
+
|
| 137 |
+
@tool
|
| 138 |
+
def web_search(query: str) -> str:
|
| 139 |
+
"""
|
| 140 |
+
Search the public internet for recent developments,
|
| 141 |
+
benchmarks, and up-to-date information.
|
| 142 |
+
"""
|
| 143 |
+
global _tavily_api_key
|
| 144 |
+
|
| 145 |
+
print(f"π Web Search called with query: {query}")
|
| 146 |
+
try:
|
| 147 |
+
# Use Tavily API for web search
|
| 148 |
+
tavily_client = TavilyClient(api_key=_tavily_api_key)
|
| 149 |
+
response = tavily_client.search(query, max_results=3)
|
| 150 |
+
|
| 151 |
+
# Format search results into readable text
|
| 152 |
+
results = []
|
| 153 |
+
for result in response.get('results', []):
|
| 154 |
+
results.append(f"Title: {result.get('title', 'N/A')}\nContent: {result.get('content', 'N/A')}\nURL: {result.get('url', 'N/A')}")
|
| 155 |
+
|
| 156 |
+
final_result = "\n\n---\n\n".join(results) if results else "No web search results found."
|
| 157 |
+
print(f"β
Web Search returned {len(results)} results")
|
| 158 |
+
return final_result
|
| 159 |
+
except Exception as e:
|
| 160 |
+
print(f"β Web search error: {str(e)}")
|
| 161 |
+
return f"Web search error: {str(e)}"
|
| 162 |
+
|
| 163 |
+
# ============================================================================
|
| 164 |
+
# TOOL NODE SETUP
|
| 165 |
+
# ============================================================================
|
| 166 |
+
|
| 167 |
+
# Combine tools into a list for the agent
|
| 168 |
+
tools = [rag_search, web_search]
|
| 169 |
+
|
| 170 |
+
# These will be initialized when initialize_clients() is called
|
| 171 |
+
tool_node = None
|
| 172 |
+
llm_with_tools = None
|
| 173 |
+
|
| 174 |
+
# ============================================================================
|
| 175 |
+
# STATE DEFINITION
|
| 176 |
+
# ============================================================================
|
| 177 |
+
|
| 178 |
+
# Define the state structure that will be passed between nodes
|
| 179 |
+
class AgentState(TypedDict):
|
| 180 |
+
messages: Annotated[List, add_messages] # Conversation history with automatic message aggregation
|
| 181 |
+
research_steps: List[str] # Track the research plan steps
|
| 182 |
+
final_answer: str # Store the synthesized final answer
|
| 183 |
+
iterations: int # Count how many research iterations have occurred
|
| 184 |
+
|
| 185 |
+
# ============================================================================
|
| 186 |
+
# CLARIFICATION NODE
|
| 187 |
+
# ============================================================================
|
| 188 |
+
|
| 189 |
+
# System prompt for the clarification phase
|
| 190 |
+
CLARIFICATION_PROMPT = """
|
| 191 |
+
You are a research assistant helping refine a user's research request.
|
| 192 |
+
|
| 193 |
+
Your goal is NOT to answer yet.
|
| 194 |
+
|
| 195 |
+
Instead:
|
| 196 |
+
|
| 197 |
+
1. Acknowledge the topic positively
|
| 198 |
+
2. Ask smart follow-up questions to narrow scope
|
| 199 |
+
3. Offer categories to choose from
|
| 200 |
+
4. Ask about:
|
| 201 |
+
- target audience
|
| 202 |
+
- depth level
|
| 203 |
+
- specific domains
|
| 204 |
+
- time range
|
| 205 |
+
- technical vs business focus
|
| 206 |
+
|
| 207 |
+
Example style:
|
| 208 |
+
|
| 209 |
+
"Great topic! Before I begin deep research, could you help me refine the scope?"
|
| 210 |
+
|
| 211 |
+
Then ask 3-5 concise questions.
|
| 212 |
+
|
| 213 |
+
DO NOT start researching yet.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
def clarification_node(state: AgentState):
|
| 217 |
+
"""
|
| 218 |
+
Node that asks clarifying questions to refine the research scope.
|
| 219 |
+
This runs BEFORE research begins.
|
| 220 |
+
"""
|
| 221 |
+
print("\n㪠Clarification phase...\n")
|
| 222 |
+
|
| 223 |
+
messages = state["messages"]
|
| 224 |
+
|
| 225 |
+
# If we already asked clarification, just wait for user input
|
| 226 |
+
if state.get("phase") == "awaiting_user":
|
| 227 |
+
return state
|
| 228 |
+
|
| 229 |
+
# Use lighter LLM to generate clarification questions
|
| 230 |
+
response = light_llm.invoke([
|
| 231 |
+
SystemMessage(content=CLARIFICATION_PROMPT),
|
| 232 |
+
messages[-1]
|
| 233 |
+
])
|
| 234 |
+
|
| 235 |
+
return {
|
| 236 |
+
"messages": [response]
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
# ============================================================================
|
| 240 |
+
# PLANNER NODE
|
| 241 |
+
# ============================================================================
|
| 242 |
+
|
| 243 |
+
# System prompt for research planning
|
| 244 |
+
PLANNER_PROMPT = """
|
| 245 |
+
You are a deep research planning assistant.
|
| 246 |
+
|
| 247 |
+
Your job is to create a DUAL-SOURCE research plan.
|
| 248 |
+
|
| 249 |
+
For each major aspect of the user question:
|
| 250 |
+
|
| 251 |
+
Generate:
|
| 252 |
+
|
| 253 |
+
- ONE query specifically designed for INTERNAL knowledge (rag_search)
|
| 254 |
+
- ONE complementary query for EXTERNAL knowledge (web_search)
|
| 255 |
+
|
| 256 |
+
Return the plan in this EXACT format:
|
| 257 |
+
|
| 258 |
+
TOPIC 1:
|
| 259 |
+
RAG_QUERY: <query text optimized for internal documents>
|
| 260 |
+
WEB_QUERY: <query text optimized for current internet info>
|
| 261 |
+
|
| 262 |
+
TOPIC 2:
|
| 263 |
+
RAG_QUERY: ...
|
| 264 |
+
WEB_QUERY: ...
|
| 265 |
+
|
| 266 |
+
TOPIC 3:
|
| 267 |
+
RAG_QUERY: ...
|
| 268 |
+
WEB_QUERY: ...
|
| 269 |
+
|
| 270 |
+
At least 3 topics must be generated.
|
| 271 |
+
|
| 272 |
+
The goal is to ensure BOTH tools are used for comprehensive coverage.
|
| 273 |
+
"""
|
| 274 |
+
|
| 275 |
+
def planner_node(state: AgentState):
|
| 276 |
+
"""
|
| 277 |
+
Node that creates a structured research plan.
|
| 278 |
+
Generates paired RAG and Web queries for each research topic.
|
| 279 |
+
"""
|
| 280 |
+
print("\nπ§ Planning research approach...\n")
|
| 281 |
+
|
| 282 |
+
# Extract the user's refined question
|
| 283 |
+
user_question = state["messages"][-1].content
|
| 284 |
+
|
| 285 |
+
messages = [
|
| 286 |
+
SystemMessage(content=PLANNER_PROMPT),
|
| 287 |
+
HumanMessage(content=user_question)
|
| 288 |
+
]
|
| 289 |
+
|
| 290 |
+
# Generate the research plan
|
| 291 |
+
plan = llm.invoke(messages)
|
| 292 |
+
|
| 293 |
+
return {
|
| 294 |
+
"messages": [plan],
|
| 295 |
+
"research_steps": [plan.content] # Store plan for tracking
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
# ============================================================================
|
| 299 |
+
# RESEARCH AGENT NODE
|
| 300 |
+
# ============================================================================
|
| 301 |
+
|
| 302 |
+
# System prompt for the research agent
|
| 303 |
+
RESEARCH_PROMPT = """
|
| 304 |
+
You are a balanced deep research assistant.
|
| 305 |
+
|
| 306 |
+
You MUST use BOTH tools for every major topic:
|
| 307 |
+
|
| 308 |
+
- rag_search β to gather internal curated knowledge
|
| 309 |
+
- web_search β to gather current external information
|
| 310 |
+
|
| 311 |
+
Do NOT rely on only one tool.
|
| 312 |
+
|
| 313 |
+
Process:
|
| 314 |
+
|
| 315 |
+
1. Look at the research plan
|
| 316 |
+
2. For each topic:
|
| 317 |
+
- First call rag_search with the RAG_QUERY
|
| 318 |
+
- Then call web_search with the WEB_QUERY
|
| 319 |
+
|
| 320 |
+
You may call tools multiple times in one response.
|
| 321 |
+
|
| 322 |
+
Continue until all planned topics have been covered.
|
| 323 |
+
|
| 324 |
+
Only stop when:
|
| 325 |
+
- every RAG query has been executed
|
| 326 |
+
- every WEB query has been executed
|
| 327 |
+
"""
|
| 328 |
+
|
| 329 |
+
def research_agent_node(state: AgentState):
|
| 330 |
+
"""
|
| 331 |
+
Node that executes the research plan by calling tools.
|
| 332 |
+
This is the core agentic loop that gathers information.
|
| 333 |
+
"""
|
| 334 |
+
print("\nπ Research agent analyzing next step...\n")
|
| 335 |
+
|
| 336 |
+
messages = state["messages"]
|
| 337 |
+
|
| 338 |
+
# Add system prompt if not already present
|
| 339 |
+
if not any(isinstance(msg, SystemMessage) for msg in messages):
|
| 340 |
+
messages = [SystemMessage(content=RESEARCH_PROMPT)] + messages
|
| 341 |
+
|
| 342 |
+
# LLM decides which tools to call based on the plan
|
| 343 |
+
response = llm_with_tools.invoke(messages)
|
| 344 |
+
|
| 345 |
+
return {
|
| 346 |
+
"messages": [response],
|
| 347 |
+
"iterations": state.get("iterations", 0) + 1 # Increment iteration counter
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
# ============================================================================
|
| 351 |
+
# SYNTHESIZER NODE
|
| 352 |
+
# ============================================================================
|
| 353 |
+
|
| 354 |
+
# System prompt for final synthesis
|
| 355 |
+
SYNTHESIS_PROMPT = """
|
| 356 |
+
You are a research report writer.
|
| 357 |
+
|
| 358 |
+
Using ALL the previous research results:
|
| 359 |
+
|
| 360 |
+
- Internal RAG findings
|
| 361 |
+
- Web findings
|
| 362 |
+
- Multiple iterations of searches
|
| 363 |
+
|
| 364 |
+
Create a detailed, well-structured final answer.
|
| 365 |
+
|
| 366 |
+
Format:
|
| 367 |
+
|
| 368 |
+
OVERVIEW
|
| 369 |
+
-------
|
| 370 |
+
|
| 371 |
+
INTERNAL KNOWLEDGE FINDINGS
|
| 372 |
+
--------------------------
|
| 373 |
+
|
| 374 |
+
WEB RESEARCH FINDINGS
|
| 375 |
+
---------------------
|
| 376 |
+
|
| 377 |
+
FINAL SYNTHESIS
|
| 378 |
+
--------------
|
| 379 |
+
|
| 380 |
+
CONCLUSION
|
| 381 |
+
---------
|
| 382 |
+
"""
|
| 383 |
+
|
| 384 |
+
def synthesizer_node(state: AgentState):
|
| 385 |
+
"""
|
| 386 |
+
Node that synthesizes all research findings into a structured report.
|
| 387 |
+
This is the final step that produces the deliverable.
|
| 388 |
+
"""
|
| 389 |
+
print("\nβοΈ Synthesizing final answer...\n")
|
| 390 |
+
|
| 391 |
+
# Clean messages to remove tool calls and tool responses
|
| 392 |
+
# (only keep actual content for cleaner synthesis)
|
| 393 |
+
clean_messages = []
|
| 394 |
+
|
| 395 |
+
for msg in state["messages"]:
|
| 396 |
+
|
| 397 |
+
# Skip any message containing tool calls
|
| 398 |
+
if hasattr(msg, "tool_calls") and msg.tool_calls:
|
| 399 |
+
continue
|
| 400 |
+
|
| 401 |
+
# Skip any raw tool response messages
|
| 402 |
+
if msg.type == "tool":
|
| 403 |
+
continue
|
| 404 |
+
|
| 405 |
+
clean_messages.append(msg)
|
| 406 |
+
|
| 407 |
+
# Add synthesis prompt and generate final report
|
| 408 |
+
messages = clean_messages + [
|
| 409 |
+
SystemMessage(content=SYNTHESIS_PROMPT)
|
| 410 |
+
]
|
| 411 |
+
|
| 412 |
+
final = llm.invoke(messages)
|
| 413 |
+
|
| 414 |
+
return {
|
| 415 |
+
"messages": [final],
|
| 416 |
+
"final_answer": final.content # Store the final answer
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
# ============================================================================
|
| 420 |
+
# ROUTING LOGIC
|
| 421 |
+
# ============================================================================
|
| 422 |
+
|
| 423 |
+
def research_router(state: AgentState) -> Literal["tools", "synthesize"]:
|
| 424 |
+
"""
|
| 425 |
+
Router that decides whether to continue research or move to synthesis.
|
| 426 |
+
|
| 427 |
+
Decision logic:
|
| 428 |
+
1. Ensure both RAG and Web tools have been used at least once
|
| 429 |
+
2. Stop if max iterations reached (safety limit)
|
| 430 |
+
3. Continue if agent is still calling tools
|
| 431 |
+
4. Otherwise, move to synthesis
|
| 432 |
+
"""
|
| 433 |
+
last_message = state["messages"][-1]
|
| 434 |
+
|
| 435 |
+
current_iterations = state.get("iterations", 0)
|
| 436 |
+
|
| 437 |
+
print(f"π Iteration count: {current_iterations}")
|
| 438 |
+
|
| 439 |
+
# Check conversation history to see which tools were used
|
| 440 |
+
history = str(state["messages"])
|
| 441 |
+
|
| 442 |
+
used_rag = "rag_search" in history
|
| 443 |
+
used_web = "web_search" in history
|
| 444 |
+
|
| 445 |
+
# Force at least one call to each tool for comprehensive research
|
| 446 |
+
if not (used_rag and used_web):
|
| 447 |
+
print("π Ensuring both RAG and Web sources are used...")
|
| 448 |
+
return "tools"
|
| 449 |
+
|
| 450 |
+
# HARD STOP: Prevent infinite loops by limiting iterations
|
| 451 |
+
if current_iterations >= MAX_ITERATIONS:
|
| 452 |
+
print("π Max iterations reached β forcing synthesis")
|
| 453 |
+
return "synthesize"
|
| 454 |
+
|
| 455 |
+
# If agent is still requesting tool calls, continue research
|
| 456 |
+
if hasattr(last_message, "tool_calls") and last_message.tool_calls:
|
| 457 |
+
print("π Continuing research loop...")
|
| 458 |
+
return "tools"
|
| 459 |
+
|
| 460 |
+
# Otherwise, research is complete
|
| 461 |
+
print("β
Research sufficient. Moving to synthesis.")
|
| 462 |
+
return "synthesize"
|
| 463 |
+
|
| 464 |
+
# ============================================================================
|
| 465 |
+
# GRAPH CONSTRUCTION
|
| 466 |
+
# ============================================================================
|
| 467 |
+
|
| 468 |
+
# ---------- CLARIFICATION GRAPH ----------
|
| 469 |
+
# Simple linear graph: just asks clarifying questions
|
| 470 |
+
clarify_graph = StateGraph(AgentState)
|
| 471 |
+
|
| 472 |
+
# Add nodes
|
| 473 |
+
clarify_graph.add_node("clarify", clarification_node)
|
| 474 |
+
|
| 475 |
+
# Add edges: START β clarify β END
|
| 476 |
+
clarify_graph.add_edge(START, "clarify")
|
| 477 |
+
clarify_graph.add_edge("clarify", END)
|
| 478 |
+
|
| 479 |
+
# Compile the graph into an executable app
|
| 480 |
+
clarify_app = clarify_graph.compile()
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
# ---------- RESEARCH WORKFLOW GRAPH ----------
|
| 484 |
+
# This will be compiled on first use after clients are initialized
|
| 485 |
+
research_app = None
|
| 486 |
+
|
| 487 |
+
def create_research_graph():
|
| 488 |
+
"""
|
| 489 |
+
Create and compile the research workflow graph.
|
| 490 |
+
Must be called after initialize_clients() so that tool_node is ready.
|
| 491 |
+
"""
|
| 492 |
+
global research_app
|
| 493 |
+
|
| 494 |
+
if tool_node is None:
|
| 495 |
+
raise ValueError("Tool node not initialized. Call initialize_clients first.")
|
| 496 |
+
|
| 497 |
+
research_graph = StateGraph(AgentState)
|
| 498 |
+
|
| 499 |
+
# Add nodes
|
| 500 |
+
research_graph.add_node("planner", planner_node)
|
| 501 |
+
research_graph.add_node("researcher", research_agent_node)
|
| 502 |
+
research_graph.add_node("tools", tool_node)
|
| 503 |
+
research_graph.add_node("synthesizer", synthesizer_node)
|
| 504 |
+
|
| 505 |
+
# Add edges
|
| 506 |
+
# Flow: START β planner β researcher β (conditional loop) β synthesizer β END
|
| 507 |
+
research_graph.add_edge(START, "planner")
|
| 508 |
+
research_graph.add_edge("planner", "researcher")
|
| 509 |
+
|
| 510 |
+
# Conditional edge: researcher decides to continue or finish
|
| 511 |
+
research_graph.add_conditional_edges(
|
| 512 |
+
"researcher",
|
| 513 |
+
research_router, # Router function decides next step
|
| 514 |
+
{
|
| 515 |
+
"tools": "tools", # Continue research
|
| 516 |
+
"synthesize": "synthesizer" # Finish and synthesize
|
| 517 |
+
}
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
# After tools execute, loop back to researcher
|
| 521 |
+
research_graph.add_edge("tools", "researcher")
|
| 522 |
+
# After synthesis, end the workflow
|
| 523 |
+
research_graph.add_edge("synthesizer", END)
|
| 524 |
+
|
| 525 |
+
# Compile the research graph
|
| 526 |
+
research_app = research_graph.compile()
|
| 527 |
+
return research_app
|
| 528 |
+
|
| 529 |
+
# ============================================================================
|
| 530 |
+
# BACKEND API FUNCTIONS
|
| 531 |
+
# ============================================================================
|
| 532 |
+
|
| 533 |
+
def create_initial_state():
|
| 534 |
+
"""
|
| 535 |
+
Initialize the session state for a new conversation.
|
| 536 |
+
Tracks: messages, iterations, answers, and current stage.
|
| 537 |
+
"""
|
| 538 |
+
return {
|
| 539 |
+
"messages": [],
|
| 540 |
+
"iterations": 0,
|
| 541 |
+
"final_answer": "",
|
| 542 |
+
"research_steps": [],
|
| 543 |
+
"stage": "awaiting_topic" # UI flow stage
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def process_message(user_input, history, state, openai_api_key, tavily_api_key, max_iterations=2):
|
| 548 |
+
"""
|
| 549 |
+
Main message processing function that handles the multi-turn conversation.
|
| 550 |
+
|
| 551 |
+
Flow:
|
| 552 |
+
1. User enters topic β Clarification questions
|
| 553 |
+
2. User answers β Deep research begins
|
| 554 |
+
3. Research completes β Final report shown
|
| 555 |
+
|
| 556 |
+
Args:
|
| 557 |
+
max_iterations: Number of research loops to perform (2 means one loop of the research node)
|
| 558 |
+
"""
|
| 559 |
+
global _tavily_api_key, MAX_ITERATIONS
|
| 560 |
+
|
| 561 |
+
# Set the global MAX_ITERATIONS with user-provided value
|
| 562 |
+
MAX_ITERATIONS = max_iterations
|
| 563 |
+
|
| 564 |
+
# Initialize clients with provided API keys
|
| 565 |
+
try:
|
| 566 |
+
initialize_clients(openai_api_key, tavily_api_key)
|
| 567 |
+
_tavily_api_key = tavily_api_key
|
| 568 |
+
# Retrieve vector store ID with initialized client
|
| 569 |
+
get_vector_store_id()
|
| 570 |
+
except ValueError as e:
|
| 571 |
+
error_msg = f"β Configuration Error: {str(e)}"
|
| 572 |
+
if history is None:
|
| 573 |
+
history = []
|
| 574 |
+
history.append({"role": "assistant", "content": error_msg})
|
| 575 |
+
return "", history, state
|
| 576 |
+
|
| 577 |
+
# Initialize state if first message
|
| 578 |
+
if state is None:
|
| 579 |
+
state = create_initial_state()
|
| 580 |
+
|
| 581 |
+
if history is None:
|
| 582 |
+
history = []
|
| 583 |
+
|
| 584 |
+
stage = state.get("stage", "awaiting_topic")
|
| 585 |
+
|
| 586 |
+
# ---- FIRST TURN: Initial topic entry ----
|
| 587 |
+
if stage == "awaiting_topic":
|
| 588 |
+
|
| 589 |
+
# Store user's initial question
|
| 590 |
+
state["messages"] = [HumanMessage(content=user_input)]
|
| 591 |
+
|
| 592 |
+
# Run clarification graph to ask follow-up questions
|
| 593 |
+
state = clarify_app.invoke(state)
|
| 594 |
+
|
| 595 |
+
clarification = state["messages"][-1].content
|
| 596 |
+
|
| 597 |
+
# Update chat history
|
| 598 |
+
history.append({"role": "user", "content": user_input})
|
| 599 |
+
history.append({"role": "assistant", "content": clarification})
|
| 600 |
+
|
| 601 |
+
# Move to next stage
|
| 602 |
+
state["stage"] = "awaiting_clarification"
|
| 603 |
+
|
| 604 |
+
return "", history, state
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
# ---- SECOND TURN: User provides clarification ----
|
| 608 |
+
elif stage == "awaiting_clarification":
|
| 609 |
+
|
| 610 |
+
# Add user's clarification to conversation
|
| 611 |
+
state["messages"].append(HumanMessage(content=user_input))
|
| 612 |
+
|
| 613 |
+
# Clean artifacts from previous interactions
|
| 614 |
+
clean_messages = []
|
| 615 |
+
for msg in state["messages"]:
|
| 616 |
+
if hasattr(msg, "tool_calls") and msg.tool_calls:
|
| 617 |
+
continue
|
| 618 |
+
if msg.type == "tool":
|
| 619 |
+
continue
|
| 620 |
+
clean_messages.append(msg)
|
| 621 |
+
|
| 622 |
+
# Reset state for fresh research
|
| 623 |
+
state["messages"] = clean_messages
|
| 624 |
+
state["iterations"] = 0
|
| 625 |
+
|
| 626 |
+
# Update UI
|
| 627 |
+
history.append({"role": "user", "content": user_input})
|
| 628 |
+
history.append({"role": "assistant", "content": "π Starting deep research... please wait..."})
|
| 629 |
+
|
| 630 |
+
# Run the full research workflow graph
|
| 631 |
+
final_state = research_app.invoke(state)
|
| 632 |
+
|
| 633 |
+
# Extract final answer
|
| 634 |
+
final_answer = final_state["messages"][-1].content
|
| 635 |
+
|
| 636 |
+
# Show result in chat
|
| 637 |
+
history.append({"role": "assistant", "content": final_answer})
|
| 638 |
+
|
| 639 |
+
# Mark research as completed
|
| 640 |
+
final_state["stage"] = "completed"
|
| 641 |
+
|
| 642 |
+
return "", history, final_state
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
# ---- AFTER COMPLETION: No further research ----
|
| 646 |
+
else:
|
| 647 |
+
history.append({"role": "assistant", "content": "Research already completed. Refresh page to start a new topic."})
|
| 648 |
return "", history, state
|