@dxos/assistant 0.8.0 → 0.8.1-main.013e445

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