Skip to content

Commit 9295ed1

Browse files
sydney-runklemdrxy
authored andcommitted
oss: code snippet fixes + other minor changes (#852)
just scoped to oss folder for now * removing old style comment + annotation syntax * removing `highlight={X,Y,Z}` syntax in favor of `# [!code highlight]` syntax inline * some of @hwchase17's initial docs feedback 👍
1 parent 78cdad7 commit 9295ed1

22 files changed

+556
-584
lines changed

src/oss/concepts/context.mdx

Lines changed: 31 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -39,30 +39,26 @@ LangGraph provides three ways to manage context, which combines the mutability a
3939

4040
**Static runtime context** represents immutable data like user metadata, tools, and database connections that are passed to an application at the start of a run via the `context` argument to `invoke`/`stream`. This data does not change during execution.
4141

42-
```python {highlight={7}}
42+
```python
4343
@dataclass
4444
class ContextSchema:
4545
user_name: str
4646

47-
graph.invoke( # (1)!
48-
{"messages": [{"role": "user", "content": "hi!"}]}, # (2)!
49-
context={"user_name": "John Smith"} # (3)!
47+
graph.invoke(
48+
{"messages": [{"role": "user", "content": "hi!"}]},
49+
context={"user_name": "John Smith"} # [!code highlight]
5050
)
5151
```
5252

53-
1. This is the invocation of the agent or graph. The `invoke` method runs the underlying graph with the provided input.
54-
2. This example uses messages as an input, which is common, but your application may use different input structures.
55-
3. This is where you pass the runtime data. The `context` parameter allows you to provide additional dependencies that the agent can use during its execution.
56-
5753
<Tabs>
5854
<Tab title="Agent prompt">
59-
```python {highlight={6,20}}
55+
```python
6056
from langchain.messages import AnyMessage
6157
from langgraph.runtime import get_runtime
6258
from langgraph.prebuilt.chat_agent_executor import AgentState
6359
from langgraph.prebuilt import create_react_agent
6460

65-
def prompt(state: AgentState) -> list[AnyMessage]:
61+
def prompt(state: AgentState) -> list[AnyMessage]: # [!code highlight]
6662
runtime = get_runtime(ContextSchema)
6763
system_msg = f"You are a helpful assistant. Address the user as {runtime.context.user_name}."
6864
return [{"role": "system", "content": system_msg}] + state["messages"]
@@ -76,32 +72,32 @@ graph.invoke( # (1)!
7672

7773
agent.invoke(
7874
{"messages": [{"role": "user", "content": "what is the weather in sf"}]},
79-
context={"user_name": "John Smith"}
75+
context={"user_name": "John Smith"} # [!code highlight]
8076
)
8177
```
8278

8379
* See [Agents](/oss/langchain/agents) for details.
8480
</Tab>
8581
<Tab title="Workflow node">
86-
```python {highlight={3}}
82+
```python
8783
from langgraph.runtime import Runtime
8884

89-
def node(state: State, runtime: Runtime[ContextSchema]):
85+
def node(state: State, runtime: Runtime[ContextSchema]): # [!code highlight]
9086
user_name = runtime.context.user_name
9187
...
9288
```
9389

9490
* See [the Graph API](/oss/langgraph/graph-api#add-runtime-configuration) for details.
9591
</Tab>
9692
<Tab title="In a tool">
97-
```python {highlight={4}}
93+
```python
9894
from langgraph.runtime import get_runtime
9995

10096
@tool
10197
def get_user_email() -> str:
10298
"""Retrieve user information based on user ID."""
10399
# simulate fetching user info from a database
104-
runtime = get_runtime(ContextSchema)
100+
runtime = get_runtime(ContextSchema) # [!code highlight]
105101
email = get_user_email_from_db(runtime.context.user_name)
106102
return email
107103
```
@@ -130,11 +126,10 @@ Config is for immutable data like user metadata or API keys. Use this when you h
130126

131127
Specify configuration using a key called **"configurable"** which is reserved for this purpose.
132128

133-
```typescript {highlight={4}}
129+
```typescript
134130
await graph.invoke(
135-
// (1)!
136-
{ messages: [{ role: "user", content: "hi!" }] }, // (2)!
137-
{ configurable: { user_id: "user_123" } } // (3)!
131+
{ messages: [{ role: "user", content: "hi!" }] },
132+
{ configurable: { user_id: "user_123" } } // [!code highlight]
138133
);
139134
```
140135
:::
@@ -151,17 +146,17 @@ await graph.invoke(
151146
State can also be accessed by the agent's **tools**, which can read or update the state as needed. See [tool calling guide](/oss/langchain/tools#short-term-memory) for details.
152147

153148
:::python
154-
```python {highlight={6,10,19}}
149+
```python
155150
from langchain.messages import AnyMessage
156151
from langchain_core.runnables import RunnableConfig
157152
from langgraph.prebuilt import create_react_agent
158153
from langgraph.prebuilt.chat_agent_executor import AgentState
159154

160-
class CustomState(AgentState): # (1)!
155+
class CustomState(AgentState): # [!code highlight]
161156
user_name: str
162157

163158
def prompt(
164-
state: CustomState
159+
state: CustomState # [!code highlight]
165160
) -> list[AnyMessage]:
166161
user_name = state["user_name"]
167162
system_msg = f"You are a helpful assistant. User's name is {user_name}"
@@ -170,7 +165,7 @@ await graph.invoke(
170165
agent = create_react_agent(
171166
model="anthropic:claude-3-7-sonnet-latest",
172167
tools=[...],
173-
state_schema=CustomState, # (2)!
168+
state_schema=CustomState, # [!code highlight]
174169
prompt=prompt
175170
)
176171

@@ -179,20 +174,17 @@ await graph.invoke(
179174
"user_name": "John Smith"
180175
})
181176
```
182-
183-
1. Define a custom state schema that extends `AgentState` or `MessagesState`.
184-
2. Pass the custom state schema to the agent. This allows the agent to access and modify the state during execution.
185177
:::
186178
187179
:::js
188-
```typescript {highlight={6,12,22}}
180+
```typescript
189181
import type { BaseMessage } from "@langchain/core/messages";
190182
import { createReactAgent } from "@langchain/langgraph/prebuilt";
191183
import { MessagesZodMeta } from "@langchain/langgraph";
192184
import { registry } from "@langchain/langgraph/zod";
193185
import * as z from "zod";
194186
195-
const CustomState = z.object({ // (1)!
187+
const CustomState = z.object({ // [!code highlight]
196188
messages: z
197189
.array(z.custom<BaseMessage>())
198190
.register(registry, MessagesZodMeta),
@@ -207,10 +199,10 @@ await graph.invoke(
207199
return [{ role: "system", content: systemMsg }, ...state.messages];
208200
};
209201
210-
const agent = createReactAgent({
202+
const agent = createReactAgent({ // [!code highlight]
211203
llm: model,
212204
tools: [...],
213-
stateSchema: CustomState, // (2)!
205+
stateSchema: CustomState, // [!code highlight]
214206
stateModifier: prompt,
215207
});
216208
@@ -219,70 +211,59 @@ await graph.invoke(
219211
userName: "John Smith",
220212
});
221213
```
222-
223-
1. Define a custom state schema that adds additional fields alongside the existing `messages` field.
224-
2. Pass the custom state schema to the agent. This allows the agent to access and modify the state during execution.
225214
:::
226215
</Tab>
227216
<Tab title="In a workflow">
228217
:::python
229-
```python {highlight={5,9,13}}
218+
```python
230219
from typing_extensions import TypedDict
231220
from langchain.messages import AnyMessage
232221
from langgraph.graph import StateGraph
233222

234-
class CustomState(TypedDict): # (1)!
223+
class CustomState(TypedDict): # [!code highlight]
235224
messages: list[AnyMessage]
236225
extra_field: int
237226

238-
def node(state: CustomState): # (2)!
227+
def node(state: CustomState): # [!code highlight]
239228
messages = state["messages"]
240229
...
241-
return { # (3)!
242-
"extra_field": state["extra_field"] + 1
230+
return { # [!code highlight]
231+
"extra_field": state["extra_field"] + 1 # [!code highlight]
243232
}
244233

245234
builder = StateGraph(State)
246235
builder.add_node(node)
247236
builder.set_entry_point("node")
248237
graph = builder.compile()
249238
```
250-
251-
1. Define a custom state
252-
2. Access the state in any node or tool
253-
3. The Graph API is designed to work as easily as possible with state. The return value of a node represents a requested update to the state.
254239
:::
255240
256241
:::js
257-
```typescript {highlight={6,6,14}}
242+
```typescript
258243
import type { BaseMessage } from "@langchain/core/messages";
259244
import { StateGraph, MessagesZodMeta, START } from "@langchain/langgraph";
260245
import { registry } from "@langchain/langgraph/zod";
261246
import * as z from "zod";
262247
263-
const CustomState = z.object({ // (1)!
248+
const CustomState = z.object({ // [!code highlight]
264249
messages: z
265250
.array(z.custom<BaseMessage>())
266251
.register(registry, MessagesZodMeta),
267252
extraField: z.number(),
268253
});
269254
270255
const builder = new StateGraph(CustomState)
271-
.addNode("node", async (state) => { // (2)!
256+
.addNode("node", async (state) => { // [!code highlight]
272257
const messages = state.messages;
273258
// ...
274-
return { // (3)!
259+
return { // [!code highlight]
275260
extraField: state.extraField + 1,
276261
};
277262
})
278263
.addEdge(START, "node");
279264
280265
const graph = builder.compile();
281266
```
282-
283-
1. Define a custom state
284-
2. Access the state in any node or tool
285-
3. The Graph API is designed to work as easily as possible with state. The return value of a node represents a requested update to the state.
286267
:::
287268
</Tab>
288269
</Tabs>

src/oss/langchain/evals.mdx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@ npm install agentevals
6161
A common way to evaluate agent performance is by comparing its trajectory (the order in which it calls its tools) against a reference trajectory:
6262

6363
:::python
64-
```python {highlight={2,39}}
64+
```python
6565
import json
66-
from agentevals.trajectory.match import create_trajectory_match_evaluator
66+
from agentevals.trajectory.match import create_trajectory_match_evaluator # [!code highlight]
6767

6868
outputs = [
6969
{
@@ -100,7 +100,7 @@ reference_outputs = [
100100

101101
# Create the evaluator
102102
evaluator = create_trajectory_match_evaluator(
103-
trajectory_match_mode="superset", # (1)!
103+
trajectory_match_mode="superset", # [!code highlight]
104104
)
105105

106106
# Run the evaluator
@@ -151,7 +151,7 @@ const referenceOutputs = [
151151
// Create the evaluator
152152
const evaluator = createTrajectoryMatchEvaluator({
153153
// Specify how the trajectories will be compared. `superset` will accept output trajectory as valid if it's a superset of the reference one. Other options include: strict, unordered and subset
154-
trajectoryMatchMode: "superset", // (1)!
154+
trajectoryMatchMode: "superset", // [!code highlight]
155155
});
156156

157157
// Run the evaluator
@@ -171,10 +171,10 @@ As a next step, learn more about how to [customize trajectory match evaluator](h
171171
You can use LLM-as-a-judge evaluator that uses an LLM to compare the trajectory against the reference outputs and output a score:
172172

173173
:::python
174-
```python {highlight={3}}
174+
```python
175175
import json
176176
from agentevals.trajectory.llm import (
177-
create_trajectory_llm_as_judge,
177+
create_trajectory_llm_as_judge, # [!code highlight]
178178
TRAJECTORY_ACCURACY_PROMPT_WITH_REFERENCE
179179
)
180180

src/oss/langchain/mcp.mdx

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,11 @@ MCP supports different transport mechanisms for client-server communication:
6666
:::python
6767
`langchain-mcp-adapters` enables agents to use tools defined across one or more MCP server.
6868

69-
```python Accessing multiple MCP servers {highlight={1,4,19,22}} icon="server"
70-
from langchain_mcp_adapters.client import MultiServerMCPClient
69+
```python Accessing multiple MCP servers icon="server"
70+
from langchain_mcp_adapters.client import MultiServerMCPClient # [!code highlight]
7171
from langchain.agents import create_agent
7272

73-
client = MultiServerMCPClient(
73+
client = MultiServerMCPClient( # [!code highlight]
7474
{
7575
"math": {
7676
"transport": "stdio", # Local subprocess communication
@@ -86,10 +86,10 @@ client = MultiServerMCPClient(
8686
}
8787
)
8888

89-
tools = await client.get_tools()
89+
tools = await client.get_tools() # [!code highlight]
9090
agent = create_agent(
9191
"anthropic:claude-3-7-sonnet-latest",
92-
tools
92+
tools # [!code highlight]
9393
)
9494
math_response = await agent.ainvoke(
9595
{"messages": [{"role": "user", "content": "what's (3 + 5) x 12?"}]}
@@ -104,12 +104,12 @@ weather_response = await agent.ainvoke(
104104
:::js
105105
`@langchain/mcp-adapters` enables agents to use tools defined across one or more MCP server.
106106

107-
```ts Accessing multiple MCP servers {highlight={1,5,19,22}} icon="server"
108-
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
107+
```ts Accessing multiple MCP servers icon="server"
108+
import { MultiServerMCPClient } from "@langchain/mcp-adapters"; // [!code highlight]
109109
import { ChatAnthropic } from "@langchain/anthropic";
110110
import { createAgent } from "langchain";
111111

112-
const client = new MultiServerMCPClient({
112+
const client = new MultiServerMCPClient({ // [!code highlight]
113113
math: {
114114
transport: "stdio", // Local subprocess communication
115115
command: "node",
@@ -123,10 +123,10 @@ const client = new MultiServerMCPClient({
123123
},
124124
});
125125

126-
const tools = await client.getTools();
126+
const tools = await client.getTools(); // [!code highlight]
127127
const agent = createAgent({
128128
llm: new ChatAnthropic({ model: "claude-3-7-sonnet-latest" }),
129-
tools,
129+
tools, // [!code highlight]
130130
});
131131

132132
const mathResponse = await agent.invoke({

0 commit comments

Comments
 (0)