@chatbotkit/agent 1.29.0 → 1.30.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.
- package/README.md +3 -3
- package/dist/cjs/agent.cjs +39 -300
- package/dist/cjs/agent.d.ts +9 -55
- package/dist/cjs/execute.cjs +309 -0
- package/dist/cjs/execute.d.ts +56 -0
- package/dist/cjs/index.cjs +6 -4
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/skills.cjs +7 -4
- package/dist/esm/agent.d.ts +9 -55
- package/dist/esm/agent.js +35 -298
- package/dist/esm/execute.d.ts +56 -0
- package/dist/esm/execute.js +305 -0
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/skills.js +3 -2
- package/package.json +22 -3
package/dist/esm/agent.js
CHANGED
|
@@ -1,304 +1,41 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
const
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const channel = `${name}_${randomSuffix}`.padEnd(16, '0');
|
|
10
|
-
channelToTool.set(channel, { name, tool });
|
|
11
|
-
if (!tool.input) {
|
|
12
|
-
return {
|
|
13
|
-
name,
|
|
14
|
-
description: tool.description,
|
|
15
|
-
parameters: ({
|
|
16
|
-
type: 'object',
|
|
17
|
-
properties: {},
|
|
18
|
-
}),
|
|
19
|
-
result: {
|
|
20
|
-
channel,
|
|
21
|
-
},
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
const schema = (zodToJsonSchema(tool.input, { target: 'openApi3' }));
|
|
25
|
-
const parameters = {
|
|
26
|
-
type: 'object',
|
|
27
|
-
properties: schema.properties || {},
|
|
28
|
-
...(schema.required && schema.required.length > 0
|
|
29
|
-
? { required: schema.required }
|
|
30
|
-
: {}),
|
|
31
|
-
};
|
|
32
|
-
return {
|
|
33
|
-
name,
|
|
34
|
-
description: tool.description,
|
|
35
|
-
parameters: (parameters),
|
|
36
|
-
result: {
|
|
37
|
-
channel,
|
|
38
|
-
},
|
|
39
|
-
};
|
|
40
|
-
})
|
|
41
|
-
: undefined;
|
|
42
|
-
const stream = client.conversation
|
|
43
|
-
.complete(null, {
|
|
44
|
-
...request,
|
|
45
|
-
functions,
|
|
46
|
-
limits: {
|
|
47
|
-
iterations: 1,
|
|
48
|
-
},
|
|
49
|
-
})
|
|
50
|
-
.stream({ abortSignal });
|
|
51
|
-
const toolEventQueue = [];
|
|
52
|
-
const runningToolPromises = [];
|
|
53
|
-
const executeToolAsync = async (channel, name, tool, args) => {
|
|
54
|
-
try {
|
|
55
|
-
let parsedArgs = args;
|
|
56
|
-
if (tool.input) {
|
|
57
|
-
const parseResult = tool.input.safeParse(args);
|
|
58
|
-
if (!parseResult.success) {
|
|
59
|
-
const errorMsg = `Invalid arguments: ${parseResult.error.message}`;
|
|
60
|
-
toolEventQueue.push({
|
|
61
|
-
type: 'toolCallError',
|
|
62
|
-
data: { name, error: errorMsg },
|
|
63
|
-
});
|
|
64
|
-
await client.channel.publish(String(channel), {
|
|
65
|
-
message: { error: errorMsg },
|
|
66
|
-
});
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
parsedArgs = parseResult.data;
|
|
70
|
-
}
|
|
71
|
-
const result = await tool.handler(parsedArgs);
|
|
72
|
-
toolEventQueue.push({
|
|
73
|
-
type: 'toolCallEnd',
|
|
74
|
-
data: { name, result },
|
|
75
|
-
});
|
|
76
|
-
await client.channel.publish(String(channel), {
|
|
77
|
-
message: { data: result },
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
catch (error) {
|
|
81
|
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
|
82
|
-
toolEventQueue.push({
|
|
83
|
-
type: 'toolCallError',
|
|
84
|
-
data: { name, error: errorMessage },
|
|
85
|
-
});
|
|
86
|
-
await client.channel.publish(String(channel), {
|
|
87
|
-
message: { error: errorMessage },
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
};
|
|
91
|
-
for await (const event of stream) {
|
|
92
|
-
if (abortSignal?.aborted) {
|
|
93
|
-
break;
|
|
94
|
-
}
|
|
95
|
-
while (toolEventQueue.length > 0) {
|
|
96
|
-
const toolEvent = toolEventQueue.shift();
|
|
97
|
-
if (toolEvent) {
|
|
98
|
-
yield toolEvent;
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
if (event.type === 'waitForChannelMessageBegin' &&
|
|
102
|
-
event.data &&
|
|
103
|
-
'channel' in event.data &&
|
|
104
|
-
'function' in event.data) {
|
|
105
|
-
const channel = (event.data.channel);
|
|
106
|
-
const args = (event.data.function).args;
|
|
107
|
-
const toolInfo = channelToTool.get(String(channel));
|
|
108
|
-
if (toolInfo) {
|
|
109
|
-
const { name, tool } = toolInfo;
|
|
110
|
-
yield {
|
|
111
|
-
type: 'toolCallStart',
|
|
112
|
-
data: {
|
|
113
|
-
name,
|
|
114
|
-
args,
|
|
115
|
-
},
|
|
116
|
-
};
|
|
117
|
-
const toolPromise = executeToolAsync(channel, name, tool, args);
|
|
118
|
-
runningToolPromises.push(toolPromise);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
yield event;
|
|
1
|
+
import { readFile } from 'fs/promises';
|
|
2
|
+
import yaml from 'js-yaml';
|
|
3
|
+
import { resolve } from 'path';
|
|
4
|
+
function parseAgentFile(content) {
|
|
5
|
+
const frontMatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)/;
|
|
6
|
+
const match = content.match(frontMatterRegex);
|
|
7
|
+
if (!match) {
|
|
8
|
+
return { frontMatter: {}, body: content.trim() };
|
|
122
9
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
10
|
+
let frontMatter = ({});
|
|
11
|
+
try {
|
|
12
|
+
const parsed = yaml.load(match[1]);
|
|
13
|
+
if (typeof parsed === 'object' && parsed !== null) {
|
|
14
|
+
frontMatter = (parsed);
|
|
127
15
|
}
|
|
128
16
|
}
|
|
129
|
-
|
|
130
|
-
await Promise.allSettled(runningToolPromises);
|
|
131
|
-
while (toolEventQueue.length > 0) {
|
|
132
|
-
const toolEvent = toolEventQueue.shift();
|
|
133
|
-
if (toolEvent) {
|
|
134
|
-
yield toolEvent;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
17
|
+
catch {
|
|
137
18
|
}
|
|
19
|
+
return { frontMatter, body: match[2].trim() };
|
|
138
20
|
}
|
|
139
|
-
export async function
|
|
140
|
-
const
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
message: `Plan created with ${input.steps.length} steps${input.rationale ? ': ' + input.rationale : ''}`,
|
|
160
|
-
};
|
|
161
|
-
},
|
|
162
|
-
},
|
|
163
|
-
progress: {
|
|
164
|
-
description: 'Update progress on the current task. Use this to track completed steps, report current status, and identify blockers.',
|
|
165
|
-
input: z.object({
|
|
166
|
-
completed: z
|
|
167
|
-
.array(z.string())
|
|
168
|
-
.optional()
|
|
169
|
-
.describe('Steps that have been completed'),
|
|
170
|
-
current: z.string().optional().describe('Current step being worked on'),
|
|
171
|
-
blockers: z
|
|
172
|
-
.array(z.string())
|
|
173
|
-
.optional()
|
|
174
|
-
.describe('Any issues preventing progress'),
|
|
175
|
-
nextSteps: z
|
|
176
|
-
.array(z.string())
|
|
177
|
-
.optional()
|
|
178
|
-
.describe('Next actions to take'),
|
|
179
|
-
}),
|
|
180
|
-
handler: async (input) => {
|
|
181
|
-
return {
|
|
182
|
-
success: true,
|
|
183
|
-
message: 'Progress updated',
|
|
184
|
-
...input,
|
|
185
|
-
};
|
|
186
|
-
},
|
|
187
|
-
},
|
|
188
|
-
exit: {
|
|
189
|
-
description: 'Exit the task execution with a status code and optional message. Status code 0 indicates success, non-zero indicates failure. Use this when all the tasks are complete or cannot proceed.',
|
|
190
|
-
input: z.object({
|
|
191
|
-
code: z
|
|
192
|
-
.number()
|
|
193
|
-
.int()
|
|
194
|
-
.min(0)
|
|
195
|
-
.max(255)
|
|
196
|
-
.describe('Exit status code (0 = success, non-zero = failure)'),
|
|
197
|
-
message: z
|
|
198
|
-
.string()
|
|
199
|
-
.optional()
|
|
200
|
-
.describe('Optional message explaining the exit reason'),
|
|
201
|
-
}),
|
|
202
|
-
handler: async (input) => {
|
|
203
|
-
exitResult = { code: input.code, message: input.message };
|
|
204
|
-
return {
|
|
205
|
-
success: true,
|
|
206
|
-
message: `Task exiting with code ${input.code}${input.message ? ': ' + input.message : ''}`,
|
|
207
|
-
};
|
|
208
|
-
},
|
|
209
|
-
},
|
|
210
|
-
abort: {
|
|
211
|
-
description: 'Immediately abort the current task. Use this when the user explicitly asks you to stop, cancel, or abort what you are doing. Set hard to true to kill running processes immediately.',
|
|
212
|
-
input: z.object({
|
|
213
|
-
reason: z.string().optional().describe('Brief reason for aborting'),
|
|
214
|
-
hard: z
|
|
215
|
-
.boolean()
|
|
216
|
-
.optional()
|
|
217
|
-
.describe('If true, immediately kill running processes. If false (default), finish the current operation gracefully.'),
|
|
218
|
-
}),
|
|
219
|
-
handler: async (input) => {
|
|
220
|
-
const reason = input.reason || 'aborted by user request';
|
|
221
|
-
exitResult = { code: 1, message: reason };
|
|
222
|
-
if (input.hard && internalAbort) {
|
|
223
|
-
internalAbort.abort(reason);
|
|
224
|
-
}
|
|
225
|
-
return {
|
|
226
|
-
success: true,
|
|
227
|
-
message: `Task aborted: ${reason}`,
|
|
228
|
-
};
|
|
229
|
-
},
|
|
230
|
-
},
|
|
231
|
-
};
|
|
232
|
-
const allTools = { ...tools, ...systemTools };
|
|
233
|
-
const systemInstruction = `
|
|
234
|
-
${options.extensions?.backstory || ''}
|
|
235
|
-
|
|
236
|
-
# Task Execution Guidelines
|
|
237
|
-
|
|
238
|
-
The goal is to complete the assigned task efficiently and effectively. Follow these guidelines:
|
|
239
|
-
|
|
240
|
-
1. **Plan First**: Use the 'plan' function to create a clear strategy before starting work
|
|
241
|
-
2. **Track Progress**: Regularly use the 'progress' function to update status and identify issues
|
|
242
|
-
3. **Use Tools**: Leverage available tools to accomplish each step of your plan
|
|
243
|
-
4. **Exit When Done**: Call the 'exit' function with code 0 when successful, or non-zero code if unable to complete
|
|
244
|
-
5. **Abort**: If the user asks you to stop, cancel, or abort, call the 'abort' function immediately. Use hard=true if processes are running that need to be killed right away.
|
|
245
|
-
6. **Be Autonomous**: Work through the task systematically without waiting for additional input
|
|
246
|
-
7. **Be Responsive**: If the user sends a new message while you are working, acknowledge it briefly and adjust your approach if needed. Always prioritize user input over your current plan.
|
|
247
|
-
`.trim();
|
|
248
|
-
let iteration = 0;
|
|
249
|
-
while (iteration < maxIterations && exitResult === null) {
|
|
250
|
-
if (abortSignal?.aborted) {
|
|
251
|
-
exitResult = {
|
|
252
|
-
code: 1,
|
|
253
|
-
message: 'Task execution aborted',
|
|
254
|
-
};
|
|
255
|
-
break;
|
|
256
|
-
}
|
|
257
|
-
iteration++;
|
|
258
|
-
yield { type: 'iteration', data: { iteration } };
|
|
259
|
-
let lastEndReason = null;
|
|
260
|
-
internalAbort = new AbortController();
|
|
261
|
-
if (abortSignal?.aborted) {
|
|
262
|
-
internalAbort.abort(abortSignal.reason);
|
|
263
|
-
}
|
|
264
|
-
else if (abortSignal) {
|
|
265
|
-
const capturedAbort = internalAbort;
|
|
266
|
-
abortSignal.addEventListener('abort', () => capturedAbort.abort(abortSignal.reason), { once: true });
|
|
267
|
-
}
|
|
268
|
-
const iterSignal = internalAbort.signal;
|
|
269
|
-
for await (const event of complete({
|
|
270
|
-
...request,
|
|
271
|
-
client,
|
|
272
|
-
messages,
|
|
273
|
-
tools: allTools,
|
|
274
|
-
abortSignal: iterSignal,
|
|
275
|
-
extensions: {
|
|
276
|
-
...options.extensions,
|
|
277
|
-
backstory: systemInstruction,
|
|
278
|
-
},
|
|
279
|
-
})) {
|
|
280
|
-
if (event.type === 'message') {
|
|
281
|
-
messages.push(event.data);
|
|
282
|
-
}
|
|
283
|
-
if (event.type === 'result') {
|
|
284
|
-
if (event.data.end.reason) {
|
|
285
|
-
lastEndReason = event.data.end.reason;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
yield event;
|
|
289
|
-
}
|
|
290
|
-
if (exitResult) {
|
|
291
|
-
break;
|
|
292
|
-
}
|
|
293
|
-
if (lastEndReason === 'stop') {
|
|
294
|
-
break;
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
if (exitResult === null) {
|
|
298
|
-
exitResult = {
|
|
299
|
-
code: 1,
|
|
300
|
-
message: `Task did not complete within ${maxIterations} iterations`,
|
|
301
|
-
};
|
|
302
|
-
}
|
|
303
|
-
yield { type: 'exit', data: exitResult };
|
|
21
|
+
export async function loadAgent(filePath) {
|
|
22
|
+
const resolvedPath = resolve(process.cwd(), filePath);
|
|
23
|
+
const content = await readFile(resolvedPath, 'utf-8');
|
|
24
|
+
const { frontMatter, body } = parseAgentFile(content);
|
|
25
|
+
const name = typeof frontMatter.name === 'string' ? frontMatter.name : undefined;
|
|
26
|
+
const description = typeof frontMatter.description === 'string'
|
|
27
|
+
? frontMatter.description
|
|
28
|
+
: undefined;
|
|
29
|
+
const model = typeof frontMatter.model === 'string' ? frontMatter.model : undefined;
|
|
30
|
+
const botId = typeof frontMatter.botId === 'string' ? frontMatter.botId : undefined;
|
|
31
|
+
const skillsetId = typeof frontMatter.skillsetId === 'string'
|
|
32
|
+
? frontMatter.skillsetId
|
|
33
|
+
: undefined;
|
|
34
|
+
const datasetId = typeof frontMatter.datasetId === 'string'
|
|
35
|
+
? frontMatter.datasetId
|
|
36
|
+
: undefined;
|
|
37
|
+
const frontMatterBackstory = typeof frontMatter.backstory === 'string' ? frontMatter.backstory : '';
|
|
38
|
+
const backstoryParts = [frontMatterBackstory, body].filter(Boolean);
|
|
39
|
+
const backstory = backstoryParts.length > 0 ? backstoryParts.join('\n\n') : undefined;
|
|
40
|
+
return { name, description, backstory, model, botId, skillsetId, datasetId };
|
|
304
41
|
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export function complete(options: Omit<ConversationCompleteRequest, "functions" | "limits"> & {
|
|
2
|
+
client: ChatBotKit;
|
|
3
|
+
tools?: Tools;
|
|
4
|
+
abortSignal?: AbortSignal;
|
|
5
|
+
}): AsyncGenerator<ConversationCompleteStreamType | ToolCallStartEvent | ToolCallEndEvent | ToolCallErrorEvent, void, unknown>;
|
|
6
|
+
export function execute(options: Omit<ConversationCompleteRequest, "functions" | "limits"> & {
|
|
7
|
+
client: ChatBotKit;
|
|
8
|
+
tools?: Tools;
|
|
9
|
+
maxIterations?: number;
|
|
10
|
+
abortSignal?: AbortSignal;
|
|
11
|
+
}): AsyncGenerator<ConversationCompleteStreamType | ToolCallStartEvent | ToolCallEndEvent | ToolCallErrorEvent | IterationEvent | ExitEvent, void, unknown>;
|
|
12
|
+
export type ZodObject = import("zod").ZodObject<any>;
|
|
13
|
+
export type ChatBotKit = import("@chatbotkit/sdk").ChatBotKit;
|
|
14
|
+
export type ConversationCompleteRequest = import("@chatbotkit/sdk/conversation/v1").ConversationCompleteRequest;
|
|
15
|
+
export type ConversationCompleteStreamType = import("@chatbotkit/sdk/conversation/v1").ConversationCompleteStreamType;
|
|
16
|
+
export type ToolDefinition<T extends ZodObject> = {
|
|
17
|
+
description: string;
|
|
18
|
+
input?: T;
|
|
19
|
+
handler: (input: any) => Promise<any>;
|
|
20
|
+
};
|
|
21
|
+
export type Tools = Record<string, ToolDefinition<ZodObject>>;
|
|
22
|
+
export type ExitResult = {
|
|
23
|
+
code: number;
|
|
24
|
+
message?: string;
|
|
25
|
+
};
|
|
26
|
+
export type ToolCallStartEvent = {
|
|
27
|
+
type: "toolCallStart";
|
|
28
|
+
data: {
|
|
29
|
+
name: string;
|
|
30
|
+
args: any;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
export type ToolCallEndEvent = {
|
|
34
|
+
type: "toolCallEnd";
|
|
35
|
+
data: {
|
|
36
|
+
name: string;
|
|
37
|
+
result: any;
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
export type ToolCallErrorEvent = {
|
|
41
|
+
type: "toolCallError";
|
|
42
|
+
data: {
|
|
43
|
+
name: string;
|
|
44
|
+
error: string;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
export type IterationEvent = {
|
|
48
|
+
type: "iteration";
|
|
49
|
+
data: {
|
|
50
|
+
iteration: number;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
export type ExitEvent = {
|
|
54
|
+
type: "exit";
|
|
55
|
+
data: ExitResult;
|
|
56
|
+
};
|