Skip to content

The agent engineering platform.

chore(langchain_v1): adding back `state_schema` to `create_agent` (#33519)

Sydney Runkledd77dbe3ab56
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py
index 31d560d07d..875e81ab4a 100644
--- a/libs/langchain_v1/langchain/agents/factory.py
+++ b/libs/langchain_v1/langchain/agents/factory.py
@@ -517,6 +517,7 @@ def create_agent( # noqa: PLR0915
system_prompt: str | None = None,
middleware: Sequence[AgentMiddleware[AgentState[ResponseT], ContextT]] = (),
response_format: ResponseFormat[ResponseT] | type[ResponseT] | None = None,
+ state_schema: type[AgentState[ResponseT]] | None = None,
context_schema: type[ContextT] | None = None,
checkpointer: Checkpointer | None = None,
store: BaseStore | None = None,
@@ -549,6 +550,11 @@ def create_agent( # noqa: PLR0915
If provided, the agent will handle structured output during the
conversation flow. Raw schemas will be wrapped in an appropriate strategy
based on model capabilities.
+ state_schema: An optional `TypedDict` schema that extends `AgentState`.
+ When provided, this schema is used instead of `AgentState` as the base
+ schema for merging with middleware state schemas. This allows users to
+ add custom state fields without needing to create custom middleware.
+ The schema must be a subclass of `AgentState[ResponseT]`.
context_schema: An optional schema for runtime context.
checkpointer: An optional checkpoint saver object. This is used for persisting
the state of the graph (e.g., as chat memory) for a single thread
@@ -762,9 +768,11 @@ def create_agent( # noqa: PLR0915
awrap_model_call_handler = _chain_async_model_call_handlers(async_handlers)
state_schemas = {m.state_schema for m in middleware}
- state_schemas.add(AgentState)
+ # Use provided state_schema if available, otherwise use base AgentState
+ base_state = state_schema if state_schema is not None else AgentState
+ state_schemas.add(base_state)
- state_schema = _resolve_schema(state_schemas, "StateSchema", None)
+ resolved_state_schema = _resolve_schema(state_schemas, "StateSchema", None)
input_schema = _resolve_schema(state_schemas, "InputSchema", "input")
output_schema = _resolve_schema(state_schemas, "OutputSchema", "output")
@@ -772,7 +780,7 @@ def create_agent( # noqa: PLR0915
graph: StateGraph[
AgentState[ResponseT], ContextT, PublicAgentState[ResponseT], PublicAgentState[ResponseT]
] = StateGraph(
- state_schema=state_schema,
+ state_schema=resolved_state_schema,
input_schema=input_schema,
output_schema=output_schema,
context_schema=context_schema,
@@ -1119,7 +1127,9 @@ def create_agent( # noqa: PLR0915
else None
)
before_agent_node = RunnableCallable(sync_before_agent, async_before_agent, trace=False)
- graph.add_node(f"{m.name}.before_agent", before_agent_node, input_schema=state_schema)
+ graph.add_node(
+ f"{m.name}.before_agent", before_agent_node, input_schema=resolved_state_schema
+ )
if (
m.__class__.before_model is not AgentMiddleware.before_model
@@ -1138,7 +1148,9 @@ def create_agent( # noqa: PLR0915
else None
)
before_node = RunnableCallable(sync_before, async_before, trace=False)
- graph.add_node(f"{m.name}.before_model", before_node, input_schema=state_schema)
+ graph.add_node(
+ f"{m.name}.before_model", before_node, input_schema=resolved_state_schema
+ )
if (
m.__class__.after_model is not AgentMiddleware.after_model
@@ -1157,7 +1169,7 @@ def create_agent( # noqa: PLR0915
else None
)
after_node = RunnableCallable(sync_after, async_after, trace=False)
- graph.add_node(f"{m.name}.after_model", after_node, input_schema=state_schema)
+ graph.add_node(f"{m.name}.after_model", after_node, input_schema=resolved_state_schema)
if (
m.__class__.after_agent is not AgentMiddleware.after_agent
@@ -1176,7 +1188,9 @@ def create_agent( # noqa: PLR0915
else None
)
after_agent_node = RunnableCallable(sync_after_agent, async_after_agent, trace=False)
- graph.add_node(f"{m.name}.after_agent", after_agent_node, input_schema=state_schema)
+ graph.add_node(
+ f"{m.name}.after_agent", after_agent_node, input_schema=resolved_state_schema
+ )
# Determine the entry node (runs once at start): before_agent -> before_model -> model
if middleware_w_before_agent:
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_state_schema.py b/libs/langchain_v1/tests/unit_tests/agents/test_state_schema.py
new file mode 100644
index 0000000000..d3962c2174
--- /dev/null
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_state_schema.py
@@ -0,0 +1,188 @@
+"""Test state_schema parameter in create_agent.
+
+This module tests that the state_schema parameter allows users to extend
+AgentState without needing to create custom middleware.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from langchain_core.messages import HumanMessage
+from langchain_core.tools import tool
+
+from langchain.agents import create_agent
+from langchain.agents.middleware.types import AgentMiddleware, AgentState
+from langchain.tools import ToolRuntime
+
+from .model import FakeToolCallingModel
+
+
+@tool
+def simple_tool(x: int) -> str:
+ """Simple tool for basic tests."""
+ return f"Result: {x}"
+
+
+def test_state_schema_single_custom_field() -> None:
+ """Test that a single custom state field is preserved through agent execution."""
+
+ class CustomState(AgentState):
+ custom_field: str
+
+ agent = create_agent(
+ model=FakeToolCallingModel(
+ tool_calls=[[{"args": {"x": 1}, "id": "call_1", "name": "simple_tool"}], []]
+ ),
+ tools=[simple_tool],
+ state_schema=CustomState,
+ )
+
+ result = agent.invoke({"messages": [HumanMessage("Test")], "custom_field": "test_value"})
+
+ assert result["custom_field"] == "test_value"
+ assert len(result["messages"]) == 4
+
+
+def test_state_schema_multiple_custom_fields() -> None:
+ """Test that multiple custom state fields are preserved through agent execution."""
+
+ class CustomState(AgentState):
+ user_id: str
+ session_id: str
+ context: str
+
+ agent = create_agent(
+ model=FakeToolCallingModel(
+ tool_calls=[[{"args": {"x": 1}, "id": "call_1", "name": "simple_tool"}], []]
+ ),
+ tools=[simple_tool],
+ state_schema=CustomState,
+ )
+
+ result = agent.invoke(
+ {
+ "messages": [HumanMessage("Test")],
+ "user_id": "user_123",
+ "session_id": "session_456",
+ "context": "test_ctx",
+ }
+ )
+
+ assert result["user_id"] == "user_123"
+ assert result["session_id"] == "session_456"
+ assert result["context"] == "test_ctx"
+ assert len(result["messages"]) == 4
+
+
+def test_state_schema_with_tool_runtime() -> None:
+ """Test that custom state fields are accessible via ToolRuntime."""
+
+ class ExtendedState(AgentState):
+ counter: int
+
+ runtime_data = {}
+
+ @tool
+ def counter_tool(x: int, runtime: ToolRuntime) -> str:
+ """Tool that accesses custom state field."""
+ runtime_data["counter"] = runtime.state["counter"]
+ return f"Counter is {runtime_data['counter']}, x is {x}"
+
+ agent = create_agent(
+ model=FakeToolCallingModel(
+ tool_calls=[[{"args": {"x": 10}, "id": "call_1", "name": "counter_tool"}], []]
+ ),
+ tools=[counter_tool],
+ state_schema=ExtendedState,
+ )
+
+ result = agent.invoke({"messages": [HumanMessage("Test")], "counter": 5})
+
+ assert runtime_data["counter"] == 5
+ assert "Counter is 5" in result["messages"][2].content
+
+
+def test_state_schema_with_middleware() -> None:
+ """Test that state_schema merges with middleware state schemas."""
+
+ class UserState(AgentState):
+ user_name: str
+
+ class MiddlewareState(AgentState):
+ middleware_data: str
+
+ middleware_calls = []
+
+ class TestMiddleware(AgentMiddleware):
+ state_schema = MiddlewareState
+
+ def before_model(self, state, runtime) -> dict[str, Any]:
+ middleware_calls.append(state.get("middleware_data", ""))
+ return {}
+
+ agent = create_agent(
+ model=FakeToolCallingModel(
+ tool_calls=[[{"args": {"x": 5}, "id": "call_1", "name": "simple_tool"}], []]
+ ),
+ tools=[simple_tool],
+ state_schema=UserState,
+ middleware=[TestMiddleware()],
+ )
+
+ result = agent.invoke(
+ {
+ "messages": [HumanMessage("Test")],
+ "user_name": "Alice",
+ "middleware_data": "test_data",
+ }
+ )
+
+ assert result["user_name"] == "Alice"
+ assert result["middleware_data"] == "test_data"
+ assert "test_data" in middleware_calls
+
+
+def test_state_schema_none_uses_default() -> None:
+ """Test that state_schema=None uses default AgentState."""
+ agent = create_agent(
+ model=FakeToolCallingModel(
+ tool_calls=[[{"args": {"x": 1}, "id": "call_1", "name": "simple_tool"}], []]
+ ),
+ tools=[simple_tool],
+ state_schema=None,
+ )
+
+ result = agent.invoke({"messages": [HumanMessage("Test")]})
+
+ assert len(result["messages"]) == 4
+ assert "Result: 1" in result["messages"][2].content
+
+
+async def test_state_schema_async() -> None:
+ """Test that state_schema works with async agents."""
+
+ class AsyncState(AgentState):
+ async_field: str
+
+ @tool
+ async def async_tool(x: int) -> str:
+ """Async tool."""
+ return f"Async: {x}"
+
+ agent = create_agent(
+ model=FakeToolCallingModel(
+ tool_calls=[[{"args": {"x": 99}, "id": "call_1", "name": "async_tool"}], []]
+ ),
+ tools=[async_tool],
+ state_schema=AsyncState,
+ )
+
+ result = await agent.ainvoke(
+ {"messages": [HumanMessage("Test async")], "async_field": "async_value"}
+ )
+
+ assert result["async_field"] == "async_value"
+ assert "Async: 99" in result["messages"][2].content