Spaces:
Build error
Build error
Upload folder using huggingface_hub
Browse filesFiles changed (3)
- deep_research.py+11-1
- research_manager.py+86-39
- writer_agent.py+33-3
13 unmodified lines141516171819104 unmodified lines12412512612712812913013 unmodified linesimport refrom huggingface_hub import HfApiimport markdown# Load environment variablesload_dotenv(override=True)104 unmodified lines# Convert markdown to HTML if neededif isinstance(report_result, str):if not report_result.strip().startswith('<'):report_result = convert_markdown_to_html(report_result)return report_result13 unmodified lines14151617181920104 unmodified lines12512612712812913013113213313413513613713813914013 unmodified linesimport refrom huggingface_hub import HfApiimport markdownimport json# Load environment variablesload_dotenv(override=True)104 unmodified lines# Convert markdown to HTML if neededif isinstance(report_result, str):if not report_result.strip().startswith('<'):# Try to parse as JSON firsttry:report_data = json.loads(report_result)if 'markdown_report' in report_data:report_result = convert_markdown_to_html(report_data['markdown_report'])else:report_result = convert_markdown_to_html(report_result)except json.JSONDecodeError:# If not JSON, treat as plain markdownreport_result = convert_markdown_to_html(report_result)return report_result
7 unmodified lines891011121318 unmodified lines32333435363738394041424310 unmodified lines545556575859606162636465666768697071721 unmodified line747576777879808182836 unmodified lines9091929394959626 unmodified lines12312412512612712812940 unmodified lines17017117217317417517617717817918018118256 unmodified lines23924024124224324424524624724824925025148 unmodified lines30030130230330430530630730830931031131231331412 unmodified lines3273283293303313323333343357 unmodified linesfrom typing import AsyncGenerator, Optional, List, Dictimport markdownimport re# Create agents with their respective toolsplanner = Agent(18 unmodified linesmodel="gpt-4")class ResearchManager:def __init__(self):self.trace_id = gen_trace_id()self.max_search_attempts = 2self.best_quality_score = 0.0self.best_results = []async def run(self, query: str) -> AsyncGenerator[str, None]:"""Run the deep research process, yielding status updates and the final report"""10 unmodified linesprint(f"\n[STATUS] {status}")yield statusprint("[DEBUG] Running planner agent")search_plan_result = await Runner.run(planner_agent,{"query": query})print(f"[DEBUG] Planner agent result: {search_plan_result}")if "error" in search_plan_result:error_msg = f"Error in planning phase: {search_plan_result['error']}"print(f"\n[ERROR] {error_msg}")yield error_msgreturnif "final_output" not in search_plan_result:error_msg = "No final_output in planner result"print(f"\n[ERROR] {error_msg}")yield error_msg1 unmodified linetry:# Ensure the final_output is a WebSearchPlan objectif isinstance(search_plan_result['final_output'], str):print(f"[DEBUG] Attempting to parse search plan as JSON: {search_plan_result['final_output'][:200]}...")try:search_plan = WebSearchPlan.model_validate_json(search_plan_result['final_output'])except Exception as json_error:print(f"[DEBUG] JSON parsing failed: {str(json_error)}")# If JSON parsing fails, try to create a WebSearchPlan object from the raw text6 unmodified lines])else:search_plan = search_plan_result['final_output']if not hasattr(search_plan, 'searches'):error_msg = "Invalid search plan format: missing 'searches' attribute"26 unmodified linesfor item in search_plan.searches:input = {"query": item.query, "reason": item.reason}print(f"[DEBUG] Creating search task for: {input}")task = Runner.run(search_agent, input)tasks.append(task)for i, task in enumerate(asyncio.as_completed(tasks), 1):40 unmodified linescontinueprint("[DEBUG] Running search evaluator")evaluation_result = await Runner.run(search_evaluator,{"query": query,"search_results": search_results})print(f"[DEBUG] Evaluation result: {evaluation_result}")if "error" in evaluation_result:56 unmodified linesprint(f"\n[STATUS] {status}")yield statusprint("[DEBUG] Running writer agent")report_result = await Runner.run(writer_agent,{"query": query,"search_results": search_results})print(f"[DEBUG] Writer agent result: {report_result}")if "error" in report_result:48 unmodified linesyield statustry:print("[DEBUG] Running email agent")# Convert markdown to HTML before sendinghtml_content = markdown.markdown(report.markdown_report)email_result = await Runner.run(email_agent,{"subject": f"Research Report: {query}","html_body": html_content})print(f"[DEBUG] Email agent result: {email_result}")if "error" in email_result:12 unmodified lines# Return final report regardless of email statusprint("\n[STATUS] Research process completed")# Convert markdown to HTML before returninghtml_report = markdown.markdown(report.markdown_report)yield html_reportexcept Exception as e:error_msg = f"Unexpected error in research process: {str(e)}"7 unmodified lines89101112131418 unmodified lines3334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410 unmodified lines1151161171181191201211221231241251261271281291301 unmodified line1321331341351361371381391401416 unmodified lines14814915015115215315426 unmodified lines18118218318418518618740 unmodified lines22822923023123223323423523623756 unmodified lines29429529629729829930030130230348 unmodified lines35235335435535635735835936036136236312 unmodified lines3763773783793803813827 unmodified linesfrom typing import AsyncGenerator, Optional, List, Dictimport markdownimport reimport json# Create agents with their respective toolsplanner = Agent(18 unmodified linesmodel="gpt-4")def convert_markdown_to_html(markdown_content: str) -> str:"""Convert markdown to HTML with proper formatting"""# First convert markdown to HTMLhtml = markdown.markdown(markdown_content, extensions=['fenced_code', 'tables'])# Add some basic stylingstyled_html = f"""<style>body {{font-family: Arial, sans-serif;line-height: 1.6;color: #333;max-width: 800px;margin: 0 auto;padding: 20px;}}h1, h2, h3 {{color: #2c3e50;margin-top: 1.5em;margin-bottom: 0.5em;}}p {{margin-bottom: 1em;}}ul, ol {{margin-bottom: 1em;padding-left: 2em;}}li {{margin-bottom: 0.5em;}}code {{background-color: #f8f9fa;padding: 0.2em 0.4em;border-radius: 3px;font-family: monospace;}}pre {{background-color: #f8f9fa;padding: 1em;border-radius: 5px;overflow-x: auto;}}blockquote {{border-left: 4px solid #2c3e50;margin: 1em 0;padding-left: 1em;color: #666;}}</style><div class="report-container">{html}</div>"""return styled_htmlclass ResearchManager:def __init__(self):self.trace_id = gen_trace_id()self.max_search_attempts = 2self.best_quality_score = 0.0self.best_results = []self.planner = Runner(planner_agent)self.searcher = Runner(search_agent)self.evaluator = Runner(search_evaluator)self.writer = Runner(writer_agent)self.emailer = Runner(email_agent)async def run(self, query: str) -> AsyncGenerator[str, None]:"""Run the deep research process, yielding status updates and the final report"""10 unmodified linesprint(f"\n[STATUS] {status}")yield statusprint("[DEBUG] Running planner agent")plan_result = await self.planner.run({"query": query})print(f"[DEBUG] Planner agent result: {plan_result}")if "error" in plan_result:error_msg = f"Error in planning phase: {plan_result['error']}"print(f"\n[ERROR] {error_msg}")yield error_msgreturnif "final_output" not in plan_result:error_msg = "No final_output in planner result"print(f"\n[ERROR] {error_msg}")yield error_msg1 unmodified linetry:# Ensure the final_output is a WebSearchPlan objectif isinstance(plan_result['final_output'], str):print(f"[DEBUG] Attempting to parse search plan as JSON: {plan_result['final_output'][:200]}...")try:search_plan = WebSearchPlan.model_validate_json(plan_result['final_output'])except Exception as json_error:print(f"[DEBUG] JSON parsing failed: {str(json_error)}")# If JSON parsing fails, try to create a WebSearchPlan object from the raw text6 unmodified lines])else:search_plan = plan_result['final_output']if not hasattr(search_plan, 'searches'):error_msg = "Invalid search plan format: missing 'searches' attribute"26 unmodified linesfor item in search_plan.searches:input = {"query": item.query, "reason": item.reason}print(f"[DEBUG] Creating search task for: {input}")task = self.searcher.run(input)tasks.append(task)for i, task in enumerate(asyncio.as_completed(tasks), 1):40 unmodified linescontinueprint("[DEBUG] Running search evaluator")evaluation_result = await self.evaluator.run({"query": query,"results": search_results})print(f"[DEBUG] Evaluation result: {evaluation_result}")if "error" in evaluation_result:56 unmodified linesprint(f"\n[STATUS] {status}")yield statusprint("[DEBUG] Running writer agent")report_result = await self.writer.run({"query": query,"evaluation": evaluation})print(f"[DEBUG] Writer agent result: {report_result}")if "error" in report_result:48 unmodified linesyield statustry:print("[DEBUG] Running email agent")# Convert markdown to HTML for emailhtml_report = convert_markdown_to_html(report.markdown_report)email_result = await self.emailer.run({"subject": f"Research Report: {query}","html_body": html_report})print(f"[DEBUG] Email agent result: {email_result}")if "error" in email_result:12 unmodified lines# Return final report regardless of email statusprint("\n[STATUS] Research process completed")yield reportexcept Exception as e:error_msg = f"Unexpected error in research process: {str(e)}"
13 unmodified lines14151617181920213 unmodified lines2526272829303113 unmodified lines' "markdown_report": "The full report in markdown format",\n'' "follow_up_questions": ["Question 1", "Question 2", "Question 3"]\n'"}\n\n""The markdown_report should be a complete, well-structured report with proper headings, ""paragraphs, and formatting. The short_summary should be concise but informative. ""The follow_up_questions should be relevant topics for further research.")3 unmodified lines"""A short 2-3 sentence summary of the findings."""markdown_report: str"""The final report"""follow_up_questions: list[str]"""Suggested topics to research further"""13 unmodified lines14151617181920212223242526272829303132333435363738394041424344454647484950513 unmodified lines5556575859606113 unmodified lines' "markdown_report": "The full report in markdown format",\n'' "follow_up_questions": ["Question 1", "Question 2", "Question 3"]\n'"}\n\n""The markdown_report should follow these formatting guidelines:\n""1. Use proper heading hierarchy (h1, h2, h3) with #, ##, ###\n""2. Use bullet points (- or *) for lists\n""3. Use numbered lists (1., 2., 3.) for sequential items\n""4. Use **bold** for emphasis and *italic* for secondary emphasis\n""5. Use > for blockquotes\n""6. Use ``` for code blocks with language specification\n""7. Use --- for horizontal rules between major sections\n""8. Use [link text](url) for hyperlinks\n""9. Use  for images\n""10. Use | for tables with proper headers\n\n""Example markdown structure:\n""# Main Title\n\n""## Introduction\n""Brief introduction to the topic...\n\n""## Key Findings\n""- Finding 1\n""- Finding 2\n""- Finding 3\n\n""## Detailed Analysis\n""### Section 1\n""Detailed content...\n\n""> Important quote or reference\n\n""### Section 2\n""More detailed content...\n\n""## Conclusion\n""Summary of findings...\n\n""## Follow-up Questions\n""1. Question 1\n""2. Question 2\n""3. Question 3\n\n""The short_summary should be concise but informative. ""The follow_up_questions should be relevant topics for further research.")3 unmodified lines"""A short 2-3 sentence summary of the findings."""markdown_report: str"""The final report in markdown format with proper structure and formatting."""follow_up_questions: list[str]"""Suggested topics to research further"""
deep_research.py+11-1
research_manager.py+86-39
writer_agent.py+33-3