Skip to content

LangGraph CLI treats InjectedState as required tool parameter and fails the validation #6241

@codeonym

Description

@codeonym

Checked other resources

  • This is a bug, not a usage question. For questions, please use the LangChain Forum (https://forum.langchain.com/).
  • I added a clear and detailed title that summarizes the issue.
  • I read what a minimal reproducible example is (https://stackoverflow.com/help/minimal-reproducible-example).
  • I included a self-contained, minimal example that demonstrates the issue INCLUDING all the relevant imports. The code run AS IS to reproduce the issue.

Example Code

from typing import Any, List, Annotated, Optional

from langchain.chat_models import init_chat_model
from typing_extensions import Literal
from langchain_core.messages import SystemMessage, BaseMessage
from langchain_core.runnables import RunnableConfig
from langchain.tools import tool
from langgraph.graph import StateGraph, END
from langgraph.types import Command
from langgraph.graph import MessagesState
from langgraph.prebuilt import ToolNode, InjectedState
from langgraph.checkpoint.memory import MemorySaver

class AgentState(MessagesState):
    proverbs: Optional[List[str]] = []
    tools: Optional[List[Any]]


@tool
def get_weather(location: str):
    """
    Get the weather for a given location.
    """
    return f"The weather for {location} is 70 degrees."

@tool
def get_jokes(theme: str, state: Annotated[AgentState, InjectedState] = None): # <- change to dict to avoid validation erro
    """Fetch a list of jokes."""

    return """
    Ok here are the jokes:
    1. Why don't scientists trust atoms? Because they make up everything!
    2. Why did the scarecrow win an award? Because he was outstanding in his field!
    3. Why don't skeletons fight each other? They don't have the guts.
    4. What do you call fake spaghetti? An impasta!
    5. Why did the bicycle fall over? Because it was two-tired!
    6. What do you call cheese that isn't yours? Nacho cheese!
    7. Why did the math book look sad? Because it had too many problems.
    8. Why can't your nose be 12 inches long? Because then it would be a foot!
    9. What do you call a bear with no teeth? A gummy bear!
    """

tools = [
    get_weather,
    get_jokes
    # your_tool_here
]

def chat_node(state: AgentState, config: RunnableConfig) -> Command[Literal["tool_node", "__end__"]]:

    # 1. Define the model
    model = init_chat_model("google_genai:gemini-2.0-flash")

    # 2. Bind the tools to the model
    model_with_tools = model.bind_tools(
        [
            *state.get("tools", []), # bind tools defined by ag-ui
            get_weather,
            get_jokes,
            # your_tool_here
        ],
        parallel_tool_calls=False,
    )

    # 3. Define the system message by which the chat model will be run
    p_ct = f"""
    You are a helpful assistant you can do the following:
    1. read proverbs
    2. add/remove/update proverbs
    3. fetch weather for a given location
    4. fetch jokes for the user
    
    here is a the current proverbs list:
    {state.get('proverbs', [])}
    
    be helpful and concise.
    """
    system_message = SystemMessage(
        content=p_ct
    )

    # 4. Run the model to generate a response
    response = model_with_tools.invoke([
        system_message,
        *state["messages"],
    ], config)

    if route_to_tool_node(response):
        # 4.1 If there are tool calls in the response, route to the tool node to handle them.
        return Command(
            goto="tool_node",
            update={
                "messages": response
            }
        )

    # 5. We've handled all tool calls, so we can end the graph.
    return Command(
        goto=END,
        update={
            "messages": response
        }
    )

tools_names = [tool_.name for tool_ in tools]
def route_to_tool_node(response: BaseMessage):
    """
    Route to tool node if any tool call in the response matches a backend tool name.
    """
    tool_calls = getattr(response, "tool_calls", None)
    if not tool_calls:
        return False
    for tool_call in tool_calls:
        if tool_call.get("name") in tools_names:
            return True
    return False


# Define the workflow graph
workflow = StateGraph(AgentState)
workflow.add_node("chat_node", chat_node)
workflow.add_node("tool_node", ToolNode(tools=tools))
workflow.add_edge("tool_node", "chat_node")
workflow.set_entry_point("chat_node")

graph = workflow.compile()

Error Message and Stack Trace (if applicable)

|-
Error: 2 validation errors for get_jokes
state.proverbs
  Field required [type=missing, input_value={'messages': [HumanMessag...': {'cache_read': 0}})]}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.11/v/missing
state.tools
  Field required [type=missing, input_value={'messages': [HumanMessag...': {'cache_read': 0}})]}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.11/v/missing
 Please fix your mistakes.

Description

Context

This error only occurs when running the graph via langgraph dev command.
The same code works correctly with FastAPI hosting.

Problem

LangGraph CLI incorrectly attempts to validate InjectedState parameters in tool schemas.
When using a typed state class (e.g., AgentState), the validation layer treats
injected state parameters as required tool arguments and fails.

Workaround

Use generic dict type instead of custom state class:

  • ❌ Before: state: Annotated[AgentState, InjectedState]
  • ✅ After: state: Annotated[dict, InjectedState]

This bypasses field-level validation while maintaining state injection functionality.

Trade-offs

  • Loss of type safety and IDE autocomplete for state fields
  • Manual type checking required when accessing state properties
  • Increased risk of runtime errors from typos or missing fields

You can view Langsmith trace here: https://smith.langchain.com/public/f774cc58-8fbe-4661-a6bf-5bab4920d392/r

System Info

ag-ui-langgraph                          0.0.15    Implementation of the AG-UI protocol for LangGraph.
ag-ui-protocol                           0.1.9     
annotated-types                          0.7.0     Reusable constraint types to use with typing.Annotated
anyio                                    4.11.0    High-level concurrency and networking framework on top of asyncio or Trio
blockbuster                              1.5.25    Utility to detect blocking calls in the async event loop
cachetools                               6.2.0     Extensible memoizing collections and decorators
certifi                                  2025.10.5 Python package for providing Mozilla's CA Bundle.
cffi                                     2.0.0     Foreign Function Interface for Python calling C code.
charset-normalizer                       3.4.3     The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet.
click                                    8.3.0     Composable command line interface toolkit
cloudpickle                              3.1.1     Pickler class to extend the standard pickle.Pickler functionality
colorama                                 0.4.6     Cross-platform colored terminal text.
copilotkit                               0.1.66    CopilotKit python SDK
cryptography                             44.0.3    cryptography is a package which provides cryptographic recipes and primitives to Python developers.
distro                                   1.9.0     Distro - an OS platform information API
fastapi                                  0.115.14  FastAPI framework, high performance, easy to learn, fast to code, ready for production
filetype                                 1.2.0     Infer file type and MIME type of any file/buffer. No external dependencies.
forbiddenfruit                           0.1.4     Patch python built-in objects
google-ai-generativelanguage             0.7.0     Google Ai Generativelanguage API client library
google-api-core                          2.25.2    Google API client core library
google-auth                              2.41.1    Google Authentication Library
googleapis-common-protos                 1.70.0    Common protobufs used in Google APIs
greenlet                                 3.2.4     Lightweight in-process concurrent programming
grpcio                                   1.75.1    HTTP/2-based RPC framework
grpcio-status                            1.75.1    Status proto mapping for gRPC
grpcio-tools                             1.75.1    Protobuf code generator for gRPC
h11                                      0.16.0    A pure-Python, bring-your-own-I/O implementation of HTTP/1.1
httpcore                                 1.0.9     A minimal low-level HTTP client.
httpx                                    0.28.1    The next generation HTTP client.
idna                                     3.10      Internationalized Domain Names in Applications (IDNA)
importlib-metadata                       8.7.0     Read metadata from Python packages
jiter                                    0.11.0    Fast iterable JSON parser.
jsonpatch                                1.33      Apply JSON-Patches (RFC 6902)
jsonpointer                              3.0.0     Identify specific nodes in a JSON document (RFC 6901)
jsonschema-rs                            0.29.1    A high-performance JSON Schema validator for Python
langchain                                0.3.27    Building applications with LLMs through composability
langchain-core                           0.3.78    Building applications with LLMs through composability
langchain-google-genai                   2.1.12    An integration package connecting Google's genai package and LangChain
langchain-openai                         0.3.34    An integration package connecting OpenAI and LangChain
langchain-text-splitters                 0.3.11    LangChain text splitting utilities
langgraph                                0.6.8     Building stateful, multi-actor applications with LLMs
langgraph-api                            0.4.35    
langgraph-checkpoint                     2.1.1     Library with base interfaces for LangGraph checkpoint savers.
langgraph-cli                            0.4.2     CLI for interacting with LangGraph API
langgraph-prebuilt                       0.6.4     Library with high-level APIs for creating and executing LangGraph agents and tools.
langgraph-runtime-inmem                  0.14.1    Inmem implementation for the LangGraph API server.
langgraph-sdk                            0.2.9     SDK for interacting with LangGraph API
langsmith                                0.4.32    Client library to connect to the LangSmith LLM Tracing and Evaluation Platform.
openai                                   2.1.0     The official Python library for the openai API
opentelemetry-api                        1.37.0    OpenTelemetry Python API
opentelemetry-exporter-otlp-proto-common 1.37.0    OpenTelemetry Protobuf encoding
opentelemetry-exporter-otlp-proto-http   1.37.0    OpenTelemetry Collector Protobuf over HTTP Exporter
opentelemetry-proto                      1.37.0    OpenTelemetry Python Proto
opentelemetry-sdk                        1.37.0    OpenTelemetry Python SDK
opentelemetry-semantic-conventions       0.58b0    OpenTelemetry Semantic Conventions
orjson                                   3.11.3    Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy
ormsgpack                                1.10.0    Fast, correct Python msgpack library supporting dataclasses, datetimes, and numpy
packaging                                25.0      Core utilities for Python packages
partialjson                              0.0.8     Parse incomplete or partial json
proto-plus                               1.26.1    Beautiful, Pythonic protocol buffers
protobuf                                 6.32.1    
pyasn1                                   0.6.1     Pure-Python implementation of ASN.1 types and DER/BER/CER codecs (X.208)
pyasn1-modules                           0.4.2     A collection of ASN.1-based protocols modules
pycparser                                2.23      C parser in Python
pydantic                                 2.11.10   Data validation using Python type hints
pydantic-core                            2.33.2    Core functionality for Pydantic validation and serialization
pyjwt                                    2.10.1    JSON Web Token implementation in Python
python-dotenv                            1.1.1     Read key-value pairs from a .env file and set them as environment variables
pyyaml                                   6.0.3     YAML parser and emitter for Python
regex                                    2025.9.18 Alternative regular expression module, to replace re.
requests                                 2.32.5    Python HTTP for Humans.
requests-toolbelt                        1.0.0     A utility belt for advanced users of python-requests
rsa                                      4.9.1     Pure-Python RSA implementation
setuptools                               80.9.0    Easily download, build, install, upgrade, and uninstall Python packages
sniffio                                  1.3.1     Sniff out which async library your code is running under
sqlalchemy                               2.0.43    Database Abstraction Library
sse-starlette                            2.1.3     SSE plugin for Starlette
starlette                                0.46.2    The little ASGI library that shines.
structlog                                25.4.0    Structured Logging for Python
tenacity                                 9.1.2     Retry code until it succeeds
tiktoken                                 0.11.0    tiktoken is a fast BPE tokeniser for use with OpenAI's models
toml                                     0.10.2    Python Library for Tom's Obvious, Minimal Language
tqdm                                     4.67.1    Fast, Extensible Progress Meter
truststore                               0.10.4    Verify certificates using native system trust stores
typing-extensions                        4.15.0    Backported and Experimental Type Hints for Python 3.9+
typing-inspection                        0.4.2     Runtime typing introspection tools
urllib3                                  2.5.0     HTTP library with thread-safe connection pooling, file post, and more.
uvicorn                                  0.29.0    The lightning-fast ASGI server.
watchfiles                               1.1.0     Simple, modern and high performance file watching and code reload in python.
xxhash                                   3.6.0     Python binding for xxHash
zipp                                     3.23.0    Backport of pathlib-compatible object wrapper for zip files
zstandard                                0.25.0    Zstandard bindings for Python

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingpendingawaiting review/confirmation by maintainer

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions