Nodes — sync, async and what they receive
Overview
In the previous lesson, you learned how MessagesState and the add_messages reducer help LangGraph maintain conversation history. State provides the shared information that moves through a workflow, but state alone cannot perform any meaningful work.
That is the responsibility of nodes.
A node is an executable unit of a LangGraph workflow. It can perform anything that you would normally implement using Python, from transforming a string to calling a language model, querying a database, retrieving documents, or interacting with an external service.
Consider a customer support agent that must understand a customer’s question, retrieve relevant information, and generate an appropriate response. Each responsibility can be implemented as a separate node.
The following diagram represents a simple customer support workflow.
Each node receives information from the graph, performs its assigned task, and returns an update. LangGraph manages the execution order and makes the updated information available to subsequent nodes.
This separation is one of the reasons LangGraph is useful for engineering agentic AI systems. Instead of implementing an entire agent inside one large Python function, you can divide it into independently understandable, observable, and testable components.
Nodes do not necessarily involve artificial intelligence. A production agent typically combines deterministic business logic with probabilistic LLM operations.
For this lesson, use Python 3.11 or newer and install the required packages:
pip install -U "langgraph>=1,<2" "langchain>=1,<2"The examples use the LangGraph 1.x Graph API. Most examples deliberately use deterministic functions or simulated services so that they do not require API credentials or paid model calls. Expected outputs are illustrative; the examples have been checked against the documented APIs but have not been executed in the lesson-authoring environment.
Node inputs and outputs
What exactly is a node?
At its simplest, a node is an ordinary Python function that accepts graph state and returns an update to that state.
The basic function signature looks like this:
def my_node(state: State) -> dict:
return {"some_field": "new value"}There is no mandatory node decorator, special base class, or inheritance requirement.
To make this function part of a LangGraph workflow, register it using builder.add_node().
LangGraph wraps the callable in its runnable execution machinery. This enables features such as tracing, asynchronous execution, retries, streaming, and configuration propagation.
Creating your first custom node
The following example demonstrates how two synchronous nodes cooperate through shared state.
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
query: str
normalized_query: NotRequired[str]
category: NotRequired[str]
def normalize(state: State) -> dict:
return {
"normalized_query": state["query"].strip().lower()
}
def classify(state: State) -> dict:
query = state["normalized_query"]
if "refund" in query:
category = "billing"
else:
category = "general"
return {"category": category}
builder = StateGraph(State)
builder.add_node("normalize", normalize)
builder.add_node("classify", classify)
builder.add_edge(START, "normalize")
builder.add_edge("normalize", "classify")
builder.add_edge("classify", END)
graph = builder.compile()
result = graph.invoke(
{"query": " I NEED A REFUND "}
)
print(result)Expected output:
{
'query': ' I NEED A REFUND ',
'normalized_query': 'i need a refund',
'category': 'billing'
}Notice that neither node returns the complete state.
The normalize node returns only normalized_query, while the classify node returns only category. LangGraph preserves the other state fields automatically.
NotRequired indicates that a field may be absent when execution begins. The TypedDict describes the expected structure for developers and static type checkers; it does not automatically perform comprehensive runtime validation.
The START and END constants represent special graph boundaries rather than custom Python functions. They establish where execution begins and terminates. We will examine edge behavior in detail in the next lesson.
How LangGraph processes node updates
Internally, LangGraph uses an execution engine called Pregel, inspired by a graph-processing model based on discrete execution steps.
A simplified execution cycle works as follows:
- Determine which nodes are ready to execute.
- Supply those nodes with the relevant state values.
- Execute the selected node functions.
- Collect their returned updates.
- Apply the state channels’ update rules and reducers.
- Schedule the next eligible nodes.
A group of nodes executing in the same logical iteration is part of a super-step.
When multiple nodes execute in the same super-step, their ordinary shared-state writes become visible to subsequent steps after the update phase. One parallel node should not assume that it can immediately observe another parallel node’s returned update.
This diagram illustrates the conceptual relationship between a node and the state management system.
The state returned by graph.invoke() is the resulting graph output, not simply the return value of the last Python function.
Returning partial state updates
Nodes should generally return dictionaries containing only the fields that they intentionally change.
Avoid modifying the received state directly or returning unnecessary copies of existing values.
For example, if a node calculates a new count, return {"count": state["count"] + 1} rather than assigning directly to state["count"].
The same principle applies to nested dictionaries and lists. Do not append directly to a list obtained from state when the intention is to communicate a graph update.
Returning explicit updates enables LangGraph to apply reducers correctly and maintain predictable behavior during parallel execution and persistence.
A node that intentionally makes no state changes can return an empty dictionary, {}. Later lessons will introduce advanced return types such as Command, which can combine state updates with control-flow instructions.
How reducers affect node outputs
A returned dictionary does not necessarily overwrite every field it contains. The behavior depends on the reducer associated with each state field.
The following example connects node outputs with the MessagesState behavior from the previous lesson.
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState
from langgraph.graph import START, END
def respond(state: MessagesState) -> dict:
latest_message = state["messages"][-1]
reply = AIMessage(
content=f"I received your message: {latest_message.content}"
)
return {"messages": [reply]}
builder = StateGraph(MessagesState)
builder.add_node("respond", respond)
builder.add_edge(START, "respond")
builder.add_edge("respond", END)
graph = builder.compile()
result = graph.invoke({
"messages": [
HumanMessage(content="How do I reset my password?")
]
})
for message in result["messages"]:
print(message.type, message.content)Expected output:
human How do I reset my password?
ai I received your message: How do I reset my password?Although the node returns only one new message, both messages appear in the final state.
This happens because MessagesState associates its messages field with the add_messages reducer. That reducer combines message updates with the existing conversation, including replacing messages when their IDs match.
The important distinction is between the update produced by a node and the state produced by applying that update.
Note: Returning the entire existing message history is unnecessary. With accumulating reducers, returning existing values alongside new ones can produce unexpected duplication or merging behavior.
Async nodes
Why asynchronous nodes exist
Many operations in agentic AI applications are I/O-bound rather than CPU-bound.
For example, an agent may spend considerable time waiting for:
- An LLM provider to generate a response.
- A vector database to return search results.
- A REST API to respond.
- A database server to execute a query.
- An external document retrieval service.
A synchronous function waits until its operation completes. An asynchronous function can suspend its execution while waiting, allowing the event loop to continue processing other available work.
You define asynchronous LangGraph nodes using Python’s async def syntax.
| Aspect | Synchronous node | Asynchronous node |
|---|---|---|
| Definition | def |
async def |
| Waiting for I/O | Typically blocking | Non-blocking when using async libraries |
| Graph invocation | invoke() or ainvoke() |
ainvoke() |
| Graph streaming | stream() or astream() |
astream() |
| Typical operations | Validation, formatting, calculations | APIs, databases, LLM requests |
| Implementation complexity | Lower | Requires async-aware libraries |
An asynchronous graph can execute both synchronous and asynchronous nodes. LangGraph can run ordinary synchronous functions through executor threads during asynchronous execution.
However, a graph containing an async-only node must use the asynchronous execution interface when that node is reached.
Creating an asynchronous node
The following example simulates a customer information service and demonstrates a graph containing both synchronous and asynchronous nodes.
import asyncio
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
customer_id: str
customer_name: NotRequired[str]
response: NotRequired[str]
async def fetch_customer(state: State) -> dict:
# Simulate waiting for a remote service.
await asyncio.sleep(0.5)
customers = {
"C101": "Asha",
"C102": "Rahul",
}
name = customers.get(
state["customer_id"], "Guest"
)
return {"customer_name": name}
def generate_response(state: State) -> dict:
return {
"response": f"Welcome, {state['customer_name']}!"
}
builder = StateGraph(State)
builder.add_node("fetch_customer", fetch_customer)
builder.add_node("respond", generate_response)
builder.add_edge(START, "fetch_customer")
builder.add_edge("fetch_customer", "respond")
builder.add_edge("respond", END)
graph = builder.compile()
async def main():
result = await graph.ainvoke(
{"customer_id": "C101"}
)
print(result["response"])
if __name__ == "__main__":
asyncio.run(main())Expected output:
Welcome, Asha!The asynchronous node waits for the simulated remote operation without blocking the event loop. Once it returns its update, the synchronous response node executes.
When working inside a Jupyter notebook that already has a running event loop, call await main() directly instead of starting another event loop with asyncio.run().
Asynchronous LLM calls inside nodes
In real agentic applications, asynchronous nodes frequently invoke language models.
Install the OpenAI model integration:
pip install -U langchain-openaiConfigure OPENAI_API_KEY in your environment before running the following example. Your provider account must also have access to the specified model.
This example demonstrates an asynchronous conversational node using the LangChain 1.x model initialization API.
import asyncio
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, MessagesState
from langgraph.graph import START, END
model = init_chat_model("openai:gpt-5.4-mini")
async def call_model(state: MessagesState) -> dict:
messages = [
SystemMessage(
content="You are a concise technical instructor."
),
*state["messages"],
]
response = await model.ainvoke(messages)
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("assistant", call_model)
builder.add_edge(START, "assistant")
builder.add_edge("assistant", END)
graph = builder.compile()
async def main():
result = await graph.ainvoke({
"messages": [
HumanMessage(
content="Explain an HTTP status code in one sentence."
)
]
})
print(result["messages"][-1].content)
if __name__ == "__main__":
asyncio.run(main())A possible output is:
An HTTP status code is a three-digit number indicating the outcome of an HTTP request.Unlike deterministic Python functions, LLM responses can vary between executions.
The system message is constructed locally rather than written into conversation state on every invocation. The returned assistant message is merged into the conversation by add_messages.
Async does not automatically mean parallel
Changing a node from def to async def does not cause subsequent graph nodes to execute simultaneously.
Graph dependencies still determine when nodes are eligible to execute.
However, independent operations inside an asynchronous node can execute concurrently using mechanisms such as asyncio.gather().
For example, fetching a customer’s profile and retrieving their order history can overlap if neither operation depends on the other’s result.
Be careful with blocking functions inside asynchronous nodes. Calling time.sleep(), a synchronous HTTP client, or a synchronous database driver directly inside async def can block the event loop.
Prefer asynchronous libraries such as httpx.AsyncClient or an asynchronous PostgreSQL driver. For unavoidable blocking I/O, consider asyncio.to_thread().
CPU-intensive calculations do not become faster simply because a function is asynchronous. Such workloads may require process-based parallelism or a separate compute service.
Extra arguments: config and runtime
Until now, nodes have received only graph state. Production applications often require additional information that does not belong in the evolving workflow state.
LangGraph supports injecting two particularly important arguments into node functions:
config, containing execution configuration.runtime, containing invocation-specific context and runtime utilities.
A node can request either argument individually or both together.
The following table explains their different responsibilities.
| Information | State | Config | Runtime context |
|---|---|---|---|
| Current user query | Yes | No | No |
| Conversation history | Yes | No | No |
| Intermediate classification | Yes | No | No |
| Tracing tags | No | Yes | No |
| Recursion limit | No | Yes | No |
| Checkpoint thread ID | No | Yes | No |
| Authenticated user ID | Usually no | No | Yes |
| Customer preferences | Usually no | No | Yes |
| Database client | No | No | Yes |
State represents information that evolves as the graph executes. Configuration controls execution, while runtime context supplies application-level dependencies and facts associated with the invocation.
LangGraph recognizes supported node parameters and supplies them automatically. You do not need to manually pass them when registering nodes with add_node().
config
Understanding RunnableConfig
RunnableConfig is a dictionary-based configuration type imported from langchain_core.runnables.
A node accesses it by declaring a parameter named config with the appropriate type annotation.
Common configuration fields include:
| Field | Purpose |
|---|---|
tags |
Categorize executions for tracing |
metadata |
Attach diagnostic information |
run_name |
Name a runnable execution |
callbacks |
Receive execution lifecycle events |
max_concurrency |
Limit supported concurrent execution |
recursion_limit |
Limit graph execution steps |
configurable |
Supply configurable execution settings, including checkpoint identifiers |
Configuration is useful for operational control and observability. It should not become an unstructured container for application data.
Reading config inside a node
The following example demonstrates reading execution metadata and enabling checkpoint persistence with a thread identifier.
from typing_extensions import TypedDict, NotRequired
from langchain_core.runnables import RunnableConfig
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict):
query: str
response: NotRequired[str]
def process(
state: State,
config: RunnableConfig,
) -> dict:
metadata = config.get("metadata", {})
tags = config.get("tags", [])
request_id = metadata.get("request_id", "unknown")
thread_id = config.get(
"configurable", {}
).get("thread_id")
print("Request:", request_id)
print("Thread:", thread_id)
print("Tags:", tags)
return {
"response": state["query"].upper()
}
builder = StateGraph(State)
builder.add_node("process", process)
builder.add_edge(START, "process")
builder.add_edge("process", END)
graph = builder.compile(
checkpointer=InMemorySaver()
)
config: RunnableConfig = {
"configurable": {
"thread_id": "support-thread-101"
},
"metadata": {
"request_id": "REQ-501"
},
"tags": ["customer-support", "development"],
"recursion_limit": 20,
}
result = graph.invoke(
{"query": "hello"},
config=config,
)
print(result["response"])Expected output:
Request: REQ-501
Thread: support-thread-101
Tags: ['customer-support', 'development']
HELLOAdditional execution metadata or tags may be present depending on the surrounding runnable configuration.
InMemorySaver enables checkpointing for this example. The thread identifier tells the checkpointer which logical execution history to associate with the invocation. We will explore checkpoint persistence in a dedicated chapter.
Setting recursion_limit to a reasonable value is particularly important when building graphs that contain loops. It limits graph execution steps rather than Python function recursion.
Similarly, max_concurrency can constrain supported graph or runnable concurrency, but it does not automatically restrict arbitrary tasks created using asyncio.gather() inside a node.
Configuration propagation
Configuration can propagate from a parent runnable to nested runnable operations. This is useful when a node invokes an LLM or another LangChain component and you want tracing information associated with the overall execution.
You can explicitly forward configuration to a nested model invocation using model.invoke(messages, config=config) or await model.ainvoke(messages, config=config).
Do not modify framework-managed configuration keys or place authentication credentials in tracing metadata. Metadata may be recorded by observability systems.
In modern LangGraph, application-specific information such as a user’s preferences, role, or account details belongs in runtime context rather than config["configurable"].
runtime
Understanding runtime context
Runtime context provides a structured way to supply information that nodes need during an invocation but that does not need to evolve as part of graph state.
Common examples include authenticated user identities, tenant identifiers, language preferences, service clients, and database connections.
Define a context schema when constructing the graph:
builder = StateGraph(
State,
context_schema=Context,
)Nodes can then request a typed Runtime[Context] argument.
Unlike state, context does not participate in state reducers. It is invocation-scoped and is not automatically saved as checkpointed graph state.
Treat context as read-only application input, even when it contains mutable service objects.
Creating a context-aware node
The following example uses the same compiled graph to generate different responses for different invocation contexts.
from dataclasses import dataclass
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
class State(TypedDict):
query: str
response: NotRequired[str]
@dataclass(frozen=True)
class Context:
customer_name: str
support_plan: str
def respond(
state: State,
runtime: Runtime[Context],
) -> dict:
context = runtime.context
if context.support_plan == "premium":
priority = "high"
else:
priority = "standard"
return {
"response": (
f"Hello, {context.customer_name}. "
f"Your query has {priority} priority."
)
}
builder = StateGraph(
State,
context_schema=Context,
)
builder.add_node("respond", respond)
builder.add_edge(START, "respond")
builder.add_edge("respond", END)
graph = builder.compile()
for context in [
Context("Asha", "premium"),
Context("Rahul", "basic"),
]:
result = graph.invoke(
{"query": "I need help"},
context=context,
)
print(result["response"])Expected output:
Hello, Asha. Your query has high priority.
Hello, Rahul. Your query has standard priority.The graph structure remains unchanged. Only the invocation context changes.
This pattern is a form of dependency injection. Rather than relying on mutable global variables or embedding customer details into node implementations, the caller provides the required context explicitly.
In production, identities and authorization-related context must come from trusted server-side authentication and authorization mechanisms, not unverified values supplied by the user.
Other runtime capabilities
The Runtime object provides more than application context.
| Runtime attribute | Purpose |
|---|---|
runtime.context |
Access invocation-specific application data |
runtime.store |
Access the configured cross-thread store |
runtime.stream_writer |
Emit custom streaming events |
The store is particularly useful when an agent needs persistent information beyond its current conversation state.
The following example demonstrates retrieving a saved customer preference and emitting a custom progress event from inside a node.
from dataclasses import dataclass
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
from langgraph.store.memory import InMemoryStore
class State(TypedDict):
query: str
preferred_language: NotRequired[str]
@dataclass(frozen=True)
class Context:
user_id: str
store = InMemoryStore()
store.put(
("users", "U101"),
"preferences",
{"language": "en"},
)
def load_preferences(
state: State,
runtime: Runtime[Context],
) -> dict:
runtime.stream_writer({
"event": "loading_preferences"
})
if runtime.store is None:
raise RuntimeError("A store is required")
item = runtime.store.get(
("users", runtime.context.user_id),
"preferences",
)
language = (
item.value["language"] if item else "en"
)
return {"preferred_language": language}
builder = StateGraph(
State,
context_schema=Context,
)
builder.add_node("load_preferences", load_preferences)
builder.add_edge(START, "load_preferences")
builder.add_edge("load_preferences", END)
graph = builder.compile(store=store)
for chunk in graph.stream(
{"query": "Hello"},
context=Context(user_id="U101"),
stream_mode=["custom", "updates"],
version="v2",
):
print(chunk["type"], chunk["data"])Expected output:
custom {'event': 'loading_preferences'}
updates {'load_preferences': {'preferred_language': 'en'}}The custom event provides progress information without modifying graph state. The returned update, however, adds preferred_language to state.
The in-memory store survives multiple invocations within the lifetime of the store instance, but it is not durable across process restarts.
Tip:
Runtimedoes not containRunnableConfig. When a node needs both execution configuration and application context, declare bothconfig: RunnableConfigandruntime: Runtime[Context]in its function signature.
Node design tips
Give each node a clear responsibility
A node should represent a meaningful unit of work.
Avoid creating one enormous node that validates requests, calls multiple services, generates responses, saves records, and sends notifications.
Separate these responsibilities when doing so improves observability, failure isolation, or recovery.
However, avoid excessive fragmentation. Several trivial transformations that always execute together may reasonably belong in the same node.
A useful boundary is an operation that you might independently test, retry, monitor, or replace.
Design for safe re-execution
Nodes may execute more than once because of retries, checkpoint recovery, or human-in-the-loop interruption and resumption.
For example, a node that charges a customer must not create another payment every time it is retried.
Design external side effects to be idempotent wherever possible. Common approaches include stable idempotency keys, database uniqueness constraints, and checking whether an operation has already completed.
LangGraph checkpointing does not automatically provide exactly-once execution for external side effects.
Keep state clean
Store information that downstream nodes genuinely need.
Avoid placing database connections, HTTP clients, API keys, open files, or large unnecessary intermediate objects inside state.
Checkpointed state should be compatible with the configured serializer. Keeping it small and structured reduces persistence overhead and simplifies debugging.
Runtime context is generally more appropriate for service dependencies.
Handle missing information explicitly
Nodes should distinguish required inputs from optional inputs.
Use direct dictionary indexing when a missing field indicates a programming or workflow error. Use .get() with a sensible default when absence is an expected business condition.
A TypedDict annotation alone does not guarantee that a field exists at runtime.
Validate important external inputs and model outputs before allowing downstream nodes to depend on them.
Test nodes independently
Because nodes are ordinary Python functions, you can unit-test their behavior without compiling or executing the entire graph.
The following example demonstrates testing a context-aware node with explicitly supplied runtime dependencies.
from dataclasses import dataclass
from typing_extensions import TypedDict
from langgraph.runtime import Runtime
class State(TypedDict):
amount: float
@dataclass(frozen=True)
class Context:
discount_rate: float
def calculate_total(
state: State,
runtime: Runtime[Context],
) -> dict:
amount = state["amount"]
discount = runtime.context.discount_rate
if not 0 <= discount <= 1:
raise ValueError("Invalid discount rate")
return {
"amount": round(amount * (1 - discount), 2)
}
state = {"amount": 100.0}
runtime = Runtime(
context=Context(discount_rate=0.10)
)
result = calculate_total(state, runtime)
assert result == {"amount": 90.0}
assert state == {"amount": 100.0}
print("All tests passed")Expected output:
All tests passedThis test verifies both the calculated update and the absence of input-state mutation.
Production test suites should additionally include graph-level integration tests that verify dependency ordering, reducer behavior, configuration propagation, and failure handling.
Common mistakes to avoid
| Mistake | Recommended approach |
|---|---|
| Mutating the received state | Return explicit state updates |
| Returning existing accumulated values | Return only the intended additions |
Calling invoke() on an async-only node graph |
Use await graph.ainvoke() |
| Using blocking network calls inside async nodes | Use asynchronous clients |
| Forgetting to await a coroutine | Await asynchronous operations explicitly |
Reading user data from configurable |
Use typed runtime context |
Expecting runtime.config to exist |
Inject RunnableConfig separately |
| Assuming async nodes automatically run in parallel | Understand graph dependencies |
| Retrying non-idempotent operations | Protect external side effects |
| Catching every exception silently | Preserve meaningful failure information |
For transient service failures, LangGraph supports node-level retry policies through RetryPolicy. For asynchronous nodes, execution timeouts can also be configured. These mechanisms will be explored in the fault-tolerance lessons.
For authoritative API details, consult the LangGraph Graph API documentation, LangGraph execution engine documentation, Runtime reference, and RunnableConfig reference.
Preparing for the next lesson
The examples in this lesson use fixed sequences of nodes. However, intelligent agents often need to choose their next operation dynamically.
A query classification node might identify a billing question, a technical issue, or a general request. Each classification could require a completely different downstream operation.
In the next lesson, Edges, conditional edges and dynamic routing, you will learn how to connect these independently designed nodes into workflows that make decisions, branch, repeat operations, and terminate appropriately.
These capabilities will form the foundation of this chapter’s hands-on project: building an intelligent query-routing system that directs incoming requests to specialized processing nodes.
Build an asynchronous query classifier
Build a graph that normalizes a customer query and asynchronously classifies it as billing, technical, or general. Use runtime context to provide the customer's support plan and preferred language. Read execution metadata through RunnableConfig and return a personalized classification response without modifying the input state.
import asyncio
from dataclasses import dataclass
from typing_extensions import TypedDict, NotRequired
from langchain_core.runnables import RunnableConfig
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
class State(TypedDict):
query: str
normalized_query: NotRequired[str]
category: NotRequired[str]
response: NotRequired[str]
@dataclass(frozen=True)
class Context:
support_plan: str
language: str
def normalize_query(state: State) -> dict:
# TODO: Strip whitespace and convert the query to lowercase.
raise NotImplementedError
async def classify_query(state: State) -> dict:
# TODO: Simulate an external classification service.
# TODO: Classify the query as billing, technical, or general.
raise NotImplementedError
def generate_response(
state: State,
config: RunnableConfig,
runtime: Runtime[Context],
) -> dict:
# TODO: Read the support plan and language from runtime.
# TODO: Read request_id from config metadata.
# TODO: Return a personalized response.
raise NotImplementedError
# TODO: Register the nodes and connect them sequentially.
# TODO: Compile the graph.
async def main():
# TODO: Invoke the graph asynchronously with context and config.
pass
if __name__ == "__main__":
asyncio.run(main())import asyncio
from dataclasses import dataclass
from typing_extensions import TypedDict, NotRequired
from langchain_core.runnables import RunnableConfig
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
class State(TypedDict):
query: str
normalized_query: NotRequired[str]
category: NotRequired[str]
response: NotRequired[str]
@dataclass(frozen=True)
class Context:
support_plan: str
language: str
def normalize_query(state: State) -> dict:
return {
"normalized_query": state["query"].strip().lower()
}
async def classify_query(state: State) -> dict:
# Simulate an external classification service.
await asyncio.sleep(0.2)
query = state["normalized_query"]
if any(word in query for word in (
"invoice", "payment", "refund", "billing"
)):
category = "billing"
elif any(word in query for word in (
"error", "bug", "crash", "login"
)):
category = "technical"
else:
category = "general"
return {"category": category}
def generate_response(
state: State,
config: RunnableConfig,
runtime: Runtime[Context],
) -> dict:
plan = runtime.context.support_plan
language = runtime.context.language
request_id = config.get("metadata", {}).get(
"request_id", "unknown"
)
print(f"Processing request {request_id}")
if language == "es":
response = (
f"Consulta clasificada como {state['category']}. "
f"Plan de soporte: {plan}."
)
else:
response = (
f"Your query was classified as {state['category']}. "
f"Your support plan is {plan}."
)
return {"response": response}
builder = StateGraph(State, context_schema=Context)
builder.add_node("normalize", normalize_query)
builder.add_node("classify", classify_query)
builder.add_node("respond", generate_response)
builder.add_edge(START, "normalize")
builder.add_edge("normalize", "classify")
builder.add_edge("classify", "respond")
builder.add_edge("respond", END)
graph = builder.compile()
async def main():
result = await graph.ainvoke(
{"query": " I need a REFUND for my invoice "},
config={
"metadata": {"request_id": "REQ-1001"},
"recursion_limit": 20,
},
context=Context(
support_plan="premium",
language="en",
),
)
print(result["normalized_query"])
print(result["category"])
print(result["response"])
assert result["category"] == "billing"
assert result["query"] == (
" I need a REFUND for my invoice "
)
if __name__ == "__main__":
asyncio.run(main())Summary
- A LangGraph node is a callable that performs a unit of work and communicates its results through state updates.
- Nodes should return only the state fields they intend to update instead of mutating the received state.
- Reducers determine whether returned updates replace, accumulate, or otherwise merge with existing state values.
- Asynchronous nodes are particularly useful for network requests, database operations, and asynchronous LLM calls.
- RunnableConfig provides execution settings, tracing metadata, concurrency controls, and persistence configuration.
- Runtime context provides typed, invocation-specific application data and dependencies without adding them to graph state.
- Small, testable, and idempotent nodes make agentic workflows easier to maintain, observe, and recover.