File size: 6,746 Bytes
69e310f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
"""Data agent — decides what to compute, then consumes MCP tools to get it.

Runs in parallel with the news agent. Every number it contributes to state came
out of the MCP tool server; the agent's own contribution is the *plan*.
"""

from __future__ import annotations

import logging
from typing import Any

from app.core.budget import BudgetExceededError
from app.core.claude import AgentRole, LLMRequest, PromptHint
from app.core.events import EventKind
from app.graph.context import RunContext, current_context
from app.graph.llm import call_model
from app.graph.prompts import DATA_AGENT_SYSTEM, PLAN_MARKET_DATA_TOOL
from app.graph.state import RunState
from app.mcp_server.client import McpToolError
from app.mcp_server.providers import MAX_HISTORY_DAYS
from app.models.market import Fundamentals, Metrics, PriceHistory
from app.models.run import RunError, RunStatus, Stage

logger = logging.getLogger(__name__)

AGENT_NAME: Stage = "data_agent"


async def _plan_targets(
    ctx: RunContext, state: RunState, targets: list[str]
) -> tuple[list[str], int, dict[str, Any]]:
    """Ask the model which tickers to pull and over what window."""
    default_days = int(state.get("days", ctx.settings.price_history_days))
    request = LLMRequest(
        role=AgentRole.DATA,
        hint=PromptHint.DATA_ANALYSE,
        system=DATA_AGENT_SYSTEM,
        messages=[
            {
                "role": "user",
                "content": (
                    f"Assigned tickers: {', '.join(targets)}.\n"
                    f"Default history window: {default_days} calendar days.\n"
                    "Call plan_market_data with the tickers to fetch and the window to use."
                ),
            }
        ],
        tools=[PLAN_MARKET_DATA_TOOL],
        forced_tool=PLAN_MARKET_DATA_TOOL.name,
        context={"tickers": targets, "days": default_days},
    )
    outcome = await call_model(ctx, request)
    plan = outcome.result.first_tool(PLAN_MARKET_DATA_TOOL.name) or {}

    # Scope containment: the model may narrow the assignment but never widen it.
    # A prompt-injected "also fetch XYZ" therefore cannot reach the provider.
    assigned = set(targets)
    requested = [
        str(t).strip().upper()
        for t in plan.get("tickers", [])
        if str(t).strip().upper() in assigned
    ]
    chosen = requested or targets

    days = plan.get("days", default_days)
    try:
        days_int = max(2, min(int(days), MAX_HISTORY_DAYS))
    except (TypeError, ValueError):
        days_int = default_days

    spend = outcome.spend.model_dump()
    return chosen, days_int, spend


async def data_agent_node(state: RunState) -> dict[str, Any]:
    """Graph node: fetch prices, fundamentals and metrics for the assigned tickers."""
    ctx = current_context()
    targets = list((state.get("plan") or {}).get("market_tickers", []))
    if not targets:
        return {"agents_completed": [AGENT_NAME]}

    await ctx.emit(
        EventKind.AGENT_STARTED,
        f"data_agent working {len(targets)} ticker(s)",
        {"agent": AGENT_NAME, "tickers": targets},
    )

    prices: dict[str, PriceHistory] = {}
    fundamentals: dict[str, Fundamentals] = {}
    metrics: dict[str, Metrics] = {}
    errors: list[RunError] = []
    attempts: dict[str, int] = {f"market:{ticker}": 1 for ticker in targets}
    spend_delta: dict[str, Any] = {}

    with (
        ctx.mcp.collect() as records,
        ctx.tracer.step("data_agent", run_id=ctx.run_id, input_data={"tickers": targets}) as span,
    ):
        try:
            chosen, days, spend_delta = await _plan_targets(ctx, state, targets)
        except BudgetExceededError as exc:
            return {
                "agents_completed": [AGENT_NAME],
                "attempts": attempts,
                "status": RunStatus.BUDGET_ABORT,
                "abort_reason": str(exc),
                "errors": [RunError(stage=AGENT_NAME, message=str(exc))],
            }

        for ticker in chosen:
            try:
                history = await ctx.mcp.get_price_history(ticker, days)
                prices[ticker] = history

                company = await ctx.mcp.get_fundamentals(ticker)
                fundamentals[ticker] = company

                computed = await ctx.mcp.compute_metrics(
                    ticker, list(history.bars), company.pe_ratio
                )
                metrics[ticker] = computed

                if history.error:
                    errors.append(RunError(stage=AGENT_NAME, ticker=ticker, message=history.error))
                if company.error:
                    errors.append(
                        RunError(
                            stage=AGENT_NAME,
                            ticker=ticker,
                            message=company.error,
                            severity="warning",
                        )
                    )
                if computed.error:
                    errors.append(RunError(stage=AGENT_NAME, ticker=ticker, message=computed.error))
            except McpToolError as exc:
                logger.warning("data agent MCP failure for %s: %s", ticker, exc)
                errors.append(
                    RunError(
                        stage=AGENT_NAME,
                        ticker=ticker,
                        message=f"MCP tool unavailable: {exc}",
                    )
                )
            except Exception as exc:
                logger.exception("unexpected data agent failure for %s", ticker)
                errors.append(
                    RunError(
                        stage=AGENT_NAME,
                        ticker=ticker,
                        message=f"unexpected failure: {type(exc).__name__}",
                    )
                )

        span.update(
            output={
                "tickers_completed": sorted(metrics),
                "errors": len(errors),
                "tool_calls": len(records),
            }
        )
        tool_call_rows = [record.to_dict() for record in records]

    ok_count = sum(1 for metric in metrics.values() if metric.ok)
    await ctx.emit(
        EventKind.AGENT_COMPLETED,
        f"data_agent finished — {ok_count}/{len(targets)} ticker(s) with metrics",
        {"agent": AGENT_NAME, "ok": ok_count, "errors": len(errors)},
    )

    update: dict[str, Any] = {
        "prices": prices,
        "fundamentals": fundamentals,
        "metrics": metrics,
        "errors": errors,
        "attempts": attempts,
        "tool_calls": tool_call_rows,
        "agents_completed": [AGENT_NAME],
    }
    if spend_delta:
        from app.models.run import TokenSpend

        update["token_spend"] = TokenSpend.model_validate(spend_delta)
    return update