pythonpyro commited on
Commit
083214f
Β·
verified Β·
1 Parent(s): c32e811

Upload 2 files

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