How to Return Tool Output and Update State Simultaneously Using Command in LangChain?

Can a tool return both its actual result and a state update when using Command? If so, what is the recommended pattern to handle both outputs?

Hi @bharathiselvan

If I understand your point correctly, you want to update the state and return the tool result itself separately, right?

Based on the signature (Types | LangChain Reference) - you can’t sparate those data - it all must be sent via state imho

A tool or node can return a Command that both updates the graph state and controls flow (e.g., route to the next node)

See those:

Thanks @pawel-twardziak , Let me check these links..

1 Like

Hi @pawel-twardziak , I have a multi-agent system built using LangChain’s create_agent.

Inside one of my tools, I’m updating a custom state variable using a Command (i.e., returning state updates from the tool). The issue I’m seeing is:

  • The custom state update is available only for the current turn

  • On the next user turn, the updated state is no longer present

Question:
Are custom state updates via Command expected to persist only when using LangGraph (specifically a tool node), and not when using LangChain’s create_agent?

In other words, does create_agent not support persistent custom state updates across turns in the same way LangGraph does? Is that the expected behavior?

Hi @bharathiselvan

No, create_agent is not “stateless-only” and it does support persistent custom state updates via Command in the same way as raw LangGraph.

Two questions:

  • Do you use checkpointer for persistence?
  • Have you defined your custom state variable in state_schema?
from typing import Annotated
from typing_extensions import TypedDict, NotRequired
from langchain.agents.middleware.types import AgentState, OmitFromInput

class MyState(AgentState):
    # visible & required input:
    user_id: str

    # only appears in output / internal, not required on input:
    computed_score: Annotated[NotRequired[float], OmitFromInput]

agent = create_agent(
    model="openai:gpt-4o",
    tools=[...],
    state_schema=MyState,  # you custom variable must be there
    checkpointer=checkpointer,  # critical for persistence
)

huge favor @bharathiselvan - if this helps you, could you mark the post as Solved?
This would prevent open-ended posts and hanging posts, as well as multi-thread posts.