Skip to content

Commit fd1e40c

Browse files
authored
Improve the Python scripts in the short term memory docs (#3912)
1 parent 007a8b4 commit fd1e40c

5 files changed

Lines changed: 596 additions & 42 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# :snippet-start: short-term-memory-usage-py
2+
from langchain.agents import create_agent
3+
from langgraph.checkpoint.memory import InMemorySaver # [!code highlight]
4+
5+
6+
def get_user_info() -> str:
7+
"""Look up information about the current user."""
8+
return "No user profile on file."
9+
10+
11+
agent = create_agent(
12+
model="openai:gpt-5.4",
13+
tools=[get_user_info],
14+
checkpointer=InMemorySaver(), # [!code highlight]
15+
)
16+
17+
thread_config = {"configurable": {"thread_id": "1"}}
18+
response = agent.invoke(
19+
{"messages": [{"role": "user", "content": "Hi! My name is Bob."}]},
20+
thread_config, # [!code highlight]
21+
)["messages"][-1].content
22+
23+
print(response) # "Hi Bob! Nice to see you here. How are you doing?"
24+
25+
response = agent.invoke(
26+
{"messages": [{"role": "user", "content": "What's my name?"}]},
27+
thread_config, # [!code highlight]
28+
)["messages"][-1].content
29+
30+
print(response) # "You are Bob!"
31+
# :snippet-end:
32+
33+
# :remove-start:
34+
if __name__ == "__main__":
35+
assert response.strip(), "expected non-empty assistant reply on second turn"
36+
messages = agent.get_state(thread_config).values["messages"]
37+
human_msgs = [m for m in messages if m.type == "human"]
38+
assert len(human_msgs) >= 2, "expected two human turns in thread history"
39+
assert "bob" in response.lower(), "expected assistant to recall the name from the first turn"
40+
print("✓ checkpointer persists conversation across turns on the same thread_id")
41+
# :remove-end:
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// :snippet-start: short-term-memory-usage-js
2+
import { createAgent, tool } from "langchain";
3+
import { MemorySaver } from "@langchain/langgraph"; // [!code highlight]
4+
import * as z from "zod";
5+
6+
const getUserInfo = tool(() => "No user profile on file.", {
7+
name: "get_user_info",
8+
description: "Look up information about the current user.",
9+
schema: z.object({}),
10+
});
11+
12+
const checkpointer = new MemorySaver(); // [!code highlight]
13+
14+
const agent = createAgent({
15+
model: "openai:gpt-5.4",
16+
tools: [getUserInfo],
17+
checkpointer,
18+
});
19+
20+
const threadConfig = { configurable: { thread_id: "1" } };
21+
let result = await agent.invoke(
22+
{ messages: [{ role: "user", content: "Hi! My name is Bob." }] },
23+
threadConfig, // [!code highlight]
24+
);
25+
let response = result.messages.at(-1)?.content;
26+
console.log(response); // "Hi Bob! Nice to see you here. How are you doing?"
27+
28+
result = await agent.invoke(
29+
{ messages: [{ role: "user", content: "What's my name?" }] },
30+
threadConfig, // [!code highlight]
31+
);
32+
response = result.messages.at(-1)?.content;
33+
console.log(response); // "You are Bob!"
34+
// :snippet-end:
35+
36+
// :remove-start:
37+
function assistantText(content: unknown): string {
38+
if (typeof content === "string") {
39+
return content;
40+
}
41+
return "";
42+
}
43+
44+
async function main() {
45+
const text = assistantText(response);
46+
if (!text.trim()) {
47+
throw new Error("expected non-empty assistant reply on second turn");
48+
}
49+
const humanCount = result.messages.filter((m) => m.type === "human").length;
50+
if (humanCount < 2) {
51+
throw new Error(`expected >=2 human turns, got ${humanCount}`);
52+
}
53+
if (!text.toLowerCase().includes("bob")) {
54+
throw new Error(
55+
"expected assistant to recall the name from the first turn",
56+
);
57+
}
58+
console.log(
59+
"✓ checkpointer persists conversation across turns on the same thread_id",
60+
);
61+
}
62+
63+
main();
64+
// :remove-end:

src/oss/langchain/short-term-memory.mdx

Lines changed: 20 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
title: Short-term memory
33
---
44

5+
import ShortTermMemoryUsagePy from '/snippets/code-samples/short-term-memory-usage-py.mdx';
6+
import ShortTermMemoryUsageJs from '/snippets/code-samples/short-term-memory-usage-js.mdx';
7+
58
## Overview
69

710
Memory is a system that remembers information about previous interactions. For AI agents, memory is crucial because it lets them remember previous interactions, learn from feedback, and adapt to user preferences. As agents tackle more complex tasks with numerous user interactions, this capability becomes essential for both efficiency and user satisfaction.
@@ -37,41 +40,14 @@ To add short-term memory (thread-level persistence) to an agent, you need to spe
3740
</Info>
3841

3942
:::python
40-
```python
41-
from langchain.agents import create_agent
42-
from langgraph.checkpoint.memory import InMemorySaver # [!code highlight]
4343

44+
<ShortTermMemoryUsagePy />
4445

45-
agent = create_agent(
46-
"gpt-5.4",
47-
tools=[get_user_info],
48-
checkpointer=InMemorySaver(), # [!code highlight]
49-
)
50-
51-
agent.invoke(
52-
{"messages": [{"role": "user", "content": "Hi! My name is Bob."}]},
53-
{"configurable": {"thread_id": "1"}}, # [!code highlight]
54-
)
55-
```
5646
:::
5747
:::js
58-
```ts {highlight={2,4, 9,14}}
59-
import { createAgent } from "langchain";
60-
import { MemorySaver } from "@langchain/langgraph";
6148

62-
const checkpointer = new MemorySaver();
49+
<ShortTermMemoryUsageJs />
6350

64-
const agent = createAgent({
65-
model: "claude-sonnet-4-6",
66-
tools: [],
67-
checkpointer,
68-
});
69-
70-
await agent.invoke(
71-
{ messages: [{ role: "user", content: "hi! i am Bob" }] },
72-
{ configurable: { thread_id: "1" } }
73-
);
74-
```
7551
:::
7652

7753
### In production
@@ -86,15 +62,17 @@ pip install langgraph-checkpoint-postgres
8662

8763
```python
8864
from langchain.agents import create_agent
89-
9065
from langgraph.checkpoint.postgres import PostgresSaver # [!code highlight]
9166

67+
def get_user_info() -> str:
68+
"""Look up information about the current user."""
69+
return "No user profile on file."
9270

9371
DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable"
9472
with PostgresSaver.from_conn_string(DB_URI) as checkpointer:
9573
checkpointer.setup() # auto create tables in PostgreSQL
9674
agent = create_agent(
97-
"gpt-5.4",
75+
"gpt-5.5",
9876
tools=[get_user_info],
9977
checkpointer=checkpointer, # [!code highlight]
10078
)
@@ -130,7 +108,7 @@ class CustomAgentState(AgentState): # [!code highlight]
130108
preferences: dict # [!code highlight]
131109

132110
agent = create_agent(
133-
"gpt-5.4",
111+
"gpt-5.5",
134112
tools=[get_user_info],
135113
state_schema=CustomAgentState, # [!code highlight]
136114
checkpointer=InMemorySaver(),
@@ -167,7 +145,7 @@ const stateExtensionMiddleware = createMiddleware({
167145

168146
const checkpointer = new MemorySaver();
169147
const agent = createAgent({
170-
model: "gpt-5.4",
148+
model: "gpt-5.5",
171149
tools: [],
172150
middleware: [stateExtensionMiddleware], // [!code highlight]
173151
checkpointer,
@@ -248,8 +226,8 @@ def trim_messages(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
248226
}
249227

250228
agent = create_agent(
251-
your_model_here,
252-
tools=your_tools_here,
229+
"gpt-5.5",
230+
tools=[...],
253231
middleware=[trim_messages],
254232
checkpointer=InMemorySaver(),
255233
)
@@ -304,8 +282,8 @@ const trimMessages = createMiddleware({
304282

305283
const checkpointer = new MemorySaver();
306284
const agent = createAgent({
307-
model: "gpt-5.4",
308-
tools: [],
285+
model: "gpt-5.5",
286+
tools: [...],
309287
middleware: [trimMessages],
310288
checkpointer,
311289
});
@@ -399,7 +377,7 @@ def delete_old_messages(state: AgentState, runtime: Runtime) -> dict | None:
399377

400378
agent = create_agent(
401379
"gpt-5-nano",
402-
tools=[],
380+
tools=[...],
403381
system_prompt="Please be concise and to the point.",
404382
middleware=[delete_old_messages],
405383
checkpointer=InMemorySaver(),
@@ -454,7 +432,7 @@ const deleteOldMessages = createMiddleware({
454432
});
455433

456434
const agent = createAgent({
457-
model: "gpt-5.4",
435+
model: "gpt-5.5",
458436
tools: [],
459437
systemPrompt: "Please be concise and to the point.",
460438
middleware: [deleteOldMessages],
@@ -521,8 +499,8 @@ from langchain_core.runnables import RunnableConfig
521499
checkpointer = InMemorySaver()
522500

523501
agent = create_agent(
524-
model="gpt-5.4",
525-
tools=[],
502+
model="gpt-5.5",
503+
tools=[...],
526504
middleware=[
527505
SummarizationMiddleware(
528506
model="gpt-5.4-mini",
@@ -559,7 +537,7 @@ import { MemorySaver } from "@langchain/langgraph";
559537
const checkpointer = new MemorySaver();
560538

561539
const agent = createAgent({
562-
model: "gpt-5.4",
540+
model: "gpt-5.5",
563541
tools: [],
564542
middleware: [
565543
summarizationMiddleware({

0 commit comments

Comments
 (0)