The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
fix(langchain): restrict narrowed `ToolStrategy` in bound tools (#39259)
Nishitha Mb7e5dda39e0a
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.pyindex 8ca411fce8..afda461d9f 100644--- a/libs/langchain_v1/langchain/agents/factory.py+++ b/libs/langchain_v1/langchain/agents/factory.py@@ -1356,8 +1356,17 @@ def create_agent(# and dicts (built-ins)final_tools = list(request.tools)if isinstance(effective_response_format, ToolStrategy):- # Add structured output tools to final tools list- structured_tools = [info.tool for info in structured_output_tools.values()]+ # Add structured output tools to final tools list, narrowed to only the+ # schemas present in the (possibly middleware-narrowed) response format.+ # This ensures middleware that narrows a union `ToolStrategy` to a subset+ # via `request.override()` actually restricts which structured output+ # tools the model can choose from.+ narrowed_tool_names = {spec.name for spec in effective_response_format.schema_specs}+ structured_tools = [+ info.tool+ for name, info in structured_output_tools.items()+ if name in narrowed_tool_names+ ]final_tools.extend(structured_tools)# Bind model based on effective response formatdiff --git a/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py b/libs/langchain_v1/tests/unit_tests/agents/test_response_format.pyindex b1c29e1a13..a869681999 100644--- a/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py+++ b/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py@@ -945,6 +945,55 @@ def test_union_of_types() -> None:assert len(response["messages"]) == 5+def test_wrap_model_call_narrows_response_format_tools() -> None:+ """`wrap_model_call` narrowing `response_format` should restrict bound tools."""++ class RecordingModel(GenericFakeChatModel):+ bound_tool_names: list[list[str]] = Field(default_factory=list)++ @override+ def bind_tools(+ self,+ tools: Sequence[dict[str, Any] | type[BaseModel] | Callable[..., Any] | BaseTool],+ **kwargs: Any,+ ) -> Runnable[LanguageModelInput, AIMessage]:+ self.bound_tool_names.append(sorted(t.name for t in tools if isinstance(t, BaseTool)))+ return self++ model = RecordingModel(+ messages=iter(+ [+ AIMessage(+ content="",+ tool_calls=[{"name": "WeatherBaseModel", "id": "1", "args": WEATHER_DATA}],+ ),+ ]+ )+ )++ class NarrowToWeatherMiddleware(AgentMiddleware):+ def wrap_model_call(+ self,+ request: ModelRequest,+ handler: Callable[[ModelRequest], ModelResponse],+ ) -> ModelCallResult:+ narrowed = request.override(response_format=ToolStrategy(WeatherBaseModel))+ return handler(narrowed)++ agent = create_agent(+ model=model,+ tools=[],+ response_format=ToolStrategy(WeatherBaseModel | LocationResponse),+ middleware=[NarrowToWeatherMiddleware()],+ )+ response = agent.invoke({"messages": [HumanMessage("What's the weather?")]})++ assert response["structured_response"] == EXPECTED_WEATHER_PYDANTIC+ # Only the narrowed tool should have been bound to the model, not the full+ # union of originally-declared structured output tools.+ assert model.bound_tool_names == [["WeatherBaseModel"]]++class TestSupportsProviderStrategy:"""Unit tests for `_supports_provider_strategy`."""