AI Hints
Home›LangChain Tutorial›Context and Errors
LangChain · Lesson 54 of 120

Runtime Context

Who is asking.

⏱ 2 min read▶ Video at 1:00:05🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

A tool like my orders needs to know which customer is asking. But we must never let the model choose the customer ID, or a clever prompt could read someone else's orders. Runtime context passes trusted data straight to tools.

Runtime Context
From the video: Runtime Context
  • Tools need the user
  • Never let the model choose
  • Trusted runtime context

Context in a tool

We describe the context as a data class, with a customer ID. The tool takes a tool runtime argument, which the model never sees. It reads the customer ID from the runtime. When we invoke the agent, our code supplies the context. Run it. The tool looks up orders for the real customer, whatever the user types.

context.pypython
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.tools import tool, ToolRuntime

ORDERS = {"cust-7": ["Dune (shipped)", "Circe (packing)"]}

@dataclass
class Ctx:
    customer_id: str

@tool
def my_orders(runtime: ToolRuntime[Ctx]) -> list[str]:
    """List the current customer's orders."""
    return ORDERS.get(runtime.context.customer_id, [])

agent = create_agent("google_genai:gemini-flash-lite-latest", tools=[my_orders], context_schema=Ctx)
out = agent.invoke({"messages": [{"role": "user", "content": "What are my orders? Be brief."}]},
                   context=Ctx(customer_id="cust-7"))
print(out["messages"][-1].text)
Output
Your orders are:
- Dune (shipped)
- Circe (packing)

Context vs state

Don't mix up context and state. Context is fixed for one run, and comes from your code, like the user ID, their permissions, or a database connection. State is the conversation, which changes as the agent works. Put anything trusted in context, never in the messages.

keyvalue
Contextfixed per run, from your code
Examplesuser ID, permissions
Statemessages, changes as it runs
Ruletrusted data in context

Summary

Runtime context passes trusted data, like the customer ID, straight to tools and middleware, where the model can't change it. Next, practise building a complete bookshop agent.

Key takeaways
  • context_schema
  • ToolRuntime
  • Model never sees it
Next up: Practice: Bookshop Agent — tools and memory