Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// :snippet-start: backends-composite-namespace-after-js
import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend } from "deepagents";

const agent = createDeepAgent({
backend: new CompositeBackend(
new StateBackend(),
{ "/memories/": new StoreBackend({
namespace: ({ config }) => [
String(config?.configurable?.langgraph_auth_user_id),
],
}) },
),
});
// :snippet-end:

// :remove-start:
if (!agent) throw new Error("expected agent");
console.log("✓ backends-composite-namespace-after validated");
// :remove-end:
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// :snippet-start: backends-composite-namespace-before-js
import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend } from "deepagents";

const agent = createDeepAgent({
backend: (config) => new CompositeBackend(
new StateBackend(config),
{ "/memories/": new StoreBackend(config, {
namespace: ({ config: cfg }) => [
String(cfg?.configurable?.langgraph_auth_user_id),
],
}) },
),
});
// :snippet-end:

// :remove-start:
if (!agent) throw new Error("expected agent");
console.log("✓ backends-composite-namespace-before validated");
// :remove-end:
14 changes: 14 additions & 0 deletions src/code-samples/deepagents/backends-namespace-factory-type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Backends: StoreBackend namespace factory type alias."""

# :snippet-start: backends-namespace-factory-type-py
from collections.abc import Callable

from langgraph.runtime import Runtime

NamespaceFactory = Callable[[Runtime], tuple[str, ...]]
# :snippet-end:

# :remove-start:
assert NamespaceFactory is not None
print("✓ backends-namespace-factory-type validated")
# :remove-end:
20 changes: 20 additions & 0 deletions src/code-samples/deepagents/backends-namespace-factory-type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// :snippet-start: backends-namespace-factory-type-js
type StoreBackendNamespaceFactory = (context: {
state: unknown;
config?: {
metadata?: Record<string, unknown>;
configurable?: Record<string, unknown>;
};
assistantId?: string;
}) => string[];
// :snippet-end:

// :remove-start:
const factory: StoreBackendNamespaceFactory = ({ assistantId }) => [
assistantId ?? "filesystem",
];
if (factory({ state: {} }).length === 0) {
throw new Error("expected namespace components");
}
console.log("✓ backends-namespace-factory-type validated");
// :remove-end:
29 changes: 29 additions & 0 deletions src/code-samples/deepagents/backends-namespace-patterns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""Backends: common StoreBackend namespace factory patterns."""

# :snippet-start: backends-namespace-patterns-py
from deepagents.backends import StoreBackend

# Per-user: each user gets their own isolated storage
backend = StoreBackend(
namespace=lambda rt: (rt.server_info.user.identity,), # [!code highlight]
)

# Per-assistant: all users of the same assistant share storage
backend = StoreBackend(
namespace=lambda rt: (
rt.server_info.assistant_id, # [!code highlight]
),
)

# Per-thread: storage scoped to a single conversation
backend = StoreBackend(
namespace=lambda rt: (
rt.execution_info.thread_id, # [!code highlight]
),
)
# :snippet-end:

# :remove-start:
assert backend is not None
print("✓ backends-namespace-patterns validated")
# :remove-end:
27 changes: 27 additions & 0 deletions src/code-samples/deepagents/backends-namespace-patterns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// :snippet-start: backends-namespace-patterns-js
import { StoreBackend } from "deepagents";

// Per-user: derive from the authenticated Agent Server user
const perUserBackend = new StoreBackend({
namespace: ({ config }) => [String(config?.configurable?.langgraph_auth_user_id)], // [!code highlight]
});

// Per-assistant: use the resolved assistant id
const perAssistantBackend = new StoreBackend({
namespace: ({ assistantId }) => [assistantId ?? "default"], // [!code highlight]
});

// Static namespace when the scope is known at construction time
const orgId = "acme";
const userId = "user-1";
const staticBackend = new StoreBackend({
namespace: ["memories", orgId, userId, "filesystem"], // [!code highlight]
});
// :snippet-end:

// :remove-start:
if (!perUserBackend || !perAssistantBackend || !staticBackend) {
throw new Error("expected StoreBackend instances");
}
console.log("✓ backends-namespace-patterns validated");
// :remove-end:
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ const store = new InMemoryStore(); // Good for local dev; omit for LangSmith Age
const agent = createDeepAgent({
model: "openai:gpt-6.1-sol",
backend: new StoreBackend({
namespace: (rt) => [rt.serverInfo.user.identity],
namespace: ({ config }) => [
String(config?.configurable?.langgraph_auth_user_id),
],
}),
store,
});
Expand Down
6 changes: 3 additions & 3 deletions src/code-samples/deepagents/overview-excluded-tools.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Overview page: harness profile with excluded filesystem tools."""
"""Overview: hide default filesystem tools via a harness profile."""

# :snippet-start: overview-excluded-tools-py
from deepagents import HarnessProfile, register_harness_profile
Expand All @@ -7,12 +7,12 @@
"anthropic:claude-sonnet-4-6",
HarnessProfile(
excluded_tools=frozenset(
{"ls", "read_file", "write_file", "edit_file", "glob", "grep"}
{"ls", "read_file", "write_file", "edit_file", "delete", "glob", "grep"}
),
),
)
# :snippet-end:

# :remove-start:
print("✓ overview-excluded-tools sample validated")
print("✓ overview-excluded-tools validated")
# :remove-end:
18 changes: 18 additions & 0 deletions src/code-samples/deepagents/overview-excluded-tools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// :snippet-start: overview-excluded-tools-js
import { registerHarnessProfile } from "deepagents";

registerHarnessProfile("anthropic:claude-sonnet-4-6", {
excludedTools: [
"ls",
"read_file",
"write_file",
"edit_file",
"glob",
"grep",
],
});
// :snippet-end:

// :remove-start:
console.log("✓ overview-excluded-tools validated");
// :remove-end:
52 changes: 52 additions & 0 deletions src/code-samples/deepagents/streaming-chunk-shapes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Deep Agents streaming: stream chunk shapes with subgraphs."""

# :remove-start:
import os

from deepagents import create_deep_agent


class _ShapeAgent:
"""Yield one illustrative chunk per stream_mode shape when no API key is set."""

def stream(self, _input, stream_mode="updates", subgraphs=True, **_kwargs):
if isinstance(stream_mode, list):
yield ((), "updates", {"model_request": {}})
return
yield ((), {"model_request": {}})


if os.environ.get("OPENAI_API_KEY"):
agent = create_deep_agent(
model="openai:gpt-6.1-sol",
system_prompt="You are a helpful research assistant",
)
else:
agent = _ShapeAgent()
# :remove-end:

# :snippet-start: streaming-chunk-shapes-py
# Single mode + subgraphs
for namespace, data in agent.stream(
{"messages": [{"role": "user", "content": "Research quantum computing"}]},
stream_mode="updates",
subgraphs=True,
):
print(namespace) # () for main agent, ("tools:<id>",) for subagent
print(data)

# Multiple modes + subgraphs
for namespace, mode, data in agent.stream(
{"messages": [{"role": "user", "content": "Research quantum computing"}]},
stream_mode=["updates", "messages", "custom"],
subgraphs=True,
):
print(mode) # "updates", "messages", or "custom"
print(namespace) # () for main agent, ("tools:<id>",) for subagent
print(data)
# :snippet-end:

# :remove-start:
assert agent is not None
print("✓ streaming-chunk-shapes validated")
# :remove-end:
60 changes: 60 additions & 0 deletions src/code-samples/deepagents/streaming-chunk-shapes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// :remove-start:
import { createDeepAgent } from "deepagents";

type StreamAgent = {
stream: (
input: unknown,
options: unknown,
) => Promise<AsyncIterable<unknown>>;
};

let agent: StreamAgent;

if (process.env.OPENAI_API_KEY) {
agent = createDeepAgent({
model: "openai:gpt-6.1-sol",
systemPrompt: "You are a helpful research assistant",
});
} else {
// Signature-only path when no model key is present: yield one chunk per shape.
agent = {
stream: async (_input, options) => {
const streamMode = (options as { streamMode?: unknown }).streamMode;
if (Array.isArray(streamMode)) {
return (async function* () {
yield [[], "updates", { model_request: {} }];
})();
}
return (async function* () {
yield [[], { model_request: {} }];
})();
},
};
}
// :remove-end:

// :snippet-start: streaming-chunk-shapes-js
// Single mode + subgraphs
for await (const [namespace, data] of await agent.stream(
{ messages: [{ role: "user", content: "Research quantum computing" }] },
{ streamMode: "updates", subgraphs: true },
)) {
console.log(namespace); // [] for main agent, ["tools:<id>"] for subagent
console.log(data);
}

// Multiple modes + subgraphs
for await (const [namespace, mode, data] of await agent.stream(
{ messages: [{ role: "user", content: "Research quantum computing" }] },
{ streamMode: ["updates", "messages", "custom"], subgraphs: true },
)) {
console.log(mode); // "updates", "messages", or "custom"
console.log(namespace); // [] for main agent, ["tools:<id>"] for subagent
console.log(data);
}
// :snippet-end:

// :remove-start:
if (!agent) throw new Error("expected agent from streaming chunk shapes sample");
console.log("✓ streaming-chunk-shapes validated");
// :remove-end:
17 changes: 17 additions & 0 deletions src/code-samples/deepagents/subagents-filter-runs-any.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// :remove-start:
import { Client } from "langsmith";

const client = new Client();
// :remove-end:

// :snippet-start: subagents-filter-runs-any-js
const runs = client.listRuns({
projectName: "<your-project>",
filter: "has(metadata, 'lc_agent_name')",
});
// :snippet-end:

// :remove-start:
if (!runs) throw new Error("expected listRuns iterator");
console.log("✓ subagents-filter-runs-any validated");
// :remove-end:
16 changes: 16 additions & 0 deletions src/code-samples/deepagents/subagents-filter-runs-by-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// :snippet-start: subagents-filter-runs-by-name-js
import { Client } from "langsmith";

const client = new Client();

const runs = client.listRuns({
projectName: "<your-project>",
filter: 'has(metadata, \'{"lc_agent_name": "research-agent"}\')',
});
// :snippet-end:

// :remove-start:
if (!client) throw new Error("expected Client");
if (!runs) throw new Error("expected listRuns iterator");
console.log("✓ subagents-filter-runs-by-name validated");
// :remove-end:
25 changes: 25 additions & 0 deletions src/code-samples/deepagents/subagents-filter-runs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Deep Agents subagents: filter LangSmith runs by lc_agent_name."""

# :snippet-start: subagents-filter-runs-by-name-py
from langsmith import Client

client = Client()

runs = client.list_runs(
project_name="<your-project>",
filter='has(metadata, \'{"lc_agent_name": "research-agent"}\')',
)
# :snippet-end:

# :snippet-start: subagents-filter-runs-any-py
runs = client.list_runs(
project_name="<your-project>",
filter="has(metadata, 'lc_agent_name')",
)
# :snippet-end:

# :remove-start:
assert client is not None
assert runs is not None
print("✓ subagents-filter-runs validated")
# :remove-end:
29 changes: 29 additions & 0 deletions src/code-samples/langchain/models-parallel-tool-calls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""Models: disable parallel tool calls."""

# :remove-start:
import os

os.environ.setdefault("OPENAI_API_KEY", "sk-test-key")

from langchain.tools import tool
from langchain_openai import ChatOpenAI


@tool
def get_weather(city: str) -> str:
"""Get the weather for a city."""
return f"Weather in {city} is sunny"


model = ChatOpenAI(model="gpt-5.4-mini")
# :remove-end:

# :snippet-start: models-parallel-tool-calls-py
model.bind_tools([get_weather], parallel_tool_calls=False)
# :snippet-end:

# :remove-start:
bound = model.bind_tools([get_weather], parallel_tool_calls=False)
assert bound is not None
print("✓ models-parallel-tool-calls validated")
# :remove-end:
Loading
Loading