@dxos/assistant 0.8.1-main.ba2dec9 → 0.8.1-staging.31c3ee1
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/dist/lib/browser/chunk-PND5VR6D.mjs +2315 -0
- package/dist/lib/browser/chunk-PND5VR6D.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +313 -1631
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +20 -6
- package/dist/lib/browser/testing/index.mjs.map +4 -4
- package/dist/lib/node/chunk-IBOBRBDF.cjs +2326 -0
- package/dist/lib/node/chunk-IBOBRBDF.cjs.map +7 -0
- package/dist/lib/node/index.cjs +321 -1629
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +22 -11
- package/dist/lib/node/testing/index.cjs.map +4 -4
- package/dist/lib/node-esm/chunk-DCQJOLSR.mjs +2317 -0
- package/dist/lib/node-esm/chunk-DCQJOLSR.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +313 -1631
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +20 -6
- package/dist/lib/node-esm/testing/index.mjs.map +4 -4
- package/dist/types/src/ai-service/defs.d.ts +8 -2
- package/dist/types/src/ai-service/defs.d.ts.map +1 -1
- package/dist/types/src/ai-service/edge-client.d.ts.map +1 -1
- package/dist/types/src/ai-service/message-collector.d.ts +16 -16
- package/dist/types/src/ai-service/message-collector.d.ts.map +1 -1
- package/dist/types/src/ai-service/ollama-client.d.ts +1 -5
- package/dist/types/src/ai-service/ollama-client.d.ts.map +1 -1
- package/dist/types/src/ai-service/parser.d.ts +8 -8
- package/dist/types/src/ai-service/parser.d.ts.map +1 -1
- package/dist/types/src/ai-service/types.d.ts +90 -156
- package/dist/types/src/ai-service/types.d.ts.map +1 -1
- package/dist/types/src/conversation/conversation.d.ts +8 -8
- package/dist/types/src/conversation/conversation.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/session/index.d.ts +2 -0
- package/dist/types/src/session/index.d.ts.map +1 -0
- package/dist/types/src/session/session.d.ts +216 -0
- package/dist/types/src/session/session.d.ts.map +1 -0
- package/dist/types/src/session/session.test.d.ts +2 -0
- package/dist/types/src/session/session.test.d.ts.map +1 -0
- package/dist/types/src/testing/index.d.ts +1 -0
- package/dist/types/src/testing/index.d.ts.map +1 -1
- package/dist/types/src/testing/ollama.d.ts +6 -0
- package/dist/types/src/testing/ollama.d.ts.map +1 -0
- package/package.json +13 -13
- package/src/ai-service/client.test.ts +14 -14
- package/src/ai-service/defs.ts +18 -3
- package/src/ai-service/edge-client.ts +3 -2
- package/src/ai-service/ollama-client.ts +50 -24
- package/src/ai-service/parser.ts +4 -2
- package/src/ai-service/stream.test.ts +28 -4
- package/src/ai-service/types.ts +2 -2
- package/src/bin/chat.ts +3 -3
- package/src/conversation/conversation.test.ts +3 -3
- package/src/conversation/conversation.ts +17 -1
- package/src/cypher/query-executor.test.ts +3 -3
- package/src/cypher/schema.test.ts +1 -1
- package/src/index.ts +1 -0
- package/src/session/index.ts +5 -0
- package/src/session/session.test.ts +257 -0
- package/src/session/session.ts +375 -0
- package/src/testing/artifacts.test.ts +6 -6
- package/src/testing/index.ts +1 -0
- package/src/testing/object-extraction.test.ts +2 -2
- package/src/testing/ollama.ts +15 -0
- package/src/testing/query.test.ts +5 -5
- package/src/testing/test-schema.ts +5 -5
- package/dist/lib/browser/chunk-AXUUNA7O.mjs +0 -565
- package/dist/lib/browser/chunk-AXUUNA7O.mjs.map +0 -7
- package/dist/lib/node/chunk-QPHGQINW.cjs +0 -577
- package/dist/lib/node/chunk-QPHGQINW.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-GOVFOBIB.mjs +0 -567
- package/dist/lib/node-esm/chunk-GOVFOBIB.mjs.map +0 -7
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2025 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { Schema as S } from 'effect';
|
|
6
|
+
import { inspect } from 'node:util';
|
|
7
|
+
import { describe, test } from 'vitest';
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
ArtifactId,
|
|
11
|
+
defineArtifact,
|
|
12
|
+
defineTool,
|
|
13
|
+
ToolResult,
|
|
14
|
+
type Message,
|
|
15
|
+
type MessageContentBlock,
|
|
16
|
+
} from '@dxos/artifact';
|
|
17
|
+
import { AIServiceEdgeClient } from '@dxos/assistant';
|
|
18
|
+
import { createStatic, EchoObject, ObjectId } from '@dxos/echo-schema';
|
|
19
|
+
import { DXN } from '@dxos/keys';
|
|
20
|
+
import { log } from '@dxos/log';
|
|
21
|
+
|
|
22
|
+
import { AISession } from './session';
|
|
23
|
+
import { AI_SERVICE_ENDPOINT } from '../testing';
|
|
24
|
+
|
|
25
|
+
// Define a calendar event artifact schema.
|
|
26
|
+
const CalendarEventSchema = S.Struct({
|
|
27
|
+
title: S.String,
|
|
28
|
+
startTime: S.String,
|
|
29
|
+
endTime: S.String,
|
|
30
|
+
description: S.String,
|
|
31
|
+
}).pipe(EchoObject({ typename: 'example.com/type/CalendarEvent', version: '0.1.0' }));
|
|
32
|
+
|
|
33
|
+
type CalendarEvent = S.Schema.Type<typeof CalendarEventSchema>;
|
|
34
|
+
|
|
35
|
+
// TODO(burdon): Flaky.
|
|
36
|
+
describe.skip('AISession with Ollama', () => {
|
|
37
|
+
test('create calendar itinerary', { timeout: 60_000 }, async () => {
|
|
38
|
+
const aiClient = new AIServiceEdgeClient({ endpoint: AI_SERVICE_ENDPOINT.REMOTE });
|
|
39
|
+
// const aiClient = new OllamaClient({
|
|
40
|
+
// overrides: { model: 'llama3.1:8b' },
|
|
41
|
+
// });
|
|
42
|
+
const session = new AISession({ operationModel: 'immediate' });
|
|
43
|
+
|
|
44
|
+
const objects = new Set<string>();
|
|
45
|
+
|
|
46
|
+
// Define calendar artifact.
|
|
47
|
+
const calendarArtifact = defineArtifact({
|
|
48
|
+
id: 'artifact:dxos.org/plugin/calendar',
|
|
49
|
+
name: 'Calendar',
|
|
50
|
+
instructions: 'Use this to create and query calendar events.',
|
|
51
|
+
schema: CalendarEventSchema,
|
|
52
|
+
tools: [
|
|
53
|
+
defineTool('calendar', {
|
|
54
|
+
name: 'query',
|
|
55
|
+
description: 'Query the calendar for events',
|
|
56
|
+
schema: S.Struct({}),
|
|
57
|
+
execute: async () => {
|
|
58
|
+
return ToolResult.Success(CALENDAR_EVENTS);
|
|
59
|
+
},
|
|
60
|
+
}),
|
|
61
|
+
],
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const tableArtifact = defineArtifact({
|
|
65
|
+
id: 'artifact:dxos.org/plugin/table',
|
|
66
|
+
name: 'Table',
|
|
67
|
+
instructions: 'Use this to create and manage tables. Each table has a unique id.',
|
|
68
|
+
schema: S.Struct({}),
|
|
69
|
+
tools: [
|
|
70
|
+
defineTool('table', {
|
|
71
|
+
name: 'create',
|
|
72
|
+
description: 'Create a table',
|
|
73
|
+
schema: S.Struct({
|
|
74
|
+
data: S.Array(S.Any).annotations({ description: 'Array of data payloads to add as rows' }),
|
|
75
|
+
}),
|
|
76
|
+
execute: async ({ data }) => {
|
|
77
|
+
log('create table', { data });
|
|
78
|
+
const id = DXN.fromLocalObjectId(ObjectId.random()).toString();
|
|
79
|
+
objects.add(id);
|
|
80
|
+
// TODO(dmaretskyi): consider xml for refs instead of @dxn:echo:@:XXXXX
|
|
81
|
+
return ToolResult.Success(`table @${id}`);
|
|
82
|
+
},
|
|
83
|
+
}),
|
|
84
|
+
],
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const mapArtifact = defineArtifact({
|
|
88
|
+
id: 'artifact:dxos.org/plugin/map',
|
|
89
|
+
name: 'Map',
|
|
90
|
+
instructions:
|
|
91
|
+
'Use this to create and manage maps. Maps source data from tables. Table id is required to create a map.',
|
|
92
|
+
schema: S.Struct({}),
|
|
93
|
+
tools: [
|
|
94
|
+
defineTool('map', {
|
|
95
|
+
name: 'create',
|
|
96
|
+
description: 'Create a map',
|
|
97
|
+
schema: S.Struct({
|
|
98
|
+
source: ArtifactId.annotations({
|
|
99
|
+
description: 'The table that will be used as the source of the map',
|
|
100
|
+
}),
|
|
101
|
+
}),
|
|
102
|
+
execute: async ({ source }) => {
|
|
103
|
+
// TODO(dmaretskyi): Use effect-schema decode instead of manual parsing.
|
|
104
|
+
const sourceId = ArtifactId.toDXN(source);
|
|
105
|
+
if (!objects.has(sourceId.toString())) {
|
|
106
|
+
return ToolResult.Error(`table id=${source} not found`);
|
|
107
|
+
}
|
|
108
|
+
log('create map', { sourceId });
|
|
109
|
+
const id = DXN.fromLocalObjectId(ObjectId.random()).toString();
|
|
110
|
+
objects.add(id);
|
|
111
|
+
// TODO(dmaretskyi): consider xml for refs instead of @dxn:echo:@:XXXXX
|
|
112
|
+
return ToolResult.Success(`map @${id}`);
|
|
113
|
+
},
|
|
114
|
+
}),
|
|
115
|
+
],
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
const scriptArtifact = defineArtifact({
|
|
119
|
+
id: 'artifact:dxos.org/plugin/script',
|
|
120
|
+
name: 'Script',
|
|
121
|
+
instructions: 'Use this to create and manage scripts',
|
|
122
|
+
schema: S.Struct({}),
|
|
123
|
+
tools: [],
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// session.streamEvent.on((event) => {
|
|
127
|
+
// printStreamEvent(event);
|
|
128
|
+
// });
|
|
129
|
+
|
|
130
|
+
session.message.on(printMessage);
|
|
131
|
+
session.userMessage.on(printMessage);
|
|
132
|
+
session.block.on(printContentBlock);
|
|
133
|
+
|
|
134
|
+
// session.update.on((update) => {
|
|
135
|
+
// log('update', { update });
|
|
136
|
+
// });
|
|
137
|
+
|
|
138
|
+
// Test creating an itinerary
|
|
139
|
+
const response = await session.run({
|
|
140
|
+
client: aiClient,
|
|
141
|
+
tools: [],
|
|
142
|
+
artifacts: [calendarArtifact, tableArtifact, mapArtifact, scriptArtifact],
|
|
143
|
+
history: [],
|
|
144
|
+
generationOptions: {
|
|
145
|
+
model: '@anthropic/claude-3-5-haiku-20241022',
|
|
146
|
+
},
|
|
147
|
+
prompt: 'create a table and map for a travel itinerary based on events in my calendar',
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
log('result', {
|
|
151
|
+
objects,
|
|
152
|
+
finalMessage: response.at(-1),
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// Travel to rome, florence, livorno, siena, madrid for conferences
|
|
158
|
+
const CALENDAR_EVENTS: CalendarEvent[] = [
|
|
159
|
+
createStatic(CalendarEventSchema, {
|
|
160
|
+
title: 'Exploring Ancient Ruins in Rome',
|
|
161
|
+
startTime: '2024-01-01T10:00:00Z',
|
|
162
|
+
endTime: '2024-01-01T11:00:00Z',
|
|
163
|
+
description: 'Tech conference at the historic Colosseum with networking opportunities',
|
|
164
|
+
}),
|
|
165
|
+
createStatic(CalendarEventSchema, {
|
|
166
|
+
title: 'Renaissance Tech Summit in Florence',
|
|
167
|
+
startTime: '2024-01-01T11:00:00Z',
|
|
168
|
+
endTime: '2024-01-01T12:00:00Z',
|
|
169
|
+
description: 'Discussing AI innovations surrounded by Renaissance art',
|
|
170
|
+
}),
|
|
171
|
+
createStatic(CalendarEventSchema, {
|
|
172
|
+
title: 'Travel to Livorno',
|
|
173
|
+
startTime: '2024-01-01T12:00:00Z',
|
|
174
|
+
endTime: '2024-01-01T13:00:00Z',
|
|
175
|
+
description: 'Travel to Livorno',
|
|
176
|
+
}),
|
|
177
|
+
createStatic(CalendarEventSchema, {
|
|
178
|
+
title: 'Travel to Siena',
|
|
179
|
+
startTime: '2024-01-01T13:00:00Z',
|
|
180
|
+
endTime: '2024-01-01T14:00:00Z',
|
|
181
|
+
description: 'Travel to Siena',
|
|
182
|
+
}),
|
|
183
|
+
createStatic(CalendarEventSchema, {
|
|
184
|
+
title: 'Travel to Madrid',
|
|
185
|
+
startTime: '2024-01-01T14:00:00Z',
|
|
186
|
+
endTime: '2024-01-01T15:00:00Z',
|
|
187
|
+
description: 'Travel to Madrid',
|
|
188
|
+
}),
|
|
189
|
+
];
|
|
190
|
+
|
|
191
|
+
const printMessage = (message: Message) => {
|
|
192
|
+
console.log(`${message.role.toUpperCase()}\n`);
|
|
193
|
+
for (const content of message.content) {
|
|
194
|
+
printContentBlock(content);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
const printContentBlock = (content: MessageContentBlock) => {
|
|
199
|
+
switch (content.type) {
|
|
200
|
+
case 'text':
|
|
201
|
+
console.log(content.text);
|
|
202
|
+
break;
|
|
203
|
+
case 'tool_use':
|
|
204
|
+
console.log(`⚙️ [Tool Use] ${content.name} ${inspect(content.input, { depth: null, colors: true })}`);
|
|
205
|
+
break;
|
|
206
|
+
case 'tool_result': {
|
|
207
|
+
let data: any;
|
|
208
|
+
try {
|
|
209
|
+
data = JSON.parse(content.content);
|
|
210
|
+
} catch {
|
|
211
|
+
data = content.content;
|
|
212
|
+
}
|
|
213
|
+
console.log(`⚙️ [Tool Result] ${content.toolUseId} ${inspect(data, { depth: null, colors: true })}`);
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
// const printStreamEvent = (event: GenerationStreamEvent) => {
|
|
220
|
+
// switch (event.type) {
|
|
221
|
+
// case 'message_start': {
|
|
222
|
+
// process.stdout.write(`${event.message.role.toUpperCase()}\n\n`);
|
|
223
|
+
// for (const content of event.message.content) {
|
|
224
|
+
// printContentBlock(content);
|
|
225
|
+
// }
|
|
226
|
+
// break;
|
|
227
|
+
// }
|
|
228
|
+
// case 'content_block_start': {
|
|
229
|
+
// printContentBlock(event.content);
|
|
230
|
+
// break;
|
|
231
|
+
// }
|
|
232
|
+
// case 'content_block_delta': {
|
|
233
|
+
// switch (event.delta.type) {
|
|
234
|
+
// case 'text_delta': {
|
|
235
|
+
// process.stdout.write(event.delta.text);
|
|
236
|
+
// break;
|
|
237
|
+
// }
|
|
238
|
+
// case 'input_json_delta': {
|
|
239
|
+
// process.stdout.write(event.delta.partial_json);
|
|
240
|
+
// break;
|
|
241
|
+
// }
|
|
242
|
+
// }
|
|
243
|
+
// break;
|
|
244
|
+
// }
|
|
245
|
+
// case 'content_block_stop': {
|
|
246
|
+
// process.stdout.write('\n');
|
|
247
|
+
// break;
|
|
248
|
+
// }
|
|
249
|
+
// case 'message_delta': {
|
|
250
|
+
// break;
|
|
251
|
+
// }
|
|
252
|
+
// case 'message_stop': {
|
|
253
|
+
// process.stdout.write('\n\n');
|
|
254
|
+
// break;
|
|
255
|
+
// }
|
|
256
|
+
// }
|
|
257
|
+
// };
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2025 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { Schema as S } from 'effect';
|
|
6
|
+
|
|
7
|
+
import { defineTool, Message, ToolResult, type ArtifactDefinition, type Tool } from '@dxos/artifact';
|
|
8
|
+
import { Event, synchronized } from '@dxos/async';
|
|
9
|
+
import { createStatic } from '@dxos/echo-schema';
|
|
10
|
+
import { invariant } from '@dxos/invariant';
|
|
11
|
+
import { log } from '@dxos/log';
|
|
12
|
+
|
|
13
|
+
import { MixedStreamParser, type AIServiceClient, type GenerateRequest, type GenerationStream } from '../ai-service';
|
|
14
|
+
import { isToolUse, runTools } from '../conversation';
|
|
15
|
+
/**
|
|
16
|
+
* Contains message history, tools, current context.
|
|
17
|
+
* Current context means the state of the app, time of day, and other contextual information.
|
|
18
|
+
* It makes requests to the model, its a state machine.
|
|
19
|
+
* It keeps track of the current goal.
|
|
20
|
+
* It manages the context window.
|
|
21
|
+
* Tracks the success criteria of reaching the goal, exposing metrics (stretch)
|
|
22
|
+
* Could be run locally in the app or remotely.
|
|
23
|
+
* Could be personal or shared.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export type SessionRunOptions = {
|
|
27
|
+
client: AIServiceClient;
|
|
28
|
+
|
|
29
|
+
artifacts: ArtifactDefinition[];
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Non-artifact specific tools.
|
|
33
|
+
*/
|
|
34
|
+
tools: Tool[];
|
|
35
|
+
|
|
36
|
+
history: Message[];
|
|
37
|
+
|
|
38
|
+
prompt: string;
|
|
39
|
+
|
|
40
|
+
generationOptions?: Pick<GenerateRequest, 'model'>;
|
|
41
|
+
|
|
42
|
+
extensions?: ToolContextExtensions;
|
|
43
|
+
|
|
44
|
+
systemPrompt?: string;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Pre-require artifacts.
|
|
48
|
+
*/
|
|
49
|
+
requiredArtifactIds?: string[];
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
type OperationModel = 'planning' | 'immediate';
|
|
53
|
+
|
|
54
|
+
export type AiSessionOptions = {
|
|
55
|
+
/**
|
|
56
|
+
* In planning mode, the model will create a plan before executing the user's request.
|
|
57
|
+
* The plan will determine the artifacts that will be used to perform the actions.
|
|
58
|
+
* In require mode, the model will select the artifacts that will be used to perform the actions.
|
|
59
|
+
*/
|
|
60
|
+
operationModel: OperationModel;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export class AISession {
|
|
64
|
+
/** SSE stream parser. */
|
|
65
|
+
private readonly _parser = new MixedStreamParser();
|
|
66
|
+
|
|
67
|
+
/** Pending messages (incl. the current user request). */
|
|
68
|
+
private _pending: Message[] = [];
|
|
69
|
+
|
|
70
|
+
/** Current streaming response. */
|
|
71
|
+
private _stream: GenerationStream | undefined;
|
|
72
|
+
|
|
73
|
+
/** Prior history from queue. */
|
|
74
|
+
private _history: Message[] = [];
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* New message.
|
|
78
|
+
*/
|
|
79
|
+
public readonly message = this._parser.message;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Complete block added to Message.
|
|
83
|
+
*/
|
|
84
|
+
public readonly block = this._parser.block;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Update partial block (while streaming).
|
|
88
|
+
*/
|
|
89
|
+
public readonly update = this._parser.update;
|
|
90
|
+
|
|
91
|
+
public readonly streamEvent = this._parser.streamEvent;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* User prompt or tool result.
|
|
95
|
+
*/
|
|
96
|
+
public readonly userMessage = new Event<Message>();
|
|
97
|
+
|
|
98
|
+
constructor(private readonly _options: AiSessionOptions) {
|
|
99
|
+
// Message complete.
|
|
100
|
+
this._parser.message.on((message) => {
|
|
101
|
+
this._pending.push(message);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
@synchronized
|
|
106
|
+
async run(options: SessionRunOptions): Promise<Message[]> {
|
|
107
|
+
const systemTools: Tool[] = [
|
|
108
|
+
defineTool('system', {
|
|
109
|
+
name: 'query_artifact_definitions',
|
|
110
|
+
description: 'Query the available artifact definitions',
|
|
111
|
+
schema: S.Struct({}),
|
|
112
|
+
execute: async () => {
|
|
113
|
+
return ToolResult.Success({
|
|
114
|
+
artifactDefinitions: options.artifacts.map((artifact) => ({
|
|
115
|
+
id: artifact.id,
|
|
116
|
+
name: artifact.name,
|
|
117
|
+
description: artifact.description,
|
|
118
|
+
})),
|
|
119
|
+
});
|
|
120
|
+
},
|
|
121
|
+
}),
|
|
122
|
+
];
|
|
123
|
+
switch (this._options.operationModel) {
|
|
124
|
+
case 'planning':
|
|
125
|
+
systemTools.push(
|
|
126
|
+
defineTool('system', {
|
|
127
|
+
name: 'create_plan',
|
|
128
|
+
description:
|
|
129
|
+
'Create a plan. Make sure that each step is independent and can be executed solely on the data returned by the previous step. The steps only share the data that is specified in the plan.',
|
|
130
|
+
schema: S.Struct({
|
|
131
|
+
goal: S.String.annotations({ description: 'The goal that the plan will achieve.' }),
|
|
132
|
+
steps: S.Array(
|
|
133
|
+
S.Struct({
|
|
134
|
+
action: S.String.annotations({
|
|
135
|
+
description: 'Complete, detailed action to perform.',
|
|
136
|
+
}),
|
|
137
|
+
input: S.String.annotations({
|
|
138
|
+
description: 'The required input data for this step. First step must not require any data.',
|
|
139
|
+
}),
|
|
140
|
+
output: S.String.annotations({
|
|
141
|
+
description: 'The output data from this step. This is passed to the next step as input.',
|
|
142
|
+
}),
|
|
143
|
+
requiredArtifactIds: S.Array(S.String).annotations({
|
|
144
|
+
description: 'The ids of the artifacts required to perform this step.',
|
|
145
|
+
examples: [['artifact:dxos.org/example/Test']],
|
|
146
|
+
}),
|
|
147
|
+
}),
|
|
148
|
+
).annotations({ description: 'Steps' }),
|
|
149
|
+
}),
|
|
150
|
+
execute: async ({ goal, steps }) => {
|
|
151
|
+
const missingArtifactIds = steps
|
|
152
|
+
.flatMap((step) => step.requiredArtifactIds)
|
|
153
|
+
.filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
|
|
154
|
+
if (missingArtifactIds.length > 0) {
|
|
155
|
+
return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(', ')}`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const stepResults: any[] = [];
|
|
159
|
+
for (const step of steps) {
|
|
160
|
+
log('executing step', { action: step.action });
|
|
161
|
+
const session = new AISession({ operationModel: 'immediate' });
|
|
162
|
+
session.message.on((ev) => this.message.emit(ev));
|
|
163
|
+
session.block.on((ev) => this.block.emit(ev));
|
|
164
|
+
session.update.on((ev) => this.update.emit(ev));
|
|
165
|
+
session.streamEvent.on((ev) => this.streamEvent.emit(ev));
|
|
166
|
+
session.userMessage.on((ev) => this.userMessage.emit(ev));
|
|
167
|
+
|
|
168
|
+
const messages = await session.run({
|
|
169
|
+
client: options.client,
|
|
170
|
+
artifacts: options.artifacts,
|
|
171
|
+
tools: options.tools,
|
|
172
|
+
history: options.history,
|
|
173
|
+
extensions: options.extensions,
|
|
174
|
+
generationOptions: options.generationOptions,
|
|
175
|
+
requiredArtifactIds: step.requiredArtifactIds.slice(),
|
|
176
|
+
prompt: `
|
|
177
|
+
You are an agent that executes the subtask in a plan.
|
|
178
|
+
|
|
179
|
+
While you know the plan's goal only focus on your subtask
|
|
180
|
+
Use the data from the previous step to complete your task.
|
|
181
|
+
Return all of the data from "output" in your last message.
|
|
182
|
+
|
|
183
|
+
Current step (that you need to complete):
|
|
184
|
+
${JSON.stringify(
|
|
185
|
+
{
|
|
186
|
+
goal,
|
|
187
|
+
input: step.input,
|
|
188
|
+
output: step.output,
|
|
189
|
+
yourTask: step.action,
|
|
190
|
+
},
|
|
191
|
+
null,
|
|
192
|
+
2,
|
|
193
|
+
)}
|
|
194
|
+
|
|
195
|
+
Previous step results:
|
|
196
|
+
${JSON.stringify(stepResults.at(-1))}.
|
|
197
|
+
`,
|
|
198
|
+
});
|
|
199
|
+
const result = messages.at(-1);
|
|
200
|
+
stepResults.push(result);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return ToolResult.Success({ stepResults });
|
|
204
|
+
},
|
|
205
|
+
}),
|
|
206
|
+
);
|
|
207
|
+
break;
|
|
208
|
+
case 'immediate':
|
|
209
|
+
systemTools.push(
|
|
210
|
+
defineTool('system', {
|
|
211
|
+
name: 'require_artifact_definitions',
|
|
212
|
+
description:
|
|
213
|
+
'Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.',
|
|
214
|
+
schema: S.Struct({
|
|
215
|
+
artifactDefinitionIds: S.Array(S.String).annotations({
|
|
216
|
+
description: 'The ids of the artifact definitions to require',
|
|
217
|
+
examples: [['artifact:dxos.org/example/Test']],
|
|
218
|
+
}),
|
|
219
|
+
}),
|
|
220
|
+
execute: async ({ artifactDefinitionIds }) => {
|
|
221
|
+
const missingArtifactDefinitionIds = artifactDefinitionIds.filter(
|
|
222
|
+
(artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId),
|
|
223
|
+
);
|
|
224
|
+
if (missingArtifactDefinitionIds.length > 0) {
|
|
225
|
+
return ToolResult.Error(
|
|
226
|
+
`One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(', ')}`,
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
for (const artifactDefinitionId of artifactDefinitionIds) {
|
|
231
|
+
requiredArtifactIds.add(artifactDefinitionId);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return ToolResult.Success({});
|
|
235
|
+
},
|
|
236
|
+
}),
|
|
237
|
+
);
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
this._history = [...options.history];
|
|
242
|
+
this._pending = [
|
|
243
|
+
createStatic(Message, {
|
|
244
|
+
role: 'user',
|
|
245
|
+
content: [{ type: 'text', text: options.prompt }],
|
|
246
|
+
}),
|
|
247
|
+
];
|
|
248
|
+
this.userMessage.emit(this._pending.at(-1)!);
|
|
249
|
+
this._stream = undefined;
|
|
250
|
+
let error: Error | undefined;
|
|
251
|
+
|
|
252
|
+
const requiredArtifactIds = new Set<string>(options.requiredArtifactIds ?? []);
|
|
253
|
+
try {
|
|
254
|
+
let more = false;
|
|
255
|
+
do {
|
|
256
|
+
const tools = [
|
|
257
|
+
...systemTools,
|
|
258
|
+
...options.tools,
|
|
259
|
+
...options.artifacts
|
|
260
|
+
.filter((artifact) => requiredArtifactIds.has(artifact.id))
|
|
261
|
+
.flatMap((artifact) => artifact.tools),
|
|
262
|
+
];
|
|
263
|
+
|
|
264
|
+
log('request', {
|
|
265
|
+
pending: this._pending.length,
|
|
266
|
+
history: this._history.length,
|
|
267
|
+
tools: tools.map((tool) => tool.name),
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
// Open request stream.
|
|
271
|
+
this._stream = await options.client.exec({
|
|
272
|
+
...(options.generationOptions ?? {}),
|
|
273
|
+
// TODO(burdon): Rename messages or separate history/message.
|
|
274
|
+
history: [...this._history, ...this._pending],
|
|
275
|
+
tools,
|
|
276
|
+
systemPrompt:
|
|
277
|
+
options.systemPrompt ??
|
|
278
|
+
createBaseInstructions({
|
|
279
|
+
availableArtifacts: Array.from(requiredArtifactIds),
|
|
280
|
+
operationModel: this._options.operationModel,
|
|
281
|
+
}),
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
// Wait until complete.
|
|
285
|
+
await this._parser.parse(this._stream);
|
|
286
|
+
await this._stream.complete();
|
|
287
|
+
|
|
288
|
+
// Add messages.
|
|
289
|
+
log('response', { pending: this._pending });
|
|
290
|
+
|
|
291
|
+
// Resolve tool use locally.
|
|
292
|
+
more = false;
|
|
293
|
+
const message = this._pending.at(-1);
|
|
294
|
+
invariant(message);
|
|
295
|
+
if (isToolUse(message)) {
|
|
296
|
+
log('tool request...');
|
|
297
|
+
const response = await runTools({
|
|
298
|
+
message: this._pending.at(-1)!,
|
|
299
|
+
tools,
|
|
300
|
+
extensions: options.extensions ?? {},
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
log('tool response', { response });
|
|
304
|
+
switch (response.type) {
|
|
305
|
+
case 'continue': {
|
|
306
|
+
this._pending = [...this._pending, response.message];
|
|
307
|
+
this.userMessage.emit(response.message);
|
|
308
|
+
more = true;
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
} while (more);
|
|
314
|
+
} catch (err) {
|
|
315
|
+
log.catch(err);
|
|
316
|
+
if (err instanceof Error && err.message.includes('Overloaded')) {
|
|
317
|
+
error = new AIServiecOverloadedError('AI service overloaded', { cause: err });
|
|
318
|
+
} else {
|
|
319
|
+
error = new Error('AI service error', { cause: err });
|
|
320
|
+
}
|
|
321
|
+
} finally {
|
|
322
|
+
this._stream = undefined;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (error) {
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
return this._pending;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
abort() {
|
|
333
|
+
this._stream?.abort();
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// TODO(burdon): Use handlebars template with effect-schema input.
|
|
338
|
+
const createBaseInstructions = ({
|
|
339
|
+
availableArtifacts,
|
|
340
|
+
operationModel,
|
|
341
|
+
}: {
|
|
342
|
+
availableArtifacts: string[];
|
|
343
|
+
operationModel: OperationModel;
|
|
344
|
+
}) => `
|
|
345
|
+
You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools.
|
|
346
|
+
Your task is to process user commands and questions and decide how best to respond.
|
|
347
|
+
In some cases, you will need to create or reference data objects called artifacts.
|
|
348
|
+
|
|
349
|
+
Follow these guidelines carefully:
|
|
350
|
+
|
|
351
|
+
Decision-making:
|
|
352
|
+
|
|
353
|
+
- Analyze the structure and type of the content in the user's message.
|
|
354
|
+
- Can you complete the task using the available artifacts?
|
|
355
|
+
- If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
|
|
356
|
+
- Identify which artifacts are relevant to the user's request.
|
|
357
|
+
${
|
|
358
|
+
operationModel === 'planning'
|
|
359
|
+
? `
|
|
360
|
+
- Break down the user's request into a step-by-step plan that you will use to execute the user's request, the plan items should include artifacts which will be used to perform the actions.
|
|
361
|
+
`
|
|
362
|
+
: `
|
|
363
|
+
- Are the required artifacts already available?
|
|
364
|
+
- If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
|
|
365
|
+
- The require'd artifact tools will be available for use after require.
|
|
366
|
+
`
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join('\n')}` : ''}
|
|
370
|
+
`;
|
|
371
|
+
|
|
372
|
+
export class AIServiecOverloadedError extends S.TaggedError<AIServiecOverloadedError>()(
|
|
373
|
+
'AIServiecOverloadedError',
|
|
374
|
+
{},
|
|
375
|
+
) {}
|
|
@@ -136,17 +136,17 @@ describe('Artifacts', () => {
|
|
|
136
136
|
]);
|
|
137
137
|
|
|
138
138
|
const stream = await client.generate({
|
|
139
|
-
model:
|
|
139
|
+
model: DEFAULT_EDGE_MODEL,
|
|
140
140
|
spaceId,
|
|
141
141
|
threadId,
|
|
142
142
|
systemPrompt: 'You are a helpful assistant.',
|
|
143
143
|
tools: [custodian],
|
|
144
144
|
});
|
|
145
145
|
for await (const event of stream) {
|
|
146
|
-
log
|
|
146
|
+
log('event', event);
|
|
147
147
|
}
|
|
148
148
|
const [message] = await stream.complete();
|
|
149
|
-
log
|
|
149
|
+
log('full message', {
|
|
150
150
|
message,
|
|
151
151
|
});
|
|
152
152
|
await client.appendMessages([message]);
|
|
@@ -164,17 +164,17 @@ describe('Artifacts', () => {
|
|
|
164
164
|
]);
|
|
165
165
|
|
|
166
166
|
const stream2 = await client.generate({
|
|
167
|
-
model:
|
|
167
|
+
model: DEFAULT_EDGE_MODEL,
|
|
168
168
|
spaceId,
|
|
169
169
|
threadId,
|
|
170
170
|
systemPrompt: 'You are a helpful assistant.',
|
|
171
171
|
tools: [custodian],
|
|
172
172
|
});
|
|
173
173
|
for await (const event of stream2) {
|
|
174
|
-
log
|
|
174
|
+
log('event', event);
|
|
175
175
|
}
|
|
176
176
|
const [message2] = await stream2.complete();
|
|
177
|
-
log
|
|
177
|
+
log('full message', {
|
|
178
178
|
message: message2,
|
|
179
179
|
});
|
|
180
180
|
});
|
package/src/testing/index.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
// test('extract objects from the DXOS explainer', async () => {
|
|
10
10
|
// const result = await runLLM({
|
|
11
|
-
// model:
|
|
11
|
+
// model: DEFAULT_EDGE_MODEL,
|
|
12
12
|
// messages: [
|
|
13
13
|
// createUserMessage(`
|
|
14
14
|
// # README
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
// backend,
|
|
64
64
|
// });
|
|
65
65
|
|
|
66
|
-
// log
|
|
66
|
+
// log('result', { result });
|
|
67
67
|
// });
|
|
68
68
|
|
|
69
69
|
// const backend = new AnthropicBackend({
|