@blocklet/pages-kit-agents 0.5.45 → 0.5.48
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.
- package/.env.local.example +7 -0
- package/cli.ts +1 -1
- package/index.ts +0 -1
- package/lib/cjs/agents/content-reviwer.d.ts +1 -1
- package/lib/cjs/agents/multi-agent-page-writer.js +3 -10
- package/lib/cjs/agents/orchestrator/index.d.ts +115 -0
- package/lib/cjs/agents/orchestrator/index.js +264 -0
- package/lib/cjs/agents/orchestrator/orchestrator-prompts.d.ts +130 -0
- package/lib/cjs/agents/orchestrator/orchestrator-prompts.js +135 -0
- package/lib/cjs/agents/page-metadata-generator.d.ts +1 -1
- package/lib/cjs/agents/page-metadata-generator.js +4 -1
- package/lib/cjs/agents/page-structure-planner.d.ts +59 -22
- package/lib/cjs/agents/page-structure-planner.js +108 -78
- package/lib/cjs/agents/router-datacache-generator.d.ts +24 -0
- package/lib/cjs/agents/router-datacache-generator.js +78 -0
- package/lib/cjs/agents/section-content-generator.js +11 -8
- package/lib/cjs/agents/template-designer.d.ts +7 -6
- package/lib/cjs/agents/template-designer.js +22 -17
- package/lib/cjs/agents/template-generator.d.ts +55 -7
- package/lib/cjs/agents/template-generator.js +99 -89
- package/lib/cjs/index.d.ts +0 -1
- package/lib/cjs/index.js +0 -1
- package/lib/cjs/prompts/fs-memory-recorder.md +59 -0
- package/lib/cjs/prompts/fs-memory-retriever.md +30 -0
- package/lib/cjs/prompts/html-generator.md +91 -0
- package/lib/cjs/prompts/page-structure-planner-prompt.md +47 -0
- package/lib/cjs/prompts/page-structure-validator-prompt.md +78 -0
- package/lib/cjs/prompts/pages-kit-template-rule.md +491 -0
- package/lib/cjs/prompts/site-map-generator.md +126 -0
- package/lib/cjs/skill-agents/parse-component-list-agent.d.ts +100 -0
- package/lib/cjs/skill-agents/parse-component-list-agent.js +198 -0
- package/lib/cjs/tsconfig.tsbuildinfo +1 -1
- package/lib/cjs/utils/agent-utils.d.ts +4 -0
- package/lib/cjs/utils/agent-utils.js +106 -0
- package/lib/esm/agents/content-reviwer.d.ts +1 -1
- package/lib/esm/agents/multi-agent-page-writer.js +5 -12
- package/lib/esm/agents/orchestrator/index.d.ts +115 -0
- package/lib/esm/agents/orchestrator/index.js +243 -0
- package/lib/esm/agents/orchestrator/orchestrator-prompts.d.ts +130 -0
- package/lib/esm/agents/orchestrator/orchestrator-prompts.js +131 -0
- package/lib/esm/agents/page-metadata-generator.d.ts +1 -1
- package/lib/esm/agents/page-metadata-generator.js +4 -1
- package/lib/esm/agents/page-structure-planner.d.ts +59 -22
- package/lib/esm/agents/page-structure-planner.js +105 -78
- package/lib/esm/agents/router-datacache-generator.d.ts +24 -0
- package/lib/esm/agents/router-datacache-generator.js +72 -0
- package/lib/esm/agents/section-content-generator.js +11 -8
- package/lib/esm/agents/template-designer.d.ts +7 -6
- package/lib/esm/agents/template-designer.js +22 -14
- package/lib/esm/agents/template-generator.d.ts +55 -7
- package/lib/esm/agents/template-generator.js +98 -88
- package/lib/esm/index.d.ts +0 -1
- package/lib/esm/index.js +0 -1
- package/lib/esm/prompts/fs-memory-recorder.md +59 -0
- package/lib/esm/prompts/fs-memory-retriever.md +30 -0
- package/lib/esm/prompts/html-generator.md +91 -0
- package/lib/esm/prompts/page-structure-planner-prompt.md +47 -0
- package/lib/esm/prompts/page-structure-validator-prompt.md +78 -0
- package/lib/esm/prompts/pages-kit-template-rule.md +491 -0
- package/lib/esm/prompts/site-map-generator.md +126 -0
- package/lib/esm/skill-agents/parse-component-list-agent.d.ts +100 -0
- package/lib/esm/skill-agents/parse-component-list-agent.js +192 -0
- package/lib/esm/tsconfig.tsbuildinfo +1 -1
- package/lib/esm/utils/agent-utils.d.ts +4 -0
- package/lib/esm/utils/agent-utils.js +105 -0
- package/lib/types/agents/content-reviwer.d.ts +1 -1
- package/lib/types/agents/orchestrator/index.d.ts +115 -0
- package/lib/types/agents/orchestrator/orchestrator-prompts.d.ts +130 -0
- package/lib/types/agents/page-metadata-generator.d.ts +1 -1
- package/lib/types/agents/page-structure-planner.d.ts +59 -22
- package/lib/types/agents/router-datacache-generator.d.ts +24 -0
- package/lib/types/agents/template-designer.d.ts +7 -6
- package/lib/types/agents/template-generator.d.ts +55 -7
- package/lib/types/index.d.ts +0 -1
- package/lib/types/skill-agents/parse-component-list-agent.d.ts +100 -0
- package/lib/types/tsconfig.tsbuildinfo +1 -1
- package/lib/types/utils/agent-utils.d.ts +4 -0
- package/package.json +10 -5
- package/workflow-cli.ts +61 -41
- package/lib/cjs/agents/page-structure-validator.d.ts +0 -30
- package/lib/cjs/agents/page-structure-validator.js +0 -124
- package/lib/esm/agents/page-structure-validator.d.ts +0 -30
- package/lib/esm/agents/page-structure-validator.js +0 -121
- package/lib/types/agents/page-structure-validator.d.ts +0 -30
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { FSMemory, FSMemoryOptions } from '@aigne/agent-library/fs-memory/index.js';
|
|
1
2
|
import { AnthropicChatModel } from '@aigne/anthropic';
|
|
2
3
|
import { OpenAIChatModel } from '@aigne/openai';
|
|
3
4
|
export declare function getModel(modelName?: string): OpenAIChatModel | AnthropicChatModel | undefined;
|
|
5
|
+
export declare function getMemory({ projectId, ...rest }: Pick<FSMemoryOptions, 'autoUpdate'> & {
|
|
6
|
+
projectId?: string;
|
|
7
|
+
}): FSMemory;
|
|
@@ -4,13 +4,108 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.getModel = getModel;
|
|
7
|
+
exports.getMemory = getMemory;
|
|
8
|
+
const index_js_1 = require("@aigne/agent-library/fs-memory/index.js");
|
|
7
9
|
const anthropic_1 = require("@aigne/anthropic");
|
|
8
10
|
const deepseek_1 = require("@aigne/deepseek");
|
|
9
11
|
const gemini_1 = require("@aigne/gemini");
|
|
10
12
|
const openai_1 = require("@aigne/openai");
|
|
11
13
|
const xai_1 = require("@aigne/xai");
|
|
12
14
|
const node_assert_1 = __importDefault(require("node:assert"));
|
|
15
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
13
16
|
const { OPENAI_API_KEY, GEMINI_API_KEY, CLAUDE_API_KEY, XAI_API_KEY, DEEPSEEK_API_KEY } = process.env;
|
|
17
|
+
// === 内置 prompt 内容,避免运行时读取文件 ===
|
|
18
|
+
const recorderInstructions = `你是一个智能的站点生成记忆管理器,负责从多轮对话和用户反馈中提取对后续站点生成有用的知识和偏好,并以结构化方式存储。
|
|
19
|
+
|
|
20
|
+
## 你的任务
|
|
21
|
+
|
|
22
|
+
- 只记录对后续站点生成、内容补全、页面设计、组件选择、风格偏好等有实际帮助的信息。
|
|
23
|
+
- 忽略无效、重复、无关、泛泛的内容。
|
|
24
|
+
- 将新的对话中,有用的信息补充到记忆中,重点记忆用户的反馈
|
|
25
|
+
- **不允许删除 existing-memory 中的记忆**
|
|
26
|
+
|
|
27
|
+
## 需要记录的内容示例
|
|
28
|
+
|
|
29
|
+
- 用户对产品/服务/公司/行业的补充、修正、详细描述
|
|
30
|
+
- 用户对目标用户、USP、CTA、痛点、案例等内容补全问题的详细回答
|
|
31
|
+
- 用户对 SiteMap、页面结构、模板设计的反馈、偏好、否定/肯定意见
|
|
32
|
+
- 用户对文案风格、页面布局、组件选择、品牌色彩等的明确要求
|
|
33
|
+
- 用户对行业、竞品、特殊需求的补充说明
|
|
34
|
+
- 用户对生成结果的纠错、修正、特殊说明
|
|
35
|
+
- 任何跨页面/全局性的偏好、约束、风格、品牌要求
|
|
36
|
+
|
|
37
|
+
## 不要记录的内容
|
|
38
|
+
|
|
39
|
+
- 一般性寒暄、确认、无实际内容的反馈
|
|
40
|
+
- 纯粹的系统提示、流程性对话
|
|
41
|
+
- 与站点生成无关的闲聊、无效输入
|
|
42
|
+
- 已经被记忆、无新意的重复内容
|
|
43
|
+
- 页面中使用了什么组件
|
|
44
|
+
|
|
45
|
+
## 操作流程
|
|
46
|
+
|
|
47
|
+
1. 读取所有历史记忆(existing-memory)
|
|
48
|
+
2. 分析当前对话内容(conversation),提取有用信息
|
|
49
|
+
3. 判断是否需要新增、更新
|
|
50
|
+
4. 会有多个 Agent 共用当前记忆,现有记忆可能和当前对话无关,保留这些记忆不做修改
|
|
51
|
+
5. 如果当前对话中信息对现有记忆有更新,可以更新现有记忆
|
|
52
|
+
6. **不允许删除 existing-memory 的记忆,可以更新**
|
|
53
|
+
7. 返回所有有用记忆
|
|
54
|
+
|
|
55
|
+
## 记忆结构
|
|
56
|
+
|
|
57
|
+
- 每条记忆应简明扼要,内容聚焦于"对后续站点生成有帮助"的知识、偏好、约束
|
|
58
|
+
- 不要存储无关、冗余、重复内容
|
|
59
|
+
|
|
60
|
+
## 记忆输出格式
|
|
61
|
+
|
|
62
|
+
- 返回所有有用记忆(existing + new),每条为独立对象
|
|
63
|
+
- existing-memory 中的记忆必须返回,条数不能减少,其中的记忆可以有更新
|
|
64
|
+
- 使用 zh 语言记录
|
|
65
|
+
|
|
66
|
+
## 现有记忆
|
|
67
|
+
|
|
68
|
+
<existing-memory>
|
|
69
|
+
{{allMemory}}
|
|
70
|
+
</existing-memory>
|
|
71
|
+
|
|
72
|
+
## 当前对话
|
|
73
|
+
|
|
74
|
+
<conversation>
|
|
75
|
+
{{content}}
|
|
76
|
+
</conversation>
|
|
77
|
+
`;
|
|
78
|
+
const retrieverInstructions = `你是一个智能的站点生成记忆检索器,负责从所有历史记忆中筛选出与当前任务最相关、最有帮助的内容,供后续 Agent 使用。
|
|
79
|
+
|
|
80
|
+
## 检索原则
|
|
81
|
+
|
|
82
|
+
- 只返回与当前任务、页面、实体、主题、设计决策等密切相关的记忆
|
|
83
|
+
- 优先返回能直接影响当前内容补全、页面设计、组件选择、风格设定等的记忆
|
|
84
|
+
- 忽略与当前任务无关的记忆
|
|
85
|
+
- 如果记忆描述出现冲突,返回后出现的记忆内容
|
|
86
|
+
|
|
87
|
+
## 检索流程
|
|
88
|
+
|
|
89
|
+
1. 读取所有历史记忆(allMemory)
|
|
90
|
+
2. 分析当前检索请求(search/query),提取关键主题
|
|
91
|
+
3. 匹配并返回最相关的记忆内容(可多条)
|
|
92
|
+
|
|
93
|
+
## 记忆输出格式
|
|
94
|
+
|
|
95
|
+
- 返回所有与当前任务最相关的记忆,每条为独立对象
|
|
96
|
+
|
|
97
|
+
## 现有记忆
|
|
98
|
+
|
|
99
|
+
<existing-memory>
|
|
100
|
+
{{allMemory}}
|
|
101
|
+
</existing-memory>
|
|
102
|
+
|
|
103
|
+
## 检索请求
|
|
104
|
+
|
|
105
|
+
<search-query>
|
|
106
|
+
{{search}}
|
|
107
|
+
</search-query>
|
|
108
|
+
`;
|
|
14
109
|
function getModel(modelName = 'openai') {
|
|
15
110
|
if (modelName?.includes('gpt')) {
|
|
16
111
|
(0, node_assert_1.default)(OPENAI_API_KEY, 'Please set the OPENAI_API_KEY environment variable');
|
|
@@ -60,3 +155,14 @@ function getModel(modelName = 'openai') {
|
|
|
60
155
|
}
|
|
61
156
|
return undefined;
|
|
62
157
|
}
|
|
158
|
+
function getMemory({ projectId = 'debug', ...rest }) {
|
|
159
|
+
// === FSMemory 配置 ===
|
|
160
|
+
const memoryRootDir = node_path_1.default.join(process.cwd(), 'project-records', projectId, 'memory');
|
|
161
|
+
const fsMemory = new index_js_1.FSMemory({
|
|
162
|
+
...(rest || {}),
|
|
163
|
+
rootDir: memoryRootDir,
|
|
164
|
+
recorderOptions: { instructions: recorderInstructions },
|
|
165
|
+
retrieverOptions: { instructions: retrieverInstructions },
|
|
166
|
+
});
|
|
167
|
+
return fsMemory;
|
|
168
|
+
}
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { AIGNE
|
|
1
|
+
import { AIGNE } from '@aigne/core';
|
|
2
2
|
import { zodSchemaToJsonSchema } from '@blocklet/pages-kit-block-studio/zod-utils';
|
|
3
3
|
import { getModel } from '../utils/agent-utils.js';
|
|
4
4
|
import { logger } from '../utils/logger.js';
|
|
5
5
|
import { generatePageMetadataAgent } from './page-metadata-generator.js';
|
|
6
|
-
import {
|
|
7
|
-
import { pageStructureValidatorAgent } from './page-structure-validator.js';
|
|
6
|
+
import { pageStructurePlannerWithReflection } from './page-structure-planner.js';
|
|
8
7
|
import { createSectionContentAgent } from './section-content-generator.js';
|
|
9
8
|
/**
|
|
10
9
|
* 多Agent协作生成页面内容
|
|
@@ -52,26 +51,20 @@ export default async function generatePageContentMultiAgent(input) {
|
|
|
52
51
|
// 3-4 使用反思工作流生成页面结构
|
|
53
52
|
const planningEngine = new AIGNE({
|
|
54
53
|
model,
|
|
55
|
-
agents: [pageStructurePlannerAgent, pageStructureValidatorAgent],
|
|
56
|
-
limits: {
|
|
57
|
-
maxAgentInvokes: 30,
|
|
58
|
-
},
|
|
59
54
|
});
|
|
60
|
-
await planningEngine.invoke(
|
|
55
|
+
const structurePlanResult = await planningEngine.invoke(pageStructurePlannerWithReflection, {
|
|
61
56
|
context,
|
|
62
57
|
question,
|
|
63
58
|
locale,
|
|
64
|
-
|
|
59
|
+
structurePlan: Object.entries(sectionsRules || {}).map(([sectionName, sectionContentPlan]) => ({
|
|
65
60
|
sectionName,
|
|
66
61
|
sectionContentPlan,
|
|
67
62
|
})),
|
|
68
63
|
outputSchema: JSON.stringify(outputSchemaJson),
|
|
69
64
|
expectedSections: JSON.stringify(sectionNames),
|
|
70
65
|
});
|
|
71
|
-
const
|
|
72
|
-
const { structurePlan } = structurePlanResult.message;
|
|
66
|
+
const { structurePlan } = structurePlanResult;
|
|
73
67
|
logger.info(`[${modelName}] Initial structure plan generated`, structurePlan);
|
|
74
|
-
await planningEngine.shutdown();
|
|
75
68
|
// 触发页面结构生成成功事件
|
|
76
69
|
if (onProgress) {
|
|
77
70
|
onProgress({
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { Agent, type AgentInvokeOptions, type AgentOptions, type Message } from '@aigne/core';
|
|
2
|
+
import { type FullPlanOutput, type StepWithResult } from './orchestrator-prompts.js';
|
|
3
|
+
/**
|
|
4
|
+
* Re-export orchestrator prompt templates and related types
|
|
5
|
+
*/
|
|
6
|
+
export * from './orchestrator-prompts.js';
|
|
7
|
+
/**
|
|
8
|
+
* Represents a complete plan with execution results
|
|
9
|
+
* @hidden
|
|
10
|
+
*/
|
|
11
|
+
export interface FullPlanWithResult {
|
|
12
|
+
/**
|
|
13
|
+
* The overall objective
|
|
14
|
+
*/
|
|
15
|
+
objective: string;
|
|
16
|
+
/**
|
|
17
|
+
* The generated complete plan
|
|
18
|
+
*/
|
|
19
|
+
plan?: FullPlanOutput;
|
|
20
|
+
/**
|
|
21
|
+
* List of executed steps with their results
|
|
22
|
+
*/
|
|
23
|
+
steps: StepWithResult[];
|
|
24
|
+
/**
|
|
25
|
+
* Final result
|
|
26
|
+
*/
|
|
27
|
+
result?: string;
|
|
28
|
+
/**
|
|
29
|
+
* Plan completion status
|
|
30
|
+
*/
|
|
31
|
+
status?: boolean;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Configuration options for the Orchestrator Agent
|
|
35
|
+
*/
|
|
36
|
+
export interface OrchestratorAgentOptions<I extends Message = Message, O extends Message = Message> extends AgentOptions<I, O> {
|
|
37
|
+
/**
|
|
38
|
+
* Maximum number of iterations to prevent infinite loops
|
|
39
|
+
* Default: 30
|
|
40
|
+
*/
|
|
41
|
+
maxIterations?: number;
|
|
42
|
+
/**
|
|
43
|
+
* Number of concurrent tasks
|
|
44
|
+
* Default: 5
|
|
45
|
+
*/
|
|
46
|
+
tasksConcurrency?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Chain step results as input to the next step
|
|
49
|
+
* Default: false
|
|
50
|
+
*/
|
|
51
|
+
chainStepResults?: boolean;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Orchestrator Agent Class
|
|
55
|
+
*
|
|
56
|
+
* This Agent is responsible for:
|
|
57
|
+
* 1. Generating an execution plan based on the objective
|
|
58
|
+
* 2. Breaking down the plan into steps and tasks
|
|
59
|
+
* 3. Coordinating the execution of steps and tasks
|
|
60
|
+
* 4. Synthesizing the final result
|
|
61
|
+
*
|
|
62
|
+
* Workflow:
|
|
63
|
+
* - Receives input objective
|
|
64
|
+
* - Uses planner to create execution plan
|
|
65
|
+
* - Executes tasks and steps according to the plan
|
|
66
|
+
* - Synthesizes final result through completer
|
|
67
|
+
*/
|
|
68
|
+
export declare class OrchestratorAgent<I extends Message = Message, O extends Message = Message> extends Agent<I, O> {
|
|
69
|
+
/**
|
|
70
|
+
* Factory method to create an OrchestratorAgent instance
|
|
71
|
+
* @param options - Configuration options for the Orchestrator Agent
|
|
72
|
+
* @returns A new OrchestratorAgent instance
|
|
73
|
+
*/
|
|
74
|
+
static from<I extends Message, O extends Message>(options: OrchestratorAgentOptions<I, O>): OrchestratorAgent<I, O>;
|
|
75
|
+
/**
|
|
76
|
+
* Creates an OrchestratorAgent instance
|
|
77
|
+
* @param options - Configuration options for the Orchestrator Agent
|
|
78
|
+
*/
|
|
79
|
+
constructor(options: OrchestratorAgentOptions<I, O>);
|
|
80
|
+
private planner;
|
|
81
|
+
private completer;
|
|
82
|
+
/**
|
|
83
|
+
* Maximum number of iterations
|
|
84
|
+
* Prevents infinite execution loops
|
|
85
|
+
*/
|
|
86
|
+
maxIterations?: number;
|
|
87
|
+
/**
|
|
88
|
+
* Number of concurrent tasks
|
|
89
|
+
* Controls how many tasks can be executed simultaneously
|
|
90
|
+
*/
|
|
91
|
+
tasksConcurrency?: number;
|
|
92
|
+
/**
|
|
93
|
+
* Whether to chain step results as input to next step
|
|
94
|
+
*/
|
|
95
|
+
chainStepResults?: boolean;
|
|
96
|
+
/**
|
|
97
|
+
* Process input and execute the orchestrator workflow
|
|
98
|
+
*
|
|
99
|
+
* Workflow:
|
|
100
|
+
* 1. Extract the objective
|
|
101
|
+
* 2. Loop until plan completion or maximum iterations:
|
|
102
|
+
* a. Generate/update execution plan
|
|
103
|
+
* b. If plan is complete, synthesize result
|
|
104
|
+
* c. Otherwise, execute steps in the plan
|
|
105
|
+
*
|
|
106
|
+
* @param input - Input message containing the objective
|
|
107
|
+
* @param options - Agent invocation options
|
|
108
|
+
* @returns Processing result
|
|
109
|
+
*/
|
|
110
|
+
process(input: I, options: AgentInvokeOptions): Promise<O>;
|
|
111
|
+
private getFullPlanInput;
|
|
112
|
+
private getFullPlan;
|
|
113
|
+
private synthesizePlanResult;
|
|
114
|
+
private executeStep;
|
|
115
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/* eslint-disable no-await-in-loop */
|
|
2
|
+
import { AIAgent, Agent, MESSAGE_KEY, PromptTemplate, createMessage, getMessage, } from '@aigne/core';
|
|
3
|
+
import { checkArguments } from '@aigne/core/utils/type-utils.js';
|
|
4
|
+
import fastq from 'fastq';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { FULL_PLAN_PROMPT_TEMPLATE, SYNTHESIZE_PLAN_USER_PROMPT_TEMPLATE, SYNTHESIZE_STEP_PROMPT_TEMPLATE, TASK_PROMPT_TEMPLATE, getFullPlanSchema, } from './orchestrator-prompts.js';
|
|
7
|
+
/**
|
|
8
|
+
* Default maximum number of iterations to prevent infinite loops
|
|
9
|
+
*/
|
|
10
|
+
const DEFAULT_MAX_ITERATIONS = 30;
|
|
11
|
+
/**
|
|
12
|
+
* Default number of concurrent tasks
|
|
13
|
+
*/
|
|
14
|
+
const DEFAULT_TASK_CONCURRENCY = 5;
|
|
15
|
+
/**
|
|
16
|
+
* Re-export orchestrator prompt templates and related types
|
|
17
|
+
*/
|
|
18
|
+
export * from './orchestrator-prompts.js';
|
|
19
|
+
/**
|
|
20
|
+
* Orchestrator Agent Class
|
|
21
|
+
*
|
|
22
|
+
* This Agent is responsible for:
|
|
23
|
+
* 1. Generating an execution plan based on the objective
|
|
24
|
+
* 2. Breaking down the plan into steps and tasks
|
|
25
|
+
* 3. Coordinating the execution of steps and tasks
|
|
26
|
+
* 4. Synthesizing the final result
|
|
27
|
+
*
|
|
28
|
+
* Workflow:
|
|
29
|
+
* - Receives input objective
|
|
30
|
+
* - Uses planner to create execution plan
|
|
31
|
+
* - Executes tasks and steps according to the plan
|
|
32
|
+
* - Synthesizes final result through completer
|
|
33
|
+
*/
|
|
34
|
+
export class OrchestratorAgent extends Agent {
|
|
35
|
+
/**
|
|
36
|
+
* Factory method to create an OrchestratorAgent instance
|
|
37
|
+
* @param options - Configuration options for the Orchestrator Agent
|
|
38
|
+
* @returns A new OrchestratorAgent instance
|
|
39
|
+
*/
|
|
40
|
+
static from(options) {
|
|
41
|
+
return new OrchestratorAgent(options);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Creates an OrchestratorAgent instance
|
|
45
|
+
* @param options - Configuration options for the Orchestrator Agent
|
|
46
|
+
*/
|
|
47
|
+
constructor(options) {
|
|
48
|
+
checkArguments('OrchestratorAgent', orchestratorAgentOptionsSchema, options);
|
|
49
|
+
super({ ...options });
|
|
50
|
+
this.maxIterations = options.maxIterations;
|
|
51
|
+
this.tasksConcurrency = options.tasksConcurrency;
|
|
52
|
+
this.chainStepResults = options.chainStepResults;
|
|
53
|
+
this.planner = new AIAgent({
|
|
54
|
+
name: 'llm_orchestration_planner',
|
|
55
|
+
instructions: FULL_PLAN_PROMPT_TEMPLATE,
|
|
56
|
+
outputSchema: () => getFullPlanSchema(this.skills),
|
|
57
|
+
});
|
|
58
|
+
this.completer = new AIAgent({
|
|
59
|
+
name: 'llm_orchestration_completer',
|
|
60
|
+
instructions: FULL_PLAN_PROMPT_TEMPLATE,
|
|
61
|
+
outputSchema: this.outputSchema,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
planner;
|
|
65
|
+
completer;
|
|
66
|
+
/**
|
|
67
|
+
* Maximum number of iterations
|
|
68
|
+
* Prevents infinite execution loops
|
|
69
|
+
*/
|
|
70
|
+
maxIterations;
|
|
71
|
+
/**
|
|
72
|
+
* Number of concurrent tasks
|
|
73
|
+
* Controls how many tasks can be executed simultaneously
|
|
74
|
+
*/
|
|
75
|
+
tasksConcurrency;
|
|
76
|
+
/**
|
|
77
|
+
* Whether to chain step results as input to next step
|
|
78
|
+
*/
|
|
79
|
+
chainStepResults;
|
|
80
|
+
/**
|
|
81
|
+
* Process input and execute the orchestrator workflow
|
|
82
|
+
*
|
|
83
|
+
* Workflow:
|
|
84
|
+
* 1. Extract the objective
|
|
85
|
+
* 2. Loop until plan completion or maximum iterations:
|
|
86
|
+
* a. Generate/update execution plan
|
|
87
|
+
* b. If plan is complete, synthesize result
|
|
88
|
+
* c. Otherwise, execute steps in the plan
|
|
89
|
+
*
|
|
90
|
+
* @param input - Input message containing the objective
|
|
91
|
+
* @param options - Agent invocation options
|
|
92
|
+
* @returns Processing result
|
|
93
|
+
*/
|
|
94
|
+
async process(input, options) {
|
|
95
|
+
const { model } = options.context;
|
|
96
|
+
if (!model)
|
|
97
|
+
throw new Error('model is required to run OrchestratorAgent');
|
|
98
|
+
const objective = getMessage(input);
|
|
99
|
+
if (!objective)
|
|
100
|
+
throw new Error('Objective is required to run OrchestratorAgent');
|
|
101
|
+
const result = {
|
|
102
|
+
objective,
|
|
103
|
+
steps: [],
|
|
104
|
+
};
|
|
105
|
+
let iterations = 0;
|
|
106
|
+
const maxIterations = this.maxIterations ?? DEFAULT_MAX_ITERATIONS;
|
|
107
|
+
while (iterations++ < maxIterations) {
|
|
108
|
+
const plan = await this.getFullPlan(result, options.context);
|
|
109
|
+
result.plan = plan;
|
|
110
|
+
if (plan.isComplete) {
|
|
111
|
+
return this.synthesizePlanResult(result, options.context);
|
|
112
|
+
}
|
|
113
|
+
for (const step of plan.steps) {
|
|
114
|
+
const stepResult = await this.executeStep(result, step, options.context);
|
|
115
|
+
result.steps.push(stepResult);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
throw new Error(`Max iterations reached: ${maxIterations}`);
|
|
119
|
+
}
|
|
120
|
+
getFullPlanInput(planResult) {
|
|
121
|
+
return {
|
|
122
|
+
objective: planResult.objective,
|
|
123
|
+
steps: planResult.steps,
|
|
124
|
+
plan: {
|
|
125
|
+
status: planResult.status ? 'Complete' : 'In Progress',
|
|
126
|
+
result: planResult.result || 'No results yet',
|
|
127
|
+
},
|
|
128
|
+
agents: this.skills.map((i) => ({
|
|
129
|
+
name: i.name,
|
|
130
|
+
description: i.description,
|
|
131
|
+
tools: i.skills.map((i) => ({ name: i.name, description: i.description })),
|
|
132
|
+
})),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
async getFullPlan(planResult, context) {
|
|
136
|
+
return context.invoke(this.planner, this.getFullPlanInput(planResult));
|
|
137
|
+
}
|
|
138
|
+
async synthesizePlanResult(planResult, context) {
|
|
139
|
+
return context.invoke(this.completer, {
|
|
140
|
+
...this.getFullPlanInput(planResult),
|
|
141
|
+
...createMessage(SYNTHESIZE_PLAN_USER_PROMPT_TEMPLATE),
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
async executeStep(planResult, step, context) {
|
|
145
|
+
const concurrency = this.tasksConcurrency ?? DEFAULT_TASK_CONCURRENCY;
|
|
146
|
+
const { model } = context;
|
|
147
|
+
if (!model)
|
|
148
|
+
throw new Error('model is required to run OrchestratorAgent');
|
|
149
|
+
let lastTaskResult = {};
|
|
150
|
+
// 将上一步最后一个任务的输入作为下一步的输入
|
|
151
|
+
if (this.chainStepResults) {
|
|
152
|
+
if (planResult.steps.length > 0) {
|
|
153
|
+
const lastStep = planResult.steps[planResult.steps.length - 1];
|
|
154
|
+
if (lastStep?.result) {
|
|
155
|
+
try {
|
|
156
|
+
const lastStepResult = JSON.parse(lastStep.result);
|
|
157
|
+
if (lastStepResult?.step?.results && Array.isArray(lastStepResult.step.results) && lastStepResult.step.results.length > 0) {
|
|
158
|
+
const lastStepResults = lastStepResult.step.results[lastStepResult.step.results.length - 1];
|
|
159
|
+
console.log('lastStepResults', lastStepResults.result);
|
|
160
|
+
lastTaskResult = JSON.parse(lastStepResults.result);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
console.error('Failed to parse last step result', error);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const queue = fastq.promise(async (task) => {
|
|
170
|
+
const agent = this.skills.find((skill) => skill.name === task.agent);
|
|
171
|
+
if (!agent)
|
|
172
|
+
throw new Error(`Agent ${task.agent} not found`);
|
|
173
|
+
const prompt = PromptTemplate.from(TASK_PROMPT_TEMPLATE).format({
|
|
174
|
+
// eslint-disable-next-line prettier/prettier
|
|
175
|
+
objective: planResult.objective,
|
|
176
|
+
step,
|
|
177
|
+
task,
|
|
178
|
+
steps: planResult.steps,
|
|
179
|
+
});
|
|
180
|
+
let result;
|
|
181
|
+
if (agent.isInvokable) {
|
|
182
|
+
result = getMessageOrJsonString(await context.invoke(agent, { ...lastTaskResult, [MESSAGE_KEY]: prompt }));
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
const executor = AIAgent.from({
|
|
186
|
+
name: 'llm_orchestration_task_executor',
|
|
187
|
+
instructions: prompt,
|
|
188
|
+
skills: agent.skills,
|
|
189
|
+
});
|
|
190
|
+
result = getMessageOrJsonString(await context.invoke(executor, this.chainStepResults ? { ...lastTaskResult } : {}));
|
|
191
|
+
}
|
|
192
|
+
return { task, result };
|
|
193
|
+
}, concurrency);
|
|
194
|
+
let results;
|
|
195
|
+
try {
|
|
196
|
+
results = await Promise.all(step.tasks.map((task) => queue.push(task)));
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
queue.kill();
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
let result = '';
|
|
203
|
+
if (!this.chainStepResults) {
|
|
204
|
+
result = getMessageOrJsonString(await context.invoke(AIAgent.from({
|
|
205
|
+
name: 'llm_orchestration_step_synthesizer',
|
|
206
|
+
instructions: SYNTHESIZE_STEP_PROMPT_TEMPLATE,
|
|
207
|
+
}), { objective: planResult.objective, step, tasks: results }));
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
const resultData = {
|
|
211
|
+
step: {
|
|
212
|
+
description: step.description,
|
|
213
|
+
results: results.map((task) => ({
|
|
214
|
+
agent: task.task.agent,
|
|
215
|
+
task: task.task.description,
|
|
216
|
+
result: task.result,
|
|
217
|
+
})),
|
|
218
|
+
},
|
|
219
|
+
};
|
|
220
|
+
result = JSON.stringify(resultData);
|
|
221
|
+
}
|
|
222
|
+
if (!result)
|
|
223
|
+
throw new Error('unexpected empty result from synthesize step\'s tasks results');
|
|
224
|
+
return {
|
|
225
|
+
step,
|
|
226
|
+
tasks: results,
|
|
227
|
+
result,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function getMessageOrJsonString(output) {
|
|
232
|
+
const entries = Object.entries(output);
|
|
233
|
+
const firstValue = entries[0]?.[1];
|
|
234
|
+
if (entries.length === 1 && typeof firstValue === 'string') {
|
|
235
|
+
return firstValue;
|
|
236
|
+
}
|
|
237
|
+
return JSON.stringify(output);
|
|
238
|
+
}
|
|
239
|
+
const orchestratorAgentOptionsSchema = z.object({
|
|
240
|
+
maxIterations: z.number().optional(),
|
|
241
|
+
tasksConcurrency: z.number().optional(),
|
|
242
|
+
chainStepResults: z.boolean().optional(),
|
|
243
|
+
});
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { Agent, Message } from '@aigne/core';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
/**
|
|
4
|
+
* @hidden
|
|
5
|
+
*/
|
|
6
|
+
export declare const SYNTHESIZE_PLAN_USER_PROMPT_TEMPLATE = "Synthesize the results of executing all steps in the plan into a cohesive result\n";
|
|
7
|
+
/**
|
|
8
|
+
* @hidden
|
|
9
|
+
*/
|
|
10
|
+
export declare function getFullPlanSchema(agents: Agent[]): z.ZodObject<{
|
|
11
|
+
steps: z.ZodArray<z.ZodObject<{
|
|
12
|
+
description: z.ZodString;
|
|
13
|
+
tasks: z.ZodArray<z.ZodObject<{
|
|
14
|
+
description: z.ZodString;
|
|
15
|
+
agent: z.ZodUnion<[z.ZodLiteral<string>, z.ZodLiteral<string>, ...z.ZodLiteral<string>[]]>;
|
|
16
|
+
}, "strip", z.ZodTypeAny, {
|
|
17
|
+
description: string;
|
|
18
|
+
agent: string;
|
|
19
|
+
}, {
|
|
20
|
+
description: string;
|
|
21
|
+
agent: string;
|
|
22
|
+
}>, "many">;
|
|
23
|
+
}, "strip", z.ZodTypeAny, {
|
|
24
|
+
description: string;
|
|
25
|
+
tasks: {
|
|
26
|
+
description: string;
|
|
27
|
+
agent: string;
|
|
28
|
+
}[];
|
|
29
|
+
}, {
|
|
30
|
+
description: string;
|
|
31
|
+
tasks: {
|
|
32
|
+
description: string;
|
|
33
|
+
agent: string;
|
|
34
|
+
}[];
|
|
35
|
+
}>, "many">;
|
|
36
|
+
isComplete: z.ZodBoolean;
|
|
37
|
+
}, "strip", z.ZodTypeAny, {
|
|
38
|
+
steps: {
|
|
39
|
+
description: string;
|
|
40
|
+
tasks: {
|
|
41
|
+
description: string;
|
|
42
|
+
agent: string;
|
|
43
|
+
}[];
|
|
44
|
+
}[];
|
|
45
|
+
isComplete: boolean;
|
|
46
|
+
}, {
|
|
47
|
+
steps: {
|
|
48
|
+
description: string;
|
|
49
|
+
tasks: {
|
|
50
|
+
description: string;
|
|
51
|
+
agent: string;
|
|
52
|
+
}[];
|
|
53
|
+
}[];
|
|
54
|
+
isComplete: boolean;
|
|
55
|
+
}>;
|
|
56
|
+
/**
|
|
57
|
+
* @hidden
|
|
58
|
+
*/
|
|
59
|
+
export type FullPlanOutput = z.infer<ReturnType<typeof getFullPlanSchema>>;
|
|
60
|
+
/**
|
|
61
|
+
* @hidden
|
|
62
|
+
*/
|
|
63
|
+
export type Step = FullPlanOutput['steps'][number];
|
|
64
|
+
/**
|
|
65
|
+
* @hidden
|
|
66
|
+
*/
|
|
67
|
+
export type Task = Step['tasks'][number];
|
|
68
|
+
/**
|
|
69
|
+
* @hidden
|
|
70
|
+
*/
|
|
71
|
+
export interface StepWithResult {
|
|
72
|
+
step: Step;
|
|
73
|
+
tasks: Array<TaskWithResult>;
|
|
74
|
+
result: string;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* @hidden
|
|
78
|
+
*/
|
|
79
|
+
export interface TaskWithResult {
|
|
80
|
+
task: Task;
|
|
81
|
+
result: string;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* @hidden
|
|
85
|
+
*/
|
|
86
|
+
export interface FullPlanInput extends Message {
|
|
87
|
+
objective: string;
|
|
88
|
+
steps: StepWithResult[];
|
|
89
|
+
plan: {
|
|
90
|
+
status: string;
|
|
91
|
+
result: string;
|
|
92
|
+
};
|
|
93
|
+
agents: {
|
|
94
|
+
name: string;
|
|
95
|
+
description?: string;
|
|
96
|
+
tools: {
|
|
97
|
+
name: string;
|
|
98
|
+
description?: string;
|
|
99
|
+
}[];
|
|
100
|
+
}[];
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* @hidden
|
|
104
|
+
*/
|
|
105
|
+
export declare const FULL_PLAN_PROMPT_TEMPLATE = "You are tasked with orchestrating a plan to complete an objective.\nYou can analyze results from the previous steps already executed to decide if the objective is complete.\nYour plan must be structured in sequential steps, with each step containing independent parallel subtasks.\n\n<objective>\n{{objective}}\n</objective>\n\n<steps_completed>\n{{#steps}}\n- Step: {{step.description}}\n Result: {{result}}\n{{/steps}}\n</steps_completed>\n\n<previous_plan_status>\n{{plan.status}}\n</previous_plan_status>\n\n<previous_plan_result>\n{{plan.result}}\n</previous_plan_result>\n\nYou have access to the following Agents(which are collections of tools/functions):\n\n<agents>\n{{#agents}}\n- Agent: {{name}}\n Description: {{description}}\n Functions:\n {{#tools}}\n - Tool: {{name}}\n Description: {{description}}\n {{/tools}}\n{{/agents}}\n</agents>\n\n- If the previous plan results achieve the objective, return isComplete=true.\n- Otherwise, generate remaining steps needed.\n- Generate a plan with all remaining steps needed.\n- Steps are sequential, but each Step can have parallel subtasks.\n- For each Step, specify a description of the step and independent subtasks that can run in parallel.\n- For each subtask specify:\n 1. Clear description of the task that an LLM can execute\n 2. Name of 1 Agent to use for the task";
|
|
106
|
+
/**
|
|
107
|
+
* @hidden
|
|
108
|
+
*/
|
|
109
|
+
export interface TaskPromptInput extends Message {
|
|
110
|
+
objective: string;
|
|
111
|
+
step: Step;
|
|
112
|
+
task: Task;
|
|
113
|
+
steps: StepWithResult[];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* @hidden
|
|
117
|
+
*/
|
|
118
|
+
export declare const TASK_PROMPT_TEMPLATE = "You are part of a larger workflow to achieve the step then the objective:\n\n<objective>\n{{objective}}\n</objective>\n\n<step>\n{{step.description}}\n</step>\n\nYour job is to accomplish only the following task:\n\n<task>\n{{task.description}}\n</task>\n\nResults so far that may provide helpful context:\n\n<steps_completed>\n{{#steps}}\n- Step: {{step.description}}\n Result: {{result}}\n{{/steps}}\n</steps_completed>\n";
|
|
119
|
+
/**
|
|
120
|
+
* @hidden
|
|
121
|
+
*/
|
|
122
|
+
export interface SynthesizeStepPromptInput extends Message {
|
|
123
|
+
objective: string;
|
|
124
|
+
step: Step;
|
|
125
|
+
tasks: TaskWithResult[];
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* @hidden
|
|
129
|
+
*/
|
|
130
|
+
export declare const SYNTHESIZE_STEP_PROMPT_TEMPLATE = "Synthesize the results of these parallel tasks into a cohesive result\n\n<objective>\n{{objective}}\n</objective>\n\n<step>\n{{step.description}}\n</step>\n\n<tasks>\n{{#tasks}}\n- Task: {{task.description}}\n Result: {{result}}\n{{/tasks}}\n</tasks>\n";
|