Deep Agents Code overview and capabilities
Deep Agents Code (dcode) is an open source coding agent built on the Deep Agents SDK. It works with any large language model and supports switching providers or models. Key capabilities include: persistent memory that carries context across conversations, customizable skills that shape behavior, approval controls that gate code execution, remote sandboxes for running agent tools remotely, goals and rubrics for defining measurable objectives, subagents for delegating work to task-specific agents, memory for storing and retrieving information across sessions, context compaction for summarizing older messages, human-in-the-loop for requiring approval for sensitive operations, MCP tools for loading external tools from Model Context Protocol servers, and tracing in LangSmith for observability.
Running content builder agent - Python invocation
From the project directory, invoke the Python content builder with: python content_writer.py (for interactive prompt) or python content_writer.py "Write a blog post about prompt engineering" (with prompt as argument).
Content builder artifact output example structure
On success, generated artifacts follow this structure: blogs/prompt-engineering/ containing post.md and hero.png, and research/prompt-engineering.md. Paths follow the skill instructions in SKILL.md.
Running content builder agent - JavaScript invocation
From the project directory, invoke the JavaScript content builder with: npx tsx content_writer.ts (for interactive prompt). Pass a prompt as extra arguments: npx tsx content_writer.ts Write a blog post about prompt engineering
Content builder agent overview and capabilities
The content builder agent is a Deep Agents example that loads voice and workflow rules from AGENTS.md and skill folders, delegates web research to a specialized subagent with web_search, drafts blog or social content following the loaded skill, and generates cover or social images with Gemini and saves files under the project directory. It demonstrates long-term memory, skills, subagents, filesystem backends, and custom tools for search and image generation.
Deep research agent overview and capabilities
A multi-step web research agent decomposes research questions into focused tasks, delegates them to specialized sub-agents, and synthesizes findings into a comprehensive report. The agent plans research using the opt-in todo list middleware, delegates focused research tasks to sub-agents with isolated context, assesses search results and plans next steps as information is gathered, and synthesizes findings with proper citations into a final report. Sub-agents conduct web searches with Tavily, fetching full webpage content for analysis.
Deep research agent execution modes
The agent can be run synchronously, where it waits for the full result and then prints it, or asynchronously by streaming updates as they come in.
Deep research agent JavaScript dependencies
For Claude: install deepagents, @langchain/anthropic, @langchain/core. For Gemini: install deepagents, @langchain/google-genai, @langchain/core.
Deep research agent prerequisites
API keys are required for: Anthropic (Claude) or Google (Gemini) as the LLM provider, Tavily for web search (optional - free tier sufficient), and LangSmith for tracing (optional).
Deep research agent Python dependencies
For Claude: install deepagents, tavily-python, httpx, markdownify, langchain-anthropic, langchain-core. For Gemini: install deepagents, tavily-python, httpx, markdownify, langchain-google-genai, langchain-core.
LangSmith tracing for deep research agents
LangSmith can be used for tracing research runs to debug and monitor multi-step behavior. Set the LANGSMITH_API_KEY environment variable before running the agent to view traces in LangSmith.
Agent invocation with streaming
Invoke a deep agent using agent.stream_events() with a messages input, a config object, and version='v3'. This streams snapshots of agent execution that can be displayed using pretty_print().
Data analysis agent example workflow
A typical data analysis agent workflow: accept a CSV file for analysis, use code execution to perform exploratory data analysis, generate visualizations using libraries like matplotlib and pandas, download the generated plots, and send the analysis and visualizations to a communication channel like Slack.
Deep Agents data analysis use case overview
Deep Agents can be used to build data analysis agents that accept CSV files, plan and track analysis steps with a todo list, perform exploratory data analysis and generate visualizations, and share results to external channels like Slack. Multi-step reasoning, code execution, and handling artifacts like scripts, reports, and plots are core capabilities deep agents are designed to handle.
Install deepagents core package
To build a deep agent, install the core deepagents package using: pip install deepagents
Deep Agents ecosystem integration
Deep Agents integrates with the broader LangChain ecosystem, including LangSmith for observability, evaluation, and deployment, and works across any model provider. Claude Agent SDK is purpose-built for Claude and Anthropic's product surface.
Deep Agents model provider flexibility
Deep Agents supports any model provider including Anthropic, OpenAI, Google, and 100+ others. Claude Agent SDK only supports Claude models through Anthropic, Bedrock, Vertex, or Azure.
Deep Agents deployment modes
Deep Agents runs in two modes without code changes: managed mode using Managed Deep Agents in LangSmith, or self-hosted mode by running langgraph build to produce a standalone Docker image deployable anywhere. Claude Agent SDK only supports self-hosted deployment, and code written against the SDK does not deploy directly to Claude managed agents.
Deep Agents server features
Deep Agents deployments include an agent server out of the box with streaming endpoints, thread management, run history, webhooks, and authentication. Claude Agent SDK requires you to write your own HTTP/WebSocket or SSE server that invokes the agent, streams tokens back, and manages conversation threads.
When to choose Claude Agent SDK
Choose Claude Agent SDK if you are already invested in the Anthropic ecosystem and wish to self-host and build the API, auth, and multi-tenant layers yourself.
When to choose Deep Agents
Choose Deep Agents if you want model and infrastructure flexibility, built-in multi-tenant deployment, and the option to run managed or self-hosted without code changes.
OpenSWE and LangSmith Fleet use Deep Agents
Deep Agents is used in production by OpenSWE and LangSmith Fleet.
Deep Agents vs Claude Agent SDK execution environment
Deep Agents supports two patterns for connecting agents to sandboxes: running the agent inside the sandbox (same as Claude Agent SDK), or running the agent outside the sandbox and using the sandbox as a tool. Claude Agent SDK only supports the first pattern where the agent runs inside a sandbox and executes tools against the sandbox's local filesystem. Deep Agents lets you pick a backend to wire these patterns together.
Stream messages from coordinator and subagents
Deep Agents can emit messages from the coordinator agent and from delegated subagents. Use stream.messages for top-level messages and subagent.messages for each delegated subagent.
stream.subagents for delegated task streaming
Deep Agents add a subagent projection on top of LangGraph streaming. Use stream.subagents when you want one stream handle per delegated task call. The projection is lightweight: it discovers subagent tasks first, and message, tool-call, and value streams are opened only when you access them on a subagent handle.
Stream tool calls at multiple agent levels
Deep Agents expose tool calls at each level of the agent tree. Use the top-level stream.tool_calls for coordinator tools and each subagent.tool_calls for delegated work.
Concurrent stream consumption in Python synchronous code
For synchronous Python code, use stream.interleave(...) instead of asyncio.gather to consume coordinator and subagent streams concurrently.
Raw protocol event ordering across coordinator and subagents
When you need exact arrival order across the coordinator and all subagents, iterate raw protocol events and use the namespace field to identify the source.
Concurrent stream consumption in Python async code
For concurrent consumption in async code, use astream_events with asyncio.gather to consume coordinator and subagent streams concurrently. This allows live UI updates when coordinator and subagent output interleave.
Frontend SDK exposes stream.subagents for subagent discovery
The frontend SDK exposes stream.subagents which provides live discovery of specialist workers, including their status and task metadata. This allows real-time rendering of subagent-specific UIs.
Deep Agents coordinator-worker architecture
Deep Agents use a coordinator-worker architecture where the main agent plans tasks and delegates to specialized subagents, each running in isolation. The coordinator sends stream data to the frontend, which can scope views to individual subagents through selector helpers.
Deep Agents built on LangGraph runtime
Deep Agents are built on the same LangGraph runtime as regular agents. The useStream hook provides the same core API and supports all LangChain frontend patterns including markdown messages, tool calling, and human-in-the-loop.
Deep Agent frontend patterns include subagent streaming, todo list, and sandbox
Three main frontend patterns are available for Deep Agents: subagent streaming for displaying specialist subagents with streaming content and progress tracking, todo list for real-time task progress, and sandbox for IDE-like UIs with file browser and code viewer.
Deep Agent SDK stream projections
The frontend SDK exposes four main projections for Deep Agent UIs: stream.messages for the coordinator conversation and final synthesis, stream.subagents for live specialist worker discovery, stream.values for shared state like todos and plans, and tool-call state for rendering filesystem and domain tools as cards.
Deep Agent frontend patterns use v1 SDK packages
Deep Agent frontend patterns use v1 frontend SDK packages for React, Vue, Svelte, and Angular. Migration guides are available for upgrading from earlier versions.
Deep Agents visualize delegation in UI
Deep agents are most useful when the UI makes delegation visible. Instead of showing a single opaque assistant bubble, the LangChain SDKs expose the coordinator, subagent discovery, custom state, and sandbox-backed artifacts so users can inspect how a long-running task is being decomposed and completed.
useStream hook for Deep Agents
The useStream hook from @langchain/react connects to Deep Agent backends the same way as with createAgent. It accepts a type parameter for type-safe stream state and provides access to stream.messages, stream.subagents, and stream.values for rendering subagent-specific UIs.
useStream selector helpers scope views to subagents
The frontend SDK provides selector helpers such as useMessages that can scope stream views to specific subagents, allowing fine-grained control over which subagent data is rendered.
Sandbox IDE frontend architecture: three parts
A sandbox IDE frontend has three parts: (1) A deep agent with a sandbox backend that gets filesystem tools automatically (read_file, write_file, edit_file, delete/execute). (2) A custom API server (FastAPI in Python or Hono in JavaScript) exposed via langgraph.json's http.app field, providing file browsing endpoints. (3) A three-panel frontend (file tree sidebar, code/diff viewer, chat panel) that syncs files in real time as the agent makes changes.
ProgressBar component with percentage display
Example React ProgressBar component that displays completion percentage:
```tsx
function ProgressBar({ percentage }: { percentage: number }) {
return (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs text-gray-500">
<span>Progress</span>
<span>{percentage}%</span>
</div>
<div className="h-2 overflow-hidden rounded-full bg-gray-200">
<div
className="h-full rounded-full bg-green-500 transition-all duration-500"
style={{ width: `${percentage}%` }}
/>
</div>
</div>
);
}
```
Combined todo list and chat layout example
Example TodoAgentLayout component combining todo list with chat:
```tsx
function TodoAgentLayout() {
const stream = useStream<typeof myAgent>({
apiUrl: AGENT_URL,
assistantId: "deep_agent_todo_list",
});
const todos = stream.values?.todos ?? [];
return (
<div className="flex h-screen flex-col">
{todos.length > 0 && (
<div className="border-b bg-gray-50 p-4">
<TodoList todos={todos} />
</div>
)}
<main className="flex-1 overflow-y-auto p-6">
<div className="mx-auto max-w-2xl space-y-4">
{stream.messages.map((msg) => (
<Message key={msg.id} message={msg} />
))}
</div>
</main>
<ChatInput
onSubmit={(text) =>
stream.submit({ messages: [{ type: "human", content: text }] })
}
isLoading={stream.isLoading}
/>
</div>
);
}
```
TodoItem component with status-specific styling
Example React TodoItem component with status-based configuration:
```tsx
function TodoItem({ todo }: { todo: Todo }) {
const config = {
pending: {
icon: "○",
textClass: "text-gray-600",
bgClass: "bg-gray-50",
iconClass: "text-gray-400",
},
in_progress: {
icon: "◉",
textClass: "text-amber-800",
bgClass: "bg-amber-50 border-amber-200",
iconClass: "text-amber-500 animate-pulse",
},
completed: {
icon: "✓",
textClass: "text-green-800 line-through",
bgClass: "bg-green-50 border-green-200",
iconClass: "text-green-500",
},
};
const style = config[todo.status];
return (
<li
className={`flex items-start gap-3 rounded-md border px-3 py-2 ${style.bgClass}`}
>
<span className={`mt-0.5 text-lg leading-none ${style.iconClass}`}>
{style.icon}
</span>
<span className={`text-sm ${style.textClass}`}>{todo.content}</span>
</li>
);
}
```
Handle loading state before agent plan creation
Before the agent has created its plan, show a loading state when isLoading is true and todos.length === 0. Display a spinner with text like 'Agent is creating a plan...'.
useStream Angular dependency injection hook example
Example Angular implementation:
```ts
import { Component, computed } from "@angular/core";
import { injectStream } from "@langchain/angular";
const AGENT_URL = "http://localhost:2024";
@Component({
selector: "app-todo-agent",
template: `
<div>
<app-todo-list [todos]="todos()" />
@for (msg of stream.messages(); track msg.id) {
<app-message [message]="msg" />
}
</div>
`,
})
export class TodoAgentComponent {
stream = injectStream<typeof myAgent>({
apiUrl: AGENT_URL,
assistantId: "deep_agent_todo_list",
});
todos = computed(() => this.stream.values()?.todos ?? []);
}
```
useStream Svelte reactive hook example
Example Svelte implementation:
```svelte
<script lang="ts">
import { useStream } from "@langchain/svelte";
const AGENT_URL = "http://localhost:2024";
const stream = useStream<typeof myAgent>({
apiUrl: AGENT_URL,
assistantId: "deep_agent_todo_list",
});
const todos = $derived(stream.values?.todos ?? []);
</script>
<div>
<TodoList {todos} />
{#each stream.messages as msg (msg.id)}
<Message message={msg} />
{/each}
</div>
```
useStream Vue composition API hook example
Example Vue implementation:
```vue
<script setup lang="ts">
import { useStream } from "@langchain/vue";
import { computed } from "vue";
const AGENT_URL = "http://localhost:2024";
const stream = useStream<typeof myAgent>({
apiUrl: AGENT_URL,
assistantId: "deep_agent_todo_list",
});
const todos = computed(() => stream.values.value?.todos ?? []);
</script>
<template>
<div>
<TodoList :todos="todos" />
<Message
v-for="msg in stream.messages.value"
:key="msg.id"
:message="msg"
/>
</div>
</template>
```
useStream React hook example for todo agent
Example React implementation:
```tsx
import { useStream } from "@langchain/react";
const AGENT_URL = "http://localhost:2024";
export function TodoAgent() {
const stream = useStream<typeof myAgent>({
apiUrl: AGENT_URL,
assistantId: "deep_agent_todo_list",
});
const todos = stream.values?.todos ?? [];
return (
<div>
<TodoList todos={todos} />
{stream.messages.map((msg) => (
<Message key={msg.id} message={msg} />
))}
</div>
);
}
```
Todo list use cases in agent workflows
The todo list pattern fits scenarios where agents execute structured plans: (1) Project planning - agent breaks projects into tasks and works through them sequentially; (2) Research workflows - research questions become todos; (3) Data processing - steps like ingestion, validation, transformation, export get their own todos; (4) Onboarding flows - agent walks through setup steps; (5) Report generation - report sections become todos for data gathering, analysis, writing, and formatting.
Todo list best practices for agent UI
Best practices for todo list UI include: (1) Show the todo list prominently as the primary progress indicator; (2) Animate status transitions using CSS for smooth responsiveness; (3) Only highlight one in_progress item to avoid UI noise; (4) Collapse or dim completed items to reduce visual weight; (5) Show the progress percentage for immediate understandability; (6) Keep the todo list in sync using reactive stream.values updates without manual polling.
TodoListMiddleware enables todo state channel
Deep agents can expose a todos state channel when you opt into TodoListMiddleware. The middleware adds the write_todos tool and persists task progress as the agent works through its plan. Task planning is opt-in; without TodoListMiddleware, stream.values.todos is not present.
Only display todo list when todos.length > 0
The todo list should only be shown when todos.length > 0. Before the agent creates its plan, there is nothing to display, so showing an empty component wastes space.
Calculating todo progress metrics from stream.values
Progress metrics can be derived directly from the todos array using array filtering. The completed count filters for status === 'completed', in_progress filters for status === 'in_progress', pending filters for status === 'pending'. The percentage is calculated as Math.round((completed / todos.length) * 100) when todos.length > 0.
Todo item status icon styling configuration
Todo items display status-specific styling: pending items show a hollow circle (○) with gray text and gray background; in_progress items show a filled circle (◉) with amber text, amber background, and animated pulse; completed items show a checkmark (✓) with green text, strikethrough text decoration, and green background.
TodoList component rendering implementation
Example TodoList React component that renders a header with task count, progress bar, and todo items:
```tsx
function TodoList({ todos }: { todos: Todo[] }) {
const completed = todos.filter((t) => t.status === "completed").length;
const percentage = todos.length
? Math.round((completed / todos.length) * 100)
: 0;
return (
<div className="rounded-lg border bg-white p-4 shadow-sm">
<div className="mb-4 flex items-center justify-between">
<h2 className="text-lg font-semibold">Agent Progress</h2>
<span className="text-sm text-gray-500">
{completed}/{todos.length} tasks
</span>
</div>
<ProgressBar percentage={percentage} />
<ul className="mt-4 space-y-2">
{todos.map((todo, i) => (
<TodoItem key={i} todo={todo} />
))}
</ul>
</div>
);
}
```
useStream hook accepts apiUrl and assistantId parameters
The useStream hook is called with an object containing apiUrl (the agent server URL, e.g., 'http://localhost:2024') and assistantId (the agent identifier, e.g., 'deep_agent_todo_list') parameters.
Todo list pattern flow in deep agents
The todo list flow works as follows: (1) User submits a request, (2) Agent creates a plan and populates todos in its state, (3) Agent begins executing and each todo transitions through pending → in_progress → completed, (4) stream.values.todos updates in real time, (5) UI re-renders with current statuses.
useStream hook exposes todos via stream.values.todos
The useStream hook exposes the todos state channel via stream.values.todos. The UI can render it reactively by accessing this property from the stream object.
Loading state handling for todo list
Example TodoList component handling empty and loading states:
```tsx
function TodoList({ todos, isLoading }: { todos: Todo[]; isLoading: boolean }) {
if (todos.length === 0 && !isLoading) {
return null;
}
if (todos.length === 0 && isLoading) {
return (
<div className="rounded-lg border bg-white p-4 shadow-sm">
<div className="flex items-center gap-2 text-sm text-gray-500">
<span className="animate-spin">⟳</span>
Agent is creating a plan...
</div>
</div>
);
}
return (
<div className="rounded-lg border bg-white p-4 shadow-sm">
{/* ... full todo list rendering */}
</div>
);
}
```
Todo status transitions during agent execution
As an agent executes, each todo transitions through three states: pending, in_progress, and completed. The stream.values.todos updates in real time as the agent progresses through these state changes.
Thread, User, and Assistant as scoping primitives in production
In production deep agents, information is shared and accessed through three primitives: Thread (a single conversation where message history and scratch files are scoped by default and don't carry over), User (someone interacting with the agent where memory and files can be private to a user or shared across users), and Assistant (a configured agent instance where memory and files can be tied to one assistant or shared across all of them). Thread_id scopes the conversation, while context carries per-run data the tools and middleware read. They are independent: changing one does not affect the other.