|
| 1 | +from contextlib import asynccontextmanager |
| 2 | +from functools import wraps |
| 3 | + |
| 4 | +from sentry_sdk.integrations import DidNotEnable |
| 5 | +from sentry_sdk.consts import SPANDATA |
| 6 | + |
| 7 | +from ..spans import ( |
| 8 | + ai_client_span, |
| 9 | + update_ai_client_span, |
| 10 | +) |
| 11 | + |
| 12 | +try: |
| 13 | + from pydantic_ai._agent_graph import ModelRequestNode # type: ignore |
| 14 | +except ImportError: |
| 15 | + raise DidNotEnable("pydantic-ai not installed") |
| 16 | + |
| 17 | +from typing import TYPE_CHECKING |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from typing import Any, Callable |
| 21 | + |
| 22 | + |
| 23 | +def _extract_span_data(node: "Any", ctx: "Any") -> "tuple[list[Any], Any, Any]": |
| 24 | + """Extract common data needed for creating chat spans. |
| 25 | +
|
| 26 | + Returns: |
| 27 | + Tuple of (messages, model, model_settings) |
| 28 | + """ |
| 29 | + # Extract model and settings from context |
| 30 | + model = None |
| 31 | + model_settings = None |
| 32 | + if hasattr(ctx, "deps"): |
| 33 | + model = getattr(ctx.deps, "model", None) |
| 34 | + model_settings = getattr(ctx.deps, "model_settings", None) |
| 35 | + |
| 36 | + # Build full message list: history + current request |
| 37 | + messages = [] |
| 38 | + if hasattr(ctx, "state") and hasattr(ctx.state, "message_history"): |
| 39 | + messages.extend(ctx.state.message_history) |
| 40 | + |
| 41 | + current_request = getattr(node, "request", None) |
| 42 | + if current_request: |
| 43 | + messages.append(current_request) |
| 44 | + |
| 45 | + return messages, model, model_settings |
| 46 | + |
| 47 | + |
| 48 | +def _patch_graph_nodes() -> None: |
| 49 | + """ |
| 50 | + Patches the graph node execution to create appropriate spans. |
| 51 | +
|
| 52 | + ModelRequestNode -> Creates ai_client span for model requests |
| 53 | + CallToolsNode -> Handles tool calls (spans created in tool patching) |
| 54 | + """ |
| 55 | + |
| 56 | + # Patch ModelRequestNode to create ai_client spans |
| 57 | + original_model_request_run = ModelRequestNode.run |
| 58 | + |
| 59 | + @wraps(original_model_request_run) |
| 60 | + async def wrapped_model_request_run(self: "Any", ctx: "Any") -> "Any": |
| 61 | + did_stream = getattr(self, "_did_stream", None) |
| 62 | + cached_result = getattr(self, "_result", None) |
| 63 | + if did_stream or cached_result is not None: |
| 64 | + return await original_model_request_run(self, ctx) |
| 65 | + |
| 66 | + messages, model, model_settings = _extract_span_data(self, ctx) |
| 67 | + |
| 68 | + with ai_client_span(messages, None, model, model_settings) as span: |
| 69 | + span.set_data(SPANDATA.GEN_AI_RESPONSE_STREAMING, False) |
| 70 | + |
| 71 | + result = await original_model_request_run(self, ctx) |
| 72 | + |
| 73 | + # Extract response from result if available |
| 74 | + model_response = None |
| 75 | + if hasattr(result, "model_response"): |
| 76 | + model_response = result.model_response |
| 77 | + |
| 78 | + update_ai_client_span(span, model_response) |
| 79 | + return result |
| 80 | + |
| 81 | + ModelRequestNode.run = wrapped_model_request_run |
| 82 | + |
| 83 | + # Patch ModelRequestNode.stream for streaming requests |
| 84 | + original_model_request_stream = ModelRequestNode.stream |
| 85 | + |
| 86 | + def create_wrapped_stream( |
| 87 | + original_stream_method: "Callable[..., Any]", |
| 88 | + ) -> "Callable[..., Any]": |
| 89 | + """Create a wrapper for ModelRequestNode.stream that creates chat spans.""" |
| 90 | + |
| 91 | + @asynccontextmanager |
| 92 | + @wraps(original_stream_method) |
| 93 | + async def wrapped_model_request_stream(self: "Any", ctx: "Any") -> "Any": |
| 94 | + did_stream = getattr(self, "_did_stream", None) |
| 95 | + if did_stream: |
| 96 | + async with original_stream_method(self, ctx) as stream: |
| 97 | + yield stream |
| 98 | + |
| 99 | + messages, model, model_settings = _extract_span_data(self, ctx) |
| 100 | + |
| 101 | + # Create chat span for streaming request |
| 102 | + with ai_client_span(messages, None, model, model_settings) as span: |
| 103 | + span.set_data(SPANDATA.GEN_AI_RESPONSE_STREAMING, True) |
| 104 | + |
| 105 | + # Call the original stream method |
| 106 | + async with original_stream_method(self, ctx) as stream: |
| 107 | + yield stream |
| 108 | + |
| 109 | + # After streaming completes, update span with response data |
| 110 | + # The ModelRequestNode stores the final response in _result |
| 111 | + model_response = None |
| 112 | + if hasattr(self, "_result") and self._result is not None: |
| 113 | + # _result is a NextNode containing the model_response |
| 114 | + if hasattr(self._result, "model_response"): |
| 115 | + model_response = self._result.model_response |
| 116 | + |
| 117 | + update_ai_client_span(span, model_response) |
| 118 | + |
| 119 | + return wrapped_model_request_stream |
| 120 | + |
| 121 | + ModelRequestNode.stream = create_wrapped_stream(original_model_request_stream) |
0 commit comments