RuntimeError
pydantic_ai.tool_decorator.RuntimeError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
result = my_tool_function()
File "pydantic_ai/tool_decorator.py", line 88, in wrapper
raise RuntimeError("Tool decorator used outside of async context")
RuntimeError: Tool decorator used outside of async context Why it happens
The Pydantic AI tool decorator requires an active async context to manage tool invocation and state. If the decorated function is called outside this context or without initializing the required context manager, it raises a RuntimeError. This ensures proper lifecycle and resource management during tool execution.
Detection
Monitor for RuntimeError exceptions with the message 'Tool decorator used outside of async context' during tool function calls, and log the call stack to identify missing async context usage.
Causes & fixes
Calling a Pydantic AI tool-decorated function outside an async context manager
Wrap calls to tool-decorated functions inside the async context manager provided by pydantic_ai.tool_decorator, e.g., using 'async with ToolContext():'
Forgetting to await an async tool function decorated by Pydantic AI
Ensure all calls to async tool functions are awaited properly to maintain the async context and avoid runtime errors
Using the tool decorator in a synchronous function without async support
Convert the calling function to async or run the tool function within an async event loop to satisfy the decorator's async context requirements
Code: broken vs fixed
from pydantic_ai import tool
@tool
def my_tool_function():
return "Hello"
result = my_tool_function() # RuntimeError: Tool decorator used outside of async context import os
import asyncio
from pydantic_ai import tool, ToolContext
os.environ["API_KEY"] = os.environ.get("API_KEY", "your_api_key_here") # Use env var for keys
@tool
def my_tool_function():
return "Hello"
async def main():
async with ToolContext(): # Added async context
result = await my_tool_function() # Await async call
print(result)
asyncio.run(main()) Workaround
Catch the RuntimeError and manually create and enter the async context before calling the tool function, or run the tool function inside an async event loop as a temporary patch.
Prevention
Always use the Pydantic AI tool decorator within its prescribed async context manager and ensure all tool calls are awaited to maintain proper lifecycle and avoid context errors.