- 
                Notifications
    You must be signed in to change notification settings 
- Fork 568
feat(integrations): pydantic-ai integration #4906
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
            sentrivana
  merged 29 commits into
  master
from
constantinius/feat/integration/pydantic-ai
  
      
      
   
  Oct 23, 2025 
      
    
  
     Merged
                    Changes from 12 commits
      Commits
    
    
            Show all changes
          
          
            29 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      f667f4b
              
                feat(integrations): added initial Pydantic AI integration implementation
              
              
                constantinius 8c26119
              
                fix: model name lookup and message history preservation
              
              
                constantinius 742d77f
              
                feat: add support for run_stream
              
              
                constantinius 76a7a67
              
                fix: deduping code
              
              
                constantinius 9d166ba
              
                fix(integrations): add pydantic-ai as an optional dependency
              
              
                constantinius 3337c19
              
                fix(integrations): fixing span description -> name
              
              
                constantinius bf3ce00
              
                feat: add include_prompts for Pydantic AI integration
              
              
                constantinius 2290901
              
                Merge branch 'master' into constantinius/feat/integration/pydantic-ai
              
              
                sentrivana c7e7ec2
              
                Add pydantic ai to ci
              
              
                sentrivana 1a2cb97
              
                add pytest-asyncio
              
              
                sentrivana b9f3357
              
                Merge branch 'master' into constantinius/feat/integration/pydantic-ai
              
              
                sentrivana 48af290
              
                fix: mypy issues
              
              
                constantinius 7263a77
              
                fix: working in feedback
              
              
                constantinius a94870e
              
                Update sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py
              
              
                constantinius 7f335f9
              
                fix(integrations): cleanups and working in feedback
              
              
                constantinius 0929e58
              
                fix(integrations): type checking import missing
              
              
                constantinius 4b40d2d
              
                fix: significantly simplifying instrumentation
              
              
                constantinius 87ebafc
              
                feat: add support for MCP Tool calls as well
              
              
                constantinius 9e20ebb
              
                test: update tests to reflect recent changes
              
              
                constantinius b25c434
              
                fix: working in feedback, making object typechecks less brittle
              
              
                constantinius 97d6b52
              
                fix: shuffling imports so that the DidNotEnable exception is actually…
              
              
                constantinius 0a32559
              
                ci: -m revert: wrong integration sentry_sdk/integrations/openai_agent…
              
              
                constantinius 0f32768
              
                chore: extracting _set_available_tools function which is used in ai_c…
              
              
                constantinius 8f41ec9
              
                fix: cleaning up context after agent finished
              
              
                constantinius de0c79c
              
                fix: superfluous patch for run_sync() as it is already handled within…
              
              
                constantinius 00c1eab
              
                fix: mypy typing info
              
              
                constantinius d2e5039
              
                fix: more mypy check fixes
              
              
                constantinius 5a309cf
              
                test: improving test coverage
              
              
                constantinius e5e1d5e
              
                Merge branch 'master' into constantinius/feat/integration/pydantic-ai
              
              
                sentrivana File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
|  | @@ -81,6 +81,7 @@ | |
| "openai-base", | ||
| "openai-notiktoken", | ||
| "openai_agents", | ||
| "pydantic_ai", | ||
| ], | ||
| "Cloud": [ | ||
| "aws_lambda", | ||
|  | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| from sentry_sdk.integrations import DidNotEnable, Integration | ||
|  | ||
| from .patches import ( | ||
| _patch_agent_run, | ||
| _patch_graph_nodes, | ||
| _patch_model_request, | ||
| _patch_tool_execution, | ||
| ) | ||
|  | ||
| try: | ||
| import pydantic_ai | ||
|  | ||
| except ImportError: | ||
| raise DidNotEnable("pydantic-ai not installed") | ||
|  | ||
|  | ||
| class PydanticAIIntegration(Integration): | ||
| identifier = "pydantic_ai" | ||
| origin = f"auto.ai.{identifier}" | ||
|  | ||
| def __init__(self, include_prompts=True): | ||
| # type: (bool) -> None | ||
| """ | ||
| Initialize the Pydantic AI integration. | ||
|  | ||
| Args: | ||
| include_prompts: Whether to include prompts and messages in span data. | ||
| Requires send_default_pii=True. Defaults to True. | ||
| """ | ||
| self.include_prompts = include_prompts | ||
|  | ||
| @staticmethod | ||
| def setup_once(): | ||
| # type: () -> None | ||
| """ | ||
| Set up the pydantic-ai integration. | ||
|  | ||
| This patches the key methods in pydantic-ai to create Sentry spans for: | ||
| - Agent workflow execution (root span) | ||
| - Individual agent invocations | ||
| - Model requests (AI client calls) | ||
| - Tool executions | ||
| """ | ||
| _patch_agent_run() | ||
| _patch_graph_nodes() | ||
| _patch_model_request() | ||
| _patch_tool_execution() | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1 @@ | ||
| SPAN_ORIGIN = "auto.ai.pydantic_ai" | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| from .agent_run import _patch_agent_run # noqa: F401 | ||
| from .graph_nodes import _patch_graph_nodes # noqa: F401 | ||
| from .model_request import _patch_model_request # noqa: F401 | ||
| from .tools import _patch_tool_execution # noqa: F401 | 
        
          
  
    
      
          
            222 changes: 222 additions & 0 deletions
          
          222 
        
  sentry_sdk/integrations/pydantic_ai/patches/agent_run.py
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,222 @@ | ||
| from functools import wraps | ||
|  | ||
| import sentry_sdk | ||
| from sentry_sdk.integrations import DidNotEnable | ||
|  | ||
| from ..spans import agent_workflow_span, invoke_agent_span, update_invoke_agent_span | ||
| from ..utils import _capture_exception | ||
|  | ||
| from typing import TYPE_CHECKING | ||
|  | ||
| if TYPE_CHECKING: | ||
| from typing import Any, Callable, Optional | ||
|  | ||
| try: | ||
| import pydantic_ai | ||
| except ImportError: | ||
| raise DidNotEnable("pydantic-ai not installed") | ||
|  | ||
|  | ||
| class _StreamingContextManagerWrapper: | ||
| """Wrapper for streaming methods that return async context managers.""" | ||
|  | ||
| def __init__(self, agent, original_ctx_manager, is_streaming=True): | ||
| # type: (Any, Any, bool) -> None | ||
| self.agent = agent | ||
| self.original_ctx_manager = original_ctx_manager | ||
| self.is_streaming = is_streaming | ||
| self._isolation_scope = None # type: Any | ||
| self._workflow_span = None # type: Optional[sentry_sdk.tracing.Span] | ||
|  | ||
| async def __aenter__(self): | ||
| # type: () -> Any | ||
| # Set up isolation scope and workflow span | ||
| self._isolation_scope = sentry_sdk.isolation_scope() | ||
| self._isolation_scope.__enter__() | ||
|  | ||
| # Store agent reference and streaming flag | ||
| sentry_sdk.get_current_scope().set_context( | ||
| "pydantic_ai_agent", {"_agent": self.agent, "_streaming": self.is_streaming} | ||
| ) | ||
|  | ||
| # Create workflow span | ||
| self._workflow_span = agent_workflow_span(self.agent) | ||
| self._workflow_span.__enter__() | ||
|  | ||
| # Enter the original context manager | ||
| result = await self.original_ctx_manager.__aenter__() | ||
| return result | ||
|  | ||
| async def __aexit__(self, exc_type, exc_val, exc_tb): | ||
| # type: (Any, Any, Any) -> None | ||
| try: | ||
| # Exit the original context manager first | ||
| await self.original_ctx_manager.__aexit__(exc_type, exc_val, exc_tb) | ||
| finally: | ||
| # Clean up workflow span | ||
| if self._workflow_span: | ||
| self._workflow_span.__exit__(exc_type, exc_val, exc_tb) | ||
|  | ||
| # Clean up isolation scope | ||
| if self._isolation_scope: | ||
| self._isolation_scope.__exit__(exc_type, exc_val, exc_tb) | ||
|  | ||
|  | ||
| def _create_run_wrapper(original_func, is_streaming=False): | ||
| # type: (Callable[..., Any], bool) -> Callable[..., Any] | ||
| """ | ||
| Wraps the Agent.run method to create a root span for the agent workflow. | ||
| Args: | ||
| original_func: The original run method | ||
| is_streaming: Whether this is a streaming method (for future use) | ||
| """ | ||
|  | ||
| @wraps(original_func) | ||
| async def wrapper(self, *args, **kwargs): | ||
| # type: (Any, *Any, **Any) -> Any | ||
| # Isolate each workflow so that when agents are run in asyncio tasks they | ||
| # don't touch each other's scopes | ||
| with sentry_sdk.isolation_scope(): | ||
| # Store agent reference and streaming flag in Sentry scope for access in nested spans | ||
| # We store the full agent to allow access to tools and system prompts | ||
| sentry_sdk.get_current_scope().set_context( | ||
| "pydantic_ai_agent", {"_agent": self, "_streaming": is_streaming} | ||
| ) | ||
|         
                  constantinius marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
|  | ||
| with agent_workflow_span(self): | ||
| result = None | ||
| try: | ||
| result = await original_func(self, *args, **kwargs) | ||
| return result | ||
| except Exception as exc: | ||
| _capture_exception(exc) | ||
|  | ||
| # It could be that there is an "invoke agent" span still open | ||
| current_span = sentry_sdk.get_current_span() | ||
| if current_span is not None and current_span.timestamp is None: | ||
| current_span.__exit__(None, None, None) | ||
|  | ||
| raise exc from None | ||
|  | ||
| return wrapper | ||
|  | ||
|  | ||
| def _create_run_sync_wrapper(original_func): | ||
| # type: (Callable[..., Any]) -> Callable[..., Any] | ||
| """ | ||
| Wraps the Agent.run_sync method to create a root span for the agent workflow. | ||
| Note: run_sync is always non-streaming. | ||
| """ | ||
|  | ||
| @wraps(original_func) | ||
| def wrapper(self, *args, **kwargs): | ||
| # type: (Any, *Any, **Any) -> Any | ||
| # Isolate each workflow so that when agents are run they | ||
| # don't touch each other's scopes | ||
| with sentry_sdk.isolation_scope(): | ||
| # Store agent reference and streaming flag in Sentry scope for access in nested spans | ||
| # We store the full agent to allow access to tools and system prompts | ||
| sentry_sdk.get_current_scope().set_context( | ||
| "pydantic_ai_agent", {"_agent": self, "_streaming": False} | ||
| ) | ||
|  | ||
| with agent_workflow_span(self): | ||
| result = None | ||
| try: | ||
| result = original_func(self, *args, **kwargs) | ||
| return result | ||
| except Exception as exc: | ||
| _capture_exception(exc) | ||
|  | ||
| # It could be that there is an "invoke agent" span still open | ||
| current_span = sentry_sdk.get_current_span() | ||
| if current_span is not None and current_span.timestamp is None: | ||
| current_span.__exit__(None, None, None) | ||
|  | ||
| raise exc from None | ||
|  | ||
| return wrapper | ||
|  | ||
|  | ||
| def _create_streaming_wrapper(original_func): | ||
| # type: (Callable[..., Any]) -> Callable[..., Any] | ||
| """ | ||
| Wraps run_stream method that returns an async context manager. | ||
| """ | ||
|  | ||
| @wraps(original_func) | ||
| def wrapper(self, *args, **kwargs): | ||
| # type: (Any, *Any, **Any) -> Any | ||
| # Call original function to get the context manager | ||
| original_ctx_manager = original_func(self, *args, **kwargs) | ||
|  | ||
| # Wrap it with our instrumentation | ||
| return _StreamingContextManagerWrapper( | ||
| agent=self, original_ctx_manager=original_ctx_manager, is_streaming=True | ||
| ) | ||
|  | ||
| return wrapper | ||
|  | ||
|  | ||
| def _create_streaming_events_wrapper(original_func): | ||
| # type: (Callable[..., Any]) -> Callable[..., Any] | ||
| """ | ||
| Wraps run_stream_events method that returns an async generator/iterator. | ||
| """ | ||
|  | ||
| @wraps(original_func) | ||
| async def wrapper(self, *args, **kwargs): | ||
| # type: (Any, *Any, **Any) -> Any | ||
| # Isolate each workflow so that when agents are run in asyncio tasks they | ||
| # don't touch each other's scopes | ||
| with sentry_sdk.isolation_scope(): | ||
| # Store agent reference and streaming flag in Sentry scope for access in nested spans | ||
| sentry_sdk.get_current_scope().set_context( | ||
| "pydantic_ai_agent", {"_agent": self, "_streaming": True} | ||
| ) | ||
|  | ||
| with agent_workflow_span(self): | ||
| try: | ||
| # Call the original generator and yield all events | ||
| async for event in original_func(self, *args, **kwargs): | ||
| yield event | ||
| except Exception as exc: | ||
| _capture_exception(exc) | ||
|  | ||
| # It could be that there is an "invoke agent" span still open | ||
| current_span = sentry_sdk.get_current_span() | ||
| if current_span is not None and current_span.timestamp is None: | ||
| current_span.__exit__(None, None, None) | ||
|  | ||
| raise exc from None | ||
|  | ||
| return wrapper | ||
|  | ||
|  | ||
| def _patch_agent_run(): | ||
| # type: () -> None | ||
| """ | ||
| Patches the Agent run methods to create spans for agent execution. | ||
| This patches both non-streaming (run, run_sync) and streaming | ||
| (run_stream, run_stream_events) methods. | ||
| """ | ||
| # Import here to avoid circular imports | ||
| from pydantic_ai.agent import Agent | ||
|         
                  constantinius marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
|  | ||
| # Store original methods | ||
| original_run = Agent.run | ||
| original_run_sync = Agent.run_sync | ||
| original_run_stream = Agent.run_stream | ||
| original_run_stream_events = Agent.run_stream_events | ||
|  | ||
| # Wrap and apply patches for non-streaming methods | ||
| Agent.run = _create_run_wrapper(original_run, is_streaming=False) # type: ignore | ||
| Agent.run_sync = _create_run_sync_wrapper(original_run_sync) # type: ignore | ||
|  | ||
| # Wrap and apply patches for streaming methods | ||
| Agent.run_stream = _create_streaming_wrapper(original_run_stream) # type: ignore | ||
| Agent.run_stream_events = _create_streaming_events_wrapper( # type: ignore[method-assign] | ||
| original_run_stream_events | ||
| ) | ||
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bug: AI Integration Auto-Enablement Issue
The
PydanticAIIntegrationwas added to_MIN_VERSIONSbut is missing from_AUTO_ENABLING_INTEGRATIONS. This prevents it from being automatically enabled whenpydantic_aiis present, which is inconsistent with other AI integrations and itsauto.ai.pydantic_aiorigin.