Skip to content

State not preserving custom fields — only messages available in runtime.state #34108

@mitht

Description

@mitht

Checked other resources

  • This is a bug, not a usage question.
  • I added a clear and descriptive title that summarizes this issue.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).
  • This is not related to the langchain-community package.
  • I posted a self-contained, minimal, reproducible example. A maintainer can copy it and run it AS IS.

Package (Required)

  • langchain
  • langchain-openai
  • langchain-anthropic
  • langchain-classic
  • langchain-core
  • langchain-cli
  • langchain-model-profiles
  • langchain-tests
  • langchain-text-splitters
  • langchain-chroma
  • langchain-deepseek
  • langchain-exa
  • langchain-fireworks
  • langchain-groq
  • langchain-huggingface
  • langchain-mistralai
  • langchain-nomic
  • langchain-ollama
  • langchain-perplexity
  • langchain-prompty
  • langchain-qdrant
  • langchain-xai
  • Other / not sure / general

Example Code (Python)

from typing import TypedDict, Annotated

from langchain.agents import create_agent
from langchain.tools import tool, ToolRuntime
from langgraph.graph import add_messages
from langgraph.types import Command
from langchain_core.messages import ToolMessage, HumanMessage
from langchain.chat_models import init_chat_model
from dataclasses import dataclass

@dataclass
class myState(TypedDict):
    messages: Annotated[list, add_messages]
    authenticated: bool
    password: str

model = init_chat_model(...)



@tool(parse_docstring=True)
def authenticate_user(
    password: str,
    runtime: ToolRuntime
):
    """
    Authenticate the user and store both the authentication result
    and the provided password into Session State.

    Args:
        password (str): The password provided by the user.

    Returns:
        ToolMessage + Command: One message to LLM, then update the State.
    """
    state = runtime.state
    is_authenticated = state.get("authenticated", False)

    message_text = (
        "🔐 Authentication successful!" if is_authenticated else "❌ Authentication failed!"
    )

    tool_call_id = runtime.tool_call_id

    return [
        ToolMessage(
            content=message_text,
            tool_call_id=tool_call_id
        ),
        Command(
            update={
                "authenticated": is_authenticated,
                "password": password  # 更新 password
            }
        )
    ]



agent = create_agent(
    model=model,
    tools=[authenticate_user],
)

state = myState(messages=[], authenticated=True, password="123456")


if __name__ == "__main__":

    result = agent.invoke(
        {
            "messages": [
                HumanMessage("To verify whether Xiaoming has passed the authentication, his password is wrong")
            ]
        },
        state=state
    )

    print("🗨️ Conversation Messages:")
    for msg in result["messages"]:
        print("  -", msg)

Error Message and Stack Trace (if applicable)

Connected to pydev debugger (build 241.19416.19)
🗨️ Conversation Messages:
  - content='To verify whether Xiaoming has passed the authentication, his password is wrong' additional_kwargs={} response_metadata={} id='35ab9670-e179-4744-a9ad-655c92d17d67'
  - content='The password provided by Xiaoming is incorrect. Therefore, he has not passed the authentication.' additional_kwargs={} response_metadata={'model': 'qwen3:8b', 'created_at': '2025-11-26T09:19:55.821754Z', 'done': True, 'done_reason': 'stop', 'total_duration': 19315913297, 'load_duration': 132382381, 'prompt_eval_count': 177, 'prompt_eval_duration': 13055502437, 'eval_count': 19, 'eval_duration': 6121174941, 'model_name': 'qwen3:8b', 'model_provider': 'ollama'} id='lc_run--0102d81d-7a79-4511-b976-f767f11be39d-0' usage_metadata={'input_tokens': 177, 'output_tokens': 19, 'total_tokens': 196}

Description

I referenced the documentation at https://docs.langchain.com/oss/python/langchain/context-engineering#state-6 and wrote a piece of code.

How can I correctly store data in the state? My code keeps failing to retrieve data from the state—it only receives the messages list.

version information:

langchain==1.0.3
langchain-core==1.0.2
langchain-ollama==1.0.0
langgraph==1.0.2
langgraph-checkpoint==3.0.0
langgraph-checkpoint-postgres==3.0.0
langgraph-prebuilt==1.0.2
langgraph-sdk==0.2.9
langsmith==0.4.38

System Info

$ python -m langchain_core.sys_info

System Information

OS: Darwin
OS Version: Darwin Kernel Version 22.2.0: Fri Nov 11 02:08:47 PST 2022; root:xnu-8792.61.2~4/RELEASE_X86_64
Python Version: 3.12.3 (v3.12.3:f6650f9ad7, Apr 9 2024, 08:18:48) [Clang 13.0.0 (clang-1300.0.29.30)]

Package Information

langchain_core: 1.0.2
langchain: 1.0.3
langsmith: 0.4.38
langchain_ollama: 1.0.0
langgraph_sdk: 0.2.9

Optional packages not installed

langserve

Other Dependencies

claude-agent-sdk: Installed. No version info available.
httpx: 0.28.1
jsonpatch: 1.33
langchain-anthropic: Installed. No version info available.
langchain-aws: Installed. No version info available.
langchain-community: Installed. No version info available.
langchain-deepseek: Installed. No version info available.
langchain-fireworks: Installed. No version info available.
langchain-google-genai: Installed. No version info available.
langchain-google-vertexai: Installed. No version info available.
langchain-groq: Installed. No version info available.
langchain-huggingface: Installed. No version info available.
langchain-mistralai: Installed. No version info available.
langchain-openai: Installed. No version info available.
langchain-perplexity: Installed. No version info available.
langchain-together: Installed. No version info available.
langchain-xai: Installed. No version info available.
langgraph: 1.0.2
langsmith-pyo3: Installed. No version info available.
ollama: 0.6.0
openai-agents: Installed. No version info available.
opentelemetry-api: Installed. No version info available.
opentelemetry-exporter-otlp-proto-http: Installed. No version info available.
opentelemetry-sdk: Installed. No version info available.
orjson: 3.11.4
packaging: 25.0
pydantic: 2.12.3
pytest: Installed. No version info available.
pyyaml: 6.0.3
requests: 2.32.5
requests-toolbelt: 1.0.0
rich: Installed. No version info available.
tenacity: 9.1.2
typing-extensions: 4.15.0
vcrpy: Installed. No version info available.
zstandard: 0.25.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugRelated to a bug, vulnerability, unexpected error with an existing featurecore`langchain-core` package issues & PRslangchain`langchain` package issues & PRs

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions