@dxos/assistant 0.8.0 → 0.8.1-main.81238a8
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-RFTY3OMK.mjs +2276 -0
- package/dist/lib/browser/chunk-RFTY3OMK.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +33 -1236
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +17 -3
- package/dist/lib/browser/testing/index.mjs.map +4 -4
- package/dist/lib/node/chunk-4ZDZUCAS.cjs +2287 -0
- package/dist/lib/node/chunk-4ZDZUCAS.cjs.map +7 -0
- package/dist/lib/node/index.cjs +40 -1236
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +40 -29
- package/dist/lib/node/testing/index.cjs.map +4 -4
- package/dist/lib/node-esm/chunk-JUVGBQBL.mjs +2278 -0
- package/dist/lib/node-esm/chunk-JUVGBQBL.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +33 -1236
- 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 +17 -3
- 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 +19 -0
- package/dist/types/src/ai-service/edge-client.d.ts.map +1 -0
- package/dist/types/src/ai-service/index.d.ts +4 -1
- package/dist/types/src/ai-service/index.d.ts.map +1 -1
- package/dist/types/src/ai-service/message-collector.d.ts +88 -0
- package/dist/types/src/ai-service/message-collector.d.ts.map +1 -0
- package/dist/types/src/ai-service/ollama-client.d.ts +39 -0
- package/dist/types/src/ai-service/ollama-client.d.ts.map +1 -0
- package/dist/types/src/ai-service/parser.d.ts +11 -9
- package/dist/types/src/ai-service/parser.d.ts.map +1 -1
- package/dist/types/src/ai-service/service.d.ts +9 -0
- package/dist/types/src/ai-service/service.d.ts.map +1 -0
- package/dist/types/src/ai-service/stream.d.ts +2 -1
- package/dist/types/src/ai-service/stream.d.ts.map +1 -1
- package/dist/types/src/ai-service/testing/mock.d.ts +2 -2
- package/dist/types/src/ai-service/testing/mock.d.ts.map +1 -1
- package/dist/types/src/ai-service/types.d.ts +91 -157
- package/dist/types/src/ai-service/types.d.ts.map +1 -1
- package/dist/types/src/conversation/conversation.d.ts +11 -9
- package/dist/types/src/conversation/conversation.d.ts.map +1 -1
- package/dist/types/src/conversation/types.d.ts +1 -1
- package/dist/types/src/conversation/types.d.ts.map +1 -1
- 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/dist/types/src/testing/query-promts.d.ts +1 -1
- package/dist/types/src/testing/query-promts.d.ts.map +1 -1
- package/dist/types/src/testing/test-data.d.ts +1 -1
- package/dist/types/src/testing/test-data.d.ts.map +1 -1
- package/dist/types/src/testing/test-schema.d.ts +1 -1
- package/dist/types/src/testing/test-schema.d.ts.map +1 -1
- package/package.json +17 -14
- package/src/ai-service/client.test.ts +100 -13
- package/src/ai-service/defs.ts +17 -2
- package/src/ai-service/{client.ts → edge-client.ts} +15 -24
- package/src/ai-service/index.ts +4 -1
- package/src/ai-service/message-collector.ts +84 -0
- package/src/ai-service/ollama-client.ts +499 -0
- package/src/ai-service/parser.ts +7 -2
- package/src/ai-service/service.ts +15 -0
- package/src/ai-service/stream.ts +5 -3
- package/src/ai-service/testing/mock.ts +7 -2
- package/src/ai-service/types.ts +3 -3
- package/src/bin/chat.ts +3 -3
- package/src/conversation/conversation.test.ts +5 -5
- package/src/conversation/conversation.ts +3 -2
- package/src/conversation/types.ts +1 -1
- package/src/testing/artifacts.test.ts +4 -4
- package/src/testing/index.ts +1 -0
- package/src/testing/object-extraction.test.ts +1 -1
- package/src/testing/ollama.ts +15 -0
- package/src/testing/query-promts.ts +1 -1
- package/src/testing/query.test.ts +4 -4
- package/src/testing/test-data.ts +1 -1
- package/src/testing/test-schema.ts +1 -1
- 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
- package/dist/types/src/ai-service/client.d.ts +0 -25
- package/dist/types/src/ai-service/client.d.ts.map +0 -1
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2025 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { Schema as S } from 'effect';
|
|
6
|
+
|
|
7
|
+
import { type MessageContentBlock, defineTool, type Tool, ToolResult } from '@dxos/artifact';
|
|
8
|
+
import { ObjectId } from '@dxos/echo-schema';
|
|
9
|
+
import { invariant } from '@dxos/invariant';
|
|
10
|
+
import { log } from '@dxos/log';
|
|
11
|
+
|
|
12
|
+
import { DEFAULT_OLLAMA_ENDPOINT } from './defs';
|
|
13
|
+
import { MessageCollector, emitMessageAsEvents } from './message-collector';
|
|
14
|
+
import { type AIServiceClient, type GenerationStream } from './service';
|
|
15
|
+
import { GenerationStreamImpl } from './stream';
|
|
16
|
+
import { ToolTypes, type GenerateRequest, type GenerationStreamEvent } from './types';
|
|
17
|
+
import { isToolUse, runTools } from '../conversation';
|
|
18
|
+
|
|
19
|
+
export type OllamaClientParams = {
|
|
20
|
+
endpoint?: string;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Tools that are executed within the client.
|
|
24
|
+
*/
|
|
25
|
+
tools?: Tool[];
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Override generation parameters.
|
|
29
|
+
*/
|
|
30
|
+
// TODO(burdon): Why not just options?
|
|
31
|
+
overrides?: {
|
|
32
|
+
model?: string;
|
|
33
|
+
temperature?: number;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Maximum number of tool invocations in a single request that is allowed to run.
|
|
38
|
+
* @default 3
|
|
39
|
+
*/
|
|
40
|
+
maxToolInvocations?: number;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export class OllamaClient implements AIServiceClient {
|
|
44
|
+
/**
|
|
45
|
+
* Check if Ollama server is running and accessible.
|
|
46
|
+
* @returns Promise that resolves to true if Ollama is running, false otherwise.
|
|
47
|
+
*/
|
|
48
|
+
static async isRunning(): Promise<boolean> {
|
|
49
|
+
try {
|
|
50
|
+
const response = await fetch(`${DEFAULT_OLLAMA_ENDPOINT}/api/version`, {
|
|
51
|
+
method: 'GET',
|
|
52
|
+
headers: {
|
|
53
|
+
'Content-Type': 'application/json',
|
|
54
|
+
},
|
|
55
|
+
signal: AbortSignal.timeout(100),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
return response.ok;
|
|
59
|
+
} catch (error) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
private readonly _endpoint: string;
|
|
65
|
+
private readonly _tools: Tool[];
|
|
66
|
+
private readonly _modelOverride?: string;
|
|
67
|
+
private readonly _temperatureOverride?: number;
|
|
68
|
+
private readonly _maxToolInvocations: number;
|
|
69
|
+
|
|
70
|
+
constructor({ endpoint, tools, overrides, maxToolInvocations }: OllamaClientParams = {}) {
|
|
71
|
+
this._endpoint = endpoint ?? DEFAULT_OLLAMA_ENDPOINT;
|
|
72
|
+
this._tools = tools ?? [];
|
|
73
|
+
this._modelOverride = overrides?.model;
|
|
74
|
+
this._temperatureOverride = overrides?.temperature;
|
|
75
|
+
this._maxToolInvocations = maxToolInvocations ?? 3;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private _getEmbededTools(clientTools: Tool[]) {
|
|
79
|
+
return [
|
|
80
|
+
...this._tools,
|
|
81
|
+
...clientTools
|
|
82
|
+
.filter((tool) => tool.type !== undefined && WELL_KNOWN_TOOLS[tool.type])
|
|
83
|
+
.map((tool) => WELL_KNOWN_TOOLS[tool.type!]),
|
|
84
|
+
];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private async *_generateStream(request: GenerateRequest, signal?: AbortSignal): AsyncIterable<GenerationStreamEvent> {
|
|
88
|
+
invariant(request.prompt === undefined, 'Prompt must be in history');
|
|
89
|
+
|
|
90
|
+
// Map DXOS request to Ollama API format.
|
|
91
|
+
const ollamaRequest: OllamaRequest = {
|
|
92
|
+
model: this._modelOverride ?? request.model ?? 'llama3',
|
|
93
|
+
messages: [],
|
|
94
|
+
stream: true,
|
|
95
|
+
options: {
|
|
96
|
+
temperature: this._temperatureOverride,
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// Add system message if provided.
|
|
101
|
+
if (request.systemPrompt) {
|
|
102
|
+
ollamaRequest.messages.push({
|
|
103
|
+
role: 'system',
|
|
104
|
+
content: request.systemPrompt,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Add history if provided.
|
|
109
|
+
if (request.history?.length) {
|
|
110
|
+
for (const message of request.history) {
|
|
111
|
+
const role = message.role === 'assistant' ? 'assistant' : 'user';
|
|
112
|
+
|
|
113
|
+
// Process message content.
|
|
114
|
+
if (message.content.length === 0) {
|
|
115
|
+
// Skip empty messages
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
for (const content of message.content) {
|
|
120
|
+
switch (content.type) {
|
|
121
|
+
case 'text': {
|
|
122
|
+
ollamaRequest.messages.push({
|
|
123
|
+
role,
|
|
124
|
+
content: content.text,
|
|
125
|
+
});
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
case 'tool_use': {
|
|
129
|
+
ollamaRequest.messages.push({
|
|
130
|
+
role: 'assistant',
|
|
131
|
+
content: '',
|
|
132
|
+
tool_calls: [
|
|
133
|
+
{
|
|
134
|
+
function: {
|
|
135
|
+
name: content.name,
|
|
136
|
+
arguments: content.input as any,
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
],
|
|
140
|
+
});
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
case 'tool_result': {
|
|
144
|
+
ollamaRequest.messages.push({
|
|
145
|
+
role: 'tool',
|
|
146
|
+
content: JSON.stringify({
|
|
147
|
+
type: 'tool_result',
|
|
148
|
+
toolUseId: content.toolUseId,
|
|
149
|
+
content: content.content,
|
|
150
|
+
}),
|
|
151
|
+
});
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Add tools if provided.
|
|
160
|
+
if (request.tools?.length || this._tools.length) {
|
|
161
|
+
const allTools = [...(request.tools ?? []), ...this._tools];
|
|
162
|
+
const withWellKnownTools = allTools.map((tool) =>
|
|
163
|
+
tool.type !== undefined && WELL_KNOWN_TOOLS[tool.type] ? WELL_KNOWN_TOOLS[tool.type] : tool,
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
if (withWellKnownTools.length > 0) {
|
|
167
|
+
ollamaRequest.tools = withWellKnownTools.map((tool) => ({
|
|
168
|
+
type: 'function',
|
|
169
|
+
function: {
|
|
170
|
+
name: tool.name,
|
|
171
|
+
description: tool.description,
|
|
172
|
+
parameters: {
|
|
173
|
+
type: 'object',
|
|
174
|
+
properties: tool.parameters?.properties,
|
|
175
|
+
required: tool.parameters?.required,
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
}));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
log.info('generate request', { history: request.history, prompt: request.prompt, ollamaRequest });
|
|
183
|
+
|
|
184
|
+
const response = await fetch(`${this._endpoint}/api/chat`, {
|
|
185
|
+
method: 'POST',
|
|
186
|
+
headers: {
|
|
187
|
+
'Content-Type': 'application/json',
|
|
188
|
+
},
|
|
189
|
+
body: JSON.stringify(ollamaRequest),
|
|
190
|
+
signal,
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// TODO(burdon): Test if model is not found.
|
|
194
|
+
if (!response.ok) {
|
|
195
|
+
throw await parseErrorResponse(response);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (!response.body) {
|
|
199
|
+
throw new Error('Ollama API returned no response body');
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Create the stream
|
|
203
|
+
const reader = response
|
|
204
|
+
.body!.pipeThrough(new TextDecoderStream())
|
|
205
|
+
.pipeThrough(new OllamaDecoderStream())
|
|
206
|
+
.getReader();
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
// Create a message ID.
|
|
210
|
+
const messageId = ObjectId.random();
|
|
211
|
+
|
|
212
|
+
// Send message_start event with proper message structure.
|
|
213
|
+
yield {
|
|
214
|
+
type: 'message_start',
|
|
215
|
+
message: {
|
|
216
|
+
id: messageId,
|
|
217
|
+
role: 'assistant',
|
|
218
|
+
content: [],
|
|
219
|
+
},
|
|
220
|
+
} as GenerationStreamEvent;
|
|
221
|
+
|
|
222
|
+
// Initialize text content block.
|
|
223
|
+
const textBlock: MessageContentBlock = {
|
|
224
|
+
type: 'text',
|
|
225
|
+
text: '',
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
let currentBlockIndex = 0;
|
|
229
|
+
|
|
230
|
+
// Send content_block_start event.
|
|
231
|
+
yield {
|
|
232
|
+
type: 'content_block_start',
|
|
233
|
+
index: currentBlockIndex,
|
|
234
|
+
content: textBlock,
|
|
235
|
+
} as GenerationStreamEvent;
|
|
236
|
+
|
|
237
|
+
while (true) {
|
|
238
|
+
const { done, value: data } = await reader.read();
|
|
239
|
+
|
|
240
|
+
if (done) {
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
log.info('ollama data', { data });
|
|
245
|
+
|
|
246
|
+
// Ollama sends chunks of text, we convert them to our event format.
|
|
247
|
+
if (data.message?.content) {
|
|
248
|
+
yield {
|
|
249
|
+
type: 'content_block_delta',
|
|
250
|
+
index: 0,
|
|
251
|
+
delta: {
|
|
252
|
+
type: 'text_delta',
|
|
253
|
+
text: data.message.content,
|
|
254
|
+
},
|
|
255
|
+
} as GenerationStreamEvent;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// If tool usage is detected.
|
|
259
|
+
if (data.message?.tool_calls && data.message?.tool_calls?.length > 0) {
|
|
260
|
+
if (data.message.tool_calls.length > 1) {
|
|
261
|
+
log.warn('Ollama returned multiple tool calls. Only the first one will be used.');
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
yield {
|
|
265
|
+
type: 'content_block_stop',
|
|
266
|
+
index: currentBlockIndex++,
|
|
267
|
+
} as GenerationStreamEvent;
|
|
268
|
+
|
|
269
|
+
yield {
|
|
270
|
+
type: 'content_block_start',
|
|
271
|
+
index: currentBlockIndex,
|
|
272
|
+
content: {
|
|
273
|
+
type: 'tool_use',
|
|
274
|
+
id: ObjectId.random(),
|
|
275
|
+
name: data.message.tool_calls[0].function.name,
|
|
276
|
+
input: sanitizeToolArguments(data.message.tool_calls[0].function.arguments),
|
|
277
|
+
},
|
|
278
|
+
} as GenerationStreamEvent;
|
|
279
|
+
|
|
280
|
+
yield {
|
|
281
|
+
type: 'message_delta',
|
|
282
|
+
delta: {
|
|
283
|
+
stopReason: 'tool_use',
|
|
284
|
+
},
|
|
285
|
+
} as GenerationStreamEvent;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Send content_block_stop and message_stop events.
|
|
290
|
+
yield {
|
|
291
|
+
type: 'content_block_stop',
|
|
292
|
+
index: currentBlockIndex,
|
|
293
|
+
} as GenerationStreamEvent;
|
|
294
|
+
|
|
295
|
+
yield {
|
|
296
|
+
type: 'message_stop',
|
|
297
|
+
} as GenerationStreamEvent;
|
|
298
|
+
} finally {
|
|
299
|
+
reader.releaseLock();
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async exec(request: GenerateRequest): Promise<GenerationStream> {
|
|
304
|
+
const controller = new AbortController();
|
|
305
|
+
|
|
306
|
+
try {
|
|
307
|
+
return new GenerationStreamImpl(
|
|
308
|
+
controller,
|
|
309
|
+
async function* (this: OllamaClient) {
|
|
310
|
+
const collector = new MessageCollector();
|
|
311
|
+
|
|
312
|
+
// Loop while running tools.
|
|
313
|
+
let toolInvocations = 0;
|
|
314
|
+
while (true) {
|
|
315
|
+
for await (const event of this._generateStream(
|
|
316
|
+
{
|
|
317
|
+
...request,
|
|
318
|
+
history: [
|
|
319
|
+
...(request.history ?? []),
|
|
320
|
+
...(request.prompt ? [request.prompt] : []),
|
|
321
|
+
...collector.messages,
|
|
322
|
+
],
|
|
323
|
+
prompt: undefined,
|
|
324
|
+
},
|
|
325
|
+
controller.signal,
|
|
326
|
+
)) {
|
|
327
|
+
collector.push(event);
|
|
328
|
+
yield event;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
if (
|
|
332
|
+
collector.messages.length > 0 &&
|
|
333
|
+
!isToolUse(collector.messages.at(-1)!, {
|
|
334
|
+
onlyToolNames: this._getEmbededTools(request.tools ?? []).map((tool) => tool.name),
|
|
335
|
+
})
|
|
336
|
+
) {
|
|
337
|
+
break;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (++toolInvocations > this._maxToolInvocations) {
|
|
341
|
+
throw new Error('Maximum number of tool invocations reached');
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const result = await runTools({
|
|
345
|
+
message: collector.messages.at(-1)!,
|
|
346
|
+
tools: this._getEmbededTools(request.tools ?? []),
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
switch (result.type) {
|
|
350
|
+
case 'continue': {
|
|
351
|
+
collector.pushMessage(result.message);
|
|
352
|
+
yield* emitMessageAsEvents(result.message);
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
case 'break': {
|
|
356
|
+
throw new Error('Tool use breaks not allowed');
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}.bind(this),
|
|
361
|
+
);
|
|
362
|
+
} catch (error) {
|
|
363
|
+
controller.abort();
|
|
364
|
+
throw error;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const sanitizeToolArguments = (args: any) => {
|
|
370
|
+
// TODO(dmaretskyi): Workaround for model bug.
|
|
371
|
+
if (args.type === 'object' && typeof args.properties === 'object' && Array.isArray(args.required)) {
|
|
372
|
+
return args.properties;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
return args;
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
const SAMPLE_IMAGE_URL = 'https://images.nightcafe.studio/jobs/BNmcRhHCM1JRKoUtqSei/BNmcRhHCM1JRKoUtqSei--1--5b9rv.jpg';
|
|
379
|
+
|
|
380
|
+
const WELL_KNOWN_TOOLS: Record<string, Tool> = {
|
|
381
|
+
[ToolTypes.TextToImage]: defineTool('system', {
|
|
382
|
+
name: 'text-to-image',
|
|
383
|
+
description: 'Generate an image from a text prompt',
|
|
384
|
+
schema: S.Struct({
|
|
385
|
+
prompt: S.String.annotations({ description: 'The text prompt describing the image to generate' }),
|
|
386
|
+
}),
|
|
387
|
+
execute: async ({ prompt }) => {
|
|
388
|
+
const image = await fetch(SAMPLE_IMAGE_URL).then(async (res) => Buffer.from(await res.arrayBuffer()));
|
|
389
|
+
|
|
390
|
+
const imageBase64 = image.toString('base64');
|
|
391
|
+
const id = ObjectId.random();
|
|
392
|
+
|
|
393
|
+
return ToolResult.Success(`The generation was successful. Image ID: ${id} Prompt: ${prompt}`, [
|
|
394
|
+
{
|
|
395
|
+
type: 'image',
|
|
396
|
+
id,
|
|
397
|
+
source: {
|
|
398
|
+
type: 'base64',
|
|
399
|
+
mediaType: 'image/jpeg',
|
|
400
|
+
data: imageBase64,
|
|
401
|
+
},
|
|
402
|
+
},
|
|
403
|
+
]);
|
|
404
|
+
},
|
|
405
|
+
}),
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
type OllamaMessage = {
|
|
409
|
+
role: 'system' | 'user' | 'assistant' | 'tool';
|
|
410
|
+
content: string;
|
|
411
|
+
tool_calls?: Array<{
|
|
412
|
+
function: {
|
|
413
|
+
name: string;
|
|
414
|
+
arguments: string;
|
|
415
|
+
};
|
|
416
|
+
}>;
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
type OllamaRequest = {
|
|
420
|
+
model: string;
|
|
421
|
+
messages: Array<OllamaMessage>;
|
|
422
|
+
stream: boolean;
|
|
423
|
+
options?: {
|
|
424
|
+
temperature?: number;
|
|
425
|
+
};
|
|
426
|
+
tools?: Array<{
|
|
427
|
+
type: 'function';
|
|
428
|
+
function: {
|
|
429
|
+
name: string;
|
|
430
|
+
description?: string;
|
|
431
|
+
parameters?: any;
|
|
432
|
+
};
|
|
433
|
+
}>;
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
type OllamaResponseData = {
|
|
437
|
+
message?: OllamaMessage;
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
class OllamaDecoderStream extends TransformStream<string, OllamaResponseData> {
|
|
441
|
+
private _buffer = '';
|
|
442
|
+
|
|
443
|
+
constructor() {
|
|
444
|
+
super({
|
|
445
|
+
transform: (chunk, controller) => {
|
|
446
|
+
this._buffer += chunk;
|
|
447
|
+
const lines = this._buffer.split('\n');
|
|
448
|
+
this._buffer = lines.pop() || '';
|
|
449
|
+
for (const line of lines) {
|
|
450
|
+
controller.enqueue(JSON.parse(line.trim()));
|
|
451
|
+
}
|
|
452
|
+
},
|
|
453
|
+
flush: (controller) => {
|
|
454
|
+
this._buffer = this._buffer.trim();
|
|
455
|
+
if (this._buffer.length > 0) {
|
|
456
|
+
controller.enqueue(JSON.parse(this._buffer));
|
|
457
|
+
}
|
|
458
|
+
},
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
class ModelDoesNotSupportToolsError extends S.TaggedError<ModelDoesNotSupportToolsError>()(
|
|
464
|
+
'ModelDoesNotSupportToolsError',
|
|
465
|
+
{
|
|
466
|
+
model: S.String,
|
|
467
|
+
},
|
|
468
|
+
) {}
|
|
469
|
+
|
|
470
|
+
class ModelNotFoundError extends S.TaggedError<ModelNotFoundError>()('ModelNotFoundError', {
|
|
471
|
+
model: S.String,
|
|
472
|
+
}) {}
|
|
473
|
+
|
|
474
|
+
const parseOllamaError = (error: string): Error => {
|
|
475
|
+
{
|
|
476
|
+
const match = error.match(/^([^']+) does not support tools$/);
|
|
477
|
+
if (match) {
|
|
478
|
+
return new ModelDoesNotSupportToolsError({ model: match[1] });
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
{
|
|
483
|
+
const match = error.match(/^model "([^"]+)" not found, try pulling it first$/);
|
|
484
|
+
if (match) {
|
|
485
|
+
return new ModelNotFoundError({ model: match[1] });
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
throw new Error(`Ollama API error: ${error}`);
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
const parseErrorResponse = async (response: Response): Promise<Error> => {
|
|
493
|
+
if (response.headers.get('content-type')?.includes('application/json')) {
|
|
494
|
+
const body = await response.json();
|
|
495
|
+
return parseOllamaError(body.error);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
throw new Error(`Ollama API error: ${response.status} ${response.statusText} ${await response.text()}`);
|
|
499
|
+
};
|
package/src/ai-service/parser.ts
CHANGED
|
@@ -9,8 +9,9 @@ import { invariant } from '@dxos/invariant';
|
|
|
9
9
|
import { log } from '@dxos/log';
|
|
10
10
|
import { isNotFalsy, safeParseJson } from '@dxos/util';
|
|
11
11
|
|
|
12
|
-
import { type GenerationStream } from './
|
|
12
|
+
import { type GenerationStream } from './service';
|
|
13
13
|
import { StreamTransform, type StreamBlock } from './transform';
|
|
14
|
+
import type { GenerationStreamEvent } from './types';
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* Parse mixed content of plain text, XML fragments, and JSON blocks.
|
|
@@ -31,6 +32,8 @@ export class MixedStreamParser {
|
|
|
31
32
|
*/
|
|
32
33
|
public update = new Event<MessageContentBlock>();
|
|
33
34
|
|
|
35
|
+
public streamEvent = new Event<GenerationStreamEvent>();
|
|
36
|
+
|
|
34
37
|
/**
|
|
35
38
|
* Current message.
|
|
36
39
|
*/
|
|
@@ -77,6 +80,8 @@ export class MixedStreamParser {
|
|
|
77
80
|
const messagesCollected: Message[] = [];
|
|
78
81
|
|
|
79
82
|
for await (const event of stream) {
|
|
83
|
+
this.streamEvent.emit(event);
|
|
84
|
+
|
|
80
85
|
// log.info('event', { type: event.type, event });
|
|
81
86
|
switch (event.type) {
|
|
82
87
|
//
|
|
@@ -88,7 +93,7 @@ export class MixedStreamParser {
|
|
|
88
93
|
log.warn('unexpected message_start');
|
|
89
94
|
}
|
|
90
95
|
|
|
91
|
-
this._message = createStatic(Message, { role:
|
|
96
|
+
this._message = createStatic(Message, { role: event.message.role, content: [...event.message.content] });
|
|
92
97
|
this.message.emit(this._message);
|
|
93
98
|
break;
|
|
94
99
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2025 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { type GenerateRequest, type GenerationStreamEvent } from './types';
|
|
6
|
+
|
|
7
|
+
// TODO(burdon): Create wrapper for edge/ollama. Create session?
|
|
8
|
+
export interface AIServiceClient {
|
|
9
|
+
exec(request: GenerateRequest): Promise<GenerationStream>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface GenerationStream extends AsyncIterable<GenerationStreamEvent> {
|
|
13
|
+
abort(): void;
|
|
14
|
+
complete(): Promise<void>;
|
|
15
|
+
}
|
package/src/ai-service/stream.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { Trigger } from '@dxos/async';
|
|
6
6
|
import { log } from '@dxos/log';
|
|
7
7
|
|
|
8
|
+
import type { GenerationStream } from './service';
|
|
8
9
|
import { type GenerationStreamEvent } from './types';
|
|
9
10
|
import { iterSSEMessages } from './util';
|
|
10
11
|
|
|
@@ -49,14 +50,14 @@ export const createGenerationStream = (response: Response, controller = new Abor
|
|
|
49
50
|
}
|
|
50
51
|
};
|
|
51
52
|
|
|
52
|
-
return new
|
|
53
|
+
return new GenerationStreamImpl(controller, iterator);
|
|
53
54
|
};
|
|
54
55
|
|
|
55
56
|
/**
|
|
56
57
|
* Server-Sent Events (SSE) stream from the AI service.
|
|
57
58
|
* https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
|
|
58
59
|
*/
|
|
59
|
-
export class
|
|
60
|
+
export class GenerationStreamImpl implements GenerationStream {
|
|
60
61
|
/**
|
|
61
62
|
* Trigger event when the stream is done.
|
|
62
63
|
*/
|
|
@@ -99,7 +100,7 @@ export class GenerationStream implements AsyncIterable<GenerationStreamEvent> {
|
|
|
99
100
|
private _createIterator(): AsyncIterator<GenerationStreamEvent> {
|
|
100
101
|
const self = this;
|
|
101
102
|
return (this._iterator ??= (() => {
|
|
102
|
-
const generator = async function* (this:
|
|
103
|
+
const generator = async function* (this: GenerationStreamImpl) {
|
|
103
104
|
try {
|
|
104
105
|
for await (const event of self._getIterator()) {
|
|
105
106
|
yield event;
|
|
@@ -107,6 +108,7 @@ export class GenerationStream implements AsyncIterable<GenerationStreamEvent> {
|
|
|
107
108
|
this._done.wake();
|
|
108
109
|
} catch (err: any) {
|
|
109
110
|
this._done.throw(err);
|
|
111
|
+
throw err;
|
|
110
112
|
}
|
|
111
113
|
};
|
|
112
114
|
|
|
@@ -2,11 +2,16 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
type GenerationStream,
|
|
7
|
+
type AIServiceClient,
|
|
8
|
+
type GenerateRequest,
|
|
9
|
+
createGenerationStream,
|
|
10
|
+
} from '@dxos/assistant';
|
|
6
11
|
|
|
7
12
|
import { createTestSSEStream } from './test-stream';
|
|
8
13
|
|
|
9
|
-
export class MockAIService implements
|
|
14
|
+
export class MockAIService implements AIServiceClient {
|
|
10
15
|
constructor(private readonly _responses: string[]) {}
|
|
11
16
|
|
|
12
17
|
// TODO(burdon): Match response to request.
|
package/src/ai-service/types.ts
CHANGED
|
@@ -2,16 +2,16 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import { Schema as S } from '
|
|
5
|
+
import { Schema as S } from 'effect';
|
|
6
6
|
|
|
7
7
|
import { Tool, Message, type MessageContentBlock, SpaceIdSchema } from '@dxos/artifact';
|
|
8
8
|
import { ObjectId } from '@dxos/echo-schema';
|
|
9
9
|
|
|
10
|
-
import {
|
|
10
|
+
import { DEFAULT_EDGE_MODELS } from './defs';
|
|
11
11
|
|
|
12
12
|
export const createArtifactElement = (id: ObjectId) => `<artifact id=${id} />`;
|
|
13
13
|
|
|
14
|
-
export const LLMModel = S.Literal(...
|
|
14
|
+
export const LLMModel = S.Literal(...DEFAULT_EDGE_MODELS);
|
|
15
15
|
|
|
16
16
|
export type LLMModel = S.Schema.Type<typeof LLMModel>;
|
|
17
17
|
|
package/src/bin/chat.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { ObjectId } from '@dxos/echo-schema';
|
|
|
10
10
|
import { SpaceId } from '@dxos/keys';
|
|
11
11
|
import { log } from '@dxos/log';
|
|
12
12
|
|
|
13
|
-
import {
|
|
13
|
+
import { AIServiceEdgeClient, ToolTypes, DEFAULT_EDGE_MODEL } from '../ai-service';
|
|
14
14
|
import { runLLM } from '../conversation';
|
|
15
15
|
import {
|
|
16
16
|
AI_SERVICE_ENDPOINT,
|
|
@@ -25,7 +25,7 @@ import {
|
|
|
25
25
|
} from '../testing';
|
|
26
26
|
|
|
27
27
|
// TOOD(burdon): Get from config.
|
|
28
|
-
const client = new
|
|
28
|
+
const client = new AIServiceEdgeClient({
|
|
29
29
|
endpoint: AI_SERVICE_ENDPOINT.LOCAL,
|
|
30
30
|
});
|
|
31
31
|
|
|
@@ -49,7 +49,7 @@ while (true) {
|
|
|
49
49
|
await client.appendMessages([createUserMessage(spaceId, threadId, prompt.message)]);
|
|
50
50
|
|
|
51
51
|
await runLLM({
|
|
52
|
-
model:
|
|
52
|
+
model: DEFAULT_EDGE_MODEL,
|
|
53
53
|
spaceId,
|
|
54
54
|
threadId,
|
|
55
55
|
system: createSystemPrompt(schemaTypes),
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Copyright 2024 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import { Schema as S } from '
|
|
5
|
+
import { Schema as S } from 'effect';
|
|
6
6
|
import { describe, test } from 'vitest';
|
|
7
7
|
|
|
8
8
|
import { createUserMessage, defineTool, ToolResult } from '@dxos/artifact';
|
|
@@ -11,12 +11,12 @@ import { SpaceId } from '@dxos/keys';
|
|
|
11
11
|
import { log } from '@dxos/log';
|
|
12
12
|
|
|
13
13
|
import { runLLM, type ConversationEvent } from './conversation';
|
|
14
|
-
import {
|
|
14
|
+
import { AIServiceEdgeClient, DEFAULT_EDGE_MODEL } from '../ai-service';
|
|
15
15
|
import { AI_SERVICE_ENDPOINT } from '../testing';
|
|
16
16
|
|
|
17
17
|
// TODO(burdon): Local live LLM test.
|
|
18
18
|
describe.skip('Conversation tests', () => {
|
|
19
|
-
const client = new
|
|
19
|
+
const client = new AIServiceEdgeClient({
|
|
20
20
|
endpoint: AI_SERVICE_ENDPOINT.LOCAL,
|
|
21
21
|
});
|
|
22
22
|
|
|
@@ -25,7 +25,7 @@ describe.skip('Conversation tests', () => {
|
|
|
25
25
|
const threadId = ObjectId.random();
|
|
26
26
|
|
|
27
27
|
const result = await runLLM({
|
|
28
|
-
model:
|
|
28
|
+
model: DEFAULT_EDGE_MODEL,
|
|
29
29
|
history: [createUserMessage(spaceId, threadId, 'Hello, how are you?')],
|
|
30
30
|
tools: [],
|
|
31
31
|
client,
|
|
@@ -56,7 +56,7 @@ describe.skip('Conversation tests', () => {
|
|
|
56
56
|
const threadId = ObjectId.random();
|
|
57
57
|
|
|
58
58
|
const result = await runLLM({
|
|
59
|
-
model:
|
|
59
|
+
model: DEFAULT_EDGE_MODEL,
|
|
60
60
|
history: [createUserMessage(spaceId, threadId, 'What is the password? Ask the custodian.')],
|
|
61
61
|
tools: [custodian],
|
|
62
62
|
client,
|