1010
1111T = TypeVar ("T" )
1212
13+
14+ class ToolUseLimitExceeded (Exception ):
15+ """Raised when tool use limit is exceeded."""
16+
17+ pass
18+
19+
1320_progress_message : ContextVar [Any ] = ContextVar ("progress_message" , default = None )
1421_tool_usage_counts : ContextVar [dict [str , int ] | None ] = ContextVar (
1522 "tool_usage_counts" , default = None
@@ -64,6 +71,7 @@ def prefect_wrapped_function(
6471 decorator : Callable [..., Callable [..., T ]] = task ,
6572 tags : set [str ] | None = None ,
6673 settings : dict [str , Any ] | None = None ,
74+ max_tool_calls : int = 10 , # Default limit per agent run (matches settings)
6775) -> Callable [..., Callable [..., T ]]:
6876 """Decorator for wrapping a function with a prefect decorator."""
6977 tags = tags or set [str ]()
@@ -102,6 +110,14 @@ async def wrapper(*args, **kwargs) -> T:
102110 _tool_usage_counts .set (counts )
103111 counts [tool_name ] += 1
104112
113+ # Check if we've exceeded the limit
114+ total_calls = sum (counts .values ())
115+ if total_calls > max_tool_calls :
116+ # Raise an exception to preserve type safety
117+ raise ToolUseLimitExceeded (
118+ "I've reached my tool use limit for this response. Please ask a follow-up question if you need more information."
119+ )
120+
105121 # Set current tool
106122 _current_tool_token = _current_tool .set (tool_name )
107123
@@ -161,11 +177,13 @@ def __init__(
161177 patch_method_name : str = "call_tool" ,
162178 tags : set [str ] | None = None ,
163179 settings : dict [str , Any ] | None = None ,
180+ max_tool_calls : int = 10 ,
164181 ):
165182 """Initialize the context manager.
166183 Args:
167184 tags: Prefect tags to apply to the flow.
168- flow_kwargs: Keyword arguments to pass to the flow.
185+ settings: Settings to pass to the decorator.
186+ max_tool_calls: Maximum number of tool calls allowed per turn.
169187 """
170188 # Import here to avoid circular imports
171189 from pydantic_ai .toolsets .abstract import AbstractToolset
@@ -176,4 +194,5 @@ def __init__(
176194 decorator = prefect_wrapped_function ,
177195 tags = tags ,
178196 settings = settings ,
197+ max_tool_calls = max_tool_calls ,
179198 )
0 commit comments