opc-agent 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,53 +6,77 @@
6
6
  npm install -g opc-agent
7
7
  ```
8
8
 
9
- ## 创建项目
9
+ ## 创建第一个智能体
10
10
 
11
11
  ```bash
12
+ # 交互式创建(会让你选模板和配置)
12
13
  opc init my-agent
13
14
  cd my-agent
14
15
  ```
15
16
 
17
+ 或者直接用模板:
18
+
19
+ ```bash
20
+ opc init my-bot --template customer-service
21
+ opc init my-bot --template sales-assistant
22
+ opc init my-bot --template knowledge-base
23
+ ```
24
+
16
25
  ## 配置
17
26
 
18
- 编辑 `.env` 文件,设置 API 密钥:
27
+ 编辑 `.env` 文件,填入你的大语言模型 API Key:
19
28
 
20
29
  ```bash
21
30
  OPC_LLM_API_KEY=your-api-key
22
- OPC_LLM_BASE_URL=https://api.openai.com/v1
23
- OPC_LLM_MODEL=gpt-4o-mini
31
+ OPC_LLM_BASE_URL=https://api.deepseek.com/v1 # DeepSeek
32
+ OPC_LLM_MODEL=deepseek-chat
24
33
  ```
25
34
 
35
+ 支持的供应商和对应的 Base URL:
36
+
37
+ | 供应商 | Base URL | 推荐模型 |
38
+ |--------|----------|---------|
39
+ | DeepSeek | `https://api.deepseek.com/v1` | `deepseek-chat` |
40
+ | 通义千问 | `https://dashscope.aliyuncs.com/compatible-mode/v1` | `qwen-plus` |
41
+ | OpenAI | `https://api.openai.com/v1` | `gpt-4o-mini` |
42
+ | Ollama (本地) | `http://localhost:11434/v1` | `llama3` |
43
+
26
44
  ## 启动
27
45
 
28
46
  ```bash
29
- # Web 服务器模式
47
+ # 启动 Web 对话服务
30
48
  opc run
31
49
 
32
- # CLI 对话模式
50
+ # 或者用命令行对话
33
51
  opc chat
52
+
53
+ # 开发模式(改代码自动重启)
54
+ opc dev
34
55
  ```
35
56
 
36
- ## 测试
57
+ 访问 `http://localhost:3000` 即可看到对话界面。
58
+
59
+ ## 校验配置
37
60
 
38
61
  ```bash
39
- opc test
62
+ opc build
40
63
  ```
41
64
 
42
- ## 查看分析
65
+ ## 运行测试
43
66
 
44
67
  ```bash
45
- opc analytics
68
+ opc test
46
69
  ```
47
70
 
48
- ## 模板
49
-
50
- 使用 `-t` 指定模板:
71
+ ## 查看数据分析
51
72
 
52
73
  ```bash
53
- opc init my-bot -t teacher
54
- opc init my-bot -t data-analyst
55
- opc init my-bot -t sales-assistant
74
+ opc analytics
56
75
  ```
57
76
 
58
- 13 个内置模板可选。
77
+ ## 下一步
78
+
79
+ - [核心概念](/zh/guide/concepts) — 理解 OAD、技能、渠道等概念
80
+ - [模板列表](/zh/guide/templates) — 查看全部 12 个场景模板
81
+ - [配置详解](/zh/guide/configuration) — OAD 文件的完整配置项
82
+ - [部署指南](/zh/guide/deployment) — Docker、OpenClaw、Hermes 部署
@@ -1,22 +1,84 @@
1
1
  # 模板
2
2
 
3
- OPC Agent 内置 13 个模板:
4
-
5
- | 模板 | 说明 |
6
- |------|------|
7
- | `customer-service` | 客服 FAQ + 人工转接 |
8
- | `sales-assistant` | 销售助手 — 产品问答 + 线索捕获 |
9
- | `knowledge-base` | 知识库 RAG 检索增强 |
10
- | `code-reviewer` | 代码审查 Bug 检测 + 风格检查 |
11
- | `hr-recruiter` | HR 招聘 简历筛选 + 面试安排 |
12
- | `project-manager` | 项目管理 任务跟踪 + 会议记录 |
13
- | `content-writer` | 内容创作 博客 + 社交媒体 + SEO |
14
- | `legal-assistant` | 法律助手 合同审查 + 合规 |
15
- | `financial-advisor` | 财务顾问 预算 + 费用跟踪 |
16
- | `executive-assistant` | 行政助手 日历 + 邮件 + 会议 |
17
- | `data-analyst` | 数据分析 数据查询 + 可视化 |
18
- | `teacher` | 教师 课程计划 + 测验 |
3
+ OPC Agent 提供 12 个开箱即用的场景模板,覆盖常见的企业智能体需求。
4
+
5
+ ## 模板列表
6
+
7
+ | 模板 | 说明 | 适用场景 |
8
+ |------|------|---------|
9
+ | `customer-service` | 客服智能体 | FAQ 自动回答 + 转人工 |
10
+ | `sales-assistant` | 销售助手 | 产品问答 + 线索捕获 + 预约 |
11
+ | `knowledge-base` | 知识库问答 | 基于文档的 RAG 语义检索 |
12
+ | `code-reviewer` | 代码审查 | Bug 检测 + 代码风格检查 |
13
+ | `hr-recruiter` | HR 招聘助手 | 简历筛选 + 面试安排 |
14
+ | `project-manager` | 项目管理 | 任务跟踪 + 会议纪要 |
15
+ | `content-writer` | 内容创作 | 博客写作 + 社媒运营 + SEO |
16
+ | `legal-assistant` | 法务助手 | 合同审查 + 合规检查 |
17
+ | `financial-advisor` | 财务顾问 | 预算管理 + 支出分析 |
18
+ | `executive-assistant` | 行政助理 | 日程管理 + 邮件处理 |
19
+ | `data-analyst` | 数据分析师 | SQL 查询 + 数据可视化 |
20
+ | `teacher` | 教学助手 | 课程设计 + 出题 + 互动 |
21
+
22
+ ## 使用模板
19
23
 
20
24
  ```bash
21
- opc init my-agent -t teacher
25
+ # 创建时指定模板
26
+ opc init my-agent --template customer-service
27
+
28
+ # 或者用简写
29
+ opc init my-agent -t sales-assistant
30
+ ```
31
+
32
+ ## 客服智能体详解
33
+
34
+ ```yaml
35
+ # customer-service/oad.yaml
36
+ apiVersion: opc/v1
37
+ kind: Agent
38
+ metadata:
39
+ name: customer-service
40
+ version: 1.0.0
41
+ description: "客服智能体:FAQ 查询 + 人工转接"
42
+ spec:
43
+ provider:
44
+ default: deepseek
45
+ model: deepseek-chat
46
+ systemPrompt: |
47
+ 你是一个友好、专业的客服助手。
48
+ 帮助客户解答产品、订单、物流、退换货等问题。
49
+ 回答要简洁、有帮助、有同理心。
50
+ skills:
51
+ - name: faq-lookup
52
+ description: "FAQ 知识库查询"
53
+ - name: human-handoff
54
+ description: "转接人工客服"
55
+ channels:
56
+ - type: web
57
+ port: 3000
58
+ ```
59
+
60
+ ## 自定义模板
61
+
62
+ 你可以基于现有模板修改,也可以从头创建:
63
+
64
+ 1. 编写 `oad.yaml` 定义智能体
65
+ 2. 继承 `BaseSkill` 实现自定义技能
66
+ 3. 将 `oad.yaml` + `README.md` 打包成一个目录
67
+
68
+ ```typescript
69
+ import { BaseSkill } from 'opc-agent';
70
+ import type { AgentContext, Message, SkillResult } from 'opc-agent';
71
+
72
+ export class MySkill extends BaseSkill {
73
+ name = 'my-skill';
74
+ description = '我的自定义技能';
75
+
76
+ async execute(context: AgentContext, message: Message): Promise<SkillResult> {
77
+ // 你的技能逻辑
78
+ if (message.content.includes('关键词')) {
79
+ return this.match('这是我的回答', 0.9);
80
+ }
81
+ return this.noMatch();
82
+ }
83
+ }
22
84
  ```
@@ -1,18 +1,88 @@
1
1
  # 测试
2
2
 
3
- 详细说明请参考 [英文版](/guide/testing)。
3
+ ## 概览
4
+
5
+ OPC Agent 内置了测试框架。你可以在 `oad.yaml` 或单独的 `tests.yaml` 中定义测试用例,用 `opc test` 一键运行。
6
+
7
+ ## 在 OAD 中定义测试
8
+
9
+ ```yaml
10
+ spec:
11
+ testing:
12
+ cases:
13
+ - name: 问候测试
14
+ input: "你好!"
15
+ expect:
16
+ contains: ["你好", "帮"]
17
+ maxLatencyMs: 5000
18
+
19
+ - name: 产品咨询
20
+ input: "你们怎么收费?"
21
+ expect:
22
+ contains: ["价格", "套餐"]
23
+ notContains: ["error"]
24
+
25
+ - name: 空输入
26
+ input: ""
27
+ expect:
28
+ maxLatencyMs: 2000
29
+ ```
30
+
31
+ ## 独立测试文件
32
+
33
+ 在 `oad.yaml` 同目录创建 `tests.yaml`:
34
+
35
+ ```yaml
36
+ cases:
37
+ - name: 冒烟测试
38
+ input: "你好"
39
+ expect:
40
+ maxLatencyMs: 10000
41
+
42
+ - name: FAQ 验证
43
+ input: "退货政策是什么?"
44
+ expect:
45
+ contains: ["退货", "退款"]
46
+ ```
4
47
 
5
48
  ## 运行测试
6
49
 
7
50
  ```bash
51
+ # 运行测试
8
52
  opc test
53
+
54
+ # JSON 格式输出
9
55
  opc test --json
56
+
57
+ # 指定 OAD 文件
10
58
  opc test -f my-agent.yaml
59
+
60
+ # 监听模式(改了代码自动重跑)
61
+ opc test --watch
11
62
  ```
12
63
 
13
- ## 部署
64
+ ## 测试报告
14
65
 
15
- ```bash
16
- opc deploy --target openclaw
17
- opc deploy --target hermes
18
66
  ```
67
+ ═══════════════════════════════════════════
68
+ OPC Agent 测试报告
69
+ ═══════════════════════════════════════════
70
+
71
+ ✔ [通过] 问候测试 (245ms)
72
+ ✔ [通过] 产品咨询 (312ms)
73
+ ✘ [失败] 空输入 (5120ms)
74
+ → 延迟 5120ms 超过上限 2000ms
75
+
76
+ ───────────────────────────────────────────
77
+ 总计: 3 通过: 2 失败: 1 耗时: 5677ms
78
+ ───────────────────────────────────────────
79
+ ```
80
+
81
+ ## 断言类型
82
+
83
+ | 断言 | 说明 |
84
+ |------|------|
85
+ | `contains` | 回复必须包含这些字符串(不区分大小写) |
86
+ | `notContains` | 回复不能包含这些字符串 |
87
+ | `toolCalled` | 指定的工具必须被调用 |
88
+ | `maxLatencyMs` | 响应必须在指定时间内完成 |
package/docs/zh/index.md CHANGED
@@ -3,7 +3,7 @@ layout: home
3
3
  hero:
4
4
  name: OPC Agent
5
5
  text: 开放智能体框架
6
- tagline: 构建、测试、运行面向业务工作站的 AI 智能体
6
+ tagline: 构建、测试、运行企业级 AI 智能体
7
7
  actions:
8
8
  - theme: brand
9
9
  text: 快速开始
@@ -12,16 +12,16 @@ hero:
12
12
  text: GitHub
13
13
  link: https://github.com/Deepleaper/opc-agent
14
14
  features:
15
- - title: 🚀 快速开始
16
- details: 2 分钟内创建智能体,内置 13 个模板
17
- - title: 📝 OAD Schema
18
- details: 基于 YAML 的声明式智能体定义
19
- - title: 🔌 多渠道
20
- details: Web、Telegram、Slack、微信、邮件、语音、WebSocket
21
- - title: 🧪 测试框架
22
- details: 在 OAD 中定义测试用例,opc test 运行
23
- - title: 📊 分析
24
- details: 跟踪消息、LLM 调用、工具使用和错误
25
- - title: 🌍 国际化
26
- details: 内置英文、中文、日文支持
15
+ - title: 30 秒上手
16
+ details: 两条命令创建智能体,开箱即用,支持 12 个场景模板
17
+ - title: 📋 OAD 声明式定义
18
+ details: YAML 文件定义智能体的一切:模型、技能、渠道、安全策略
19
+ - title: 📡 多渠道部署
20
+ details: Web、Telegram、Slack、微信公众号、飞书、WebSocket,一套代码到处运行
21
+ - title: 🧪 内置测试框架
22
+ details: 在 OAD 文件中定义测试用例,opc test 一键验证智能体行为
23
+ - title: 🔌 多模型支持
24
+ details: DeepSeek、通义千问、OpenAI、Anthropic、Ollama,不绑定任何一家
25
+ - title: 🧠 知识库 RAG
26
+ details: 添加文档自动构建知识库,智能体回答时语义检索增强
27
27
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opc-agent",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "Open Agent Framework — Build, test, and run AI Agents for business workstations",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -0,0 +1,192 @@
1
+ import { BaseChannel } from './index';
2
+ import type { Message } from '../core/types';
3
+
4
+ /**
5
+ * Discord Channel — v1.1.0
6
+ *
7
+ * Supports:
8
+ * - Discord Bot via Gateway (WebSocket) or HTTP interactions
9
+ * - Slash commands, message content intent
10
+ * - Thread-based conversations
11
+ * - Reactions, embeds
12
+ *
13
+ * Env vars:
14
+ * DISCORD_BOT_TOKEN — bot token
15
+ * DISCORD_APPLICATION_ID — application ID for slash commands
16
+ */
17
+
18
+ export interface DiscordChannelConfig {
19
+ /** Bot token */
20
+ botToken?: string;
21
+ /** Application ID */
22
+ applicationId?: string;
23
+ /** Guild IDs to register slash commands (empty = global) */
24
+ guildIds?: string[];
25
+ /** Whether to use threads for conversations */
26
+ useThreads?: boolean;
27
+ }
28
+
29
+ export class DiscordChannel extends BaseChannel {
30
+ readonly type = 'discord';
31
+ private config: DiscordChannelConfig;
32
+ private ws: import('ws').WebSocket | null = null;
33
+ private heartbeatInterval: ReturnType<typeof setInterval> | null = null;
34
+ private sequenceNumber: number | null = null;
35
+ private sessionId: string | null = null;
36
+ private resumeUrl: string | null = null;
37
+
38
+ constructor(config: DiscordChannelConfig = {}) {
39
+ super();
40
+ this.config = {
41
+ botToken: config.botToken ?? process.env.DISCORD_BOT_TOKEN ?? '',
42
+ applicationId: config.applicationId ?? process.env.DISCORD_APPLICATION_ID ?? '',
43
+ guildIds: config.guildIds ?? [],
44
+ useThreads: config.useThreads ?? true,
45
+ };
46
+ }
47
+
48
+ async start(): Promise<void> {
49
+ if (!this.config.botToken) {
50
+ console.warn('[DiscordChannel] No bot token. Set DISCORD_BOT_TOKEN.');
51
+ return;
52
+ }
53
+
54
+ // Get gateway URL
55
+ const gatewayResp = await fetch('https://discord.com/api/v10/gateway/bot', {
56
+ headers: { Authorization: `Bot ${this.config.botToken}` },
57
+ });
58
+ const gatewayData = await gatewayResp.json() as { url: string };
59
+ const wsUrl = `${gatewayData.url}?v=10&encoding=json`;
60
+
61
+ const { WebSocket } = await import('ws');
62
+ this.ws = new WebSocket(wsUrl);
63
+
64
+ this.ws.on('message', async (data: Buffer) => {
65
+ const payload = JSON.parse(data.toString());
66
+ this.sequenceNumber = payload.s ?? this.sequenceNumber;
67
+
68
+ switch (payload.op) {
69
+ case 10: // Hello
70
+ this.startHeartbeat(payload.d.heartbeat_interval);
71
+ this.identify();
72
+ break;
73
+ case 11: // Heartbeat ACK
74
+ break;
75
+ case 0: // Dispatch
76
+ if (payload.t === 'READY') {
77
+ this.sessionId = payload.d.session_id;
78
+ this.resumeUrl = payload.d.resume_gateway_url;
79
+ console.log(`[DiscordChannel] Connected as ${payload.d.user.username}`);
80
+ } else if (payload.t === 'MESSAGE_CREATE') {
81
+ await this.handleMessage(payload.d);
82
+ }
83
+ break;
84
+ }
85
+ });
86
+
87
+ this.ws.on('close', (code: number) => {
88
+ console.log(`[DiscordChannel] WebSocket closed: ${code}`);
89
+ this.stopHeartbeat();
90
+ // Auto-reconnect after 5s for resumable codes
91
+ if (code !== 4004 && code !== 4014) {
92
+ setTimeout(() => this.start(), 5000);
93
+ }
94
+ });
95
+
96
+ this.ws.on('error', (err: Error) => {
97
+ console.error('[DiscordChannel] WebSocket error:', err.message);
98
+ });
99
+ }
100
+
101
+ async stop(): Promise<void> {
102
+ this.stopHeartbeat();
103
+ if (this.ws) {
104
+ this.ws.close(1000);
105
+ this.ws = null;
106
+ }
107
+ }
108
+
109
+ private identify(): void {
110
+ this.ws?.send(JSON.stringify({
111
+ op: 2,
112
+ d: {
113
+ token: this.config.botToken,
114
+ intents: (1 << 9) | (1 << 15), // GUILD_MESSAGES | MESSAGE_CONTENT
115
+ properties: {
116
+ os: process.platform,
117
+ browser: 'opc-agent',
118
+ device: 'opc-agent',
119
+ },
120
+ },
121
+ }));
122
+ }
123
+
124
+ private startHeartbeat(intervalMs: number): void {
125
+ this.stopHeartbeat();
126
+ // Send first heartbeat with jitter
127
+ setTimeout(() => {
128
+ this.sendHeartbeat();
129
+ this.heartbeatInterval = setInterval(() => this.sendHeartbeat(), intervalMs);
130
+ }, intervalMs * Math.random());
131
+ }
132
+
133
+ private stopHeartbeat(): void {
134
+ if (this.heartbeatInterval) {
135
+ clearInterval(this.heartbeatInterval);
136
+ this.heartbeatInterval = null;
137
+ }
138
+ }
139
+
140
+ private sendHeartbeat(): void {
141
+ this.ws?.send(JSON.stringify({ op: 1, d: this.sequenceNumber }));
142
+ }
143
+
144
+ private async handleMessage(d: Record<string, unknown>): Promise<void> {
145
+ // Ignore bot messages
146
+ const author = d.author as Record<string, unknown>;
147
+ if (author?.bot) return;
148
+ if (!d.content || !this.handler) return;
149
+
150
+ const msg: Message = {
151
+ id: `discord_${d.id}`,
152
+ role: 'user',
153
+ content: d.content as string,
154
+ timestamp: new Date(d.timestamp as string).getTime(),
155
+ metadata: {
156
+ sessionId: `discord_${d.channel_id}`,
157
+ chatId: d.channel_id as string,
158
+ userId: author.id as string,
159
+ platform: 'discord',
160
+ guildId: d.guild_id as string | undefined,
161
+ threadId: (d as Record<string, unknown>).thread?.toString(),
162
+ },
163
+ };
164
+
165
+ const response = await this.handler(msg);
166
+ await this.sendMessage(d.channel_id as string, response.content);
167
+ }
168
+
169
+ async sendMessage(channelId: string, content: string): Promise<void> {
170
+ // Discord max message length is 2000
171
+ const chunks = this.splitMessage(content, 2000);
172
+ for (const chunk of chunks) {
173
+ await fetch(`https://discord.com/api/v10/channels/${channelId}/messages`, {
174
+ method: 'POST',
175
+ headers: {
176
+ 'Content-Type': 'application/json',
177
+ Authorization: `Bot ${this.config.botToken}`,
178
+ },
179
+ body: JSON.stringify({ content: chunk }),
180
+ });
181
+ }
182
+ }
183
+
184
+ private splitMessage(text: string, maxLen: number): string[] {
185
+ if (text.length <= maxLen) return [text];
186
+ const parts: string[] = [];
187
+ for (let i = 0; i < text.length; i += maxLen) {
188
+ parts.push(text.slice(i, i + maxLen));
189
+ }
190
+ return parts;
191
+ }
192
+ }