Accessing custom state using ToolRuntime

I’m trying to access my LangGraph state from inside a tool using ToolRuntime.
My state is defined as:

class BasicChatState(TypedDict):
    user_query: Optional[str]
    messages: Annotated[list, add_messages]

I invoke the app like this:

result = app.invoke(
    {
        "messages": [HumanMessage(content=text)],
        "user_query": text,
    },
    config={
        "configurable": {
            "thread_id": session_id
        }
    }
)

Inside the tool, I’m attempting to read the state:

@tool
def analytic_record(runtime: ToolRuntime) -> str:
    print(runtime.state.get("user_query"))

But I’m unable to access the state this way.
Can someone explain the correct method to retrieve state inside a tool using ToolRuntime?

hi @Najiya

Are you getting any error? Or just empty value?

Have you tried this:

@tool
def analytic_record(
    user_query: Annotated[str | None, InjectedState("user_query")]
) -> str:
    print(user_query)
    return "ok"
1 Like

I figured out the issue.
The reason I couldn’t access the state inside the tool was because I hadn’t passed the state_schema when creating the agent. Once I included the correct state_schema in create_agent, the state values became available as expected.

1 Like

Do you how the agent is accessing state_schema if i had not included it while creating agent. Because when i print the runtime earlier, i could find only messages in it as the state

how do you create the agent? With create_agent?

yes..with create_agent

then I think it’s because the default schema for create_agent is a schema with messages only

1 Like