@blocklet/pages-kit-agents 0.5.56 → 0.6.0

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.
@@ -1,135 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SYNTHESIZE_STEP_PROMPT_TEMPLATE = exports.TASK_PROMPT_TEMPLATE = exports.FULL_PLAN_PROMPT_TEMPLATE = exports.SYNTHESIZE_PLAN_USER_PROMPT_TEMPLATE = void 0;
4
- exports.getFullPlanSchema = getFullPlanSchema;
5
- const json_schema_js_1 = require("@aigne/core/utils/json-schema.js");
6
- const type_utils_js_1 = require("@aigne/core/utils/type-utils.js");
7
- const zod_1 = require("zod");
8
- /**
9
- * @hidden
10
- */
11
- exports.SYNTHESIZE_PLAN_USER_PROMPT_TEMPLATE = `\
12
- Synthesize the results of executing all steps in the plan into a cohesive result
13
- `;
14
- /**
15
- * @hidden
16
- */
17
- function getFullPlanSchema(agents) {
18
- const agentNames = agents.map((i) => i.name);
19
- if (new Set(agentNames).size !== agentNames.length) {
20
- const dup = (0, type_utils_js_1.duplicates)(agentNames);
21
- throw new Error(`Duplicate agent names found in orchestrator: ${dup.join(',')}`);
22
- }
23
- const TaskSchema = zod_1.z.object({
24
- description: zod_1.z.string().describe('Detailed description of the task'),
25
- agent: zod_1.z
26
- .union((0, json_schema_js_1.ensureZodUnionArray)(agents.map((i) => zod_1.z.literal(i.name))))
27
- .describe('Name of the agent to execute the task'),
28
- });
29
- const StepSchema = zod_1.z.object({
30
- description: zod_1.z.string().describe('Detailed description of the step'),
31
- tasks: zod_1.z.array(TaskSchema).describe('Tasks that can run in parallel in this step'),
32
- });
33
- return zod_1.z.object({
34
- steps: zod_1.z.array(StepSchema).describe('All sequential steps in the plan'),
35
- isComplete: zod_1.z.boolean().describe('Whether the previous plan results achieve the objective'),
36
- });
37
- }
38
- /**
39
- * @hidden
40
- */
41
- exports.FULL_PLAN_PROMPT_TEMPLATE = `You are tasked with orchestrating a plan to complete an objective.
42
- You can analyze results from the previous steps already executed to decide if the objective is complete.
43
- Your plan must be structured in sequential steps, with each step containing independent parallel subtasks.
44
-
45
- <objective>
46
- {{objective}}
47
- </objective>
48
-
49
- <steps_completed>
50
- {{#steps}}
51
- - Step: {{step.description}}
52
- Result: {{result}}
53
- {{/steps}}
54
- </steps_completed>
55
-
56
- <previous_plan_status>
57
- {{plan.status}}
58
- </previous_plan_status>
59
-
60
- <previous_plan_result>
61
- {{plan.result}}
62
- </previous_plan_result>
63
-
64
- You have access to the following Agents(which are collections of tools/functions):
65
-
66
- <agents>
67
- {{#agents}}
68
- - Agent: {{name}}
69
- Description: {{description}}
70
- Functions:
71
- {{#tools}}
72
- - Tool: {{name}}
73
- Description: {{description}}
74
- {{/tools}}
75
- {{/agents}}
76
- </agents>
77
-
78
- - If the previous plan results achieve the objective, return isComplete=true.
79
- - Otherwise, generate remaining steps needed.
80
- - Generate a plan with all remaining steps needed.
81
- - Steps are sequential, but each Step can have parallel subtasks.
82
- - For each Step, specify a description of the step and independent subtasks that can run in parallel.
83
- - For each subtask specify:
84
- 1. Clear description of the task that an LLM can execute
85
- 2. Name of 1 Agent to use for the task`;
86
- /**
87
- * @hidden
88
- */
89
- exports.TASK_PROMPT_TEMPLATE = `\
90
- You are part of a larger workflow to achieve the step then the objective:
91
-
92
- <objective>
93
- {{objective}}
94
- </objective>
95
-
96
- <step>
97
- {{step.description}}
98
- </step>
99
-
100
- Your job is to accomplish only the following task:
101
-
102
- <task>
103
- {{task.description}}
104
- </task>
105
-
106
- Results so far that may provide helpful context:
107
-
108
- <steps_completed>
109
- {{#steps}}
110
- - Step: {{step.description}}
111
- Result: {{result}}
112
- {{/steps}}
113
- </steps_completed>
114
- `;
115
- /**
116
- * @hidden
117
- */
118
- exports.SYNTHESIZE_STEP_PROMPT_TEMPLATE = `\
119
- Synthesize the results of these parallel tasks into a cohesive result
120
-
121
- <objective>
122
- {{objective}}
123
- </objective>
124
-
125
- <step>
126
- {{step.description}}
127
- </step>
128
-
129
- <tasks>
130
- {{#tasks}}
131
- - Task: {{task.description}}
132
- Result: {{result}}
133
- {{/tasks}}
134
- </tasks>
135
- `;
@@ -1,115 +0,0 @@
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
- }
@@ -1,243 +0,0 @@
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
- });
@@ -1,130 +0,0 @@
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";