Spaces:
Sleeping
Sleeping
Download research2_manager.py from lemosryan007/deep_research: direct link, hf CLI and curl.
- Browser
- Download file 6.73 kB
-
https://huggingface.co/spaces/lemosryan007/deep_research/resolve/main/research2_manager.py
- Command line
-
hf download hf://spaces/lemosryan007/deep_research/research2_manager.py
-
curl -L -o research2_manager.py https://huggingface.co/spaces/lemosryan007/deep_research/resolve/main/research2_manager.py
6.73 kB
| from typing import List, Optional | |
| import asyncio | |
| from agents import Runner, trace, gen_trace_id | |
| from planner_agent import planner_agent, WebSearchItem, WebSearchPlan | |
| from search_agent import search_agent | |
| from writer_agent import writer_agent, ReportData | |
| from clarifier_agent import clarifier_agent | |
| from evaluator_agent import evaluator_agent, EvalFeedback | |
| MAX_ROUNDS = 3 | |
| PARALLEL_SEARCHES = 5 | |
| class ResearchManager: | |
| """ | |
| Agentic controller: | |
| 1. Ask 3 clarifying questions | |
| 2. Wait for user clarifications (or proceed without) | |
| 3. Plan searches | |
| 4. Execute & evaluate | |
| 5. Write & display report | |
| """ | |
| async def run(self, query: str, clarifications: Optional[str] = None): | |
| """Run the full research process and stream updates to the UI.""" | |
| trace_id = gen_trace_id() | |
| with trace("Research trace", trace_id=trace_id): | |
| print(f"๐ View trace: https://platform.openai.com/traces/trace?trace_id={trace_id}") | |
| yield f"View trace: https://platform.openai.com/traces/trace?trace_id={trace_id}" | |
| # ---- (0) Clarify ------------------------------------------------- | |
| if not clarifications: | |
| yield "๐งญ Generating 3 clarifying questions..." | |
| questions = await self.get_clarifying_questions(query) | |
| yield ( | |
| "Here are 3 clarifying questions to guide your research:\n\n" | |
| f"{questions}\n\n" | |
| "๐ Please provide your answers (or modified questions), then re-run to continue." | |
| ) | |
| # Pause here โ don't continue yet | |
| return | |
| # ---- (1) Combine clarifications --------------------------------- | |
| refined_query = f"Original Query:\n{query}\n\nUser Clarifications:\n{clarifications}" | |
| yield "โ Clarifications received. Proceeding with refined query.\n" | |
| # ---- (2) Plan --------------------------------------------------- | |
| yield "๐งฉ Planning searches..." | |
| search_plan = await self.plan_searches(refined_query) | |
| yield f"๐ Planned {len(search_plan.searches)} searches. Starting execution..." | |
| # ---- (3) Execute / Evaluate / Optimize loop --------------------- | |
| all_summaries: List[str] = [] | |
| for round_idx in range(1, MAX_ROUNDS + 1): | |
| yield f"๐ Searching (round {round_idx}/{MAX_ROUNDS})..." | |
| round_summaries = await self.perform_searches(search_plan) | |
| all_summaries.extend([s for s in round_summaries if s]) | |
| yield "๐งฎ Evaluating coverage and quality..." | |
| feedback: EvalFeedback = await self.evaluate_coverage(refined_query, all_summaries) | |
| decision = feedback.action | |
| print(f"[Evaluator] score={feedback.coverage_score} decision={decision}") | |
| if decision == "finalize" or round_idx == MAX_ROUNDS: | |
| break | |
| if decision == "continue" and feedback.additional_queries: | |
| search_plan = WebSearchPlan( | |
| searches=[WebSearchItem(reason="Evaluator-suggested gap fill", query=q) | |
| for q in feedback.additional_queries] | |
| ) | |
| elif decision == "refine_plan": | |
| notes = "\n".join(feedback.missing_questions or []) | |
| refined_for_planner = ( | |
| f"{refined_query}\n\nEvaluator notes to address:\n{notes}\n" | |
| f"Improve breadth/recency/authority; avoid duplicates." | |
| ) | |
| search_plan = await self.plan_searches(refined_for_planner) | |
| # ---- (4) Write report ------------------------------------------- | |
| yield "๏ฟฝ๏ฟฝ Writing report..." | |
| report = await self.write_report(refined_query, all_summaries) | |
| # ---- (5) Display report ----------------------------------------- | |
| yield "โ Research complete. Displaying report below.\n" | |
| yield "๐ -------- FINAL REPORT -------- ๐\n" | |
| yield report.markdown_report | |
| print("๐ Final report generated.\n") | |
| # ------------------------ AGENT STEPS ------------------------ | |
| async def get_clarifying_questions(self, query: str) -> str: | |
| """Generate clarifying questions from Clarifier agent.""" | |
| prompt = ( | |
| "Generate three short clarifying questions to scope this research.\n" | |
| f"Original query: {query}" | |
| ) | |
| res = await Runner.run(clarifier_agent, prompt) | |
| return res.final_output.strip() | |
| async def plan_searches(self, refined_query: str) -> WebSearchPlan: | |
| result = await Runner.run(planner_agent, f"Query: {refined_query}") | |
| return result.final_output_as(WebSearchPlan) | |
| async def perform_searches(self, search_plan: WebSearchPlan) -> List[str]: | |
| tasks = [] | |
| results: List[str] = [] | |
| async def _worker(item: WebSearchItem): | |
| try: | |
| input_ = f"Search term: {item.query}\nReason for searching: {item.reason}" | |
| r = await Runner.run(search_agent, input_) | |
| return str(r.final_output) | |
| except Exception as e: | |
| print(f"โ ๏ธ Search failed for {item.query}: {e}") | |
| return None | |
| sem = asyncio.Semaphore(PARALLEL_SEARCHES) | |
| async def _sem_task(item): | |
| async with sem: | |
| return await _worker(item) | |
| for it in search_plan.searches: | |
| tasks.append(asyncio.create_task(_sem_task(it))) | |
| for idx, coro in enumerate(asyncio.as_completed(tasks), start=1): | |
| res = await coro | |
| if res: | |
| results.append(res) | |
| print(f"โ Search {idx}/{len(tasks)} complete") | |
| return results | |
| async def evaluate_coverage(self, refined_query: str, summaries: List[str]) -> EvalFeedback: | |
| evaluator_input = ( | |
| "Evaluate research coverage and quality.\n" | |
| "Return JSON matching EvalFeedback schema.\n\n" | |
| f"Refined query:\n{refined_query}\n\n" | |
| f"Current summaries ({len(summaries)}):\n{summaries}\n" | |
| ) | |
| res = await Runner.run(evaluator_agent, evaluator_input) | |
| return res.final_output_as(EvalFeedback) | |
| async def write_report(self, refined_query: str, search_results: List[str]) -> ReportData: | |
| input_ = f"Original query: {refined_query}\nSummarized search results: {search_results}" | |
| res = await Runner.run(writer_agent, input_) | |
| return res.final_output_as(ReportData) | |