@dxos/assistant 0.7.4-df37807
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/LICENSE +8 -0
- package/README.md +24 -0
- package/dist/lib/browser/chunk-AKP45LQH.mjs +1394 -0
- package/dist/lib/browser/chunk-AKP45LQH.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +71 -0
- package/dist/lib/browser/index.mjs.map +7 -0
- package/dist/lib/browser/meta.json +1 -0
- package/dist/lib/browser/testing/index.mjs +601 -0
- package/dist/lib/browser/testing/index.mjs.map +7 -0
- package/dist/lib/node/chunk-G6CGWEMO.cjs +1418 -0
- package/dist/lib/node/chunk-G6CGWEMO.cjs.map +7 -0
- package/dist/lib/node/index.cjs +93 -0
- package/dist/lib/node/index.cjs.map +7 -0
- package/dist/lib/node/meta.json +1 -0
- package/dist/lib/node/testing/index.cjs +619 -0
- package/dist/lib/node/testing/index.cjs.map +7 -0
- package/dist/lib/node-esm/chunk-WUPUPEFB.mjs +1396 -0
- package/dist/lib/node-esm/chunk-WUPUPEFB.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +72 -0
- package/dist/lib/node-esm/index.mjs.map +7 -0
- package/dist/lib/node-esm/meta.json +1 -0
- package/dist/lib/node-esm/testing/index.mjs +602 -0
- package/dist/lib/node-esm/testing/index.mjs.map +7 -0
- package/dist/types/src/ai-service/client.d.ts +48 -0
- package/dist/types/src/ai-service/client.d.ts.map +1 -0
- package/dist/types/src/ai-service/client.test.d.ts +2 -0
- package/dist/types/src/ai-service/client.test.d.ts.map +1 -0
- package/dist/types/src/ai-service/index.d.ts +3 -0
- package/dist/types/src/ai-service/index.d.ts.map +1 -0
- package/dist/types/src/ai-service/schema.d.ts +296 -0
- package/dist/types/src/ai-service/schema.d.ts.map +1 -0
- package/dist/types/src/ai-service/sse.d.ts +34 -0
- package/dist/types/src/ai-service/sse.d.ts.map +1 -0
- package/dist/types/src/bin/chat.d.ts +2 -0
- package/dist/types/src/bin/chat.d.ts.map +1 -0
- package/dist/types/src/conversation/conversation.d.ts +23 -0
- package/dist/types/src/conversation/conversation.d.ts.map +1 -0
- package/dist/types/src/conversation/conversation.test.d.ts +2 -0
- package/dist/types/src/conversation/conversation.test.d.ts.map +1 -0
- package/dist/types/src/conversation/index.d.ts +3 -0
- package/dist/types/src/conversation/index.d.ts.map +1 -0
- package/dist/types/src/conversation/types.d.ts +48 -0
- package/dist/types/src/conversation/types.d.ts.map +1 -0
- package/dist/types/src/cypher/ast.d.ts +56 -0
- package/dist/types/src/cypher/ast.d.ts.map +1 -0
- package/dist/types/src/cypher/combinators.d.ts +14 -0
- package/dist/types/src/cypher/combinators.d.ts.map +1 -0
- package/dist/types/src/cypher/combinators.test.d.ts +2 -0
- package/dist/types/src/cypher/combinators.test.d.ts.map +1 -0
- package/dist/types/src/cypher/echo-data-source.d.ts +16 -0
- package/dist/types/src/cypher/echo-data-source.d.ts.map +1 -0
- package/dist/types/src/cypher/execution-plan.d.ts +49 -0
- package/dist/types/src/cypher/execution-plan.d.ts.map +1 -0
- package/dist/types/src/cypher/execution-plan.test.d.ts +2 -0
- package/dist/types/src/cypher/execution-plan.test.d.ts.map +1 -0
- package/dist/types/src/cypher/index.d.ts +5 -0
- package/dist/types/src/cypher/index.d.ts.map +1 -0
- package/dist/types/src/cypher/parjs.d.ts +4 -0
- package/dist/types/src/cypher/parjs.d.ts.map +1 -0
- package/dist/types/src/cypher/parser.d.ts +6 -0
- package/dist/types/src/cypher/parser.d.ts.map +1 -0
- package/dist/types/src/cypher/query-executor.d.ts +26 -0
- package/dist/types/src/cypher/query-executor.d.ts.map +1 -0
- package/dist/types/src/cypher/query-executor.test.d.ts +2 -0
- package/dist/types/src/cypher/query-executor.test.d.ts.map +1 -0
- package/dist/types/src/cypher/schema.d.ts +12 -0
- package/dist/types/src/cypher/schema.d.ts.map +1 -0
- package/dist/types/src/cypher/schema.test.d.ts +2 -0
- package/dist/types/src/cypher/schema.test.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +4 -0
- package/dist/types/src/index.d.ts.map +1 -0
- package/dist/types/src/sanity.test.d.ts +2 -0
- package/dist/types/src/sanity.test.d.ts.map +1 -0
- package/dist/types/src/testing/index.d.ts +5 -0
- package/dist/types/src/testing/index.d.ts.map +1 -0
- package/dist/types/src/testing/logger.d.ts +12 -0
- package/dist/types/src/testing/logger.d.ts.map +1 -0
- package/dist/types/src/testing/object-extraction.test.d.ts +1 -0
- package/dist/types/src/testing/object-extraction.test.d.ts.map +1 -0
- package/dist/types/src/testing/query-promts.d.ts +5 -0
- package/dist/types/src/testing/query-promts.d.ts.map +1 -0
- package/dist/types/src/testing/query.test.d.ts +2 -0
- package/dist/types/src/testing/query.test.d.ts.map +1 -0
- package/dist/types/src/testing/test-data.d.ts +29 -0
- package/dist/types/src/testing/test-data.d.ts.map +1 -0
- package/dist/types/src/testing/test-schema.d.ts +50 -0
- package/dist/types/src/testing/test-schema.d.ts.map +1 -0
- package/dist/types/src/util/index.d.ts +2 -0
- package/dist/types/src/util/index.d.ts.map +1 -0
- package/dist/types/src/util/trim.d.ts +5 -0
- package/dist/types/src/util/trim.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -0
- package/package.json +64 -0
- package/src/ai-service/client.test.ts +162 -0
- package/src/ai-service/client.ts +243 -0
- package/src/ai-service/index.ts +6 -0
- package/src/ai-service/schema.ts +260 -0
- package/src/ai-service/sse.ts +336 -0
- package/src/bin/chat.ts +79 -0
- package/src/conversation/conversation.test.ts +74 -0
- package/src/conversation/conversation.ts +134 -0
- package/src/conversation/index.ts +6 -0
- package/src/conversation/types.ts +90 -0
- package/src/cypher/ast.ts +75 -0
- package/src/cypher/combinators.test.ts +137 -0
- package/src/cypher/combinators.ts +149 -0
- package/src/cypher/echo-data-source.ts +105 -0
- package/src/cypher/execution-plan.test.ts +42 -0
- package/src/cypher/execution-plan.ts +208 -0
- package/src/cypher/index.ts +8 -0
- package/src/cypher/parjs-shims.d.ts +6 -0
- package/src/cypher/parjs.ts +10 -0
- package/src/cypher/parser.ts +19 -0
- package/src/cypher/query-executor.test.ts +47 -0
- package/src/cypher/query-executor.ts +145 -0
- package/src/cypher/schema.test.ts +17 -0
- package/src/cypher/schema.ts +82 -0
- package/src/index.ts +7 -0
- package/src/sanity.test.ts +9 -0
- package/src/testing/index.ts +8 -0
- package/src/testing/logger.ts +128 -0
- package/src/testing/object-extraction.test.ts +71 -0
- package/src/testing/query-promts.ts +75 -0
- package/src/testing/query.test.ts +90 -0
- package/src/testing/test-data.ts +366 -0
- package/src/testing/test-schema.ts +80 -0
- package/src/util/index.ts +5 -0
- package/src/util/trim.ts +15 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
// Copied from anthropic SDK source
|
|
4
|
+
//
|
|
5
|
+
|
|
6
|
+
export async function* iterSSEMessages(
|
|
7
|
+
response: Response,
|
|
8
|
+
controller: AbortController,
|
|
9
|
+
): AsyncGenerator<ServerSentEvent, void, unknown> {
|
|
10
|
+
if (!response.body) {
|
|
11
|
+
controller.abort();
|
|
12
|
+
throw new Error('Attempted to iterate over a response with no body');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const sseDecoder = new SSEDecoder();
|
|
16
|
+
const lineDecoder = new LineDecoder();
|
|
17
|
+
|
|
18
|
+
const iter = readableStreamAsyncIterable<Bytes>(response.body);
|
|
19
|
+
for await (const sseChunk of iterSSEChunks(iter)) {
|
|
20
|
+
for (const line of lineDecoder.decode(sseChunk)) {
|
|
21
|
+
const sse = sseDecoder.decode(line);
|
|
22
|
+
if (sse) {
|
|
23
|
+
yield sse;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
for (const line of lineDecoder.flush()) {
|
|
29
|
+
const sse = sseDecoder.decode(line);
|
|
30
|
+
if (sse) {
|
|
31
|
+
yield sse;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type ServerSentEvent = {
|
|
37
|
+
event: string | null;
|
|
38
|
+
data: string;
|
|
39
|
+
raw: string[];
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Given an async iterable iterator, iterates over it and yields full
|
|
44
|
+
* SSE chunks, i.e. yields when a double new-line is encountered.
|
|
45
|
+
*/
|
|
46
|
+
async function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> {
|
|
47
|
+
let data = new Uint8Array();
|
|
48
|
+
|
|
49
|
+
for await (const chunk of iterator) {
|
|
50
|
+
if (chunk == null) {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const binaryChunk =
|
|
55
|
+
chunk instanceof ArrayBuffer
|
|
56
|
+
? new Uint8Array(chunk)
|
|
57
|
+
: typeof chunk === 'string'
|
|
58
|
+
? new TextEncoder().encode(chunk)
|
|
59
|
+
: chunk;
|
|
60
|
+
|
|
61
|
+
const newData = new Uint8Array(data.length + binaryChunk.length);
|
|
62
|
+
newData.set(data);
|
|
63
|
+
newData.set(binaryChunk, data.length);
|
|
64
|
+
data = newData;
|
|
65
|
+
|
|
66
|
+
let patternIndex;
|
|
67
|
+
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
|
|
68
|
+
yield data.slice(0, patternIndex);
|
|
69
|
+
data = data.slice(patternIndex);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (data.length > 0) {
|
|
74
|
+
yield data;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const findDoubleNewlineIndex = (buffer: Uint8Array): number => {
|
|
79
|
+
// This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
|
|
80
|
+
// and returns the index right after the first occurrence of any pattern,
|
|
81
|
+
// or -1 if none of the patterns are found.
|
|
82
|
+
const newline = 0x0a; // \n
|
|
83
|
+
const carriage = 0x0d; // \r
|
|
84
|
+
|
|
85
|
+
for (let i = 0; i < buffer.length - 2; i++) {
|
|
86
|
+
if (buffer[i] === newline && buffer[i + 1] === newline) {
|
|
87
|
+
// \n\n
|
|
88
|
+
return i + 2;
|
|
89
|
+
}
|
|
90
|
+
if (buffer[i] === carriage && buffer[i + 1] === carriage) {
|
|
91
|
+
// \r\r
|
|
92
|
+
return i + 2;
|
|
93
|
+
}
|
|
94
|
+
if (
|
|
95
|
+
buffer[i] === carriage &&
|
|
96
|
+
buffer[i + 1] === newline &&
|
|
97
|
+
i + 3 < buffer.length &&
|
|
98
|
+
buffer[i + 2] === carriage &&
|
|
99
|
+
buffer[i + 3] === newline
|
|
100
|
+
) {
|
|
101
|
+
// \r\n\r\n
|
|
102
|
+
return i + 4;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return -1;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
class SSEDecoder {
|
|
110
|
+
private data: string[];
|
|
111
|
+
private event: string | null;
|
|
112
|
+
private chunks: string[];
|
|
113
|
+
|
|
114
|
+
constructor() {
|
|
115
|
+
this.event = null;
|
|
116
|
+
this.data = [];
|
|
117
|
+
this.chunks = [];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
decode(line: string) {
|
|
121
|
+
if (line.endsWith('\r')) {
|
|
122
|
+
line = line.substring(0, line.length - 1);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (!line) {
|
|
126
|
+
// empty line and we didn't previously encounter any messages
|
|
127
|
+
if (!this.event && !this.data.length) {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const sse: ServerSentEvent = {
|
|
132
|
+
event: this.event,
|
|
133
|
+
data: this.data.join('\n'),
|
|
134
|
+
raw: this.chunks,
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
this.event = null;
|
|
138
|
+
this.data = [];
|
|
139
|
+
this.chunks = [];
|
|
140
|
+
|
|
141
|
+
return sse;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
this.chunks.push(line);
|
|
145
|
+
|
|
146
|
+
if (line.startsWith(':')) {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let [fieldname, _, value] = partition(line, ':');
|
|
151
|
+
|
|
152
|
+
if (value.startsWith(' ')) {
|
|
153
|
+
value = value.substring(1);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (fieldname === 'event') {
|
|
157
|
+
this.event = value;
|
|
158
|
+
} else if (fieldname === 'data') {
|
|
159
|
+
this.data.push(value);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** This is an internal helper function that's just used for testing */
|
|
167
|
+
export const _decodeChunks = (chunks: string[]): string[] => {
|
|
168
|
+
const decoder = new LineDecoder();
|
|
169
|
+
const lines: string[] = [];
|
|
170
|
+
for (const chunk of chunks) {
|
|
171
|
+
lines.push(...decoder.decode(chunk));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return lines;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const partition = (str: string, delimiter: string): [string, string, string] => {
|
|
178
|
+
const index = str.indexOf(delimiter);
|
|
179
|
+
if (index !== -1) {
|
|
180
|
+
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return [str, '', ''];
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Most browsers don't yet have async iterable support for ReadableStream,
|
|
188
|
+
* and Node has a very different way of reading bytes from its "ReadableStream".
|
|
189
|
+
*
|
|
190
|
+
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
|
|
191
|
+
*/
|
|
192
|
+
export function readableStreamAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {
|
|
193
|
+
if (stream[Symbol.asyncIterator]) {
|
|
194
|
+
return stream;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const reader = stream.getReader();
|
|
198
|
+
return {
|
|
199
|
+
next: async () => {
|
|
200
|
+
try {
|
|
201
|
+
const result = await reader.read();
|
|
202
|
+
if (result?.done) {
|
|
203
|
+
reader.releaseLock();
|
|
204
|
+
} // release lock when stream becomes closed
|
|
205
|
+
return result;
|
|
206
|
+
} catch (e) {
|
|
207
|
+
reader.releaseLock(); // release lock when stream becomes errored
|
|
208
|
+
throw e;
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
return: async () => {
|
|
212
|
+
const cancelPromise = reader.cancel();
|
|
213
|
+
reader.releaseLock();
|
|
214
|
+
await cancelPromise;
|
|
215
|
+
return { done: true, value: undefined };
|
|
216
|
+
},
|
|
217
|
+
[Symbol.asyncIterator]() {
|
|
218
|
+
return this;
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined;
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
|
|
227
|
+
* reading lines from text.
|
|
228
|
+
*
|
|
229
|
+
* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
|
|
230
|
+
*/
|
|
231
|
+
export class LineDecoder {
|
|
232
|
+
// prettier-ignore
|
|
233
|
+
static NEWLINE_CHARS = new Set(['\n', '\r']);
|
|
234
|
+
static NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
235
|
+
|
|
236
|
+
buffer: string[];
|
|
237
|
+
trailingCR: boolean;
|
|
238
|
+
textDecoder: any; // TextDecoder found in browsers; not typed to avoid pulling in either "dom" or "node" types.
|
|
239
|
+
|
|
240
|
+
constructor() {
|
|
241
|
+
this.buffer = [];
|
|
242
|
+
this.trailingCR = false;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
decode(chunk: Bytes): string[] {
|
|
246
|
+
let text = this.decodeText(chunk);
|
|
247
|
+
|
|
248
|
+
if (this.trailingCR) {
|
|
249
|
+
text = '\r' + text;
|
|
250
|
+
this.trailingCR = false;
|
|
251
|
+
}
|
|
252
|
+
if (text.endsWith('\r')) {
|
|
253
|
+
this.trailingCR = true;
|
|
254
|
+
text = text.slice(0, -1);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (!text) {
|
|
258
|
+
return [];
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || '');
|
|
262
|
+
let lines = text.split(LineDecoder.NEWLINE_REGEXP);
|
|
263
|
+
|
|
264
|
+
// if there is a trailing new line then the last entry will be an empty
|
|
265
|
+
// string which we don't care about
|
|
266
|
+
if (trailingNewline) {
|
|
267
|
+
lines.pop();
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (lines.length === 1 && !trailingNewline) {
|
|
271
|
+
this.buffer.push(lines[0]!);
|
|
272
|
+
return [];
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (this.buffer.length > 0) {
|
|
276
|
+
lines = [this.buffer.join('') + lines[0], ...lines.slice(1)];
|
|
277
|
+
this.buffer = [];
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
if (!trailingNewline) {
|
|
281
|
+
this.buffer = [lines.pop() || ''];
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return lines;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
decodeText(bytes: Bytes): string {
|
|
288
|
+
if (bytes == null) {
|
|
289
|
+
return '';
|
|
290
|
+
}
|
|
291
|
+
if (typeof bytes === 'string') {
|
|
292
|
+
return bytes;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Node:
|
|
296
|
+
if (typeof Buffer !== 'undefined') {
|
|
297
|
+
if (bytes instanceof Buffer) {
|
|
298
|
+
return bytes.toString();
|
|
299
|
+
}
|
|
300
|
+
if (bytes instanceof Uint8Array) {
|
|
301
|
+
return Buffer.from(bytes).toString();
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
throw new Error(
|
|
305
|
+
`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`,
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Browser
|
|
310
|
+
if (typeof TextDecoder !== 'undefined') {
|
|
311
|
+
if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
|
|
312
|
+
this.textDecoder ??= new TextDecoder('utf8');
|
|
313
|
+
return this.textDecoder.decode(bytes);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
throw new Error(
|
|
317
|
+
`Unexpected: received non-Uint8Array/ArrayBuffer (${
|
|
318
|
+
(bytes as any).constructor.name
|
|
319
|
+
}) in a web platform. Please report this error.`,
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
throw new Error('Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.');
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
flush(): string[] {
|
|
327
|
+
if (!this.buffer.length && !this.trailingCR) {
|
|
328
|
+
return [];
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const lines = [this.buffer.join('')];
|
|
332
|
+
this.buffer = [];
|
|
333
|
+
this.trailingCR = false;
|
|
334
|
+
return lines;
|
|
335
|
+
}
|
|
336
|
+
}
|
package/src/bin/chat.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import inquirer from 'inquirer';
|
|
6
|
+
|
|
7
|
+
import { SpaceId } from '@dxos/keys';
|
|
8
|
+
|
|
9
|
+
import { AIServiceClientImpl, ObjectId, ToolTypes } from '../ai-service';
|
|
10
|
+
import { runLLM, createUserMessage } from '../conversation';
|
|
11
|
+
import {
|
|
12
|
+
createLogger,
|
|
13
|
+
createCypherTool,
|
|
14
|
+
createSystemPrompt,
|
|
15
|
+
createTestData,
|
|
16
|
+
Contact,
|
|
17
|
+
Org,
|
|
18
|
+
Project,
|
|
19
|
+
Task,
|
|
20
|
+
} from '../testing';
|
|
21
|
+
import { readFileSync, writeFileSync } from 'fs';
|
|
22
|
+
|
|
23
|
+
// TODO(burdon): Move out of src?
|
|
24
|
+
|
|
25
|
+
const ENDPOINT = 'http://localhost:8787';
|
|
26
|
+
// const ENDPOINT = 'https://ai-service.dxos.workers.dev';
|
|
27
|
+
|
|
28
|
+
const client = new AIServiceClientImpl({
|
|
29
|
+
endpoint: ENDPOINT,
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const dataSource = createTestData();
|
|
33
|
+
|
|
34
|
+
const cypherTool = createCypherTool(dataSource);
|
|
35
|
+
|
|
36
|
+
const schemaTypes = [Org, Project, Task, Contact];
|
|
37
|
+
|
|
38
|
+
const spaceId = SpaceId.random();
|
|
39
|
+
const threadId = ObjectId.random();
|
|
40
|
+
|
|
41
|
+
while (true) {
|
|
42
|
+
const prompt = await inquirer.prompt([
|
|
43
|
+
{
|
|
44
|
+
type: 'input',
|
|
45
|
+
name: 'message',
|
|
46
|
+
message: 'Enter a message:',
|
|
47
|
+
},
|
|
48
|
+
]);
|
|
49
|
+
await client.insertMessages([createUserMessage(spaceId, threadId, prompt.message)]);
|
|
50
|
+
|
|
51
|
+
await runLLM({
|
|
52
|
+
model: '@anthropic/claude-3-5-sonnet-20241022',
|
|
53
|
+
spaceId,
|
|
54
|
+
threadId,
|
|
55
|
+
system: createSystemPrompt(schemaTypes),
|
|
56
|
+
tools: [
|
|
57
|
+
cypherTool,
|
|
58
|
+
{
|
|
59
|
+
name: 'text-to-image',
|
|
60
|
+
type: ToolTypes.TextToImage,
|
|
61
|
+
},
|
|
62
|
+
],
|
|
63
|
+
client,
|
|
64
|
+
logger: createLogger({
|
|
65
|
+
stream: true,
|
|
66
|
+
filter: (e) => {
|
|
67
|
+
return true;
|
|
68
|
+
},
|
|
69
|
+
onImage: (img) => {
|
|
70
|
+
const path = `/tmp/image-${img.id}.jpeg`;
|
|
71
|
+
writeFileSync(path, Buffer.from(img.source.data, 'base64'));
|
|
72
|
+
console.log(`Saved image to ${path}`);
|
|
73
|
+
// Print image in iTerm using ANSI escape sequence
|
|
74
|
+
const imageData = img.source.data;
|
|
75
|
+
process.stdout.write('\x1b]1337;File=inline=1:' + imageData + '\x07');
|
|
76
|
+
},
|
|
77
|
+
}),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { Schema as S } from '@effect/schema';
|
|
6
|
+
import { describe, test } from 'vitest';
|
|
7
|
+
|
|
8
|
+
import { SpaceId } from '@dxos/keys';
|
|
9
|
+
import { log } from '@dxos/log';
|
|
10
|
+
|
|
11
|
+
import { runLLM, type ConversationEvent } from './conversation';
|
|
12
|
+
import { createUserMessage, defineTool, LLMToolResult } from './types';
|
|
13
|
+
import { AIServiceClientImpl, ObjectId } from '../ai-service';
|
|
14
|
+
|
|
15
|
+
const ENDPOINT = 'http://localhost:8787';
|
|
16
|
+
|
|
17
|
+
describe.skip('Conversation tests', () => {
|
|
18
|
+
const client = new AIServiceClientImpl({
|
|
19
|
+
endpoint: ENDPOINT,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('hello', async ({ expect }) => {
|
|
23
|
+
const spaceId = SpaceId.random();
|
|
24
|
+
const threadId = ObjectId.random();
|
|
25
|
+
|
|
26
|
+
await client.insertMessages([createUserMessage(spaceId, threadId, 'Hello, how are you?')]);
|
|
27
|
+
const result = await runLLM({
|
|
28
|
+
model: '@anthropic/claude-3-5-sonnet-20241022',
|
|
29
|
+
spaceId,
|
|
30
|
+
threadId,
|
|
31
|
+
tools: [],
|
|
32
|
+
client,
|
|
33
|
+
logger: messageLogger,
|
|
34
|
+
});
|
|
35
|
+
log.info('result', { result });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test('tool call', async ({ expect }) => {
|
|
39
|
+
const custodian = defineTool({
|
|
40
|
+
name: 'custodian',
|
|
41
|
+
description: 'Custodian can tell you the password if you say the magic word',
|
|
42
|
+
schema: S.Struct({
|
|
43
|
+
magicWord: S.String.annotations({ description: 'The magic word. Should be exactly "pretty please"' }),
|
|
44
|
+
}),
|
|
45
|
+
execute: async ({ magicWord }) => {
|
|
46
|
+
if (magicWord === 'pretty please') {
|
|
47
|
+
return LLMToolResult.Success('The password is: "The sky is gray"');
|
|
48
|
+
} else {
|
|
49
|
+
return LLMToolResult.Error('Wrong magic word');
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const spaceId = SpaceId.random();
|
|
55
|
+
const threadId = ObjectId.random();
|
|
56
|
+
|
|
57
|
+
await client.insertMessages([createUserMessage(spaceId, threadId, 'What is the password? Ask the custodian.')]);
|
|
58
|
+
const result = await runLLM({
|
|
59
|
+
model: '@anthropic/claude-3-5-sonnet-20241022',
|
|
60
|
+
spaceId,
|
|
61
|
+
threadId,
|
|
62
|
+
tools: [custodian],
|
|
63
|
+
client,
|
|
64
|
+
logger: messageLogger,
|
|
65
|
+
});
|
|
66
|
+
log.info('result', { result });
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const messageLogger = (event: ConversationEvent) => {
|
|
70
|
+
if (event.type === 'message') {
|
|
71
|
+
log.info('message', { message: event.message });
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
});
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { invariant } from '@dxos/invariant';
|
|
6
|
+
import { type SpaceId } from '@dxos/keys';
|
|
7
|
+
import { log } from '@dxos/log';
|
|
8
|
+
|
|
9
|
+
import { type LLMToolDefinition } from './types';
|
|
10
|
+
import { ObjectId, type LLMTool } from '../ai-service';
|
|
11
|
+
import { type AIServiceClient, type Message, type ResultStreamEvent, type LLMModel } from '../ai-service';
|
|
12
|
+
|
|
13
|
+
export type CreateLLMConversationParams = {
|
|
14
|
+
model: LLMModel;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* System prompt that specifies instructions for the LLM.
|
|
18
|
+
*/
|
|
19
|
+
system?: string;
|
|
20
|
+
|
|
21
|
+
spaceId: SpaceId;
|
|
22
|
+
threadId: ObjectId;
|
|
23
|
+
|
|
24
|
+
tools: LLMTool[];
|
|
25
|
+
|
|
26
|
+
client: AIServiceClient;
|
|
27
|
+
|
|
28
|
+
logger?: (event: ConversationEvent) => void;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type ConversationEvent =
|
|
32
|
+
| {
|
|
33
|
+
type: 'message';
|
|
34
|
+
message: Message;
|
|
35
|
+
}
|
|
36
|
+
| ResultStreamEvent;
|
|
37
|
+
|
|
38
|
+
export const runLLM = async (params: CreateLLMConversationParams) => {
|
|
39
|
+
let conversationResult: any = null;
|
|
40
|
+
|
|
41
|
+
const generate = async () => {
|
|
42
|
+
log('llm generate', { tools: params.tools });
|
|
43
|
+
const beginTs = Date.now();
|
|
44
|
+
const result = await params.client.generate({
|
|
45
|
+
model: params.model,
|
|
46
|
+
spaceId: params.spaceId,
|
|
47
|
+
threadId: params.threadId,
|
|
48
|
+
systemPrompt: params.system,
|
|
49
|
+
tools: params.tools as any,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
for await (const event of result) {
|
|
53
|
+
params.logger?.(event);
|
|
54
|
+
}
|
|
55
|
+
const messages = await result.complete();
|
|
56
|
+
const message = messages.at(-1);
|
|
57
|
+
|
|
58
|
+
log('llm result', { time: Date.now() - beginTs, message });
|
|
59
|
+
invariant(message);
|
|
60
|
+
params.logger?.({ type: 'message', message });
|
|
61
|
+
await params.client.insertMessages(
|
|
62
|
+
messages.map((msg) => ({ ...msg, content: msg.content.filter((c) => c.type !== 'image') })),
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
const isToolUse = message.content.at(-1)?.type === 'tool_use';
|
|
66
|
+
if (isToolUse) {
|
|
67
|
+
const toolCalls = message.content.filter((c) => c.type === 'tool_use');
|
|
68
|
+
invariant(toolCalls.length === 1);
|
|
69
|
+
const toolCall = toolCalls[0];
|
|
70
|
+
const tool = params.tools.find((t) => t.name === toolCall.name);
|
|
71
|
+
if (!tool) {
|
|
72
|
+
throw new Error(`Tool not found: ${toolCall.name}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const toolResult = await tool.execute(toolCall.input, {});
|
|
76
|
+
switch (toolResult.kind) {
|
|
77
|
+
case 'error': {
|
|
78
|
+
log('tool error', { message: toolResult.message });
|
|
79
|
+
const resultMessage: Message = {
|
|
80
|
+
id: ObjectId.random(),
|
|
81
|
+
spaceId: params.spaceId,
|
|
82
|
+
threadId: params.threadId,
|
|
83
|
+
role: 'user',
|
|
84
|
+
content: [
|
|
85
|
+
{
|
|
86
|
+
type: 'tool_result',
|
|
87
|
+
toolUseId: toolCall.id,
|
|
88
|
+
content: toolResult.message,
|
|
89
|
+
isError: true,
|
|
90
|
+
},
|
|
91
|
+
],
|
|
92
|
+
};
|
|
93
|
+
params.logger?.({ type: 'message', message: resultMessage });
|
|
94
|
+
await params.client.insertMessages([resultMessage]);
|
|
95
|
+
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
case 'success': {
|
|
99
|
+
log('tool success', { result: toolResult.result });
|
|
100
|
+
const resultMessage: Message = {
|
|
101
|
+
id: ObjectId.random(),
|
|
102
|
+
spaceId: params.spaceId,
|
|
103
|
+
threadId: params.threadId,
|
|
104
|
+
role: 'user',
|
|
105
|
+
content: [
|
|
106
|
+
{
|
|
107
|
+
type: 'tool_result',
|
|
108
|
+
toolUseId: toolCall.id,
|
|
109
|
+
content: JSON.stringify(toolResult.result),
|
|
110
|
+
},
|
|
111
|
+
],
|
|
112
|
+
};
|
|
113
|
+
params.logger?.({ type: 'message', message: resultMessage });
|
|
114
|
+
await params.client.insertMessages([resultMessage]);
|
|
115
|
+
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
case 'break': {
|
|
119
|
+
log('tool break', { result: toolResult.result });
|
|
120
|
+
conversationResult = toolResult.result;
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return false;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
// eslint-disable-next-line no-empty
|
|
129
|
+
while (await generate()) {}
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
result: conversationResult,
|
|
133
|
+
};
|
|
134
|
+
};
|