# @deepagents/agent 中文文档

规范地址：https://npmcn.com/package/%40deepagents/agent/

版本：7\.5\.2
npm 元数据更新时间：2026-11-08T13:59:14.255Z
中文译文更新时间：2026-11-12T07:02:09.414Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40deepagents/agent
原文对照：https://npmcn.com/package/%40deepagents/agent/?lang=original
项目主页：https://github.com/JanuaryLabs/deepagents#readme
源码仓库：https://github.com/JanuaryLabs/deepagents

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：209 kB，56 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：11 个
- peer 依赖：zod ^4\.4\.3
- 首次发布：2025-10-22T15:36:29.299Z
- 最新版本发布：2026-11-08T13:59:13.921Z
- 近 30 天下载量：2717（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：82（近 12 个月 79 个）

## 中文简介

用TypeScript构建多代理AI系统的框架. 创建使用工具的代理,通过交接进行协调,并合作解决复杂任务.

## 安装

```sh
npm install @deepagents/agent
```

也可以使用：`pnpm add @deepagents/agent`、`yarn add @deepagents/agent`、`bun add @deepagents/agent`

## README

# @ deepagents/ 代理服务器

用TypeScript构建多代理AI系统的框架. 创建使用工具的代理,通过交接进行协调,并合作解决复杂任务.

## 特征

-   **代理组成** - 建立具有特定作用和能力的模块化代理人
-   **工具整合** - 与Vercel AI SDK工具兼容
-   **处理** - 特工可以自动委托给专门人员
-   **结构化输出** - 与Zod计划进行类型安全反应
-   **流线** - 实时流出反应
-   **背景共享** - 特工之间的安全状态

## 安装

```bash
npm install @deepagents/agent
```

需要节点js LTS 和 a `zod` 相对依赖.

## 快速启动

### 简单代理

```typescript
import { openai } from '@ai-sdk/openai';

import { agent, execute, user } from '@deepagents/agent';

const assistant = agent({
  name: 'assistant',
  model: openai('gpt-4o'),
  prompt: 'You are a helpful assistant.',
});

const stream = execute(assistant, 'Hello!', {});

for await (const chunk of stream.textStream) {
  process.stdout.write(chunk);
}
```

### 有工具的代理

```typescript
import { openai } from '@ai-sdk/openai';
import { tool } from 'ai';
import { z } from 'zod';

import { agent, execute } from '@deepagents/agent';

const weatherTool = tool({
  description: 'Get weather for a location',
  parameters: z.object({
    location: z.string(),
  }),
  execute: async ({ location }) => {
    return { temperature: 72, condition: 'sunny', location };
  },
});

const weatherAgent = agent({
  name: 'weather_agent',
  model: openai('gpt-4o'),
  prompt: 'You help users check the weather.',
  tools: { weather: weatherTool },
});

const stream = execute(weatherAgent, 'What is the weather in Tokyo?', {});
console.log(await stream.text);
```

### 拥有交接权的多代理人

```typescript
import { openai } from '@ai-sdk/openai';

import { agent, instructions, swarm } from '@deepagents/agent';

const researcher = agent({
  name: 'researcher',
  model: openai('gpt-4o'),
  prompt: 'You research topics and provide detailed information.',
  handoffDescription: 'Handles research and fact-finding tasks',
  tools: {/* research tools */},
});

const writer = agent({
  name: 'writer',
  model: openai('gpt-4o'),
  prompt: 'You write clear, engaging content based on research.',
  handoffDescription: 'Handles writing and content creation',
});

const coordinator = agent({
  name: 'coordinator',
  model: openai('gpt-4o'),
  prompt: instructions({
    purpose: ['Coordinate research and writing tasks'],
    routine: [
      'Analyze the request',
      'Use transfer_to_researcher for fact-finding',
      'Use transfer_to_writer for content creation',
    ],
  }),
  handoffs: [researcher, writer],
});

// Agents automatically transfer control via transfer_to_<agent_name> tools
const stream = swarm(coordinator, 'Write a blog post about AI agents', {});
```

### 结构化输出

```typescript
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

import { agent, generate } from '@deepagents/agent';

const analyzer = agent({
  name: 'analyzer',
  model: openai('gpt-4o'),
  prompt: 'Analyze the sentiment of the given text.',
  output: z.object({
    sentiment: z.enum(['positive', 'negative', 'neutral']),
    confidence: z.number(),
    keywords: z.array(z.string()),
  }),
});

const result = await generate(analyzer, 'I love this product!', {});
console.log(result.output);
// { sentiment: 'positive', confidence: 0.95, keywords: ['love', 'product'] }
```

### 背景变量

代理和工具之间的共享状态 :

```typescript
import { type ToolExecutionOptions, tool } from 'ai';
import { z } from 'zod';

import { agent, execute } from '@deepagents/agent';

// A `type`, not an `interface`: the AI SDK requires a tool context to
// extend Record<string, unknown>, which an interface does not.
type AppContext = {
  userId: string;
  preferences: Record<string, string>;
};

const preferenceTool = tool({
  description: 'Save user preference',
  inputSchema: z.object({
    key: z.string(),
    value: z.string(),
  }),
  execute: async (
    { key, value },
    { context }: ToolExecutionOptions<AppContext>,
  ) => {
    context.preferences[key] = value;
    return `Saved ${key}=${value}`;
  },
});

const assistant = agent<unknown, AppContext>({
  name: 'assistant',
  model: openai('gpt-4o'),
  prompt: (ctx) => `Help user ${ctx?.userId} manage their preferences.`,
  tools: { savePreference: preferenceTool },
});

const context: AppContext = { userId: 'user123', preferences: {} };
const stream = execute(assistant, 'Set my theme to dark', context);
await stream.text;

console.log(context.preferences); // { theme: 'dark' }
```

## API 参考

### `agent(config)`

创建新代理 :

```typescript
agent<Output, ContextIn, ContextOut>({
  name: string;                    // Agent identifier (required)
  model: LanguageModel;            // AI SDK model (required)
  prompt: string | string[] | ((ctx?) => string);  // Instructions
  tools?: ToolSet;                 // Available tools
  handoffs?: Agent[];              // Agents to delegate to
  handoffDescription?: string;     // When to use this agent
  output?: z.Schema<Output>;       // Structured output schema
  temperature?: number;            // LLM temperature
  toolChoice?: ToolChoice;         // 'auto' | 'none' | 'required'
})
```

### `instructions({ purpose, routine })`

结构化提示的助手 :

```typescript
instructions({
  purpose: string | string[],  // Agent's role
  routine: string[],           // Step-by-step workflow
})

// For swarm coordination
instructions.swarm({ purpose, routine })
```

### 执行函数

```typescript
// Streaming execution
execute(agent, messages, context, config?)
stream(agent, messages, context, config?)  // alias

// Non-streaming execution
generate(agent, messages, context, config?)

// High-level UI streaming with handoff support
swarm(agent, messages, context, abortSignal?)
```

### 公用事业

```typescript
// Create user message
user(message: string): UIMessage

// Extract structured output
toOutput<T>(result): Promise<T>
```

## AI 模式提供者

与任何模型提供者一起工作 [维塞尔 AI SDK](https://sdk.vercel.ai/docs)数字 :

```typescript
import { anthropic } from '@ai-sdk/anthropic';
import { google } from '@ai-sdk/google';
import { groq } from '@ai-sdk/groq';
import { openai } from '@ai-sdk/openai';

const agent1 = agent({ model: openai('gpt-4o') /* ... */ });
const agent2 = agent({
  model: anthropic('claude-sonnet-4-20250514') /* ... */,
});
const agent3 = agent({ model: google('gemini-1.5-pro') /* ... */ });
```

## 文档

备有文件全文 [(原始内容存档于2013-10-12) (日语). januarylabs.github.io/deepagents](https://januarylabs.github.io/deepagents/docs/agent)。 。 。 .

## 仓库

[github.com/ 1月Labs/深潜剂](https://github.com/JanuaryLabs/deepagents)

## 常见问题

### @deepagents/agent 是什么？

用TypeScript构建多代理AI系统的框架\. 创建使用工具的代理,通过交接进行协调,并合作解决复杂任务\.

### 如何安装 @deepagents/agent？

在项目目录运行 npm install @deepagents/agent，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：zod（^4\.4\.3）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @deepagents/agent 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @deepagents/agent 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @deepagents/agent 可以商用吗？

@deepagents/agent 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @deepagents/agent 的下载量有多少？

根据 npm 官方下载统计，@deepagents/agent 在 2026/10/12 – 2026/11/10 这 30 天内被下载 2,717 次，日均约 91 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @deepagents/agent 还在维护吗？

最新版本 7\.5\.2 发布于 2026/11/08（3 天前）；至今共发布 82 个版本，其中过去 12 个月发布了 79 个；首次发布于 2025/10/22。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

