|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import time |
| 5 | +from collections.abc import Sequence |
| 6 | + |
| 7 | +from rich.console import Console |
| 8 | + |
| 9 | +from agents import Runner, RunResult, custom_span, gen_trace_id, trace |
| 10 | + |
| 11 | +from .agents.financials_agent import financials_agent |
| 12 | +from .agents.planner_agent import FinancialSearchItem, FinancialSearchPlan, planner_agent |
| 13 | +from .agents.risk_agent import risk_agent |
| 14 | +from .agents.search_agent import search_agent |
| 15 | +from .agents.verifier_agent import VerificationResult, verifier_agent |
| 16 | +from .agents.writer_agent import FinancialReportData, writer_agent |
| 17 | +from .printer import Printer |
| 18 | + |
| 19 | + |
| 20 | +async def _summary_extractor(run_result: RunResult) -> str: |
| 21 | + """Custom output extractor for sub‑agents that return an AnalysisSummary.""" |
| 22 | + # The financial/risk analyst agents emit an AnalysisSummary with a `summary` field. |
| 23 | + # We want the tool call to return just that summary text so the writer can drop it inline. |
| 24 | + return str(run_result.final_output.summary) |
| 25 | + |
| 26 | + |
| 27 | +class FinancialResearchManager: |
| 28 | + """ |
| 29 | + Orchestrates the full flow: planning, searching, sub‑analysis, writing, and verification. |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__(self) -> None: |
| 33 | + self.console = Console() |
| 34 | + self.printer = Printer(self.console) |
| 35 | + |
| 36 | + async def run(self, query: str) -> None: |
| 37 | + trace_id = gen_trace_id() |
| 38 | + with trace("Financial research trace", trace_id=trace_id): |
| 39 | + self.printer.update_item( |
| 40 | + "trace_id", |
| 41 | + f"View trace: https://platform.openai.com/traces/{trace_id}", |
| 42 | + is_done=True, |
| 43 | + hide_checkmark=True, |
| 44 | + ) |
| 45 | + self.printer.update_item( |
| 46 | + "start", "Starting financial research...", is_done=True) |
| 47 | + search_plan = await self._plan_searches(query) |
| 48 | + search_results = await self._perform_searches(search_plan) |
| 49 | + report = await self._write_report(query, search_results) |
| 50 | + verification = await self._verify_report(report) |
| 51 | + |
| 52 | + final_report = f"Report summary\n\n{report.short_summary}" |
| 53 | + self.printer.update_item( |
| 54 | + "final_report", final_report, is_done=True) |
| 55 | + |
| 56 | + self.printer.end() |
| 57 | + |
| 58 | + # Print to stdout |
| 59 | + print("\n\n=====REPORT=====\n\n") |
| 60 | + print(f"Report:\n{report.markdown_report}") |
| 61 | + print("\n\n=====FOLLOW UP QUESTIONS=====\n\n") |
| 62 | + print("\n".join(report.follow_up_questions)) |
| 63 | + print("\n\n=====VERIFICATION=====\n\n") |
| 64 | + print(verification) |
| 65 | + |
| 66 | + async def _plan_searches(self, query: str) -> FinancialSearchPlan: |
| 67 | + self.printer.update_item("planning", "Planning searches...") |
| 68 | + result = await Runner.run(planner_agent, f"Query: {query}") |
| 69 | + self.printer.update_item( |
| 70 | + "planning", |
| 71 | + f"Will perform {len(result.final_output.searches)} searches", |
| 72 | + is_done=True, |
| 73 | + ) |
| 74 | + return result.final_output_as(FinancialSearchPlan) |
| 75 | + |
| 76 | + async def _perform_searches(self, search_plan: FinancialSearchPlan) -> Sequence[str]: |
| 77 | + with custom_span("Search the web"): |
| 78 | + self.printer.update_item("searching", "Searching...") |
| 79 | + tasks = [asyncio.create_task(self._search(item)) |
| 80 | + for item in search_plan.searches] |
| 81 | + results: list[str] = [] |
| 82 | + num_completed = 0 |
| 83 | + for task in asyncio.as_completed(tasks): |
| 84 | + result = await task |
| 85 | + if result is not None: |
| 86 | + results.append(result) |
| 87 | + num_completed += 1 |
| 88 | + self.printer.update_item( |
| 89 | + "searching", f"Searching... {num_completed}/{len(tasks)} completed" |
| 90 | + ) |
| 91 | + self.printer.mark_item_done("searching") |
| 92 | + return results |
| 93 | + |
| 94 | + async def _search(self, item: FinancialSearchItem) -> str | None: |
| 95 | + input_data = f"Search term: {item.query}\nReason: {item.reason}" |
| 96 | + try: |
| 97 | + result = await Runner.run(search_agent, input_data) |
| 98 | + return str(result.final_output) |
| 99 | + except Exception: |
| 100 | + return None |
| 101 | + |
| 102 | + async def _write_report(self, query: str, search_results: Sequence[str]) -> FinancialReportData: |
| 103 | + # Expose the specialist analysts as tools so the writer can invoke them inline |
| 104 | + # and still produce the final FinancialReportData output. |
| 105 | + fundamentals_tool = financials_agent.as_tool( |
| 106 | + tool_name="fundamentals_analysis", |
| 107 | + tool_description="Use to get a short write‑up of key financial metrics", |
| 108 | + custom_output_extractor=_summary_extractor, |
| 109 | + ) |
| 110 | + risk_tool = risk_agent.as_tool( |
| 111 | + tool_name="risk_analysis", |
| 112 | + tool_description="Use to get a short write‑up of potential red flags", |
| 113 | + custom_output_extractor=_summary_extractor, |
| 114 | + ) |
| 115 | + writer_with_tools = writer_agent.clone( |
| 116 | + tools=[fundamentals_tool, risk_tool]) |
| 117 | + self.printer.update_item("writing", "Thinking about report...") |
| 118 | + input_data = f"Original query: {query}\nSummarized search results: {search_results}" |
| 119 | + result = Runner.run_streamed(writer_with_tools, input_data) |
| 120 | + update_messages = [ |
| 121 | + "Planning report structure...", |
| 122 | + "Writing sections...", |
| 123 | + "Finalizing report...", |
| 124 | + ] |
| 125 | + last_update = time.time() |
| 126 | + next_message = 0 |
| 127 | + async for _ in result.stream_events(): |
| 128 | + if time.time() - last_update > 5 and next_message < len(update_messages): |
| 129 | + self.printer.update_item( |
| 130 | + "writing", update_messages[next_message]) |
| 131 | + next_message += 1 |
| 132 | + last_update = time.time() |
| 133 | + self.printer.mark_item_done("writing") |
| 134 | + return result.final_output_as(FinancialReportData) |
| 135 | + |
| 136 | + async def _verify_report(self, report: FinancialReportData) -> VerificationResult: |
| 137 | + self.printer.update_item("verifying", "Verifying report...") |
| 138 | + result = await Runner.run(verifier_agent, report.markdown_report) |
| 139 | + self.printer.mark_item_done("verifying") |
| 140 | + return result.final_output_as(VerificationResult) |
0 commit comments