Avoid complex 'lambda' functions; prefer named functions for clarity and debugging
"process_inputs": lambda inputs: process_inputs(_scrub_inputs(inputs)),
1"""Agent factory for creating agents with middleware support."""23from __future__ import annotations45import functools6import importlib7import itertools8import re9from dataclasses import dataclass, field, fields10from typing import (11 TYPE_CHECKING,12 Annotated,13 Any,14 Generic,15 cast,16 get_args,17 get_origin,18 get_type_hints,19)2021from langchain_core.language_models.chat_models import BaseChatModel22from langchain_core.messages import (23 AIMessage,24 AnyMessage,25 RemoveMessage,26 SystemMessage,27 ToolMessage,28)29from langchain_core.tools import BaseTool30from langgraph._internal._runnable import RunnableCallable31from langgraph.constants import END, START32from langgraph.graph.message import REMOVE_ALL_MESSAGES33from langgraph.graph.state import StateGraph34from langgraph.prebuilt import ToolCallTransformer35from langgraph.prebuilt.tool_node import ToolNode36from langgraph.types import Command, Send37from langsmith import traceable38from typing_extensions import NotRequired, Required, TypedDict, overload3940from langchain.agents._subagent_transformer import SubagentTransformer41from langchain.agents.middleware._trace_policy import (42 _node_trace_policy,43 _resolved_transform,44)45from langchain.agents.middleware.types import (46 AgentMiddleware,47 AgentState,48 ContextT,49 ExtendedModelResponse,50 InputAgentState,51 JumpTo,52 ModelRequest,53 ModelResponse,54 OmitFromSchema,55 OutputAgentState,56 ResponseT,57 StateT_co,58 ToolCallRequest,59)60from langchain.agents.structured_output import (61 AutoStrategy,62 MultipleStructuredOutputsError,63 OutputToolBinding,64 ProviderStrategy,65 ProviderStrategyBinding,66 ResponseFormat,67 StructuredOutputError,68 StructuredOutputValidationError,69 ToolStrategy,70)71from langchain.chat_models import init_chat_model727374@dataclass75class _ComposedExtendedModelResponse(Generic[ResponseT]):76 """Internal result from composed `wrap_model_call` middleware.7778 Unlike `ExtendedModelResponse` (user-facing, single command), this holds the79 full list of commands accumulated across all middleware layers during80 composition.81 """8283 model_response: ModelResponse[ResponseT]84 """The underlying model response."""8586 commands: list[Command[Any]] = field(default_factory=list)87 """Commands accumulated from all middleware layers (inner-first, then outer)."""888990if TYPE_CHECKING:91 from collections.abc import Awaitable, Callable, Iterable, Sequence9293 from langchain_core.messages import InvalidToolCall94 from langchain_core.runnables import Runnable, RunnableConfig95 from langgraph.cache.base import BaseCache96 from langgraph.graph.state import CompiledStateGraph97 from langgraph.runtime import Runtime98 from langgraph.store.base import BaseStore99 from langgraph.stream._mux import TransformerFactory100 from langgraph.types import Checkpointer101102 from langchain.agents.middleware.types import ToolCallWrapper103104 _ModelCallHandler = Callable[105 [ModelRequest[ContextT], Callable[[ModelRequest[ContextT]], ModelResponse]],106 ModelResponse | AIMessage | ExtendedModelResponse,107 ]108109 _ComposedModelCallHandler = Callable[110 [ModelRequest[ContextT], Callable[[ModelRequest[ContextT]], ModelResponse]],111 _ComposedExtendedModelResponse,112 ]113114 _AsyncModelCallHandler = Callable[115 [ModelRequest[ContextT], Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse]]],116 Awaitable[ModelResponse | AIMessage | ExtendedModelResponse],117 ]118119 _ComposedAsyncModelCallHandler = Callable[120 [ModelRequest[ContextT], Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse]]],121 Awaitable[_ComposedExtendedModelResponse],122 ]123124125STRUCTURED_OUTPUT_ERROR_TEMPLATE = "Error: {error}\n Please fix your mistakes."126127DYNAMIC_TOOL_ERROR_TEMPLATE = """128Middleware added tools that the agent doesn't know how to execute.129130Unknown tools: {unknown_tool_names}131Registered tools: {available_tool_names}132133This happens when middleware modifies `request.tools` in `wrap_model_call` to include134tools that weren't passed to `create_agent()`.135136How to fix this:137138Option 1: Register tools at agent creation (recommended for most cases)139 Pass the tools to `create_agent(tools=[...])` or set them on `middleware.tools`.140 This makes tools available for every agent invocation.141142Option 2: Handle dynamic tools in middleware (for tools created at runtime)143 Implement `wrap_tool_call` to execute tools that are added dynamically:144145 class MyMiddleware(AgentMiddleware):146 def wrap_tool_call(self, request, handler):147 if request.tool_call["name"] == "dynamic_tool":148 # Execute the dynamic tool yourself or override with tool instance149 return handler(request.override(tool=my_dynamic_tool))150 return handler(request)151""".strip()152153154def _scrub_inputs(inputs: dict[str, Any]) -> dict[str, Any]:155 """Remove `runtime` and `handler` from trace inputs before sending to LangSmith."""156 filtered = inputs.copy()157 filtered.pop("handler", None)158 req = filtered.get("request")159 if isinstance(req, (ModelRequest, ToolCallRequest)):160 filtered["request"] = {161 f.name: getattr(req, f.name) for f in fields(req) if f.name != "runtime"162 }163 return filtered164165166def _wrap_trace_kwargs(middleware: AgentMiddleware[Any, Any]) -> dict[str, Any]:167 """`traceable` kwargs for a middleware's `wrap_*` hook spans.168169 The `_scrub_inputs` baseline (strip the unserializable `handler`/`runtime`) always170 runs first; the effective `TracePolicy` (the middleware's own, else the process-wide171 default) composes on top. The effective policy is resolved at call time, so a172 `configure_trace_policy` call after `create_agent` still applies.173 """174 process_inputs = _resolved_transform(middleware.trace_policy, "process_inputs")175 process_outputs = _resolved_transform(middleware.trace_policy, "process_outputs")176 return {177 "process_inputs": lambda inputs: process_inputs(_scrub_inputs(inputs)),178 "process_outputs": process_outputs,179 }180181182FALLBACK_MODELS_WITH_STRUCTURED_OUTPUT = [183 # If model profile data are not available, model names matching these patterns184 # are assumed to support provider-native structured output. These are regexes185 # so matches stay bounded to model-name segments instead of arbitrary substrings.186 r"(^|[/:.])gpt-4\.1($|[-/:])",187 r"(^|[/:.])gpt-4o($|[-/:])",188 r"(^|[/:.])gpt-5($|[-/:])",189 r"(^|[/:.])gpt-5\.1($|[-/:])",190 r"(^|[/:.])gpt-5\.2(-\d{4}-\d{2}-\d{2})?($|[/:])",191 r"(^|[/:.])gpt-5\.2-(chat|codex)($|[-/:])",192 r"(^|[/:.])gpt-5\.3($|[-/:])",193 r"(^|[/:.])gpt-5\.4(-\d{4}-\d{2}-\d{2})?($|[/:])",194 r"(^|[/:.])gpt-5\.4-(mini|nano)($|[-/:])",195 r"(^|[/:.])gpt-5\.5($|[-/:])",196 r"(^|[/:.])gpt-6-(astra|luna|sol)($|[-/:])",197 r"(^|[/:.])claude-(fable|mythos)-5(?:-\d{8})?(?:-v\d(?::\d)?)?($|[/:])",198 r"(^|[/:.])claude-haiku-4-5(?:-\d{8})?(?:-v\d(?::\d)?)?($|[/:])",199 r"(^|[/:.])claude-opus-4-(5|6|7|8)(?:-\d{8})?(?:-v\d(?::\d)?)?($|[/:])",200 r"(^|[/:.])claude-sonnet-4-(5|6)(?:-\d{8})?(?:-v\d(?::\d)?)?($|[/:])",201 r"(^|[/:.])grok-4($|[-.:/])",202 r"(^|[/:.])grok-build($|[-/:])",203]204205206def _normalize_to_model_response(207 result: ModelResponse | AIMessage | ExtendedModelResponse,208) -> ModelResponse:209 """Normalize middleware return value to ModelResponse.210211 At inner composition boundaries, `ExtendedModelResponse` is unwrapped to its212 underlying `ModelResponse` so that inner middleware always sees `ModelResponse`213 from the handler.214 """215 if isinstance(result, AIMessage):216 return ModelResponse(result=[result], structured_response=None)217 if isinstance(result, ExtendedModelResponse):218 return result.model_response219 return result220221222def _build_commands(223 model_response: ModelResponse,224 middleware_commands: list[Command[Any]] | None = None,225 *,226 has_structured_output: bool = False,227 repaired_messages: list[AnyMessage] | None = None,228) -> list[Command[Any]]:229 """Build a list of Commands from a model response and middleware commands.230231 The first Command contains the model response state (messages and optional232 structured_response). Middleware commands are appended as-is.233234 Args:235 model_response: The model response containing messages and optional236 structured output.237 middleware_commands: Commands accumulated from middleware layers during238 composition (inner-first ordering).239 has_structured_output: Whether the agent was configured with a240 `response_format`. When `True` and no structured response was241 produced, `structured_response` is explicitly cleared to avoid a242 stale value from a previous checkpointed turn.243 repaired_messages: Complete message history after repairing invalid tool calls.244245 Returns:246 List of `Command` objects ready to be returned from a model node.247 """248 messages = model_response.result249 if repaired_messages is not None:250 messages = [251 RemoveMessage(id=REMOVE_ALL_MESSAGES),252 *repaired_messages,253 *model_response.result,254 ]255 state: dict[str, Any] = {"messages": messages}256257 if model_response.structured_response is not None:258 state["structured_response"] = model_response.structured_response259 elif has_structured_output:260 state["structured_response"] = None261262 for cmd in middleware_commands or []:263 if cmd.goto:264 msg = (265 "Command goto is not yet supported in wrap_model_call middleware. "266 "Use the jump_to state field with before_model/after_model hooks instead."267 )268 raise NotImplementedError(msg)269 if cmd.resume:270 msg = "Command resume is not yet supported in wrap_model_call middleware."271 raise NotImplementedError(msg)272 if cmd.graph:273 msg = "Command graph is not yet supported in wrap_model_call middleware."274 raise NotImplementedError(msg)275276 commands: list[Command[Any]] = [Command(update=state)]277 commands.extend(middleware_commands or [])278 return commands279280281def _chain_model_call_handlers(282 handlers: Sequence[_ModelCallHandler[ContextT]],283) -> _ComposedModelCallHandler[ContextT] | None:284 """Compose multiple `wrap_model_call` handlers into single middleware stack.285286 Composes handlers so first in list becomes outermost layer. Each handler receives a287 handler callback to execute inner layers. Commands from each layer are accumulated288 into a list (inner-first, then outer) without merging.289290 Args:291 handlers: List of handlers.292293 First handler wraps all others.294295 Returns:296 Composed handler returning `_ComposedExtendedModelResponse`,297 or `None` if handlers empty.298 """299 if not handlers:300 return None301302 def _to_composed_result(303 result: ModelResponse | AIMessage | ExtendedModelResponse | _ComposedExtendedModelResponse,304 extra_commands: list[Command[Any]] | None = None,305 ) -> _ComposedExtendedModelResponse:306 """Normalize any handler result to _ComposedExtendedModelResponse."""307 commands: list[Command[Any]] = list(extra_commands or [])308 if isinstance(result, _ComposedExtendedModelResponse):309 commands.extend(result.commands)310 model_response = result.model_response311 elif isinstance(result, ExtendedModelResponse):312 model_response = result.model_response313 if result.command is not None:314 commands.append(result.command)315 else:316 model_response = _normalize_to_model_response(result)317318 return _ComposedExtendedModelResponse(model_response=model_response, commands=commands)319320 if len(handlers) == 1:321 single_handler = handlers[0]322323 def normalized_single(324 request: ModelRequest[ContextT],325 handler: Callable[[ModelRequest[ContextT]], ModelResponse],326 ) -> _ComposedExtendedModelResponse:327 return _to_composed_result(single_handler(request, handler))328329 return normalized_single330331 def compose_two(332 outer: _ModelCallHandler[ContextT] | _ComposedModelCallHandler[ContextT],333 inner: _ModelCallHandler[ContextT] | _ComposedModelCallHandler[ContextT],334 ) -> _ComposedModelCallHandler[ContextT]:335 """Compose two handlers where outer wraps inner."""336337 def composed(338 request: ModelRequest[ContextT],339 handler: Callable[[ModelRequest[ContextT]], ModelResponse],340 ) -> _ComposedExtendedModelResponse:341 # Closure variable to capture inner's commands before normalizing342 accumulated_commands: list[Command[Any]] = []343344 def inner_handler(req: ModelRequest[ContextT]) -> ModelResponse:345 # Clear on each call for retry safety346 accumulated_commands.clear()347 inner_result = inner(req, handler)348 if isinstance(inner_result, _ComposedExtendedModelResponse):349 accumulated_commands.extend(inner_result.commands)350 return inner_result.model_response351 if isinstance(inner_result, ExtendedModelResponse):352 if inner_result.command is not None:353 accumulated_commands.append(inner_result.command)354 return inner_result.model_response355 return _normalize_to_model_response(inner_result)356357 outer_result = outer(request, inner_handler)358 return _to_composed_result(359 outer_result,360 extra_commands=accumulated_commands or None,361 )362363 return composed364365 # Compose right-to-left: outer(inner(innermost(handler)))366 composed_handler = compose_two(handlers[-2], handlers[-1])367 for h in reversed(handlers[:-2]):368 composed_handler = compose_two(h, composed_handler)369370 return composed_handler371372373def _chain_async_model_call_handlers(374 handlers: Sequence[_AsyncModelCallHandler[ContextT]],375) -> _ComposedAsyncModelCallHandler[ContextT] | None:376 """Compose multiple async `wrap_model_call` handlers into single middleware stack.377378 Commands from each layer are accumulated into a list (inner-first, then outer)379 without merging.380381 Args:382 handlers: List of async handlers.383384 First handler wraps all others.385386 Returns:387 Composed async handler returning `_ComposedExtendedModelResponse`,388 or `None` if handlers empty.389 """390 if not handlers:391 return None392393 def _to_composed_result(394 result: ModelResponse | AIMessage | ExtendedModelResponse | _ComposedExtendedModelResponse,395 extra_commands: list[Command[Any]] | None = None,396 ) -> _ComposedExtendedModelResponse:397 """Normalize any handler result to _ComposedExtendedModelResponse."""398 commands: list[Command[Any]] = list(extra_commands or [])399 if isinstance(result, _ComposedExtendedModelResponse):400 commands.extend(result.commands)401 model_response = result.model_response402 elif isinstance(result, ExtendedModelResponse):403 model_response = result.model_response404 if result.command is not None:405 commands.append(result.command)406 else:407 model_response = _normalize_to_model_response(result)408409 return _ComposedExtendedModelResponse(model_response=model_response, commands=commands)410411 if len(handlers) == 1:412 single_handler = handlers[0]413414 async def normalized_single(415 request: ModelRequest[ContextT],416 handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse]],417 ) -> _ComposedExtendedModelResponse:418 return _to_composed_result(await single_handler(request, handler))419420 return normalized_single421422 def compose_two(423 outer: _AsyncModelCallHandler[ContextT] | _ComposedAsyncModelCallHandler[ContextT],424 inner: _AsyncModelCallHandler[ContextT] | _ComposedAsyncModelCallHandler[ContextT],425 ) -> _ComposedAsyncModelCallHandler[ContextT]:426 """Compose two async handlers where outer wraps inner."""427428 async def composed(429 request: ModelRequest[ContextT],430 handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse]],431 ) -> _ComposedExtendedModelResponse:432 # Closure variable to capture inner's commands before normalizing433 accumulated_commands: list[Command[Any]] = []434435 async def inner_handler(req: ModelRequest[ContextT]) -> ModelResponse:436 # Clear on each call for retry safety437 accumulated_commands.clear()438 inner_result = await inner(req, handler)439 if isinstance(inner_result, _ComposedExtendedModelResponse):440 accumulated_commands.extend(inner_result.commands)441 return inner_result.model_response442 if isinstance(inner_result, ExtendedModelResponse):443 if inner_result.command is not None:444 accumulated_commands.append(inner_result.command)445 return inner_result.model_response446 return _normalize_to_model_response(inner_result)447448 outer_result = await outer(request, inner_handler)449 return _to_composed_result(450 outer_result,451 extra_commands=accumulated_commands or None,452 )453454 return composed455456 # Compose right-to-left: outer(inner(innermost(handler)))457 composed_handler = compose_two(handlers[-2], handlers[-1])458 for h in reversed(handlers[:-2]):459 composed_handler = compose_two(h, composed_handler)460461 return composed_handler462463464@functools.lru_cache(maxsize=100)465def _get_schema_type_hints(schema: type) -> dict[str, Any]:466 """Return cached type hints for a schema."""467 return get_type_hints(schema, include_extras=True)468469470def _resolve_schemas(schemas: list[type]) -> tuple[type, type, type]:471 """Resolve state, input, and output schemas for the given schemas.472473 Schemas are merged in list order; later entries override earlier ones when the474 same field is declared by multiple schemas. Duplicates are harmless — a type475 that appears more than once is processed at its last position.476 """477 schema_hints: dict[type, dict[str, Any]] = {}478 for schema in schemas:479 # Reinsert duplicates so dict iteration reflects their final position.480 schema_hints.pop(schema, None)481 schema_hints[schema] = _get_schema_type_hints(schema)482 return (483 _resolve_schema(schema_hints, "StateSchema", None),484 _resolve_schema(schema_hints, "InputSchema", "input"),485 _resolve_schema(schema_hints, "OutputSchema", "output"),486 )487488489def _resolve_schema(490 schema_hints: dict[type, dict[str, Any]],491 schema_name: str,492 omit_flag: str | None = None,493) -> type:494 """Resolve schema by merging schemas and optionally respecting `OmitFromSchema` annotations.495496 Args:497 schema_hints: Resolved schema annotations to merge498 schema_name: Name for the generated `TypedDict`499 omit_flag: If specified, omit fields with this flag set (`'input'` or500 `'output'`)501502 Returns:503 Merged schema as `TypedDict`504 """505 all_annotations = {}506507 for hints in schema_hints.values():508 for field_name, field_type in hints.items():509 should_omit = False510511 if omit_flag:512 metadata = _extract_metadata(field_type)513 for meta in metadata:514 if isinstance(meta, OmitFromSchema) and getattr(meta, omit_flag) is True:515 should_omit = True516 break517518 if not should_omit:519 all_annotations[field_name] = field_type520521 # `TypedDict` dynamically creates a class, but type checkers don't infer that522 # the runtime result satisfies this function's `type` return contract.523 return cast("type", TypedDict(schema_name, all_annotations)) # type: ignore[operator]524525526def _extract_metadata(type_: type) -> list[Any]:527 """Extract metadata from a field type, handling `Required`/`NotRequired` and `Annotated` wrappers.""" # noqa: E501528 # Handle Required[Annotated[...]] or NotRequired[Annotated[...]]529 if get_origin(type_) in {Required, NotRequired}:530 inner_type = get_args(type_)[0]531 if get_origin(inner_type) is Annotated:532 return list(get_args(inner_type)[1:])533534 # Handle direct Annotated[...]535 elif get_origin(type_) is Annotated:536 return list(get_args(type_)[1:])537538 return []539540541def _get_can_jump_to(middleware: AgentMiddleware[Any, Any], hook_name: str) -> list[JumpTo]:542 """Get the `can_jump_to` list from either sync or async hook methods.543544 Args:545 middleware: The middleware instance to inspect.546 hook_name: The name of the hook (`'before_model'` or `'after_model'`).547548 Returns:549 List of jump destinations, or empty list if not configured.550 """551 # Get the base class method for comparison552 base_sync_method = getattr(AgentMiddleware, hook_name, None)553 base_async_method = getattr(AgentMiddleware, f"a{hook_name}", None)554555 # Try sync method first - only if it's overridden from base class556 sync_method = getattr(middleware.__class__, hook_name, None)557 if (558 sync_method559 and sync_method is not base_sync_method560 and hasattr(sync_method, "__can_jump_to__")561 ):562 # `hasattr` proves the metadata exists at runtime, but not its value type.563 return cast("list[JumpTo]", sync_method.__can_jump_to__)564565 # Try async method - only if it's overridden from base class566 async_method = getattr(middleware.__class__, f"a{hook_name}", None)567 if (568 async_method569 and async_method is not base_async_method570 and hasattr(async_method, "__can_jump_to__")571 ):572 # `hasattr` proves the metadata exists at runtime, but not its value type.573 return cast("list[JumpTo]", async_method.__can_jump_to__)574575 return []576577578def _supports_provider_strategy(579 model: str | BaseChatModel, tools: list[BaseTool | dict[str, Any]] | None = None580) -> bool:581 """Check if a model supports provider-specific structured output.582583 Args:584 model: Model name string or `BaseChatModel` instance.585 tools: Optional list of tools provided to the agent.586587 Needed because some models don't support structured output together with tool calling.588589 Returns:590 `True` if the model supports provider-specific structured output, `False` otherwise.591 """592 model_name: str | None = None593 if isinstance(model, str):594 model_name = model595 elif isinstance(model, BaseChatModel):596 model_name = (597 getattr(model, "model_name", None)598 or getattr(model, "model", None)599 or getattr(model, "model_id", "")600 )601 model_profile = model.profile602 if (603 model_profile is not None604 and model_profile.get("structured_output")605 # We make an exception for Gemini < 3-series models, which currently do not support606 # simultaneous tool use with structured output; 3-series can.607 and not (608 tools609 and isinstance(model_name, str)610 and "gemini" in model_name.lower()611 and "gemini-3" not in model_name.lower()612 )613 ):614 return True615616 return (617 any(618 re.search(pattern, model_name.lower())619 for pattern in FALLBACK_MODELS_WITH_STRUCTURED_OUTPUT620 )621 if model_name622 else False623 )624625626def _is_openai_compatible_model(model: BaseChatModel) -> bool:627 """Check if a model inherits from `BaseChatOpenAI`.628629 Used to redundantly set `strict=True` on tools when `response_format` is630 provided, as older versions of `langchain-openai` do not auto-set it.631 Covers `ChatOpenAI`, `ChatDeepSeek`, `ChatXAI`, etc.632633 Args:634 model: The chat model to check.635636 Returns:637 `True` if the model inherits from `BaseChatOpenAI`, `False` otherwise.638 """639 try:640 base_chat_openai = importlib.import_module("langchain_openai.chat_models.base")641 except ImportError:642 return False643 return isinstance(model, base_chat_openai.BaseChatOpenAI)644645646def _handle_structured_output_error(647 exception: Exception,648 response_format: ResponseFormat[Any],649) -> tuple[bool, str]:650 """Handle structured output error.651652 Returns `(should_retry, retry_tool_message)`.653 """654 if not isinstance(response_format, ToolStrategy):655 return False, ""656657 handle_errors = response_format.handle_errors658659 if handle_errors is False:660 return False, ""661 if handle_errors is True:662 return True, STRUCTURED_OUTPUT_ERROR_TEMPLATE.format(error=str(exception))663 if isinstance(handle_errors, str):664 return True, handle_errors665 if isinstance(handle_errors, type):666 if issubclass(handle_errors, Exception) and isinstance(exception, handle_errors):667 return True, STRUCTURED_OUTPUT_ERROR_TEMPLATE.format(error=str(exception))668 return False, ""669 if isinstance(handle_errors, tuple):670 if any(isinstance(exception, exc_type) for exc_type in handle_errors):671 return True, STRUCTURED_OUTPUT_ERROR_TEMPLATE.format(error=str(exception))672 return False, ""673 return True, handle_errors(exception)674675676def _invalid_tool_call_message(tool_call: InvalidToolCall) -> ToolMessage | None:677 tool_call_id = tool_call.get("id")678 if tool_call_id is None:679 return None680 name = tool_call.get("name") or "unknown"681 return ToolMessage(682 content=(683 f"Tool call {name} with id {tool_call_id} could not be executed - "684 "arguments were malformed or truncated."685 ),686 name=name,687 tool_call_id=tool_call_id,688 status="error",689 )690691692def _patch_invalid_tool_calls(messages: Sequence[AnyMessage]) -> list[AnyMessage]:693 answered_ids = {694 message.tool_call_id for message in messages if isinstance(message, ToolMessage)695 }696 patched_messages: list[AnyMessage] = []697 for message in messages:698 patched_messages.append(message)699 if not isinstance(message, AIMessage):700 continue701 for tool_call in message.invalid_tool_calls:702 if tool_call.get("id") in answered_ids:703 continue704 if tool_message := _invalid_tool_call_message(tool_call):705 patched_messages.append(tool_message)706 answered_ids.add(tool_message.tool_call_id)707 return patched_messages708709710def _chain_tool_call_wrappers(711 wrappers: Sequence[ToolCallWrapper],712) -> ToolCallWrapper | None:713 """Compose wrappers into middleware stack (first = outermost).714715 Args:716 wrappers: Wrappers in middleware order.717718 Returns:719 Composed wrapper, or `None` if empty.720721 Example:722 ```python723 wrapper = _chain_tool_call_wrappers([auth, cache, retry])724 # Request flows: auth -> cache -> retry -> tool725 # Response flows: tool -> retry -> cache -> auth726 ```727 """728 if not wrappers:729 return None730731 if len(wrappers) == 1:732 return wrappers[0]733734 def compose_two(outer: ToolCallWrapper, inner: ToolCallWrapper) -> ToolCallWrapper:735 """Compose two wrappers where outer wraps inner."""736737 def composed(738 request: ToolCallRequest,739 execute: Callable[[ToolCallRequest], ToolMessage | Command[Any]],740 ) -> ToolMessage | Command[Any]:741 # Create a callable that invokes inner with the original execute742 def call_inner(req: ToolCallRequest) -> ToolMessage | Command[Any]:743 return inner(req, execute)744745 # Outer can call call_inner multiple times746 return outer(request, call_inner)747748 return composed749750 # Chain all wrappers: first -> second -> ... -> last751 result = wrappers[-1]752 for wrapper in reversed(wrappers[:-1]):753 result = compose_two(wrapper, result)754755 return result756757758def _chain_async_tool_call_wrappers(759 wrappers: Sequence[760 Callable[761 [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]],762 Awaitable[ToolMessage | Command[Any]],763 ]764 ],765) -> (766 Callable[767 [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]],768 Awaitable[ToolMessage | Command[Any]],769 ]770 | None771):772 """Compose async wrappers into middleware stack (first = outermost).773774 Args:775 wrappers: Async wrappers in middleware order.776777 Returns:778 Composed async wrapper, or `None` if empty.779 """780 if not wrappers:781 return None782783 if len(wrappers) == 1:784 return wrappers[0]785786 def compose_two(787 outer: Callable[788 [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]],789 Awaitable[ToolMessage | Command[Any]],790 ],791 inner: Callable[792 [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]],793 Awaitable[ToolMessage | Command[Any]],794 ],795 ) -> Callable[796 [ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]],797 Awaitable[ToolMessage | Command[Any]],798 ]:799 """Compose two async wrappers where outer wraps inner."""800801 async def composed(802 request: ToolCallRequest,803 execute: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],804 ) -> ToolMessage | Command[Any]:805 # Create an async callable that invokes inner with the original execute806 async def call_inner(req: ToolCallRequest) -> ToolMessage | Command[Any]:807 return await inner(req, execute)808809 # Outer can call call_inner multiple times810 return await outer(request, call_inner)811812 return composed813814 # Chain all wrappers: first -> second -> ... -> last815 result = wrappers[-1]816 for wrapper in reversed(wrappers[:-1]):817 result = compose_two(wrapper, result)818819 return result820821822# No `response_format`: there is no structured output, so `ResponseT` resolves to `Any`.823@overload824def create_agent(825 model: str | BaseChatModel,826 tools: Sequence[BaseTool | Callable[..., Any] | dict[str, Any]] | None = None,827 *,828 system_prompt: str | SystemMessage | None = None,829 middleware: Sequence[AgentMiddleware[StateT_co, ContextT]] = (),830 response_format: None = None,831 state_schema: None = None,832 context_schema: type[ContextT] | None = None,833 checkpointer: Checkpointer | None = None,834 store: BaseStore | None = None,835 interrupt_before: list[str] | None = None,836 interrupt_after: list[str] | None = None,837 debug: bool = False,838 name: str | None = None,839 cache: BaseCache[Any] | None = None,840 transformers: Sequence[TransformerFactory] | None = None,841) -> CompiledStateGraph[AgentState[Any], ContextT, InputAgentState, OutputAgentState[Any]]: ...842843844# Raw-dict `response_format`: structured output is an untyped `dict[str, Any]`.845@overload846def create_agent(847 model: str | BaseChatModel,848 tools: Sequence[BaseTool | Callable[..., Any] | dict[str, Any]] | None = None,849 *,850 system_prompt: str | SystemMessage | None = None,851 middleware: Sequence[AgentMiddleware[StateT_co, ContextT]] = (),852 response_format: dict[str, Any],853 state_schema: type[AgentState[dict[str, Any]]] | None = None,854 context_schema: type[ContextT] | None = None,855 checkpointer: Checkpointer | None = None,856 store: BaseStore | None = None,857 interrupt_before: list[str] | None = None,858 interrupt_after: list[str] | None = None,859 debug: bool = False,860 name: str | None = None,861 cache: BaseCache[Any] | None = None,862 transformers: Sequence[TransformerFactory] | None = None,863) -> CompiledStateGraph[864 AgentState[dict[str, Any]], ContextT, InputAgentState, OutputAgentState[dict[str, Any]]865]: ...866867868# Schema-typed `response_format`: `ResponseT` is inferred from the schema/type.869@overload870def create_agent(871 model: str | BaseChatModel,872 tools: Sequence[BaseTool | Callable[..., Any] | dict[str, Any]] | None = None,873 *,874 system_prompt: str | SystemMessage | None = None,875 middleware: Sequence[AgentMiddleware[StateT_co, ContextT]] = (),876 response_format: ResponseFormat[ResponseT] | type[ResponseT] | None = None,877 state_schema: type[AgentState[ResponseT]] | None = None,878 context_schema: type[ContextT] | None = None,879 checkpointer: Checkpointer | None = None,880 store: BaseStore | None = None,881 interrupt_before: list[str] | None = None,882 interrupt_after: list[str] | None = None,883 debug: bool = False,884 name: str | None = None,885 cache: BaseCache[Any] | None = None,886 transformers: Sequence[TransformerFactory] | None = None,887) -> CompiledStateGraph[888 AgentState[ResponseT], ContextT, InputAgentState, OutputAgentState[ResponseT]889]: ...890891892def create_agent(893 model: str | BaseChatModel,894 tools: Sequence[BaseTool | Callable[..., Any] | dict[str, Any]] | None = None,895 *,896 system_prompt: str | SystemMessage | None = None,897 middleware: Sequence[AgentMiddleware[StateT_co, ContextT]] = (),898 response_format: ResponseFormat[ResponseT] | type[ResponseT] | dict[str, Any] | None = None,899 state_schema: type[AgentState[ResponseT]] | None = None,900 context_schema: type[ContextT] | None = None,901 checkpointer: Checkpointer | None = None,902 store: BaseStore | None = None,903 interrupt_before: list[str] | None = None,904 interrupt_after: list[str] | None = None,905 debug: bool = False,906 name: str | None = None,907 cache: BaseCache[Any] | None = None,908 transformers: Sequence[TransformerFactory] | None = None,909) -> CompiledStateGraph[910 AgentState[ResponseT], ContextT, InputAgentState, OutputAgentState[ResponseT]911]:912 """Creates an agent graph that calls tools in a loop until a stopping condition is met.913914 For more details on using `create_agent`,915 visit the [Agents](https://docs.langchain.com/oss/python/langchain/agents) docs.916917 Args:918 model: The language model for the agent.919920 Can be a string identifier (e.g., `"openai:gpt-5.5"`) or a direct chat model921 instance (e.g., [`ChatOpenAI`][langchain_openai.ChatOpenAI] or other another922 [LangChain chat model](https://docs.langchain.com/oss/python/integrations/chat)).923924 For a full list of supported model strings, see925 [`init_chat_model`][langchain.chat_models.init_chat_model(model_provider)].926927 !!! tip ""928929 See the [Models](https://docs.langchain.com/oss/python/langchain/models)930 docs for more information.931 tools: A list of tools, `dict`, or `Callable`.932933 If `None` or an empty list, the agent will consist of a model node without a934 tool calling loop.935936937 !!! tip ""938939 See the [Tools](https://docs.langchain.com/oss/python/langchain/tools)940 docs for more information.941 system_prompt: An optional system prompt for the LLM.942943 Can be a `str` (which will be converted to a `SystemMessage`) or a944 `SystemMessage` instance directly. The system message is added to the945 beginning of the message list when calling the model.946 middleware: A sequence of middleware instances to apply to the agent.947948 Middleware can intercept and modify agent behavior at various stages.949950 !!! tip ""951952 See the [Middleware](https://docs.langchain.com/oss/python/langchain/middleware)953 docs for more information.954 response_format: An optional configuration for structured responses.955956 Can be a `ToolStrategy`, `ProviderStrategy`, or a Pydantic model class.957958 If provided, the agent will handle structured output during the959 conversation flow.960961 Raw schemas will be wrapped in an appropriate strategy based on model962 capabilities.963964 !!! tip ""965966 See the [Structured output](https://docs.langchain.com/oss/python/langchain/structured-output)967 docs for more information.968 state_schema: An optional `TypedDict` schema that extends `AgentState`.969970 When provided, this schema is used instead of `AgentState` as the base971 schema for merging with middleware state schemas. This allows users to972 add custom state fields without needing to create custom middleware.973974 Generally, it's recommended to use `state_schema` extensions via middleware975 to keep relevant extensions scoped to corresponding hooks / tools.976 context_schema: An optional schema for runtime context.977 checkpointer: An optional checkpoint saver object.978979 Used for persisting the state of the graph (e.g., as chat memory) for a980 single thread (e.g., a single conversation).981 store: An optional store object.982983 Used for persisting data across multiple threads (e.g., multiple984 conversations / users).985 interrupt_before: An optional list of node names to interrupt before.986987 Useful if you want to add a user confirmation or other interrupt988 before taking an action.989 interrupt_after: An optional list of node names to interrupt after.990991 Useful if you want to return directly or run additional processing992 on an output.993 debug: Whether to enable verbose logging for graph execution.994995 When enabled, prints detailed information about each node execution, state996 updates, and transitions during agent runtime. Useful for debugging997 middleware behavior and understanding agent execution flow.998 name: An optional name for the `CompiledStateGraph`.9991000 This name will be automatically used when adding the agent graph to1001 another graph as a subgraph node - particularly useful for building1002 multi-agent systems.1003 cache: An optional `BaseCache` instance to enable caching of graph execution.1004 transformers: Optional sequence of scope-aware `StreamTransformer`1005 factories to register on the compiled graph in addition to1006 the agent defaults. Each factory is invoked as `factory(scope)`1007 so every invocation receives a fresh instance. The final order1008 on the compiled graph is: `ToolCallTransformer`, then any1009 factories declared by middleware via1010 `AgentMiddleware.transformers`, then any factories supplied here.10111012 Returns:1013 A compiled `StateGraph` that can be used for chat interactions.10141015 Raises:1016 AssertionError: If duplicate middleware instances are provided.10171018 The agent node calls the language model with the messages list (after applying1019 the system prompt). If the resulting [`AIMessage`][langchain.messages.AIMessage]1020 contains `tool_calls`, the graph will then call the tools. The tools node executes1021 the tools and adds the responses to the messages list as1022 [`ToolMessage`][langchain.messages.ToolMessage] objects. The agent node then calls1023 the language model again. The process repeats until no more `tool_calls` are present1024 in the response. The agent then returns the full list of messages.10251026 Example:1027 ```python1028 from langchain.agents import create_agent102910301031 def check_weather(location: str) -> str:1032 '''Return the weather forecast for the specified location.'''1033 return f"It's always sunny in {location}"103410351036 graph = create_agent(1037 model="anthropic:claude-sonnet-4-5-20250929",1038 tools=[check_weather],1039 system_prompt="You are a helpful assistant",1040 )1041 inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}1042 for chunk in graph.stream(inputs, stream_mode="updates"):1043 print(chunk)1044 ```1045 """1046 # init chat model1047 if isinstance(model, str):1048 model = init_chat_model(model)10491050 # Convert system_prompt to SystemMessage if needed1051 system_message: SystemMessage | None = None1052 if system_prompt is not None:1053 if isinstance(system_prompt, SystemMessage):1054 system_message = system_prompt1055 else:1056 system_message = SystemMessage(content=system_prompt)10571058 # Handle tools being None or empty1059 if tools is None:1060 tools = []10611062 # Convert response format and setup structured output tools1063 # Raw schemas are wrapped in AutoStrategy to preserve auto-detection intent.1064 # AutoStrategy is converted to ToolStrategy upfront to calculate tools during agent creation,1065 # but may be replaced with ProviderStrategy later based on model capabilities.1066 initial_response_format: ToolStrategy[Any] | ProviderStrategy[Any] | AutoStrategy[Any] | None1067 if response_format is None:1068 initial_response_format = None1069 elif isinstance(response_format, (ToolStrategy, ProviderStrategy, AutoStrategy)):1070 # Explicit Tool/Provider strategy, or AutoStrategy for later capability detection1071 initial_response_format = response_format1072 else:1073 # Raw schema - wrap in AutoStrategy to enable auto-detection1074 initial_response_format = AutoStrategy(schema=response_format)10751076 # For AutoStrategy, convert to ToolStrategy to setup tools upfront1077 # (may be replaced with ProviderStrategy later based on model)1078 tool_strategy_for_setup: ToolStrategy[Any] | None = None1079 if isinstance(initial_response_format, AutoStrategy):1080 tool_strategy_for_setup = ToolStrategy(schema=initial_response_format.schema)1081 elif isinstance(initial_response_format, ToolStrategy):1082 tool_strategy_for_setup = initial_response_format10831084 structured_output_tools: dict[str, OutputToolBinding[Any]] = {}1085 if tool_strategy_for_setup:1086 for response_schema in tool_strategy_for_setup.schema_specs:1087 structured_tool_info = OutputToolBinding.from_schema_spec(response_schema)1088 structured_output_tools[structured_tool_info.tool.name] = structured_tool_info1089 middleware_tools = [t for m in middleware for t in getattr(m, "tools", [])]10901091 # Collect middleware with wrap_tool_call or awrap_tool_call hooks1092 # Include middleware with either implementation to ensure NotImplementedError is raised1093 # when middleware doesn't support the execution path1094 middleware_w_wrap_tool_call = [1095 m1096 for m in middleware1097 if m.__class__.wrap_tool_call is not AgentMiddleware.wrap_tool_call1098 or m.__class__.awrap_tool_call is not AgentMiddleware.awrap_tool_call1099 ]11001101 # Chain all wrap_tool_call handlers into a single composed handler1102 wrap_tool_call_wrapper = None1103 if middleware_w_wrap_tool_call:1104 wrappers = [1105 traceable(name=f"{m.name}.wrap_tool_call", **_wrap_trace_kwargs(m))(m.wrap_tool_call)1106 for m in middleware_w_wrap_tool_call1107 ]1108 wrap_tool_call_wrapper = _chain_tool_call_wrappers(wrappers)11091110 # Collect middleware with awrap_tool_call or wrap_tool_call hooks1111 # Include middleware with either implementation to ensure NotImplementedError is raised1112 # when middleware doesn't support the execution path1113 middleware_w_awrap_tool_call = [1114 m1115 for m in middleware1116 if m.__class__.awrap_tool_call is not AgentMiddleware.awrap_tool_call1117 or m.__class__.wrap_tool_call is not AgentMiddleware.wrap_tool_call1118 ]11191120 # Chain all awrap_tool_call handlers into a single composed async handler1121 awrap_tool_call_wrapper = None1122 if middleware_w_awrap_tool_call:1123 async_wrappers = [1124 traceable(name=f"{m.name}.awrap_tool_call", **_wrap_trace_kwargs(m))(m.awrap_tool_call)1125 for m in middleware_w_awrap_tool_call1126 ]1127 awrap_tool_call_wrapper = _chain_async_tool_call_wrappers(async_wrappers)11281129 # Setup tools1130 tool_node: ToolNode | None = None1131 # Extract built-in provider tools (dict format) and regular tools (BaseTool/callables)1132 built_in_tools = [t for t in tools if isinstance(t, dict)]1133 regular_tools = [t for t in tools if not isinstance(t, dict)]11341135 # Tools that require client-side execution (must be in ToolNode)1136 available_tools = middleware_tools + regular_tools11371138 # Create ToolNode if we have client-side tools OR if middleware defines wrap_tool_call1139 # (which may handle dynamically registered tools)1140 tool_node = (1141 ToolNode(1142 tools=available_tools,1143 wrap_tool_call=wrap_tool_call_wrapper,1144 awrap_tool_call=awrap_tool_call_wrapper,1145 )1146 if available_tools or wrap_tool_call_wrapper or awrap_tool_call_wrapper1147 else None1148 )11491150 # Default tools for ModelRequest initialization1151 # Use converted BaseTool instances from ToolNode (not raw callables)1152 # Include built-ins and converted tools (can be changed dynamically by middleware)1153 # Structured tools are NOT included - they're added dynamically based on response_format1154 if tool_node:1155 default_tools = list(tool_node.tools_by_name.values()) + built_in_tools1156 else:1157 default_tools = list(built_in_tools)11581159 # validate middleware1160 if len({m.name for m in middleware}) != len(middleware):1161 msg = "Please remove duplicate middleware instances."1162 raise AssertionError(msg)1163 middleware_w_before_agent = [1164 m1165 for m in middleware1166 if m.__class__.before_agent is not AgentMiddleware.before_agent1167 or m.__class__.abefore_agent is not AgentMiddleware.abefore_agent1168 ]1169 middleware_w_before_model = [1170 m1171 for m in middleware1172 if m.__class__.before_model is not AgentMiddleware.before_model1173 or m.__class__.abefore_model is not AgentMiddleware.abefore_model1174 ]1175 middleware_w_after_model = [1176 m1177 for m in middleware1178 if m.__class__.after_model is not AgentMiddleware.after_model1179 or m.__class__.aafter_model is not AgentMiddleware.aafter_model1180 ]1181 middleware_w_after_agent = [1182 m1183 for m in middleware1184 if m.__class__.after_agent is not AgentMiddleware.after_agent1185 or m.__class__.aafter_agent is not AgentMiddleware.aafter_agent1186 ]1187 # Collect middleware with wrap_model_call or awrap_model_call hooks1188 # Include middleware with either implementation to ensure NotImplementedError is raised1189 # when middleware doesn't support the execution path1190 middleware_w_wrap_model_call = [1191 m1192 for m in middleware1193 if m.__class__.wrap_model_call is not AgentMiddleware.wrap_model_call1194 or m.__class__.awrap_model_call is not AgentMiddleware.awrap_model_call1195 ]1196 # Collect middleware with awrap_model_call or wrap_model_call hooks1197 # Include middleware with either implementation to ensure NotImplementedError is raised1198 # when middleware doesn't support the execution path1199 middleware_w_awrap_model_call = [1200 m1201 for m in middleware1202 if m.__class__.awrap_model_call is not AgentMiddleware.awrap_model_call1203 or m.__class__.wrap_model_call is not AgentMiddleware.wrap_model_call1204 ]12051206 # Compose wrap_model_call handlers into a single middleware stack (sync)1207 wrap_model_call_handler = None1208 if middleware_w_wrap_model_call:1209 sync_handlers = [1210 traceable(name=f"{m.name}.wrap_model_call", **_wrap_trace_kwargs(m))(m.wrap_model_call)1211 for m in middleware_w_wrap_model_call1212 ]1213 wrap_model_call_handler = _chain_model_call_handlers(sync_handlers)12141215 # Compose awrap_model_call handlers into a single middleware stack (async)1216 awrap_model_call_handler = None1217 if middleware_w_awrap_model_call:1218 async_handlers = [1219 traceable(name=f"{m.name}.awrap_model_call", **_wrap_trace_kwargs(m))(1220 m.awrap_model_call1221 )1222 for m in middleware_w_awrap_model_call1223 ]1224 awrap_model_call_handler = _chain_async_model_call_handlers(async_handlers)12251226 base_state = state_schema if state_schema is not None else AgentState1227 # Build an ordered list: middleware schemas first (in registration order),1228 # base_state last so it wins any field conflict. This lets the caller's1229 # explicit state_schema override middleware annotations — e.g. passing1230 # a DeltaChannel-annotated schema wins over BinaryOperatorAggregate from1231 # AgentState without requiring a post-compilation patch.1232 state_schemas: list[type] = [*(m.state_schema for m in middleware), base_state]12331234 resolved_state_schema, input_schema, output_schema = _resolve_schemas(state_schemas)12351236 # create graph, add nodes1237 graph: StateGraph[1238 AgentState[ResponseT], ContextT, InputAgentState, OutputAgentState[ResponseT]1239 ] = StateGraph(1240 state_schema=resolved_state_schema,1241 input_schema=input_schema,1242 output_schema=output_schema,1243 context_schema=context_schema,1244 )12451246 def _handle_model_output(1247 output: AIMessage, effective_response_format: ResponseFormat[Any] | None1248 ) -> dict[str, Any]:1249 """Handle model output including structured responses.12501251 Args:1252 output: The AI message output from the model.1253 effective_response_format: The actual strategy used (may differ from initial1254 if auto-detected).1255 """1256 # Handle structured output with provider strategy1257 if isinstance(effective_response_format, ProviderStrategy):1258 if not output.tool_calls:1259 provider_strategy_binding = ProviderStrategyBinding.from_schema_spec(1260 effective_response_format.schema_spec1261 )1262 try:1263 structured_response = provider_strategy_binding.parse(output)1264 except Exception as exc:1265 schema_name = getattr(1266 effective_response_format.schema_spec.schema, "__name__", "response_format"1267 )1268 validation_error = StructuredOutputValidationError(schema_name, exc, output)1269 raise validation_error from exc1270 else:1271 return {"messages": [output], "structured_response": structured_response}1272 return {"messages": [output]}12731274 # Handle structured output with tool strategy1275 if (1276 isinstance(effective_response_format, ToolStrategy)1277 and isinstance(output, AIMessage)1278 and output.tool_calls1279 ):1280 structured_tool_calls = [1281 tc for tc in output.tool_calls if tc["name"] in structured_output_tools1282 ]12831284 if structured_tool_calls:1285 exception: StructuredOutputError | None = None1286 if len(structured_tool_calls) > 1:1287 # Handle multiple structured outputs error1288 tool_names = [tc["name"] for tc in structured_tool_calls]1289 exception = MultipleStructuredOutputsError(tool_names, output)1290 should_retry, error_message = _handle_structured_output_error(1291 exception, effective_response_format1292 )1293 if not should_retry:1294 raise exception12951296 # Add error messages and retry1297 tool_messages = [1298 ToolMessage(1299 content=error_message,1300 tool_call_id=tc["id"],1301 name=tc["name"],1302 )1303 for tc in structured_tool_calls1304 ]1305 return {"messages": [output, *tool_messages]}13061307 # Handle single structured output1308 tool_call = structured_tool_calls[0]1309 try:1310 structured_tool_binding = structured_output_tools[tool_call["name"]]1311 structured_response = structured_tool_binding.parse(tool_call["args"])13121313 tool_message_content = (1314 effective_response_format.tool_message_content1315 or f"Returning structured response: {structured_response}"1316 )13171318 return {1319 "messages": [1320 output,1321 ToolMessage(1322 content=tool_message_content,1323 tool_call_id=tool_call["id"],1324 name=tool_call["name"],1325 ),1326 ],1327 "structured_response": structured_response,1328 }1329 except Exception as exc:1330 exception = StructuredOutputValidationError(tool_call["name"], exc, output)1331 should_retry, error_message = _handle_structured_output_error(1332 exception, effective_response_format1333 )1334 if not should_retry:1335 raise exception from exc13361337 return {1338 "messages": [1339 output,1340 ToolMessage(1341 content=error_message,1342 tool_call_id=tool_call["id"],1343 name=tool_call["name"],1344 ),1345 ],1346 }13471348 return {"messages": [output]}13491350 def _get_bound_model(1351 request: ModelRequest[ContextT],1352 ) -> tuple[Runnable[Any, Any], ResponseFormat[Any] | None]:1353 """Get the model with appropriate tool bindings.13541355 Performs auto-detection of strategy if needed based on model capabilities.13561357 Args:1358 request: The model request containing model, tools, and response format.13591360 Returns:1361 Tuple of `(bound_model, effective_response_format)` where1362 `effective_response_format` is the actual strategy used (may differ from1363 initial if auto-detected).13641365 Raises:1366 ValueError: If middleware returned unknown client-side tool names.1367 ValueError: If `ToolStrategy` specifies tools not declared upfront.1368 """1369 # Validate ONLY client-side tools that need to exist in tool_node1370 # Skip validation when wrap_tool_call is defined, as middleware may handle1371 # dynamic tools that are added at runtime via wrap_model_call1372 has_wrap_tool_call = wrap_tool_call_wrapper or awrap_tool_call_wrapper13731374 # Build map of available client-side tools from the ToolNode1375 # (which has already converted callables)1376 available_tools_by_name = {}1377 if tool_node:1378 available_tools_by_name = tool_node.tools_by_name.copy()13791380 # Check if any requested tools are unknown CLIENT-SIDE tools1381 # Only validate if wrap_tool_call is NOT defined (no dynamic tool handling)1382 if not has_wrap_tool_call:1383 unknown_tool_names = []1384 for t in request.tools:1385 # Only validate BaseTool instances (skip built-in dict tools)1386 if isinstance(t, dict):1387 continue1388 if isinstance(t, BaseTool) and t.name not in available_tools_by_name:1389 unknown_tool_names.append(t.name)13901391 if unknown_tool_names:1392 available_tool_names = sorted(available_tools_by_name.keys())1393 msg = DYNAMIC_TOOL_ERROR_TEMPLATE.format(1394 unknown_tool_names=unknown_tool_names,1395 available_tool_names=available_tool_names,1396 )1397 raise ValueError(msg)13981399 # Normalize raw schemas to AutoStrategy1400 # (handles middleware override with raw Pydantic classes)1401 response_format: ResponseFormat[Any] | Any | None = request.response_format1402 if response_format is not None and not isinstance(1403 response_format, (AutoStrategy, ToolStrategy, ProviderStrategy)1404 ):1405 response_format = AutoStrategy(schema=response_format)14061407 # Determine effective response format (auto-detect if needed)1408 effective_response_format: ResponseFormat[Any] | None1409 if isinstance(response_format, AutoStrategy):1410 # User provided raw schema via AutoStrategy - auto-detect best strategy based on model1411 if _supports_provider_strategy(request.model, tools=request.tools):1412 # Model supports provider strategy - use it1413 effective_response_format = ProviderStrategy(schema=response_format.schema)1414 elif response_format is initial_response_format and tool_strategy_for_setup is not None:1415 # Model doesn't support provider strategy - use ToolStrategy1416 # Reuse the strategy from setup if possible to preserve tool names1417 effective_response_format = tool_strategy_for_setup1418 else:1419 effective_response_format = ToolStrategy(schema=response_format.schema)1420 else:1421 # User explicitly specified a strategy - preserve it1422 effective_response_format = response_format14231424 # Build final tools list including structured output tools1425 # request.tools now only contains BaseTool instances (converted from callables)1426 # and dicts (built-ins)1427 final_tools = list(request.tools)1428 if isinstance(effective_response_format, ToolStrategy):1429 # Add structured output tools to final tools list, narrowed to only the1430 # schemas present in the (possibly middleware-narrowed) response format.1431 # This ensures middleware that narrows a union `ToolStrategy` to a subset1432 # via `request.override()` actually restricts which structured output1433 # tools the model can choose from.1434 narrowed_tool_names = {spec.name for spec in effective_response_format.schema_specs}1435 structured_tools = [1436 info.tool1437 for name, info in structured_output_tools.items()1438 if name in narrowed_tool_names1439 ]1440 final_tools.extend(structured_tools)14411442 # Bind model based on effective response format1443 if isinstance(effective_response_format, ProviderStrategy):1444 # (Backward compatibility) Use OpenAI format structured output1445 # Redundantly set strict=True on tools for OpenAI-compatible models, as older1446 # versions of langchain-openai do not auto-set it in bind_tools.1447 kwargs = effective_response_format.to_model_kwargs()1448 bind_kwargs: dict[str, Any] = {**kwargs, **request.model_settings}1449 if _is_openai_compatible_model(request.model) and not getattr(1450 request.model, "use_responses_api", False1451 ):1452 bind_kwargs["strict"] = True1453 return (1454 request.model.bind_tools(final_tools, **bind_kwargs),1455 effective_response_format,1456 )14571458 if isinstance(effective_response_format, ToolStrategy):1459 # Current implementation requires that tools used for structured output1460 # have to be declared upfront when creating the agent as part of the1461 # response format. Middleware is allowed to change the response format1462 # to a subset of the original structured tools when using ToolStrategy,1463 # but not to add new structured tools that weren't declared upfront.1464 # Compute output binding1465 for tc in effective_response_format.schema_specs:1466 if tc.name not in structured_output_tools:1467 msg = (1468 f"ToolStrategy specifies tool '{tc.name}' "1469 "which wasn't declared in the original "1470 "response format when creating the agent."1471 )1472 raise ValueError(msg)14731474 # Force tool use if we have structured output tools1475 tool_choice = "any" if structured_output_tools else request.tool_choice1476 return (1477 request.model.bind_tools(1478 final_tools, tool_choice=tool_choice, **request.model_settings1479 ),1480 effective_response_format,1481 )14821483 # No structured output - standard model binding1484 if final_tools:1485 return (1486 request.model.bind_tools(1487 final_tools, tool_choice=request.tool_choice, **request.model_settings1488 ),1489 None,1490 )1491 return request.model.bind(**request.model_settings), None14921493 def _execute_model_sync(request: ModelRequest[ContextT]) -> ModelResponse:1494 """Execute model and return response.14951496 This is the core model execution logic wrapped by `wrap_model_call` handlers.14971498 Raises any exceptions that occur during model invocation.1499 """1500 # Get the bound model (with auto-detection if needed)1501 model_, effective_response_format = _get_bound_model(request)1502 messages = request.messages1503 if request.system_message:1504 messages = [request.system_message, *messages]15051506 output = model_.invoke(messages)1507 if name:1508 output.name = name15091510 # Handle model output to get messages and structured_response1511 handled_output = _handle_model_output(output, effective_response_format)1512 messages_list = handled_output["messages"]1513 structured_response = handled_output.get("structured_response")15141515 return ModelResponse(1516 result=messages_list,1517 structured_response=structured_response,1518 )15191520 def model_node(state: AgentState[Any], runtime: Runtime[ContextT]) -> list[Command[Any]]:1521 """Sync model request handler with sequential middleware processing."""1522 messages = _patch_invalid_tool_calls(state["messages"])1523 request = ModelRequest(1524 model=model,1525 tools=default_tools,1526 system_message=system_message,1527 response_format=initial_response_format,1528 messages=messages,1529 tool_choice=None,1530 state=state,1531 runtime=runtime,1532 )15331534 has_structured_output = initial_response_format is not None1535 if wrap_model_call_handler is None:1536 model_response = _execute_model_sync(request)1537 return _build_commands(1538 model_response,1539 has_structured_output=has_structured_output,1540 repaired_messages=messages if messages != state["messages"] else None,1541 )15421543 result = wrap_model_call_handler(request, _execute_model_sync)1544 return _build_commands(1545 result.model_response,1546 result.commands,1547 has_structured_output=has_structured_output,1548 repaired_messages=messages if messages != state["messages"] else None,1549 )15501551 async def _execute_model_async(request: ModelRequest[ContextT]) -> ModelResponse:1552 """Execute model asynchronously and return response.15531554 This is the core async model execution logic wrapped by `wrap_model_call`1555 handlers.15561557 Raises any exceptions that occur during model invocation.1558 """1559 # Get the bound model (with auto-detection if needed)1560 model_, effective_response_format = _get_bound_model(request)1561 messages = request.messages1562 if request.system_message:1563 messages = [request.system_message, *messages]15641565 output = await model_.ainvoke(messages)1566 if name:1567 output.name = name15681569 # Handle model output to get messages and structured_response1570 handled_output = _handle_model_output(output, effective_response_format)1571 messages_list = handled_output["messages"]1572 structured_response = handled_output.get("structured_response")15731574 return ModelResponse(1575 result=messages_list,1576 structured_response=structured_response,1577 )15781579 async def amodel_node(state: AgentState[Any], runtime: Runtime[ContextT]) -> list[Command[Any]]:1580 """Async model request handler with sequential middleware processing."""1581 messages = _patch_invalid_tool_calls(state["messages"])1582 request = ModelRequest(1583 model=model,1584 tools=default_tools,1585 system_message=system_message,1586 response_format=initial_response_format,1587 messages=messages,1588 tool_choice=None,1589 state=state,1590 runtime=runtime,1591 )15921593 has_structured_output = initial_response_format is not None1594 if awrap_model_call_handler is None:1595 model_response = await _execute_model_async(request)1596 return _build_commands(1597 model_response,1598 has_structured_output=has_structured_output,1599 repaired_messages=messages if messages != state["messages"] else None,1600 )16011602 result = await awrap_model_call_handler(request, _execute_model_async)1603 return _build_commands(1604 result.model_response,1605 result.commands,1606 has_structured_output=has_structured_output,1607 repaired_messages=messages if messages != state["messages"] else None,1608 )16091610 # Use sync or async based on model capabilities1611 graph.add_node("model", RunnableCallable(model_node, amodel_node, trace=False))16121613 # Only add tools node if we have tools1614 if tool_node is not None:1615 graph.add_node("tools", tool_node)16161617 # Add middleware nodes1618 for m in middleware:1619 if (1620 m.__class__.before_agent is not AgentMiddleware.before_agent1621 or m.__class__.abefore_agent is not AgentMiddleware.abefore_agent1622 ):1623 # Use RunnableCallable to support both sync and async1624 # Pass None for sync if not overridden to avoid signature conflicts1625 sync_before_agent = (1626 m.before_agent1627 if m.__class__.before_agent is not AgentMiddleware.before_agent1628 else None1629 )1630 async_before_agent = (1631 m.abefore_agent1632 if m.__class__.abefore_agent is not AgentMiddleware.abefore_agent1633 else None1634 )1635 before_agent_node = RunnableCallable(sync_before_agent, async_before_agent, trace=False)1636 graph.add_node(1637 f"{m.name}.before_agent",1638 before_agent_node,1639 input_schema=resolved_state_schema,1640 trace_policy=_node_trace_policy(m.trace_policy),1641 )16421643 if (1644 m.__class__.before_model is not AgentMiddleware.before_model1645 or m.__class__.abefore_model is not AgentMiddleware.abefore_model1646 ):1647 # Use RunnableCallable to support both sync and async1648 # Pass None for sync if not overridden to avoid signature conflicts1649 sync_before = (1650 m.before_model1651 if m.__class__.before_model is not AgentMiddleware.before_model1652 else None1653 )1654 async_before = (1655 m.abefore_model1656 if m.__class__.abefore_model is not AgentMiddleware.abefore_model1657 else None1658 )1659 before_node = RunnableCallable(sync_before, async_before, trace=False)1660 graph.add_node(1661 f"{m.name}.before_model",1662 before_node,1663 input_schema=resolved_state_schema,1664 trace_policy=_node_trace_policy(m.trace_policy),1665 )16661667 if (1668 m.__class__.after_model is not AgentMiddleware.after_model1669 or m.__class__.aafter_model is not AgentMiddleware.aafter_model1670 ):1671 # Use RunnableCallable to support both sync and async1672 # Pass None for sync if not overridden to avoid signature conflicts1673 sync_after = (1674 m.after_model1675 if m.__class__.after_model is not AgentMiddleware.after_model1676 else None1677 )1678 async_after = (1679 m.aafter_model1680 if m.__class__.aafter_model is not AgentMiddleware.aafter_model1681 else None1682 )1683 after_node = RunnableCallable(sync_after, async_after, trace=False)1684 graph.add_node(1685 f"{m.name}.after_model",1686 after_node,1687 input_schema=resolved_state_schema,1688 trace_policy=_node_trace_policy(m.trace_policy),1689 )16901691 if (1692 m.__class__.after_agent is not AgentMiddleware.after_agent1693 or m.__class__.aafter_agent is not AgentMiddleware.aafter_agent1694 ):1695 # Use RunnableCallable to support both sync and async1696 # Pass None for sync if not overridden to avoid signature conflicts1697 sync_after_agent = (1698 m.after_agent1699 if m.__class__.after_agent is not AgentMiddleware.after_agent1700 else None1701 )1702 async_after_agent = (1703 m.aafter_agent1704 if m.__class__.aafter_agent is not AgentMiddleware.aafter_agent1705 else None1706 )1707 after_agent_node = RunnableCallable(sync_after_agent, async_after_agent, trace=False)1708 graph.add_node(1709 f"{m.name}.after_agent",1710 after_agent_node,1711 input_schema=resolved_state_schema,1712 trace_policy=_node_trace_policy(m.trace_policy),1713 )17141715 # Determine the entry node (runs once at start): before_agent -> before_model -> model1716 if middleware_w_before_agent:1717 entry_node = f"{middleware_w_before_agent[0].name}.before_agent"1718 elif middleware_w_before_model:1719 entry_node = f"{middleware_w_before_model[0].name}.before_model"1720 else:1721 entry_node = "model"17221723 # Determine the loop entry node (beginning of agent loop, excludes before_agent)1724 # This is where tools will loop back to for the next iteration1725 if middleware_w_before_model:1726 loop_entry_node = f"{middleware_w_before_model[0].name}.before_model"1727 else:1728 loop_entry_node = "model"17291730 # Determine the loop exit node (end of each iteration, can run multiple times)1731 # This is after_model or model, but NOT after_agent1732 if middleware_w_after_model:1733 loop_exit_node = f"{middleware_w_after_model[0].name}.after_model"1734 else:1735 loop_exit_node = "model"17361737 # Determine the exit node (runs once at end): after_agent or END1738 if middleware_w_after_agent:1739 exit_node = f"{middleware_w_after_agent[-1].name}.after_agent"1740 else:1741 exit_node = END17421743 graph.add_edge(START, entry_node)1744 # add conditional edges only if tools exist1745 if tool_node is not None:1746 # Only include exit_node in destinations if any tool has return_direct=True1747 # or if there are structured output tools1748 tools_to_model_destinations = [loop_entry_node]1749 if (1750 any(tool.return_direct for tool in tool_node.tools_by_name.values())1751 or structured_output_tools1752 ):1753 tools_to_model_destinations.append(exit_node)17541755 graph.add_conditional_edges(1756 "tools",1757 RunnableCallable(1758 _make_tools_to_model_edge(1759 tool_node=tool_node,1760 model_destination=loop_entry_node,1761 structured_output_tools=structured_output_tools,1762 end_destination=exit_node,1763 ),1764 trace=False,1765 ),1766 tools_to_model_destinations,1767 )17681769 # Include loop_entry_node when middleware can inject synthetic tool1770 # messages, or when structured output or after-model hooks can reroute there.1771 model_to_tools_destinations = ["tools", exit_node]1772 if response_format or loop_exit_node != "model" or middleware_w_wrap_model_call:1773 model_to_tools_destinations.append(loop_entry_node)17741775 graph.add_conditional_edges(1776 loop_exit_node,1777 RunnableCallable(1778 _make_model_to_tools_edge(1779 model_destination=loop_entry_node,1780 structured_output_tools=structured_output_tools,1781 end_destination=exit_node,1782 ),1783 trace=False,1784 ),1785 model_to_tools_destinations,1786 )1787 elif len(structured_output_tools) > 0:1788 graph.add_conditional_edges(1789 loop_exit_node,1790 RunnableCallable(1791 _make_model_to_model_edge(1792 model_destination=loop_entry_node,1793 end_destination=exit_node,1794 ),1795 trace=False,1796 ),1797 [loop_entry_node, exit_node],1798 )1799 elif loop_exit_node == "model":1800 # If no tools and no after_model, go directly to exit_node1801 graph.add_edge(loop_exit_node, exit_node)1802 # No tools but we have after_model - connect after_model to exit_node1803 else:1804 _add_middleware_edge(1805 graph,1806 name=f"{middleware_w_after_model[0].name}.after_model",1807 default_destination=exit_node,1808 model_destination=loop_entry_node,1809 end_destination=exit_node,1810 can_jump_to=_get_can_jump_to(middleware_w_after_model[0], "after_model"),1811 )18121813 # Add before_agent middleware edges1814 if middleware_w_before_agent:1815 for m1, m2 in itertools.pairwise(middleware_w_before_agent):1816 _add_middleware_edge(1817 graph,1818 name=f"{m1.name}.before_agent",1819 default_destination=f"{m2.name}.before_agent",1820 model_destination=loop_entry_node,1821 end_destination=exit_node,1822 can_jump_to=_get_can_jump_to(m1, "before_agent"),1823 )1824 # Connect last before_agent to loop_entry_node (before_model or model)1825 _add_middleware_edge(1826 graph,1827 name=f"{middleware_w_before_agent[-1].name}.before_agent",1828 default_destination=loop_entry_node,1829 model_destination=loop_entry_node,1830 end_destination=exit_node,1831 can_jump_to=_get_can_jump_to(middleware_w_before_agent[-1], "before_agent"),1832 )18331834 # Add before_model middleware edges1835 if middleware_w_before_model:1836 for m1, m2 in itertools.pairwise(middleware_w_before_model):1837 _add_middleware_edge(1838 graph,1839 name=f"{m1.name}.before_model",1840 default_destination=f"{m2.name}.before_model",1841 model_destination=loop_entry_node,1842 end_destination=exit_node,1843 can_jump_to=_get_can_jump_to(m1, "before_model"),1844 )1845 # Go directly to model after the last before_model1846 _add_middleware_edge(1847 graph,1848 name=f"{middleware_w_before_model[-1].name}.before_model",1849 default_destination="model",1850 model_destination=loop_entry_node,1851 end_destination=exit_node,1852 can_jump_to=_get_can_jump_to(middleware_w_before_model[-1], "before_model"),1853 )18541855 # Add after_model middleware edges1856 if middleware_w_after_model:1857 graph.add_edge("model", f"{middleware_w_after_model[-1].name}.after_model")1858 for idx in range(len(middleware_w_after_model) - 1, 0, -1):1859 m1 = middleware_w_after_model[idx]1860 m2 = middleware_w_after_model[idx - 1]1861 _add_middleware_edge(1862 graph,1863 name=f"{m1.name}.after_model",1864 default_destination=f"{m2.name}.after_model",1865 model_destination=loop_entry_node,1866 end_destination=exit_node,1867 can_jump_to=_get_can_jump_to(m1, "after_model"),1868 )1869 # Note: Connection from after_model to after_agent/END is handled above1870 # in the conditional edges section18711872 # Add after_agent middleware edges1873 if middleware_w_after_agent:1874 # Chain after_agent middleware (runs once at the very end, before END)1875 for idx in range(len(middleware_w_after_agent) - 1, 0, -1):1876 m1 = middleware_w_after_agent[idx]1877 m2 = middleware_w_after_agent[idx - 1]1878 _add_middleware_edge(1879 graph,1880 name=f"{m1.name}.after_agent",1881 default_destination=f"{m2.name}.after_agent",1882 model_destination=loop_entry_node,1883 end_destination=exit_node,1884 can_jump_to=_get_can_jump_to(m1, "after_agent"),1885 )18861887 # Connect the last after_agent to END1888 _add_middleware_edge(1889 graph,1890 name=f"{middleware_w_after_agent[0].name}.after_agent",1891 default_destination=END,1892 model_destination=loop_entry_node,1893 end_destination=exit_node,1894 can_jump_to=_get_can_jump_to(middleware_w_after_agent[0], "after_agent"),1895 )18961897 # Set recursion limit to 9_9991898 # https://github.com/langchain-ai/langgraph/issues/73131899 config: RunnableConfig = {"recursion_limit": 9_999}1900 config["metadata"] = {"ls_integration": "langchain_create_agent"}1901 if name:1902 config["metadata"]["lc_agent_name"] = name19031904 # Middleware that makes internal model calls (e.g. `SummarizationMiddleware`)1905 # each declare `InternalCallTransformer` on their own `transformers` tuple so1906 # it's only registered when one of them is actually in use.1907 middleware_transformers = [t for m in middleware for t in getattr(m, "transformers", ())]19081909 return graph.compile(1910 checkpointer=checkpointer,1911 store=store,1912 interrupt_before=interrupt_before,1913 interrupt_after=interrupt_after,1914 debug=debug,1915 name=name,1916 cache=cache,1917 transformers=_dedupe_transformers(1918 [1919 ToolCallTransformer,1920 SubagentTransformer,1921 *middleware_transformers,1922 *(transformers or ()),1923 ]1924 ),1925 ).with_config(config)192619271928def _dedupe_transformers(1929 factories: Iterable[TransformerFactory],1930) -> list[TransformerFactory]:1931 """Order-preserving de-dup of transformer factories, by identity.19321933 `AgentMiddleware.transformers` accepts any scope-aware callable, and1934 callables aren't required to be hashable (e.g. a dataclass-based factory1935 with `__hash__ = None`), so this can't use a `set`/`dict` keyed on the1936 factories themselves. Combining several middleware that each declare the1937 same shared transformer class (e.g. `InternalCallTransformer`) would1938 otherwise register it once per middleware.19391940 Args:1941 factories: Transformer factories to de-dup, in registration order.19421943 Returns:1944 The same factories with exact repeats (by `is`) removed, order kept.1945 """1946 seen_ids: set[int] = set()1947 deduped: list[TransformerFactory] = []1948 for factory in factories:1949 if id(factory) not in seen_ids:1950 seen_ids.add(id(factory))1951 deduped.append(factory)1952 return deduped195319541955def _resolve_jump(1956 jump_to: JumpTo | None,1957 *,1958 model_destination: str,1959 end_destination: str,1960) -> str | None:1961 if jump_to == "model":1962 return model_destination1963 if jump_to == "end":1964 return end_destination1965 if jump_to == "tools":1966 return "tools"1967 return None196819691970def _fetch_last_ai_and_tool_messages(1971 messages: list[AnyMessage],1972) -> tuple[AIMessage | None, list[ToolMessage]]:1973 """Return the last AI message and any subsequent tool messages.19741975 Args:1976 messages: List of messages to search through.19771978 Returns:1979 A tuple of (last_ai_message, tool_messages). If no AIMessage is found,1980 returns (None, []). Callers must handle the None case appropriately.1981 """1982 for i in range(len(messages) - 1, -1, -1):1983 if isinstance(messages[i], AIMessage):1984 last_ai_message = cast("AIMessage", messages[i])1985 tool_messages = [m for m in messages[i + 1 :] if isinstance(m, ToolMessage)]1986 return last_ai_message, tool_messages19871988 return None, []198919901991def _make_model_to_tools_edge(1992 *,1993 model_destination: str,1994 structured_output_tools: dict[str, OutputToolBinding[Any]],1995 end_destination: str,1996) -> Callable[[dict[str, Any]], str | list[Send] | None]:1997 def model_to_tools(1998 state: dict[str, Any],1999 ) -> str | list[Send] | None:2000 # 1. If there's an explicit jump_to in the state, use it
Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.
Generated by searchcode.com · powered by code_get_file + code_get_findings