@dxos/assistant 0.7.4 → 0.7.5-labs.5f04cf6
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-37SDA65J.mjs +565 -0
- package/dist/lib/browser/chunk-37SDA65J.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +936 -47
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +14 -8
- package/dist/lib/browser/testing/index.mjs.map +4 -4
- package/dist/lib/node/chunk-UYNIAO5N.cjs +577 -0
- package/dist/lib/node/chunk-UYNIAO5N.cjs.map +7 -0
- package/dist/lib/node/index.cjs +936 -54
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +20 -13
- package/dist/lib/node/testing/index.cjs.map +4 -4
- package/dist/lib/node-esm/chunk-AR24K7TY.mjs +567 -0
- package/dist/lib/node-esm/chunk-AR24K7TY.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +936 -47
- 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 +14 -8
- package/dist/lib/node-esm/testing/index.mjs.map +4 -4
- package/dist/types/src/ai-service/client.d.ts +16 -32
- package/dist/types/src/ai-service/client.d.ts.map +1 -1
- package/dist/types/src/ai-service/defs.d.ts +134 -0
- package/dist/types/src/ai-service/defs.d.ts.map +1 -0
- package/dist/types/src/ai-service/index.d.ts +3 -1
- package/dist/types/src/ai-service/index.d.ts.map +1 -1
- package/dist/types/src/ai-service/parser.d.ts +40 -0
- package/dist/types/src/ai-service/parser.d.ts.map +1 -0
- package/dist/types/src/ai-service/stream.d.ts +35 -0
- package/dist/types/src/ai-service/stream.d.ts.map +1 -0
- package/dist/types/src/ai-service/stream.test.d.ts +2 -0
- package/dist/types/src/ai-service/stream.test.d.ts.map +1 -0
- package/dist/types/src/ai-service/util/index.d.ts +2 -0
- package/dist/types/src/ai-service/util/index.d.ts.map +1 -0
- package/dist/types/src/ai-service/{sse.d.ts → util/sse.d.ts} +5 -0
- package/dist/types/src/ai-service/util/sse.d.ts.map +1 -0
- package/dist/types/src/conversation/conversation.d.ts +56 -5
- package/dist/types/src/conversation/conversation.d.ts.map +1 -1
- package/dist/types/src/conversation/index.d.ts +0 -1
- package/dist/types/src/conversation/index.d.ts.map +1 -1
- package/dist/types/src/conversation/types.d.ts +44 -13
- package/dist/types/src/conversation/types.d.ts.map +1 -1
- package/dist/types/src/cypher/combinators.d.ts.map +1 -1
- package/dist/types/src/cypher/parjs.d.ts +1 -1
- package/dist/types/src/cypher/parjs.d.ts.map +1 -1
- package/dist/types/src/cypher/schema.d.ts.map +1 -1
- package/dist/types/src/testing/artifacts.test.d.ts +1 -0
- package/dist/types/src/testing/artifacts.test.d.ts.map +1 -0
- package/dist/types/src/testing/data.d.ts +2 -0
- package/dist/types/src/testing/data.d.ts.map +1 -0
- package/dist/types/src/testing/defs.d.ts +5 -0
- package/dist/types/src/testing/defs.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/logger.d.ts +1 -1
- package/dist/types/src/testing/logger.d.ts.map +1 -1
- 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 +4 -4
- package/package.json +20 -18
- package/src/ai-service/client.test.ts +28 -28
- package/src/ai-service/client.ts +31 -177
- package/src/ai-service/defs.ts +98 -0
- package/src/ai-service/index.ts +3 -1
- package/src/ai-service/parser.ts +183 -0
- package/src/ai-service/stream.test.ts +106 -0
- package/src/ai-service/stream.test.txt +33 -0
- package/src/ai-service/stream.ts +182 -0
- package/src/ai-service/util/index.ts +5 -0
- package/src/ai-service/{sse.ts → util/sse.ts} +5 -0
- package/src/bin/chat.ts +8 -10
- package/src/conversation/conversation.test.ts +13 -17
- package/src/conversation/conversation.ts +113 -18
- package/src/conversation/index.ts +0 -1
- package/src/conversation/types.ts +55 -16
- package/src/cypher/combinators.test.ts +4 -4
- package/src/cypher/combinators.ts +0 -1
- package/src/cypher/execution-plan.test.ts +5 -3
- package/src/cypher/parjs-shims.d.ts +4 -0
- package/src/cypher/parjs.ts +2 -2
- package/src/cypher/query-executor.test.ts +1 -1
- package/src/cypher/schema.ts +0 -1
- package/src/index.ts +1 -1
- package/src/testing/artifacts.test.ts +182 -0
- package/src/testing/data.ts +13 -0
- package/src/testing/defs.ts +8 -0
- package/src/testing/index.ts +1 -0
- package/src/testing/logger.ts +3 -2
- package/src/testing/query-promts.ts +3 -3
- package/src/testing/query.test.ts +11 -10
- package/src/testing/test-data.ts +1 -1
- package/vendor/parjs-browser.mjs +4 -0
- package/vendor/parjs-default.mjs +8 -0
- package/dist/lib/browser/chunk-AKP45LQH.mjs +0 -1394
- package/dist/lib/browser/chunk-AKP45LQH.mjs.map +0 -7
- package/dist/lib/node/chunk-G6CGWEMO.cjs +0 -1418
- package/dist/lib/node/chunk-G6CGWEMO.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-WUPUPEFB.mjs +0 -1396
- package/dist/lib/node-esm/chunk-WUPUPEFB.mjs.map +0 -7
- package/dist/types/src/ai-service/schema.d.ts +0 -296
- package/dist/types/src/ai-service/schema.d.ts.map +0 -1
- package/dist/types/src/ai-service/sse.d.ts.map +0 -1
- package/dist/types/src/sanity.test.d.ts +0 -2
- package/dist/types/src/sanity.test.d.ts.map +0 -1
- package/src/ai-service/schema.ts +0 -260
- package/src/sanity.test.ts +0 -9
|
@@ -1,1418 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
var chunk_G6CGWEMO_exports = {};
|
|
20
|
-
__export(chunk_G6CGWEMO_exports, {
|
|
21
|
-
AIServiceClientImpl: () => AIServiceClientImpl,
|
|
22
|
-
EchoDataSource: () => EchoDataSource,
|
|
23
|
-
GenerateRequest: () => GenerateRequest,
|
|
24
|
-
GenerationStream: () => GenerationStream,
|
|
25
|
-
ImageSource: () => ImageSource,
|
|
26
|
-
LLMModel: () => LLMModel,
|
|
27
|
-
LLMTool: () => LLMTool,
|
|
28
|
-
LLMToolDefinition: () => LLMToolDefinition,
|
|
29
|
-
LLMToolResult: () => LLMToolResult,
|
|
30
|
-
Message: () => Message,
|
|
31
|
-
MessageContentBlock: () => MessageContentBlock,
|
|
32
|
-
MessageFromDb: () => MessageFromDb,
|
|
33
|
-
MessageImageContentBlock: () => MessageImageContentBlock,
|
|
34
|
-
MessageRole: () => MessageRole,
|
|
35
|
-
MessageTextContentBlock: () => MessageTextContentBlock,
|
|
36
|
-
MessageToolResultContentBlock: () => MessageToolResultContentBlock,
|
|
37
|
-
MessageToolUseContentBlock: () => MessageToolUseContentBlock,
|
|
38
|
-
ObjectId: () => ObjectId,
|
|
39
|
-
ObjectIdBrand: () => ObjectIdBrand,
|
|
40
|
-
Space: () => Space,
|
|
41
|
-
SpaceIdSchema: () => SpaceIdSchema,
|
|
42
|
-
Thread: () => Thread,
|
|
43
|
-
ToolTypes: () => ToolTypes,
|
|
44
|
-
createUserMessage: () => createUserMessage,
|
|
45
|
-
defineTool: () => defineTool,
|
|
46
|
-
executeQuery: () => executeQuery,
|
|
47
|
-
executeQueryPlan: () => executeQueryPlan,
|
|
48
|
-
formatInferredRelationshipLabel: () => formatInferredRelationshipLabel,
|
|
49
|
-
formatJsonSchemaForLLM: () => formatJsonSchemaForLLM,
|
|
50
|
-
formatNodeLabel: () => formatNodeLabel,
|
|
51
|
-
isReference: () => isReference,
|
|
52
|
-
parseCypherQuery: () => parseCypherQuery,
|
|
53
|
-
runLLM: () => runLLM,
|
|
54
|
-
trim: () => trim
|
|
55
|
-
});
|
|
56
|
-
module.exports = __toCommonJS(chunk_G6CGWEMO_exports);
|
|
57
|
-
var import_schema = require("@effect/schema");
|
|
58
|
-
var import_ulidx = require("ulidx");
|
|
59
|
-
var import_echo_schema = require("@dxos/echo-schema");
|
|
60
|
-
var import_keys = require("@dxos/keys");
|
|
61
|
-
var import_schema2 = require("@effect/schema");
|
|
62
|
-
var import_async = require("@dxos/async");
|
|
63
|
-
var import_invariant = require("@dxos/invariant");
|
|
64
|
-
var import_parjs = require("#parjs");
|
|
65
|
-
var import_log = require("@dxos/log");
|
|
66
|
-
var import_util = require("@dxos/util");
|
|
67
|
-
var import_invariant2 = require("@dxos/invariant");
|
|
68
|
-
var import_log2 = require("@dxos/log");
|
|
69
|
-
var import_debug = require("@dxos/debug");
|
|
70
|
-
var import_echo_schema2 = require("@dxos/echo-schema");
|
|
71
|
-
var import_debug2 = require("@dxos/debug");
|
|
72
|
-
var import_echo_db = require("@dxos/echo-db");
|
|
73
|
-
var import_echo_schema3 = require("@dxos/echo-schema");
|
|
74
|
-
var import_live_object = require("@dxos/live-object");
|
|
75
|
-
var import_log3 = require("@dxos/log");
|
|
76
|
-
var import_invariant3 = require("@dxos/invariant");
|
|
77
|
-
var import_log4 = require("@dxos/log");
|
|
78
|
-
var import_schema3 = require("@effect/schema");
|
|
79
|
-
var import_echo_schema4 = require("@dxos/echo-schema");
|
|
80
|
-
var import_echo_schema5 = require("@dxos/echo-schema");
|
|
81
|
-
var import_log5 = require("@dxos/log");
|
|
82
|
-
var SpaceIdSchema = import_schema.Schema.String.pipe(import_schema.Schema.filter(import_keys.SpaceId.isValid));
|
|
83
|
-
var ObjectIdBrand = Symbol("@dxos/echo/ObjectId");
|
|
84
|
-
var ObjectIdSchema = import_schema.Schema.ULID.pipe(import_schema.Schema.brand(ObjectIdBrand));
|
|
85
|
-
var ObjectId = class extends ObjectIdSchema {
|
|
86
|
-
static random() {
|
|
87
|
-
return (0, import_ulidx.ulid)();
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
var Space = import_schema.Schema.Struct({
|
|
91
|
-
id: SpaceIdSchema
|
|
92
|
-
});
|
|
93
|
-
var Thread = import_schema.Schema.Struct({
|
|
94
|
-
id: ObjectId,
|
|
95
|
-
spaceId: SpaceIdSchema
|
|
96
|
-
});
|
|
97
|
-
var MessageRole = import_schema.Schema.String.pipe(import_schema.Schema.filter((role) => role === "user" || role === "assistant"));
|
|
98
|
-
var MessageTextContentBlock = import_schema.Schema.Struct({
|
|
99
|
-
type: import_schema.Schema.Literal("text"),
|
|
100
|
-
text: import_schema.Schema.String
|
|
101
|
-
}).pipe(import_schema.Schema.mutable);
|
|
102
|
-
var ImageSource = import_schema.Schema.Struct({
|
|
103
|
-
type: import_schema.Schema.Literal("base64"),
|
|
104
|
-
media_type: import_schema.Schema.Literal("image/jpeg", "image/png", "image/gif", "image/webp"),
|
|
105
|
-
data: import_schema.Schema.String
|
|
106
|
-
}).pipe(import_schema.Schema.mutable);
|
|
107
|
-
var MessageImageContentBlock = import_schema.Schema.Struct({
|
|
108
|
-
type: import_schema.Schema.Literal("image"),
|
|
109
|
-
id: import_schema.Schema.optional(import_schema.Schema.String),
|
|
110
|
-
source: import_schema.Schema.optional(ImageSource)
|
|
111
|
-
}).pipe(import_schema.Schema.mutable);
|
|
112
|
-
var MessageToolUseContentBlock = import_schema.Schema.Struct({
|
|
113
|
-
type: import_schema.Schema.Literal("tool_use"),
|
|
114
|
-
/**
|
|
115
|
-
* Opaque service-defined ID of the tool invocation.
|
|
116
|
-
* Used to match the tool result block.
|
|
117
|
-
*/
|
|
118
|
-
id: import_schema.Schema.String,
|
|
119
|
-
/**
|
|
120
|
-
* Tool name.
|
|
121
|
-
*/
|
|
122
|
-
name: import_schema.Schema.String,
|
|
123
|
-
input: import_schema.Schema.Unknown,
|
|
124
|
-
/**
|
|
125
|
-
* Used to accumulate the partial tool input JSON in streaming mode.
|
|
126
|
-
*/
|
|
127
|
-
inputJson: import_schema.Schema.optional(import_schema.Schema.String)
|
|
128
|
-
}).pipe(import_schema.Schema.mutable);
|
|
129
|
-
var MessageToolResultContentBlock = import_schema.Schema.Struct({
|
|
130
|
-
type: import_schema.Schema.Literal("tool_result"),
|
|
131
|
-
toolUseId: import_schema.Schema.String,
|
|
132
|
-
content: import_schema.Schema.String,
|
|
133
|
-
isError: import_schema.Schema.optional(import_schema.Schema.Boolean)
|
|
134
|
-
});
|
|
135
|
-
var MessageContentBlock = import_schema.Schema.Union(MessageTextContentBlock, MessageImageContentBlock, MessageToolUseContentBlock, MessageToolResultContentBlock);
|
|
136
|
-
var Message = import_schema.Schema.Struct({
|
|
137
|
-
id: ObjectId,
|
|
138
|
-
threadId: import_schema.Schema.optional(ObjectId),
|
|
139
|
-
spaceId: import_schema.Schema.optional(SpaceIdSchema),
|
|
140
|
-
role: MessageRole,
|
|
141
|
-
content: import_schema.Schema.Array(MessageContentBlock).pipe(import_schema.Schema.mutable),
|
|
142
|
-
/**
|
|
143
|
-
* ID of the message from the foreign provider.
|
|
144
|
-
*/
|
|
145
|
-
// TODO(dmaretskyi): Should be in meta/keys.
|
|
146
|
-
foreignId: import_schema.Schema.optional(import_schema.Schema.String)
|
|
147
|
-
});
|
|
148
|
-
var MessageFromDb = import_schema.Schema.Struct({
|
|
149
|
-
...Message.fields,
|
|
150
|
-
content: import_schema.Schema.propertySignature(Message.fields.content.pipe((schema) => import_schema.Schema.parseJson(schema))).pipe(import_schema.Schema.fromKey("contentJson"))
|
|
151
|
-
});
|
|
152
|
-
var LLMModel = import_schema.Schema.Literal("@hf/nousresearch/hermes-2-pro-mistral-7b", "@anthropic/claude-3-5-sonnet-20241022", "@anthropic/claude-3-5-haiku-20241022", "@ollama/llama-3-2-3b", "@ollama/llama-3-1-nemotron-70b-instruct", "@ollama/llama-3-1-nemotron-mini-4b-instruct");
|
|
153
|
-
var ToolTypes = Object.freeze({
|
|
154
|
-
// TODO(dmaretskyi): Not implemented yet.
|
|
155
|
-
// DatabaseQuery: 'database_query',
|
|
156
|
-
TextToImage: "text_to_image"
|
|
157
|
-
});
|
|
158
|
-
var LLMTool = import_schema.Schema.Struct({
|
|
159
|
-
name: import_schema.Schema.String,
|
|
160
|
-
/**
|
|
161
|
-
* If the tool is implemented by the service a type should be provided.
|
|
162
|
-
* For user-implemented tools, this field should be omitted.
|
|
163
|
-
* See {@link ToolTypes} for the list of supported types.
|
|
164
|
-
*/
|
|
165
|
-
type: import_schema.Schema.optional(import_schema.Schema.String),
|
|
166
|
-
/**
|
|
167
|
-
* Required for user-implemented tools.
|
|
168
|
-
*/
|
|
169
|
-
description: import_schema.Schema.optional(import_schema.Schema.String),
|
|
170
|
-
/**
|
|
171
|
-
* Input schema for the tool in the JSON Schema format.
|
|
172
|
-
* Required for user-implemented tools.
|
|
173
|
-
*/
|
|
174
|
-
parameters: import_schema.Schema.optional(import_echo_schema.JsonSchemaType),
|
|
175
|
-
/**
|
|
176
|
-
* Tool-specific options.
|
|
177
|
-
*/
|
|
178
|
-
options: import_schema.Schema.optional(import_schema.Schema.Any),
|
|
179
|
-
/**
|
|
180
|
-
* Javascript function to execute the tool.
|
|
181
|
-
*/
|
|
182
|
-
execute: import_schema.Schema.optional(import_schema.Schema.Any)
|
|
183
|
-
});
|
|
184
|
-
var GenerateRequest = import_schema.Schema.Struct({
|
|
185
|
-
model: LLMModel,
|
|
186
|
-
spaceId: SpaceIdSchema,
|
|
187
|
-
threadId: ObjectId,
|
|
188
|
-
/**
|
|
189
|
-
* System instructions to the LLM.
|
|
190
|
-
*/
|
|
191
|
-
// TODO(dmaretskyi): Should this be part of the thread?.
|
|
192
|
-
systemPrompt: import_schema.Schema.optional(import_schema.Schema.String),
|
|
193
|
-
/**
|
|
194
|
-
* Tools available for the LLM.
|
|
195
|
-
*/
|
|
196
|
-
tools: import_schema.Schema.Array(LLMTool).pipe(import_schema.Schema.mutable)
|
|
197
|
-
});
|
|
198
|
-
async function* iterSSEMessages(response, controller) {
|
|
199
|
-
if (!response.body) {
|
|
200
|
-
controller.abort();
|
|
201
|
-
throw new Error("Attempted to iterate over a response with no body");
|
|
202
|
-
}
|
|
203
|
-
const sseDecoder = new SSEDecoder();
|
|
204
|
-
const lineDecoder = new LineDecoder();
|
|
205
|
-
const iter = readableStreamAsyncIterable(response.body);
|
|
206
|
-
for await (const sseChunk of iterSSEChunks(iter)) {
|
|
207
|
-
for (const line of lineDecoder.decode(sseChunk)) {
|
|
208
|
-
const sse = sseDecoder.decode(line);
|
|
209
|
-
if (sse) {
|
|
210
|
-
yield sse;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
for (const line of lineDecoder.flush()) {
|
|
215
|
-
const sse = sseDecoder.decode(line);
|
|
216
|
-
if (sse) {
|
|
217
|
-
yield sse;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
async function* iterSSEChunks(iterator) {
|
|
222
|
-
let data = new Uint8Array();
|
|
223
|
-
for await (const chunk of iterator) {
|
|
224
|
-
if (chunk == null) {
|
|
225
|
-
continue;
|
|
226
|
-
}
|
|
227
|
-
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
|
|
228
|
-
const newData = new Uint8Array(data.length + binaryChunk.length);
|
|
229
|
-
newData.set(data);
|
|
230
|
-
newData.set(binaryChunk, data.length);
|
|
231
|
-
data = newData;
|
|
232
|
-
let patternIndex;
|
|
233
|
-
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
|
|
234
|
-
yield data.slice(0, patternIndex);
|
|
235
|
-
data = data.slice(patternIndex);
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
if (data.length > 0) {
|
|
239
|
-
yield data;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
var findDoubleNewlineIndex = (buffer) => {
|
|
243
|
-
const newline = 10;
|
|
244
|
-
const carriage = 13;
|
|
245
|
-
for (let i = 0; i < buffer.length - 2; i++) {
|
|
246
|
-
if (buffer[i] === newline && buffer[i + 1] === newline) {
|
|
247
|
-
return i + 2;
|
|
248
|
-
}
|
|
249
|
-
if (buffer[i] === carriage && buffer[i + 1] === carriage) {
|
|
250
|
-
return i + 2;
|
|
251
|
-
}
|
|
252
|
-
if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
|
|
253
|
-
return i + 4;
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
return -1;
|
|
257
|
-
};
|
|
258
|
-
var SSEDecoder = class {
|
|
259
|
-
constructor() {
|
|
260
|
-
this.event = null;
|
|
261
|
-
this.data = [];
|
|
262
|
-
this.chunks = [];
|
|
263
|
-
}
|
|
264
|
-
decode(line) {
|
|
265
|
-
if (line.endsWith("\r")) {
|
|
266
|
-
line = line.substring(0, line.length - 1);
|
|
267
|
-
}
|
|
268
|
-
if (!line) {
|
|
269
|
-
if (!this.event && !this.data.length) {
|
|
270
|
-
return null;
|
|
271
|
-
}
|
|
272
|
-
const sse = {
|
|
273
|
-
event: this.event,
|
|
274
|
-
data: this.data.join("\n"),
|
|
275
|
-
raw: this.chunks
|
|
276
|
-
};
|
|
277
|
-
this.event = null;
|
|
278
|
-
this.data = [];
|
|
279
|
-
this.chunks = [];
|
|
280
|
-
return sse;
|
|
281
|
-
}
|
|
282
|
-
this.chunks.push(line);
|
|
283
|
-
if (line.startsWith(":")) {
|
|
284
|
-
return null;
|
|
285
|
-
}
|
|
286
|
-
let [fieldname, _, value] = partition(line, ":");
|
|
287
|
-
if (value.startsWith(" ")) {
|
|
288
|
-
value = value.substring(1);
|
|
289
|
-
}
|
|
290
|
-
if (fieldname === "event") {
|
|
291
|
-
this.event = value;
|
|
292
|
-
} else if (fieldname === "data") {
|
|
293
|
-
this.data.push(value);
|
|
294
|
-
}
|
|
295
|
-
return null;
|
|
296
|
-
}
|
|
297
|
-
};
|
|
298
|
-
var partition = (str, delimiter) => {
|
|
299
|
-
const index = str.indexOf(delimiter);
|
|
300
|
-
if (index !== -1) {
|
|
301
|
-
return [
|
|
302
|
-
str.substring(0, index),
|
|
303
|
-
delimiter,
|
|
304
|
-
str.substring(index + delimiter.length)
|
|
305
|
-
];
|
|
306
|
-
}
|
|
307
|
-
return [
|
|
308
|
-
str,
|
|
309
|
-
"",
|
|
310
|
-
""
|
|
311
|
-
];
|
|
312
|
-
};
|
|
313
|
-
function readableStreamAsyncIterable(stream) {
|
|
314
|
-
if (stream[Symbol.asyncIterator]) {
|
|
315
|
-
return stream;
|
|
316
|
-
}
|
|
317
|
-
const reader = stream.getReader();
|
|
318
|
-
return {
|
|
319
|
-
next: async () => {
|
|
320
|
-
try {
|
|
321
|
-
const result = await reader.read();
|
|
322
|
-
if (result?.done) {
|
|
323
|
-
reader.releaseLock();
|
|
324
|
-
}
|
|
325
|
-
return result;
|
|
326
|
-
} catch (e) {
|
|
327
|
-
reader.releaseLock();
|
|
328
|
-
throw e;
|
|
329
|
-
}
|
|
330
|
-
},
|
|
331
|
-
return: async () => {
|
|
332
|
-
const cancelPromise = reader.cancel();
|
|
333
|
-
reader.releaseLock();
|
|
334
|
-
await cancelPromise;
|
|
335
|
-
return {
|
|
336
|
-
done: true,
|
|
337
|
-
value: void 0
|
|
338
|
-
};
|
|
339
|
-
},
|
|
340
|
-
[Symbol.asyncIterator]() {
|
|
341
|
-
return this;
|
|
342
|
-
}
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
var LineDecoder = class _LineDecoder {
|
|
346
|
-
static {
|
|
347
|
-
this.NEWLINE_CHARS = /* @__PURE__ */ new Set([
|
|
348
|
-
"\n",
|
|
349
|
-
"\r"
|
|
350
|
-
]);
|
|
351
|
-
}
|
|
352
|
-
static {
|
|
353
|
-
this.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
354
|
-
}
|
|
355
|
-
constructor() {
|
|
356
|
-
this.buffer = [];
|
|
357
|
-
this.trailingCR = false;
|
|
358
|
-
}
|
|
359
|
-
decode(chunk) {
|
|
360
|
-
let text = this.decodeText(chunk);
|
|
361
|
-
if (this.trailingCR) {
|
|
362
|
-
text = "\r" + text;
|
|
363
|
-
this.trailingCR = false;
|
|
364
|
-
}
|
|
365
|
-
if (text.endsWith("\r")) {
|
|
366
|
-
this.trailingCR = true;
|
|
367
|
-
text = text.slice(0, -1);
|
|
368
|
-
}
|
|
369
|
-
if (!text) {
|
|
370
|
-
return [];
|
|
371
|
-
}
|
|
372
|
-
const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
|
|
373
|
-
let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
|
|
374
|
-
if (trailingNewline) {
|
|
375
|
-
lines.pop();
|
|
376
|
-
}
|
|
377
|
-
if (lines.length === 1 && !trailingNewline) {
|
|
378
|
-
this.buffer.push(lines[0]);
|
|
379
|
-
return [];
|
|
380
|
-
}
|
|
381
|
-
if (this.buffer.length > 0) {
|
|
382
|
-
lines = [
|
|
383
|
-
this.buffer.join("") + lines[0],
|
|
384
|
-
...lines.slice(1)
|
|
385
|
-
];
|
|
386
|
-
this.buffer = [];
|
|
387
|
-
}
|
|
388
|
-
if (!trailingNewline) {
|
|
389
|
-
this.buffer = [
|
|
390
|
-
lines.pop() || ""
|
|
391
|
-
];
|
|
392
|
-
}
|
|
393
|
-
return lines;
|
|
394
|
-
}
|
|
395
|
-
decodeText(bytes) {
|
|
396
|
-
if (bytes == null) {
|
|
397
|
-
return "";
|
|
398
|
-
}
|
|
399
|
-
if (typeof bytes === "string") {
|
|
400
|
-
return bytes;
|
|
401
|
-
}
|
|
402
|
-
if (typeof Buffer !== "undefined") {
|
|
403
|
-
if (bytes instanceof Buffer) {
|
|
404
|
-
return bytes.toString();
|
|
405
|
-
}
|
|
406
|
-
if (bytes instanceof Uint8Array) {
|
|
407
|
-
return Buffer.from(bytes).toString();
|
|
408
|
-
}
|
|
409
|
-
throw new Error(`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.`);
|
|
410
|
-
}
|
|
411
|
-
if (typeof TextDecoder !== "undefined") {
|
|
412
|
-
if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
|
|
413
|
-
this.textDecoder ??= new TextDecoder("utf8");
|
|
414
|
-
return this.textDecoder.decode(bytes);
|
|
415
|
-
}
|
|
416
|
-
throw new Error(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
|
|
417
|
-
}
|
|
418
|
-
throw new Error("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.");
|
|
419
|
-
}
|
|
420
|
-
flush() {
|
|
421
|
-
if (!this.buffer.length && !this.trailingCR) {
|
|
422
|
-
return [];
|
|
423
|
-
}
|
|
424
|
-
const lines = [
|
|
425
|
-
this.buffer.join("")
|
|
426
|
-
];
|
|
427
|
-
this.buffer = [];
|
|
428
|
-
this.trailingCR = false;
|
|
429
|
-
return lines;
|
|
430
|
-
}
|
|
431
|
-
};
|
|
432
|
-
var __dxlog_file = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/ai-service/client.ts";
|
|
433
|
-
var AIServiceClientImpl = class {
|
|
434
|
-
constructor({ endpoint }) {
|
|
435
|
-
this._endpoint = endpoint;
|
|
436
|
-
}
|
|
437
|
-
async getSpace(spaceId) {
|
|
438
|
-
throw new Error("Not implemented");
|
|
439
|
-
}
|
|
440
|
-
async getThread(spaceId, threadId) {
|
|
441
|
-
throw new Error("Not implemented");
|
|
442
|
-
}
|
|
443
|
-
async getMessagesInThread(spaceId, threadId) {
|
|
444
|
-
const res = await fetch(`${this._endpoint}/space/${spaceId}/thread/${threadId}/message`);
|
|
445
|
-
return import_schema2.Schema.decodePromise(import_schema2.Schema.Array(Message).pipe(import_schema2.Schema.mutable))((await res.json()).data.results);
|
|
446
|
-
}
|
|
447
|
-
async insertMessages(messages) {
|
|
448
|
-
const res = await fetch(`${this._endpoint}/message`, {
|
|
449
|
-
method: "POST",
|
|
450
|
-
headers: {
|
|
451
|
-
"Content-Type": "application/json"
|
|
452
|
-
},
|
|
453
|
-
body: JSON.stringify({
|
|
454
|
-
messages: await import_schema2.Schema.encodePromise(import_schema2.Schema.Array(Message))(messages)
|
|
455
|
-
})
|
|
456
|
-
});
|
|
457
|
-
if (!res.ok) {
|
|
458
|
-
throw new Error(await res.text());
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
// TODO(dmaretskyi): Accept partial message schema.
|
|
462
|
-
async updateMessage(spaceId, threadId, messageId, message) {
|
|
463
|
-
throw new Error("Not implemented");
|
|
464
|
-
}
|
|
465
|
-
async generate(request) {
|
|
466
|
-
const response = await fetch(`${this._endpoint}/generate`, {
|
|
467
|
-
method: "POST",
|
|
468
|
-
headers: {
|
|
469
|
-
"Content-Type": "application/json"
|
|
470
|
-
},
|
|
471
|
-
body: JSON.stringify(request)
|
|
472
|
-
});
|
|
473
|
-
(0, import_invariant.invariant)(response.body instanceof ReadableStream, void 0, {
|
|
474
|
-
F: __dxlog_file,
|
|
475
|
-
L: 81,
|
|
476
|
-
S: this,
|
|
477
|
-
A: [
|
|
478
|
-
"response.body instanceof ReadableStream",
|
|
479
|
-
""
|
|
480
|
-
]
|
|
481
|
-
});
|
|
482
|
-
return GenerationStream.fromSSEResponse({
|
|
483
|
-
spaceId: request.spaceId,
|
|
484
|
-
threadId: request.threadId
|
|
485
|
-
}, response);
|
|
486
|
-
}
|
|
487
|
-
};
|
|
488
|
-
var GenerationStream = class _GenerationStream {
|
|
489
|
-
static fromSSEResponse(params, response) {
|
|
490
|
-
const controller = new AbortController();
|
|
491
|
-
const iterator = async function* () {
|
|
492
|
-
for await (const sse of iterSSEMessages(response, controller)) {
|
|
493
|
-
if (sse.event === "completion") {
|
|
494
|
-
try {
|
|
495
|
-
yield JSON.parse(sse.data);
|
|
496
|
-
} catch (e) {
|
|
497
|
-
console.error("Could not parse message into JSON:", sse.data);
|
|
498
|
-
console.error("From chunk:", sse.raw);
|
|
499
|
-
throw e;
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
|
|
503
|
-
try {
|
|
504
|
-
yield JSON.parse(sse.data);
|
|
505
|
-
} catch (e) {
|
|
506
|
-
console.error("Could not parse message into JSON:", sse.data);
|
|
507
|
-
console.error("From chunk:", sse.raw);
|
|
508
|
-
throw e;
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
if (sse.event === "ping") {
|
|
512
|
-
continue;
|
|
513
|
-
}
|
|
514
|
-
if (sse.event === "error") {
|
|
515
|
-
throw new Error(`Message generation error: ${sse.data}`);
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
};
|
|
519
|
-
return new _GenerationStream(params, iterator);
|
|
520
|
-
}
|
|
521
|
-
constructor(_params, _getIterator) {
|
|
522
|
-
this._params = _params;
|
|
523
|
-
this._getIterator = _getIterator;
|
|
524
|
-
this._previousMessages = [];
|
|
525
|
-
this._accumulatedMessage = void 0;
|
|
526
|
-
this._done = new import_async.Trigger();
|
|
527
|
-
this._iterator = void 0;
|
|
528
|
-
}
|
|
529
|
-
[Symbol.asyncIterator]() {
|
|
530
|
-
return this._createIterator();
|
|
531
|
-
}
|
|
532
|
-
cancel() {
|
|
533
|
-
throw new Error("Not implemented");
|
|
534
|
-
}
|
|
535
|
-
get accumulatedMessages() {
|
|
536
|
-
return [
|
|
537
|
-
...this._previousMessages,
|
|
538
|
-
...this._accumulatedMessage == null ? [] : [
|
|
539
|
-
this._accumulatedMessage
|
|
540
|
-
]
|
|
541
|
-
];
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* Returns the complete message list generated by the AI service.
|
|
545
|
-
*/
|
|
546
|
-
async complete() {
|
|
547
|
-
await this._done.wait();
|
|
548
|
-
return this.accumulatedMessages;
|
|
549
|
-
}
|
|
550
|
-
_createIterator() {
|
|
551
|
-
const self = this;
|
|
552
|
-
return this._iterator ??= async function* () {
|
|
553
|
-
for await (const event of self._getIterator()) {
|
|
554
|
-
self._processEvent(event);
|
|
555
|
-
yield event;
|
|
556
|
-
}
|
|
557
|
-
}();
|
|
558
|
-
}
|
|
559
|
-
_processEvent(event) {
|
|
560
|
-
switch (event.type) {
|
|
561
|
-
case "message_start": {
|
|
562
|
-
if (this._accumulatedMessage) {
|
|
563
|
-
this._previousMessages.push(this._accumulatedMessage);
|
|
564
|
-
this._accumulatedMessage = void 0;
|
|
565
|
-
}
|
|
566
|
-
this._accumulatedMessage = {
|
|
567
|
-
...event.message,
|
|
568
|
-
threadId: this._params.threadId,
|
|
569
|
-
spaceId: this._params.spaceId
|
|
570
|
-
};
|
|
571
|
-
break;
|
|
572
|
-
}
|
|
573
|
-
case "message_delta": {
|
|
574
|
-
if (this._accumulatedMessage === void 0) {
|
|
575
|
-
throw new Error("Received message delta without a message start");
|
|
576
|
-
}
|
|
577
|
-
break;
|
|
578
|
-
}
|
|
579
|
-
case "message_stop": {
|
|
580
|
-
if (this._accumulatedMessage === void 0) {
|
|
581
|
-
throw new Error("Received message stop without a message start");
|
|
582
|
-
}
|
|
583
|
-
break;
|
|
584
|
-
}
|
|
585
|
-
case "content_block_start": {
|
|
586
|
-
(0, import_invariant.invariant)(this._accumulatedMessage, void 0, {
|
|
587
|
-
F: __dxlog_file,
|
|
588
|
-
L: 212,
|
|
589
|
-
S: this,
|
|
590
|
-
A: [
|
|
591
|
-
"this._accumulatedMessage",
|
|
592
|
-
""
|
|
593
|
-
]
|
|
594
|
-
});
|
|
595
|
-
this._accumulatedMessage.content.push(event.content);
|
|
596
|
-
break;
|
|
597
|
-
}
|
|
598
|
-
case "content_block_delta": {
|
|
599
|
-
(0, import_invariant.invariant)(this._accumulatedMessage, void 0, {
|
|
600
|
-
F: __dxlog_file,
|
|
601
|
-
L: 217,
|
|
602
|
-
S: this,
|
|
603
|
-
A: [
|
|
604
|
-
"this._accumulatedMessage",
|
|
605
|
-
""
|
|
606
|
-
]
|
|
607
|
-
});
|
|
608
|
-
const snapshotContent = this._accumulatedMessage.content.at(event.index);
|
|
609
|
-
if (snapshotContent?.type === "text" && event.delta.type === "text_delta") {
|
|
610
|
-
snapshotContent.text += event.delta.text;
|
|
611
|
-
} else if (snapshotContent?.type === "tool_use" && event.delta.type === "input_json_delta") {
|
|
612
|
-
snapshotContent.inputJson ??= "";
|
|
613
|
-
snapshotContent.inputJson += event.delta.partial_json;
|
|
614
|
-
}
|
|
615
|
-
break;
|
|
616
|
-
}
|
|
617
|
-
case "content_block_stop": {
|
|
618
|
-
(0, import_invariant.invariant)(this._accumulatedMessage, void 0, {
|
|
619
|
-
F: __dxlog_file,
|
|
620
|
-
L: 233,
|
|
621
|
-
S: this,
|
|
622
|
-
A: [
|
|
623
|
-
"this._accumulatedMessage",
|
|
624
|
-
""
|
|
625
|
-
]
|
|
626
|
-
});
|
|
627
|
-
const lastBlock = this._accumulatedMessage.content.at(-1);
|
|
628
|
-
if (lastBlock?.type === "tool_use") {
|
|
629
|
-
lastBlock.input = JSON.parse(lastBlock.inputJson ?? "");
|
|
630
|
-
}
|
|
631
|
-
break;
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
this._done.wake();
|
|
635
|
-
}
|
|
636
|
-
};
|
|
637
|
-
var ws = import_parjs.parjs.whitespace();
|
|
638
|
-
var nothing = import_parjs.parjs.string("").pipe(import_parjs.parjsCombinators.map(() => null));
|
|
639
|
-
var optional = (parser) => parser.pipe(import_parjs.parjsCombinators.recover(() => ({
|
|
640
|
-
kind: "Soft"
|
|
641
|
-
})), import_parjs.parjsCombinators.or(nothing));
|
|
642
|
-
var keyword = (word) => import_parjs.parjs.string(word).pipe(import_parjs.parjsCombinators.map(() => word));
|
|
643
|
-
var identifier = import_parjs.parjs.regexp(/[a-zA-Z_][a-zA-Z0-9_]*/).pipe(import_parjs.parjsCombinators.map((match) => ({
|
|
644
|
-
astKind: "Identifier",
|
|
645
|
-
name: match[0]
|
|
646
|
-
})));
|
|
647
|
-
var numberLiteral = import_parjs.parjs.regexp(/-?\d+(\.\d+)?/).pipe(import_parjs.parjsCombinators.map(Number));
|
|
648
|
-
var stringLiteral = import_parjs.parjs.regexp(/"([^"]*)"|'([^']*)'/).pipe(import_parjs.parjsCombinators.map((match) => ({
|
|
649
|
-
astKind: "StringLiteral",
|
|
650
|
-
value: match[1] || match[2]
|
|
651
|
-
})));
|
|
652
|
-
var variableTag = identifier.pipe(import_parjs.parjsCombinators.map((variable) => variable)).expects("variable tag");
|
|
653
|
-
var label = identifier.pipe(import_parjs.parjsCombinators.map((name) => name));
|
|
654
|
-
var property = identifier.pipe(import_parjs.parjsCombinators.then(import_parjs.parjs.string(":"), ws, stringLiteral), import_parjs.parjsCombinators.map(([key, , , value]) => ({
|
|
655
|
-
key,
|
|
656
|
-
value
|
|
657
|
-
})));
|
|
658
|
-
var properties = property.pipe(import_parjs.parjsCombinators.manySepBy(","), import_parjs.parjsCombinators.between("{", "}"), import_parjs.parjsCombinators.map((properties2) => ({
|
|
659
|
-
astKind: "Properties",
|
|
660
|
-
properties: properties2
|
|
661
|
-
})));
|
|
662
|
-
var nodePattern = optional(variableTag).pipe(import_parjs.parjsCombinators.then(":"), import_parjs.parjsCombinators.then(ws, label, ws), import_parjs.parjsCombinators.then(optional(properties)), import_parjs.parjsCombinators.between("(", ")"), import_parjs.parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
|
|
663
|
-
astKind: "NodePattern",
|
|
664
|
-
variable,
|
|
665
|
-
label: label2,
|
|
666
|
-
properties: properties2
|
|
667
|
-
})));
|
|
668
|
-
var relationshipPattern = optional(variableTag).pipe(import_parjs.parjsCombinators.then(":"), import_parjs.parjsCombinators.then(ws, label, ws), import_parjs.parjsCombinators.then(optional(properties)), import_parjs.parjsCombinators.between("[", "]"), import_parjs.parjsCombinators.map(([[[variable], _, label2], properties2]) => ({
|
|
669
|
-
astKind: "RelationshipPattern",
|
|
670
|
-
variable,
|
|
671
|
-
label: label2,
|
|
672
|
-
properties: properties2
|
|
673
|
-
})));
|
|
674
|
-
var graphPatternConnector = import_parjs.parjs.string("->").pipe(import_parjs.parjsCombinators.or("<-", "-"), import_parjs.parjsCombinators.map((x) => ({
|
|
675
|
-
astKind: "GraphPatternConnector",
|
|
676
|
-
direction: x
|
|
677
|
-
})));
|
|
678
|
-
var graphPattern = nodePattern.pipe(import_parjs.parjsCombinators.or(relationshipPattern), import_parjs.parjsCombinators.manySepBy(graphPatternConnector), import_parjs.parjsCombinators.map((segments) => ({
|
|
679
|
-
astKind: "GraphPattern",
|
|
680
|
-
segments
|
|
681
|
-
})));
|
|
682
|
-
var matchClause = keyword("MATCH").pipe(import_parjs.parjsCombinators.then(ws), import_parjs.parjsCombinators.then(graphPattern), import_parjs.parjsCombinators.map(([, pattern]) => ({
|
|
683
|
-
astKind: "MatchClause",
|
|
684
|
-
pattern
|
|
685
|
-
})));
|
|
686
|
-
var memberExpression = identifier.pipe(import_parjs.parjsCombinators.manySepBy("."), import_parjs.parjsCombinators.map((path) => ({
|
|
687
|
-
astKind: "MemberExpression",
|
|
688
|
-
path
|
|
689
|
-
})));
|
|
690
|
-
var equalsPredicate = memberExpression.pipe(import_parjs.parjsCombinators.then(ws, import_parjs.parjs.string("="), ws, stringLiteral), import_parjs.parjsCombinators.map(([left, , , , right]) => ({
|
|
691
|
-
astKind: "EqualsPredicate",
|
|
692
|
-
left,
|
|
693
|
-
right
|
|
694
|
-
})));
|
|
695
|
-
var whereClause = keyword("WHERE").pipe(import_parjs.parjsCombinators.then(ws, equalsPredicate.pipe(import_parjs.parjsCombinators.between(ws, ws), import_parjs.parjsCombinators.manySepBy(import_parjs.parjs.string("AND"))), ws), import_parjs.parjsCombinators.map(([, , predicates]) => ({
|
|
696
|
-
astKind: "WhereClause",
|
|
697
|
-
predicates
|
|
698
|
-
})));
|
|
699
|
-
var returnClause = keyword("RETURN").pipe(import_parjs.parjsCombinators.then(ws, memberExpression.pipe(import_parjs.parjsCombinators.then(optional(import_parjs.parjs.string("AS").pipe(import_parjs.parjsCombinators.between(ws), import_parjs.parjsCombinators.then(identifier))), ws), import_parjs.parjsCombinators.manySepBy(import_parjs.parjs.string(",").pipe(import_parjs.parjsCombinators.then(ws)))), ws), import_parjs.parjsCombinators.map(([, , fields]) => ({
|
|
700
|
-
astKind: "ReturnClause",
|
|
701
|
-
fields: fields.map(([f]) => f)
|
|
702
|
-
})));
|
|
703
|
-
var cypherQuery = ws.pipe(import_parjs.parjsCombinators.then(matchClause, ws, optional(whereClause), ws, returnClause, ws), import_parjs.parjsCombinators.map(([, matchClause2, , whereClause2, , returnClause2]) => ({
|
|
704
|
-
astKind: "CypherQuery",
|
|
705
|
-
matchClause: matchClause2,
|
|
706
|
-
whereClause: whereClause2,
|
|
707
|
-
returnClause: returnClause2
|
|
708
|
-
})));
|
|
709
|
-
var parseCypherQuery = (query) => {
|
|
710
|
-
const parseResult = cypherQuery.parse(query);
|
|
711
|
-
if (parseResult.isOk) {
|
|
712
|
-
return {
|
|
713
|
-
ast: parseResult.value
|
|
714
|
-
};
|
|
715
|
-
} else {
|
|
716
|
-
throw new Error(`Failed to parse query: ${parseResult}`);
|
|
717
|
-
}
|
|
718
|
-
};
|
|
719
|
-
var __dxlog_file2 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/cypher/execution-plan.ts";
|
|
720
|
-
var createExecutionPlan = (query) => {
|
|
721
|
-
return new ExecutionPlanBuilder().build(query);
|
|
722
|
-
};
|
|
723
|
-
var ExecutionPlanBuilder = class {
|
|
724
|
-
constructor() {
|
|
725
|
-
this.counter = 0;
|
|
726
|
-
}
|
|
727
|
-
newVariable() {
|
|
728
|
-
return `anon_${this.counter++}`;
|
|
729
|
-
}
|
|
730
|
-
build(query) {
|
|
731
|
-
(0, import_log2.log)("Creating execution plan for query", {
|
|
732
|
-
query
|
|
733
|
-
}, {
|
|
734
|
-
F: __dxlog_file2,
|
|
735
|
-
L: 76,
|
|
736
|
-
S: this,
|
|
737
|
-
C: (f, a) => f(...a)
|
|
738
|
-
});
|
|
739
|
-
return {
|
|
740
|
-
steps: [
|
|
741
|
-
...this.createStepsForMatchClause(query.ast.matchClause),
|
|
742
|
-
...query.ast.whereClause ? this.createStepsForWhereClause(query.ast.whereClause) : [],
|
|
743
|
-
...this.createStepsForReturnClause(query.ast.returnClause)
|
|
744
|
-
],
|
|
745
|
-
output: {
|
|
746
|
-
fields: this.getOutputFields(query.ast.returnClause)
|
|
747
|
-
}
|
|
748
|
-
};
|
|
749
|
-
}
|
|
750
|
-
createStepsForMatchClause(match) {
|
|
751
|
-
(0, import_invariant2.invariant)(match.pattern.segments.length > 0, void 0, {
|
|
752
|
-
F: __dxlog_file2,
|
|
753
|
-
L: 90,
|
|
754
|
-
S: this,
|
|
755
|
-
A: [
|
|
756
|
-
"match.pattern.segments.length > 0",
|
|
757
|
-
""
|
|
758
|
-
]
|
|
759
|
-
});
|
|
760
|
-
const firstSegment = match.pattern.segments[0];
|
|
761
|
-
(0, import_invariant2.invariant)(firstSegment.astKind === "NodePattern", void 0, {
|
|
762
|
-
F: __dxlog_file2,
|
|
763
|
-
L: 92,
|
|
764
|
-
S: this,
|
|
765
|
-
A: [
|
|
766
|
-
"firstSegment.astKind === 'NodePattern'",
|
|
767
|
-
""
|
|
768
|
-
]
|
|
769
|
-
});
|
|
770
|
-
let lastNodeVariable = firstSegment.variable?.name ?? this.newVariable();
|
|
771
|
-
const steps = [];
|
|
772
|
-
steps.push({
|
|
773
|
-
type: "NodeScan",
|
|
774
|
-
label: firstSegment.label.name,
|
|
775
|
-
into: lastNodeVariable
|
|
776
|
-
});
|
|
777
|
-
if (firstSegment.properties) {
|
|
778
|
-
for (const property2 of firstSegment.properties.properties) {
|
|
779
|
-
steps.push({
|
|
780
|
-
type: "FilterByProperty",
|
|
781
|
-
variable: lastNodeVariable,
|
|
782
|
-
property: property2.key.name,
|
|
783
|
-
value: property2.value.value
|
|
784
|
-
});
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
for (let i = 1; i < match.pattern.segments.length; i++) {
|
|
788
|
-
const relationshipSegment = match.pattern.segments[i++];
|
|
789
|
-
(0, import_invariant2.invariant)(relationshipSegment.astKind === "RelationshipPattern", void 0, {
|
|
790
|
-
F: __dxlog_file2,
|
|
791
|
-
L: 115,
|
|
792
|
-
S: this,
|
|
793
|
-
A: [
|
|
794
|
-
"relationshipSegment.astKind === 'RelationshipPattern'",
|
|
795
|
-
""
|
|
796
|
-
]
|
|
797
|
-
});
|
|
798
|
-
const nodeSegment = match.pattern.segments[i];
|
|
799
|
-
(0, import_invariant2.invariant)(nodeSegment.astKind === "NodePattern", void 0, {
|
|
800
|
-
F: __dxlog_file2,
|
|
801
|
-
L: 117,
|
|
802
|
-
S: this,
|
|
803
|
-
A: [
|
|
804
|
-
"nodeSegment.astKind === 'NodePattern'",
|
|
805
|
-
""
|
|
806
|
-
]
|
|
807
|
-
});
|
|
808
|
-
const leftSeparator = match.pattern.segments.separators[i - 2];
|
|
809
|
-
const rightSeparator = match.pattern.segments.separators[i - 1];
|
|
810
|
-
const direction = getDirection(leftSeparator.direction, rightSeparator.direction);
|
|
811
|
-
const relationshipVariable = relationshipSegment.variable?.name ?? this.newVariable();
|
|
812
|
-
const nodeVariable = nodeSegment.variable?.name ?? this.newVariable();
|
|
813
|
-
steps.push({
|
|
814
|
-
type: "RelationshipScan",
|
|
815
|
-
label: relationshipSegment.label.name,
|
|
816
|
-
direction,
|
|
817
|
-
anchor: lastNodeVariable,
|
|
818
|
-
relationshipInto: relationshipVariable,
|
|
819
|
-
nodeInto: nodeVariable
|
|
820
|
-
});
|
|
821
|
-
if (relationshipSegment.properties) {
|
|
822
|
-
for (const property2 of relationshipSegment.properties.properties) {
|
|
823
|
-
steps.push({
|
|
824
|
-
type: "FilterByProperty",
|
|
825
|
-
variable: relationshipVariable,
|
|
826
|
-
property: property2.key.name,
|
|
827
|
-
value: property2.value.value
|
|
828
|
-
});
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
if (nodeSegment.label) {
|
|
832
|
-
steps.push({
|
|
833
|
-
type: "FilterByLabel",
|
|
834
|
-
variable: nodeVariable,
|
|
835
|
-
label: nodeSegment.label.name
|
|
836
|
-
});
|
|
837
|
-
}
|
|
838
|
-
if (nodeSegment.properties) {
|
|
839
|
-
for (const property2 of nodeSegment.properties.properties) {
|
|
840
|
-
steps.push({
|
|
841
|
-
type: "FilterByProperty",
|
|
842
|
-
variable: nodeVariable,
|
|
843
|
-
property: property2.key.name,
|
|
844
|
-
value: property2.value.value
|
|
845
|
-
});
|
|
846
|
-
}
|
|
847
|
-
}
|
|
848
|
-
lastNodeVariable = nodeVariable;
|
|
849
|
-
}
|
|
850
|
-
return steps;
|
|
851
|
-
}
|
|
852
|
-
createStepsForWhereClause(where) {
|
|
853
|
-
return [];
|
|
854
|
-
}
|
|
855
|
-
createStepsForReturnClause(returnClause2) {
|
|
856
|
-
return [
|
|
857
|
-
{
|
|
858
|
-
type: "ProduceResults",
|
|
859
|
-
fields: returnClause2.fields.map((field) => ({
|
|
860
|
-
name: field.path.map((p) => p.name).join("_"),
|
|
861
|
-
variable: field.path[0].name,
|
|
862
|
-
path: field.path.length > 1 ? field.path.slice(1).map((p) => p.name).join(".") : "$"
|
|
863
|
-
}))
|
|
864
|
-
}
|
|
865
|
-
];
|
|
866
|
-
}
|
|
867
|
-
getOutputFields(returnClause2) {
|
|
868
|
-
return returnClause2.fields.map((field) => field.path.map((p) => p.name).join("_"));
|
|
869
|
-
}
|
|
870
|
-
};
|
|
871
|
-
var getDirection = (left, right) => {
|
|
872
|
-
if (left === "-" && right === "->") {
|
|
873
|
-
return "out";
|
|
874
|
-
} else if (left === "<-" && right === "-") {
|
|
875
|
-
return "in";
|
|
876
|
-
} else if (left === "-" && right === "-") {
|
|
877
|
-
return "both";
|
|
878
|
-
}
|
|
879
|
-
throw new Error(`Invalid direction: ()${left}[]${right}()`);
|
|
880
|
-
};
|
|
881
|
-
var __dxlog_file3 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/cypher/query-executor.ts";
|
|
882
|
-
var executeQueryPlan = async (dataSource, plan) => {
|
|
883
|
-
let buffer = [];
|
|
884
|
-
const results = [];
|
|
885
|
-
for (const step of plan.steps) {
|
|
886
|
-
(0, import_log.log)("begin step", {
|
|
887
|
-
step
|
|
888
|
-
}, {
|
|
889
|
-
F: __dxlog_file3,
|
|
890
|
-
L: 41,
|
|
891
|
-
S: void 0,
|
|
892
|
-
C: (f, a) => f(...a)
|
|
893
|
-
});
|
|
894
|
-
switch (step.type) {
|
|
895
|
-
case "NodeScan": {
|
|
896
|
-
const nodes = await dataSource.getNodes({
|
|
897
|
-
label: step.label
|
|
898
|
-
});
|
|
899
|
-
buffer.push(...nodes.map((node) => ({
|
|
900
|
-
[step.into]: node
|
|
901
|
-
})));
|
|
902
|
-
break;
|
|
903
|
-
}
|
|
904
|
-
case "FilterByLabel": {
|
|
905
|
-
buffer = buffer.filter((item) => {
|
|
906
|
-
const node = item[step.variable];
|
|
907
|
-
return node && node.kind === "node" && node.label === step.label;
|
|
908
|
-
});
|
|
909
|
-
break;
|
|
910
|
-
}
|
|
911
|
-
case "FilterByProperty": {
|
|
912
|
-
buffer = buffer.filter((item) => {
|
|
913
|
-
const node = item[step.variable];
|
|
914
|
-
return node && node.kind === "node" && node.properties[step.property] === step.value;
|
|
915
|
-
});
|
|
916
|
-
break;
|
|
917
|
-
}
|
|
918
|
-
case "RelationshipScan": {
|
|
919
|
-
const relationships = await dataSource.getRelationships({
|
|
920
|
-
label: step.label
|
|
921
|
-
});
|
|
922
|
-
for (const tuple of [
|
|
923
|
-
...buffer
|
|
924
|
-
]) {
|
|
925
|
-
if (tuple[step.anchor].kind !== "node") {
|
|
926
|
-
continue;
|
|
927
|
-
}
|
|
928
|
-
const filteredRelationships = relationships.filter((relationship) => {
|
|
929
|
-
switch (step.direction) {
|
|
930
|
-
case "in":
|
|
931
|
-
return relationship.target.id === tuple[step.anchor].id;
|
|
932
|
-
case "out":
|
|
933
|
-
return relationship.source.id === tuple[step.anchor].id;
|
|
934
|
-
case "both":
|
|
935
|
-
return relationship.source.id === tuple[step.anchor].id || relationship.target.id === tuple[step.anchor].id;
|
|
936
|
-
default:
|
|
937
|
-
throw new Error(`Unknown direction: ${step.direction}`);
|
|
938
|
-
}
|
|
939
|
-
});
|
|
940
|
-
for (let i = 0; i < filteredRelationships.length; i++) {
|
|
941
|
-
const relationship = filteredRelationships[i];
|
|
942
|
-
const newTuple = i === 0 ? tuple : {
|
|
943
|
-
...tuple
|
|
944
|
-
};
|
|
945
|
-
if (newTuple !== tuple) {
|
|
946
|
-
buffer.push(newTuple);
|
|
947
|
-
}
|
|
948
|
-
newTuple[step.relationshipInto] = relationship;
|
|
949
|
-
switch (step.direction) {
|
|
950
|
-
case "in":
|
|
951
|
-
newTuple[step.nodeInto] = relationship.source;
|
|
952
|
-
break;
|
|
953
|
-
case "out":
|
|
954
|
-
newTuple[step.nodeInto] = relationship.target;
|
|
955
|
-
break;
|
|
956
|
-
case "both":
|
|
957
|
-
newTuple[step.nodeInto] = relationship.source.id === newTuple[step.anchor].id ? relationship.target : relationship.source;
|
|
958
|
-
break;
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
}
|
|
962
|
-
break;
|
|
963
|
-
}
|
|
964
|
-
case "ProduceResults": {
|
|
965
|
-
for (const tuple of buffer) {
|
|
966
|
-
const result = {};
|
|
967
|
-
for (const field of step.fields) {
|
|
968
|
-
result[field.name] = jsonPathGet(tuple[field.variable].properties, field.path);
|
|
969
|
-
}
|
|
970
|
-
results.push(result);
|
|
971
|
-
}
|
|
972
|
-
break;
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
(0, import_log.log)("finish step", {
|
|
976
|
-
buffer: buffer.map((tuple) => (0, import_util.mapValues)(tuple, (x) => x.id)),
|
|
977
|
-
results
|
|
978
|
-
}, {
|
|
979
|
-
F: __dxlog_file3,
|
|
980
|
-
L: 118,
|
|
981
|
-
S: void 0,
|
|
982
|
-
C: (f, a) => f(...a)
|
|
983
|
-
});
|
|
984
|
-
}
|
|
985
|
-
return results;
|
|
986
|
-
};
|
|
987
|
-
var executeQuery = (dataSource, query) => {
|
|
988
|
-
const plan = createExecutionPlan(parseCypherQuery(query));
|
|
989
|
-
return executeQueryPlan(dataSource, plan);
|
|
990
|
-
};
|
|
991
|
-
var jsonPathGet = (obj, path) => {
|
|
992
|
-
if (path === "" || path === "$") {
|
|
993
|
-
return obj;
|
|
994
|
-
}
|
|
995
|
-
const parts = path.split(".");
|
|
996
|
-
if (parts[0] === "$") {
|
|
997
|
-
parts.shift();
|
|
998
|
-
}
|
|
999
|
-
let result = obj;
|
|
1000
|
-
for (const part of parts) {
|
|
1001
|
-
result = result?.[part];
|
|
1002
|
-
}
|
|
1003
|
-
return result;
|
|
1004
|
-
};
|
|
1005
|
-
var trim = (strings, ...values) => {
|
|
1006
|
-
const combined = strings.reduce((acc, str, i) => {
|
|
1007
|
-
return acc + str + (values[i] || "");
|
|
1008
|
-
}, "");
|
|
1009
|
-
return combined.replace("/^\n/", "").replace(/\n$/, "");
|
|
1010
|
-
};
|
|
1011
|
-
var formatJsonSchemaForLLM = (schemaTypes) => {
|
|
1012
|
-
return schemaTypes.flatMap((schema) => [
|
|
1013
|
-
formatNodeSchema(schema),
|
|
1014
|
-
...formatInferredRelationships(schema, schemaTypes)
|
|
1015
|
-
]);
|
|
1016
|
-
};
|
|
1017
|
-
var formatNodeSchema = (schema) => {
|
|
1018
|
-
const label2 = formatNodeLabel(schema.typename ?? (0, import_debug.raise)(new Error("Schema must have $id")));
|
|
1019
|
-
const properties2 = Object.entries(schema.properties).filter(([key, prop]) => key !== "id" && !isReference(prop));
|
|
1020
|
-
return trim`
|
|
1021
|
-
<node>
|
|
1022
|
-
(:${label2})
|
|
1023
|
-
|
|
1024
|
-
<description>${schema.description}</description>
|
|
1025
|
-
|
|
1026
|
-
<properties>
|
|
1027
|
-
${properties2.map(([key, value]) => {
|
|
1028
|
-
return trim`
|
|
1029
|
-
<${key}>
|
|
1030
|
-
<type>${value.type}</type>
|
|
1031
|
-
<description>${value.description}</description>
|
|
1032
|
-
</${key}>
|
|
1033
|
-
`;
|
|
1034
|
-
})}
|
|
1035
|
-
</properties>
|
|
1036
|
-
</node>
|
|
1037
|
-
`;
|
|
1038
|
-
};
|
|
1039
|
-
var formatInferredRelationships = (schema, allSchema) => {
|
|
1040
|
-
const nodeLabel = formatNodeLabel(schema.typename ?? (0, import_debug.raise)(new Error("Schema must have $id")));
|
|
1041
|
-
const relationships = Object.entries(schema.properties).filter(([key, prop]) => isReference(prop));
|
|
1042
|
-
return relationships.map(([key, value]) => {
|
|
1043
|
-
const relationshipLabel = formatInferredRelationshipLabel(schema.typename ?? (0, import_debug.raise)(new Error("Schema must have $id")), key);
|
|
1044
|
-
const targetSchema = allSchema.find((schema2) => `dxn:type/${schema2.typename}` === value.reference?.schema.$ref);
|
|
1045
|
-
const targetLabel = targetSchema ? formatNodeLabel(targetSchema?.typename ?? "") : "";
|
|
1046
|
-
return trim`
|
|
1047
|
-
<relationship>
|
|
1048
|
-
(:${nodeLabel})-[:${relationshipLabel}]->(:${targetLabel})
|
|
1049
|
-
|
|
1050
|
-
<description>${value.description}</description>
|
|
1051
|
-
</relationship>
|
|
1052
|
-
`;
|
|
1053
|
-
});
|
|
1054
|
-
};
|
|
1055
|
-
var formatNodeLabel = (typename) => {
|
|
1056
|
-
return typename.replace(/^example\.com\/type\//g, "");
|
|
1057
|
-
};
|
|
1058
|
-
var formatInferredRelationshipLabel = (typename, property2) => {
|
|
1059
|
-
const nodeLabel = formatNodeLabel(typename);
|
|
1060
|
-
return `${nodeLabel}_${property2}`.toUpperCase();
|
|
1061
|
-
};
|
|
1062
|
-
var isReference = (schema) => schema.$id === import_echo_schema2.JSON_SCHEMA_ECHO_REF_ID || schema.type === "array" && schema.items?.$id === import_echo_schema2.JSON_SCHEMA_ECHO_REF_ID;
|
|
1063
|
-
function _ts_decorate(decorators, target, key, desc) {
|
|
1064
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
1065
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
1066
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
1067
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
1068
|
-
}
|
|
1069
|
-
var __dxlog_file4 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/cypher/echo-data-source.ts";
|
|
1070
|
-
var EchoDataSource = class {
|
|
1071
|
-
constructor(_db) {
|
|
1072
|
-
this._db = _db;
|
|
1073
|
-
}
|
|
1074
|
-
async getNodes({ label: label2 }) {
|
|
1075
|
-
if (!label2) {
|
|
1076
|
-
const { objects: objects2 } = await this._db.query().run();
|
|
1077
|
-
return objects2.map(this._objectToNode);
|
|
1078
|
-
}
|
|
1079
|
-
const schema = (await this._getAllSchema()).find((s) => (0, import_echo_schema3.getSchemaTypename)(s)?.endsWith(label2));
|
|
1080
|
-
if (!schema) {
|
|
1081
|
-
return [];
|
|
1082
|
-
}
|
|
1083
|
-
const { objects } = await this._db.query(import_echo_db.Filter.schema(schema)).run();
|
|
1084
|
-
return objects.map(this._objectToNode);
|
|
1085
|
-
}
|
|
1086
|
-
async getRelationships({ label: label2 }) {
|
|
1087
|
-
const syntheticRefRelationships = (await this._getAllSchema()).filter((schema) => (0, import_echo_schema3.getSchemaTypename)(schema) !== import_echo_schema3.StoredSchema.typename).flatMap((schema) => {
|
|
1088
|
-
const jsonSchema = (0, import_echo_schema3.toJsonSchema)(schema);
|
|
1089
|
-
const relationships = Object.entries(jsonSchema.properties).filter(([key, prop]) => isReference(prop));
|
|
1090
|
-
return relationships.map(([key, value]) => {
|
|
1091
|
-
const relationshipLabel = formatInferredRelationshipLabel(jsonSchema.typename ?? (0, import_debug2.raise)(new Error("Schema must have typename")), key);
|
|
1092
|
-
return {
|
|
1093
|
-
label: relationshipLabel,
|
|
1094
|
-
schema,
|
|
1095
|
-
property: key
|
|
1096
|
-
};
|
|
1097
|
-
});
|
|
1098
|
-
});
|
|
1099
|
-
const relationship = syntheticRefRelationships.find((r) => r.label === label2);
|
|
1100
|
-
if (!relationship) {
|
|
1101
|
-
return [];
|
|
1102
|
-
}
|
|
1103
|
-
const { objects } = await this._db.query(import_echo_db.Filter.schema(relationship.schema)).run();
|
|
1104
|
-
return (await Promise.all(objects.map((object) => this._projectRefRelationship(object, relationship.property)))).flat();
|
|
1105
|
-
}
|
|
1106
|
-
async _getAllSchema() {
|
|
1107
|
-
return [
|
|
1108
|
-
...await this._db.schemaRegistry.query().run(),
|
|
1109
|
-
// TODO(dmaretskyi): Remove once we can serialize recursive schema.
|
|
1110
|
-
...this._db.graph.schemaRegistry.schemas.filter((s) => (0, import_echo_schema3.getSchemaTypename)(s)?.startsWith("example.org"))
|
|
1111
|
-
].filter((schema) => (0, import_echo_schema3.getSchemaTypename)(schema) !== import_echo_schema3.StoredSchema.typename);
|
|
1112
|
-
}
|
|
1113
|
-
_objectToNode(object) {
|
|
1114
|
-
const { id, ...properties2 } = object;
|
|
1115
|
-
return {
|
|
1116
|
-
id,
|
|
1117
|
-
kind: "node",
|
|
1118
|
-
label: formatNodeLabel((0, import_echo_schema3.getSchemaTypename)((0, import_live_object.getSchema)(object))),
|
|
1119
|
-
properties: properties2
|
|
1120
|
-
};
|
|
1121
|
-
}
|
|
1122
|
-
async _projectRefRelationship(object, prop) {
|
|
1123
|
-
if (!object[prop]) {
|
|
1124
|
-
return [];
|
|
1125
|
-
}
|
|
1126
|
-
const value = Array.isArray(object[prop]) ? object[prop] : [
|
|
1127
|
-
object[prop]
|
|
1128
|
-
];
|
|
1129
|
-
return Promise.all(value.map(async (ref) => {
|
|
1130
|
-
const target = await ref.load();
|
|
1131
|
-
return {
|
|
1132
|
-
id: `${object.id}-${prop}-${target.id}`,
|
|
1133
|
-
kind: "relationship",
|
|
1134
|
-
label: formatInferredRelationshipLabel((0, import_echo_schema3.getSchemaTypename)((0, import_live_object.getSchema)(object)), prop),
|
|
1135
|
-
properties: {},
|
|
1136
|
-
source: this._objectToNode(object),
|
|
1137
|
-
target: this._objectToNode(target)
|
|
1138
|
-
};
|
|
1139
|
-
}));
|
|
1140
|
-
}
|
|
1141
|
-
};
|
|
1142
|
-
_ts_decorate([
|
|
1143
|
-
import_log3.log.method(void 0, void 0, {
|
|
1144
|
-
F: __dxlog_file4,
|
|
1145
|
-
L: 17,
|
|
1146
|
-
S: void 0,
|
|
1147
|
-
C: (f, a) => f(...a)
|
|
1148
|
-
})
|
|
1149
|
-
], EchoDataSource.prototype, "getNodes", null);
|
|
1150
|
-
_ts_decorate([
|
|
1151
|
-
import_log3.log.method(void 0, void 0, {
|
|
1152
|
-
F: __dxlog_file4,
|
|
1153
|
-
L: 34,
|
|
1154
|
-
S: void 0,
|
|
1155
|
-
C: (f, a) => f(...a)
|
|
1156
|
-
})
|
|
1157
|
-
], EchoDataSource.prototype, "getRelationships", null);
|
|
1158
|
-
var __dxlog_file5 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/conversation/conversation.ts";
|
|
1159
|
-
var runLLM = async (params) => {
|
|
1160
|
-
let conversationResult = null;
|
|
1161
|
-
const generate = async () => {
|
|
1162
|
-
(0, import_log4.log)("llm generate", {
|
|
1163
|
-
tools: params.tools
|
|
1164
|
-
}, {
|
|
1165
|
-
F: __dxlog_file5,
|
|
1166
|
-
L: 42,
|
|
1167
|
-
S: void 0,
|
|
1168
|
-
C: (f, a) => f(...a)
|
|
1169
|
-
});
|
|
1170
|
-
const beginTs = Date.now();
|
|
1171
|
-
const result = await params.client.generate({
|
|
1172
|
-
model: params.model,
|
|
1173
|
-
spaceId: params.spaceId,
|
|
1174
|
-
threadId: params.threadId,
|
|
1175
|
-
systemPrompt: params.system,
|
|
1176
|
-
tools: params.tools
|
|
1177
|
-
});
|
|
1178
|
-
for await (const event of result) {
|
|
1179
|
-
params.logger?.(event);
|
|
1180
|
-
}
|
|
1181
|
-
const messages = await result.complete();
|
|
1182
|
-
const message = messages.at(-1);
|
|
1183
|
-
(0, import_log4.log)("llm result", {
|
|
1184
|
-
time: Date.now() - beginTs,
|
|
1185
|
-
message
|
|
1186
|
-
}, {
|
|
1187
|
-
F: __dxlog_file5,
|
|
1188
|
-
L: 58,
|
|
1189
|
-
S: void 0,
|
|
1190
|
-
C: (f, a) => f(...a)
|
|
1191
|
-
});
|
|
1192
|
-
(0, import_invariant3.invariant)(message, void 0, {
|
|
1193
|
-
F: __dxlog_file5,
|
|
1194
|
-
L: 59,
|
|
1195
|
-
S: void 0,
|
|
1196
|
-
A: [
|
|
1197
|
-
"message",
|
|
1198
|
-
""
|
|
1199
|
-
]
|
|
1200
|
-
});
|
|
1201
|
-
params.logger?.({
|
|
1202
|
-
type: "message",
|
|
1203
|
-
message
|
|
1204
|
-
});
|
|
1205
|
-
await params.client.insertMessages(messages.map((msg) => ({
|
|
1206
|
-
...msg,
|
|
1207
|
-
content: msg.content.filter((c) => c.type !== "image")
|
|
1208
|
-
})));
|
|
1209
|
-
const isToolUse = message.content.at(-1)?.type === "tool_use";
|
|
1210
|
-
if (isToolUse) {
|
|
1211
|
-
const toolCalls = message.content.filter((c) => c.type === "tool_use");
|
|
1212
|
-
(0, import_invariant3.invariant)(toolCalls.length === 1, void 0, {
|
|
1213
|
-
F: __dxlog_file5,
|
|
1214
|
-
L: 68,
|
|
1215
|
-
S: void 0,
|
|
1216
|
-
A: [
|
|
1217
|
-
"toolCalls.length === 1",
|
|
1218
|
-
""
|
|
1219
|
-
]
|
|
1220
|
-
});
|
|
1221
|
-
const toolCall = toolCalls[0];
|
|
1222
|
-
const tool = params.tools.find((t) => t.name === toolCall.name);
|
|
1223
|
-
if (!tool) {
|
|
1224
|
-
throw new Error(`Tool not found: ${toolCall.name}`);
|
|
1225
|
-
}
|
|
1226
|
-
const toolResult = await tool.execute(toolCall.input, {});
|
|
1227
|
-
switch (toolResult.kind) {
|
|
1228
|
-
case "error": {
|
|
1229
|
-
(0, import_log4.log)("tool error", {
|
|
1230
|
-
message: toolResult.message
|
|
1231
|
-
}, {
|
|
1232
|
-
F: __dxlog_file5,
|
|
1233
|
-
L: 78,
|
|
1234
|
-
S: void 0,
|
|
1235
|
-
C: (f, a) => f(...a)
|
|
1236
|
-
});
|
|
1237
|
-
const resultMessage = {
|
|
1238
|
-
id: ObjectId.random(),
|
|
1239
|
-
spaceId: params.spaceId,
|
|
1240
|
-
threadId: params.threadId,
|
|
1241
|
-
role: "user",
|
|
1242
|
-
content: [
|
|
1243
|
-
{
|
|
1244
|
-
type: "tool_result",
|
|
1245
|
-
toolUseId: toolCall.id,
|
|
1246
|
-
content: toolResult.message,
|
|
1247
|
-
isError: true
|
|
1248
|
-
}
|
|
1249
|
-
]
|
|
1250
|
-
};
|
|
1251
|
-
params.logger?.({
|
|
1252
|
-
type: "message",
|
|
1253
|
-
message: resultMessage
|
|
1254
|
-
});
|
|
1255
|
-
await params.client.insertMessages([
|
|
1256
|
-
resultMessage
|
|
1257
|
-
]);
|
|
1258
|
-
return true;
|
|
1259
|
-
}
|
|
1260
|
-
case "success": {
|
|
1261
|
-
(0, import_log4.log)("tool success", {
|
|
1262
|
-
result: toolResult.result
|
|
1263
|
-
}, {
|
|
1264
|
-
F: __dxlog_file5,
|
|
1265
|
-
L: 99,
|
|
1266
|
-
S: void 0,
|
|
1267
|
-
C: (f, a) => f(...a)
|
|
1268
|
-
});
|
|
1269
|
-
const resultMessage = {
|
|
1270
|
-
id: ObjectId.random(),
|
|
1271
|
-
spaceId: params.spaceId,
|
|
1272
|
-
threadId: params.threadId,
|
|
1273
|
-
role: "user",
|
|
1274
|
-
content: [
|
|
1275
|
-
{
|
|
1276
|
-
type: "tool_result",
|
|
1277
|
-
toolUseId: toolCall.id,
|
|
1278
|
-
content: JSON.stringify(toolResult.result)
|
|
1279
|
-
}
|
|
1280
|
-
]
|
|
1281
|
-
};
|
|
1282
|
-
params.logger?.({
|
|
1283
|
-
type: "message",
|
|
1284
|
-
message: resultMessage
|
|
1285
|
-
});
|
|
1286
|
-
await params.client.insertMessages([
|
|
1287
|
-
resultMessage
|
|
1288
|
-
]);
|
|
1289
|
-
return true;
|
|
1290
|
-
}
|
|
1291
|
-
case "break": {
|
|
1292
|
-
(0, import_log4.log)("tool break", {
|
|
1293
|
-
result: toolResult.result
|
|
1294
|
-
}, {
|
|
1295
|
-
F: __dxlog_file5,
|
|
1296
|
-
L: 119,
|
|
1297
|
-
S: void 0,
|
|
1298
|
-
C: (f, a) => f(...a)
|
|
1299
|
-
});
|
|
1300
|
-
conversationResult = toolResult.result;
|
|
1301
|
-
return false;
|
|
1302
|
-
}
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
return false;
|
|
1306
|
-
};
|
|
1307
|
-
while (await generate()) {
|
|
1308
|
-
}
|
|
1309
|
-
return {
|
|
1310
|
-
result: conversationResult
|
|
1311
|
-
};
|
|
1312
|
-
};
|
|
1313
|
-
var __dxlog_file6 = "/Users/yarolegovich/Documents/Workspace/dxos/packages/experimental/assistant/src/conversation/types.ts";
|
|
1314
|
-
var createUserMessage = (spaceId, threadId, text) => ({
|
|
1315
|
-
id: ObjectId.random(),
|
|
1316
|
-
spaceId,
|
|
1317
|
-
threadId,
|
|
1318
|
-
role: "user",
|
|
1319
|
-
content: [
|
|
1320
|
-
{
|
|
1321
|
-
type: "text",
|
|
1322
|
-
text
|
|
1323
|
-
}
|
|
1324
|
-
]
|
|
1325
|
-
});
|
|
1326
|
-
var LLMToolDefinition = import_schema3.Schema.Struct({
|
|
1327
|
-
name: import_schema3.Schema.String,
|
|
1328
|
-
description: import_schema3.Schema.String,
|
|
1329
|
-
parameters: import_echo_schema5.JsonSchemaType,
|
|
1330
|
-
execute: import_schema3.Schema.Any
|
|
1331
|
-
});
|
|
1332
|
-
var LLMToolResult = Object.freeze({
|
|
1333
|
-
/**
|
|
1334
|
-
* The tool execution was successful.
|
|
1335
|
-
* Gives the result back to the LLM.
|
|
1336
|
-
*/
|
|
1337
|
-
Success: (result) => ({
|
|
1338
|
-
kind: "success",
|
|
1339
|
-
result
|
|
1340
|
-
}),
|
|
1341
|
-
Error: (message) => ({
|
|
1342
|
-
kind: "error",
|
|
1343
|
-
message
|
|
1344
|
-
}),
|
|
1345
|
-
/**
|
|
1346
|
-
* Stop the conversation and return the result.
|
|
1347
|
-
*/
|
|
1348
|
-
Break: (result) => ({
|
|
1349
|
-
kind: "break",
|
|
1350
|
-
result
|
|
1351
|
-
})
|
|
1352
|
-
});
|
|
1353
|
-
var defineTool = ({ name, description, schema, execute }) => {
|
|
1354
|
-
return {
|
|
1355
|
-
name,
|
|
1356
|
-
description,
|
|
1357
|
-
parameters: toFunctionParameterSchema(schema),
|
|
1358
|
-
execute: (params, context) => {
|
|
1359
|
-
const sanitized = import_schema3.Schema.decodeSync(schema)(params);
|
|
1360
|
-
return execute(sanitized, context);
|
|
1361
|
-
}
|
|
1362
|
-
};
|
|
1363
|
-
};
|
|
1364
|
-
var toFunctionParameterSchema = (schema) => {
|
|
1365
|
-
const jsonSchema = (0, import_echo_schema4.toJsonSchema)(schema);
|
|
1366
|
-
(0, import_log5.log)("tool schema", {
|
|
1367
|
-
jsonSchema
|
|
1368
|
-
}, {
|
|
1369
|
-
F: __dxlog_file6,
|
|
1370
|
-
L: 83,
|
|
1371
|
-
S: void 0,
|
|
1372
|
-
C: (f, a) => f(...a)
|
|
1373
|
-
});
|
|
1374
|
-
for (const key in jsonSchema.properties) {
|
|
1375
|
-
if (typeof jsonSchema.properties[key].description !== "string") {
|
|
1376
|
-
throw new Error(`Property missing description: ${key}`);
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
return jsonSchema;
|
|
1380
|
-
};
|
|
1381
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
1382
|
-
0 && (module.exports = {
|
|
1383
|
-
AIServiceClientImpl,
|
|
1384
|
-
EchoDataSource,
|
|
1385
|
-
GenerateRequest,
|
|
1386
|
-
GenerationStream,
|
|
1387
|
-
ImageSource,
|
|
1388
|
-
LLMModel,
|
|
1389
|
-
LLMTool,
|
|
1390
|
-
LLMToolDefinition,
|
|
1391
|
-
LLMToolResult,
|
|
1392
|
-
Message,
|
|
1393
|
-
MessageContentBlock,
|
|
1394
|
-
MessageFromDb,
|
|
1395
|
-
MessageImageContentBlock,
|
|
1396
|
-
MessageRole,
|
|
1397
|
-
MessageTextContentBlock,
|
|
1398
|
-
MessageToolResultContentBlock,
|
|
1399
|
-
MessageToolUseContentBlock,
|
|
1400
|
-
ObjectId,
|
|
1401
|
-
ObjectIdBrand,
|
|
1402
|
-
Space,
|
|
1403
|
-
SpaceIdSchema,
|
|
1404
|
-
Thread,
|
|
1405
|
-
ToolTypes,
|
|
1406
|
-
createUserMessage,
|
|
1407
|
-
defineTool,
|
|
1408
|
-
executeQuery,
|
|
1409
|
-
executeQueryPlan,
|
|
1410
|
-
formatInferredRelationshipLabel,
|
|
1411
|
-
formatJsonSchemaForLLM,
|
|
1412
|
-
formatNodeLabel,
|
|
1413
|
-
isReference,
|
|
1414
|
-
parseCypherQuery,
|
|
1415
|
-
runLLM,
|
|
1416
|
-
trim
|
|
1417
|
-
});
|
|
1418
|
-
//# sourceMappingURL=chunk-G6CGWEMO.cjs.map
|