@mastra/clickhouse 0.2.7-alpha.1
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/.turbo/turbo-build.log +23 -0
- package/CHANGELOG.md +11 -0
- package/LICENSE +44 -0
- package/README.md +122 -0
- package/dist/_tsup-dts-rollup.d.cts +83 -0
- package/dist/_tsup-dts-rollup.d.ts +83 -0
- package/dist/index.cjs +635 -0
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +633 -0
- package/docker-compose.yaml +15 -0
- package/eslint.config.js +6 -0
- package/package.json +45 -0
- package/src/index.ts +1 -0
- package/src/storage/index.test.ts +391 -0
- package/src/storage/index.ts +751 -0
- package/tsconfig.json +5 -0
- package/vitest.config.ts +12 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var storage = require('@mastra/core/storage');
|
|
4
|
+
var client = require('@clickhouse/client');
|
|
5
|
+
|
|
6
|
+
// src/storage/index.ts
|
|
7
|
+
function safelyParseJSON(jsonString) {
|
|
8
|
+
try {
|
|
9
|
+
return JSON.parse(jsonString);
|
|
10
|
+
} catch {
|
|
11
|
+
return {};
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
var TABLE_ENGINES = {
|
|
15
|
+
[storage.TABLE_MESSAGES]: `MergeTree()`,
|
|
16
|
+
[storage.TABLE_WORKFLOW_SNAPSHOT]: `ReplacingMergeTree()`,
|
|
17
|
+
[storage.TABLE_TRACES]: `MergeTree()`,
|
|
18
|
+
[storage.TABLE_THREADS]: `ReplacingMergeTree()`,
|
|
19
|
+
[storage.TABLE_EVALS]: `MergeTree()`
|
|
20
|
+
};
|
|
21
|
+
var COLUMN_TYPES = {
|
|
22
|
+
text: "String",
|
|
23
|
+
timestamp: "DateTime64(3)",
|
|
24
|
+
uuid: "String",
|
|
25
|
+
jsonb: "String",
|
|
26
|
+
integer: "Int64",
|
|
27
|
+
bigint: "Int64"
|
|
28
|
+
};
|
|
29
|
+
function transformRows(rows) {
|
|
30
|
+
return rows.map((row) => transformRow(row));
|
|
31
|
+
}
|
|
32
|
+
function transformRow(row) {
|
|
33
|
+
if (!row) {
|
|
34
|
+
return row;
|
|
35
|
+
}
|
|
36
|
+
if (row.createdAt) {
|
|
37
|
+
row.createdAt = new Date(row.createdAt);
|
|
38
|
+
}
|
|
39
|
+
if (row.updatedAt) {
|
|
40
|
+
row.updatedAt = new Date(row.updatedAt);
|
|
41
|
+
}
|
|
42
|
+
return row;
|
|
43
|
+
}
|
|
44
|
+
var ClickhouseStore = class extends storage.MastraStorage {
|
|
45
|
+
db;
|
|
46
|
+
constructor(config) {
|
|
47
|
+
super({ name: "ClickhouseStore" });
|
|
48
|
+
this.db = client.createClient({
|
|
49
|
+
url: config.url,
|
|
50
|
+
username: config.username,
|
|
51
|
+
password: config.password,
|
|
52
|
+
clickhouse_settings: {
|
|
53
|
+
date_time_input_format: "best_effort",
|
|
54
|
+
date_time_output_format: "iso",
|
|
55
|
+
// This is crucial
|
|
56
|
+
use_client_time_zone: 1,
|
|
57
|
+
output_format_json_quote_64bit_integers: 0
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
getEvalsByAgentName(_agentName, _type) {
|
|
62
|
+
throw new Error("Method not implemented.");
|
|
63
|
+
}
|
|
64
|
+
async batchInsert({ tableName, records }) {
|
|
65
|
+
try {
|
|
66
|
+
await this.db.insert({
|
|
67
|
+
table: tableName,
|
|
68
|
+
values: records.map((record) => ({
|
|
69
|
+
...Object.fromEntries(
|
|
70
|
+
Object.entries(record).map(([key, value]) => [
|
|
71
|
+
key,
|
|
72
|
+
storage.TABLE_SCHEMAS[tableName]?.[key]?.type === "timestamp" ? new Date(value).toISOString() : value
|
|
73
|
+
])
|
|
74
|
+
)
|
|
75
|
+
})),
|
|
76
|
+
format: "JSONEachRow",
|
|
77
|
+
clickhouse_settings: {
|
|
78
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
79
|
+
date_time_input_format: "best_effort",
|
|
80
|
+
use_client_time_zone: 1,
|
|
81
|
+
output_format_json_quote_64bit_integers: 0
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
} catch (error) {
|
|
85
|
+
console.error(`Error inserting into ${tableName}:`, error);
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async getTraces({
|
|
90
|
+
name,
|
|
91
|
+
scope,
|
|
92
|
+
page,
|
|
93
|
+
perPage,
|
|
94
|
+
attributes
|
|
95
|
+
}) {
|
|
96
|
+
const limit = perPage;
|
|
97
|
+
const offset = page * perPage;
|
|
98
|
+
const args = {};
|
|
99
|
+
const conditions = [];
|
|
100
|
+
if (name) {
|
|
101
|
+
conditions.push(`name LIKE CONCAT({var_name:String}, '%')`);
|
|
102
|
+
args.var_name = name;
|
|
103
|
+
}
|
|
104
|
+
if (scope) {
|
|
105
|
+
conditions.push(`scope = {var_scope:String}`);
|
|
106
|
+
args.var_scope = scope;
|
|
107
|
+
}
|
|
108
|
+
if (attributes) {
|
|
109
|
+
Object.entries(attributes).forEach(([key, value]) => {
|
|
110
|
+
conditions.push(`JSONExtractString(attributes, '${key}') = {var_${key}:String}`);
|
|
111
|
+
args[`var_${key}`] = value;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
115
|
+
const result = await this.db.query({
|
|
116
|
+
query: `SELECT *, toDateTime64(createdAt, 3) as createdAt FROM ${storage.TABLE_TRACES} ${whereClause} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`,
|
|
117
|
+
query_params: args,
|
|
118
|
+
clickhouse_settings: {
|
|
119
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
120
|
+
date_time_input_format: "best_effort",
|
|
121
|
+
date_time_output_format: "iso",
|
|
122
|
+
use_client_time_zone: 1,
|
|
123
|
+
output_format_json_quote_64bit_integers: 0
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
if (!result) {
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
const resp = await result.json();
|
|
130
|
+
const rows = resp.data;
|
|
131
|
+
return rows.map((row) => ({
|
|
132
|
+
id: row.id,
|
|
133
|
+
parentSpanId: row.parentSpanId,
|
|
134
|
+
traceId: row.traceId,
|
|
135
|
+
name: row.name,
|
|
136
|
+
scope: row.scope,
|
|
137
|
+
kind: row.kind,
|
|
138
|
+
status: safelyParseJSON(row.status),
|
|
139
|
+
events: safelyParseJSON(row.events),
|
|
140
|
+
links: safelyParseJSON(row.links),
|
|
141
|
+
attributes: safelyParseJSON(row.attributes),
|
|
142
|
+
startTime: row.startTime,
|
|
143
|
+
endTime: row.endTime,
|
|
144
|
+
other: safelyParseJSON(row.other),
|
|
145
|
+
createdAt: row.createdAt
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
148
|
+
async createTable({
|
|
149
|
+
tableName,
|
|
150
|
+
schema
|
|
151
|
+
}) {
|
|
152
|
+
try {
|
|
153
|
+
const columns = Object.entries(schema).map(([name, def]) => {
|
|
154
|
+
const constraints = [];
|
|
155
|
+
if (!def.nullable) constraints.push("NOT NULL");
|
|
156
|
+
return `"${name}" ${COLUMN_TYPES[def.type]} ${constraints.join(" ")}`;
|
|
157
|
+
}).join(",\n");
|
|
158
|
+
const sql = tableName === storage.TABLE_WORKFLOW_SNAPSHOT ? `
|
|
159
|
+
CREATE TABLE IF NOT EXISTS ${tableName} (
|
|
160
|
+
${["id String"].concat(columns)}
|
|
161
|
+
)
|
|
162
|
+
ENGINE = ${TABLE_ENGINES[tableName]}
|
|
163
|
+
PARTITION BY "createdAt"
|
|
164
|
+
PRIMARY KEY (createdAt, run_id, workflow_name)
|
|
165
|
+
ORDER BY (createdAt, run_id, workflow_name)
|
|
166
|
+
SETTINGS index_granularity = 8192;
|
|
167
|
+
` : `
|
|
168
|
+
CREATE TABLE IF NOT EXISTS ${tableName} (
|
|
169
|
+
${columns}
|
|
170
|
+
)
|
|
171
|
+
ENGINE = ${TABLE_ENGINES[tableName]}
|
|
172
|
+
PARTITION BY "createdAt"
|
|
173
|
+
PRIMARY KEY (createdAt, id)
|
|
174
|
+
ORDER BY (createdAt, id)
|
|
175
|
+
SETTINGS index_granularity = 8192;
|
|
176
|
+
`;
|
|
177
|
+
await this.db.query({
|
|
178
|
+
query: sql,
|
|
179
|
+
clickhouse_settings: {
|
|
180
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
181
|
+
date_time_input_format: "best_effort",
|
|
182
|
+
date_time_output_format: "iso",
|
|
183
|
+
use_client_time_zone: 1,
|
|
184
|
+
output_format_json_quote_64bit_integers: 0
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
} catch (error) {
|
|
188
|
+
console.error(`Error creating table ${tableName}:`, error);
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async clearTable({ tableName }) {
|
|
193
|
+
try {
|
|
194
|
+
await this.db.query({
|
|
195
|
+
query: `TRUNCATE TABLE ${tableName}`,
|
|
196
|
+
clickhouse_settings: {
|
|
197
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
198
|
+
date_time_input_format: "best_effort",
|
|
199
|
+
date_time_output_format: "iso",
|
|
200
|
+
use_client_time_zone: 1,
|
|
201
|
+
output_format_json_quote_64bit_integers: 0
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
} catch (error) {
|
|
205
|
+
console.error(`Error clearing table ${tableName}:`, error);
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async insert({ tableName, record }) {
|
|
210
|
+
try {
|
|
211
|
+
await this.db.insert({
|
|
212
|
+
table: tableName,
|
|
213
|
+
values: [
|
|
214
|
+
{
|
|
215
|
+
...record,
|
|
216
|
+
createdAt: record.createdAt.toISOString(),
|
|
217
|
+
updatedAt: record.updatedAt.toISOString()
|
|
218
|
+
}
|
|
219
|
+
],
|
|
220
|
+
format: "JSONEachRow",
|
|
221
|
+
clickhouse_settings: {
|
|
222
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
223
|
+
output_format_json_quote_64bit_integers: 0,
|
|
224
|
+
date_time_input_format: "best_effort",
|
|
225
|
+
use_client_time_zone: 1
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
} catch (error) {
|
|
229
|
+
console.error(`Error inserting into ${tableName}:`, error);
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async load({ tableName, keys }) {
|
|
234
|
+
try {
|
|
235
|
+
const keyEntries = Object.entries(keys);
|
|
236
|
+
const conditions = keyEntries.map(
|
|
237
|
+
([key], index) => `"${key}" = {var_${key}:${COLUMN_TYPES[storage.TABLE_SCHEMAS[tableName]?.[key]?.type ?? "text"]}}`
|
|
238
|
+
).join(" AND ");
|
|
239
|
+
const values = keyEntries.reduce((acc, [key, value]) => {
|
|
240
|
+
return { ...acc, [`var_${key}`]: value };
|
|
241
|
+
}, {});
|
|
242
|
+
const result = await this.db.query({
|
|
243
|
+
query: `SELECT *, toDateTime64(createdAt, 3) as createdAt, toDateTime64(updatedAt, 3) as updatedAt FROM ${tableName} ${TABLE_ENGINES[tableName].startsWith("ReplacingMergeTree") ? "FINAL" : ""} WHERE ${conditions}`,
|
|
244
|
+
query_params: values,
|
|
245
|
+
clickhouse_settings: {
|
|
246
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
247
|
+
date_time_input_format: "best_effort",
|
|
248
|
+
date_time_output_format: "iso",
|
|
249
|
+
use_client_time_zone: 1,
|
|
250
|
+
output_format_json_quote_64bit_integers: 0
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
if (!result) {
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
const rows = await result.json();
|
|
257
|
+
if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
|
|
258
|
+
const snapshot = rows.data[0];
|
|
259
|
+
if (!snapshot) {
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
if (typeof snapshot.snapshot === "string") {
|
|
263
|
+
snapshot.snapshot = JSON.parse(snapshot.snapshot);
|
|
264
|
+
}
|
|
265
|
+
return transformRow(snapshot);
|
|
266
|
+
}
|
|
267
|
+
const data = transformRow(rows.data[0]);
|
|
268
|
+
return data;
|
|
269
|
+
} catch (error) {
|
|
270
|
+
console.error(`Error loading from ${tableName}:`, error);
|
|
271
|
+
throw error;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
async getThreadById({ threadId }) {
|
|
275
|
+
try {
|
|
276
|
+
const result = await this.db.query({
|
|
277
|
+
query: `SELECT
|
|
278
|
+
id,
|
|
279
|
+
"resourceId",
|
|
280
|
+
title,
|
|
281
|
+
metadata,
|
|
282
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
283
|
+
toDateTime64(updatedAt, 3) as updatedAt
|
|
284
|
+
FROM "${storage.TABLE_THREADS}"
|
|
285
|
+
FINAL
|
|
286
|
+
WHERE id = {var_id:String}`,
|
|
287
|
+
query_params: { var_id: threadId },
|
|
288
|
+
clickhouse_settings: {
|
|
289
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
290
|
+
date_time_input_format: "best_effort",
|
|
291
|
+
date_time_output_format: "iso",
|
|
292
|
+
use_client_time_zone: 1,
|
|
293
|
+
output_format_json_quote_64bit_integers: 0
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
const rows = await result.json();
|
|
297
|
+
const thread = transformRow(rows.data[0]);
|
|
298
|
+
if (!thread) {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
...thread,
|
|
303
|
+
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
304
|
+
createdAt: thread.createdAt,
|
|
305
|
+
updatedAt: thread.updatedAt
|
|
306
|
+
};
|
|
307
|
+
} catch (error) {
|
|
308
|
+
console.error(`Error getting thread ${threadId}:`, error);
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
async getThreadsByResourceId({ resourceId }) {
|
|
313
|
+
try {
|
|
314
|
+
const result = await this.db.query({
|
|
315
|
+
query: `SELECT
|
|
316
|
+
id,
|
|
317
|
+
"resourceId",
|
|
318
|
+
title,
|
|
319
|
+
metadata,
|
|
320
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
321
|
+
toDateTime64(updatedAt, 3) as updatedAt
|
|
322
|
+
FROM "${storage.TABLE_THREADS}"
|
|
323
|
+
WHERE "resourceId" = {var_resourceId:String}`,
|
|
324
|
+
query_params: { var_resourceId: resourceId },
|
|
325
|
+
clickhouse_settings: {
|
|
326
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
327
|
+
date_time_input_format: "best_effort",
|
|
328
|
+
date_time_output_format: "iso",
|
|
329
|
+
use_client_time_zone: 1,
|
|
330
|
+
output_format_json_quote_64bit_integers: 0
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
const rows = await result.json();
|
|
334
|
+
const threads = transformRows(rows.data);
|
|
335
|
+
return threads.map((thread) => ({
|
|
336
|
+
...thread,
|
|
337
|
+
metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
|
|
338
|
+
createdAt: thread.createdAt,
|
|
339
|
+
updatedAt: thread.updatedAt
|
|
340
|
+
}));
|
|
341
|
+
} catch (error) {
|
|
342
|
+
console.error(`Error getting threads for resource ${resourceId}:`, error);
|
|
343
|
+
throw error;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
async saveThread({ thread }) {
|
|
347
|
+
try {
|
|
348
|
+
await this.db.insert({
|
|
349
|
+
table: storage.TABLE_THREADS,
|
|
350
|
+
values: [
|
|
351
|
+
{
|
|
352
|
+
...thread,
|
|
353
|
+
createdAt: thread.createdAt.toISOString(),
|
|
354
|
+
updatedAt: thread.updatedAt.toISOString()
|
|
355
|
+
}
|
|
356
|
+
],
|
|
357
|
+
format: "JSONEachRow",
|
|
358
|
+
clickhouse_settings: {
|
|
359
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
360
|
+
date_time_input_format: "best_effort",
|
|
361
|
+
use_client_time_zone: 1,
|
|
362
|
+
output_format_json_quote_64bit_integers: 0
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
return thread;
|
|
366
|
+
} catch (error) {
|
|
367
|
+
console.error("Error saving thread:", error);
|
|
368
|
+
throw error;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
async updateThread({
|
|
372
|
+
id,
|
|
373
|
+
title,
|
|
374
|
+
metadata
|
|
375
|
+
}) {
|
|
376
|
+
try {
|
|
377
|
+
const existingThread = await this.getThreadById({ threadId: id });
|
|
378
|
+
if (!existingThread) {
|
|
379
|
+
throw new Error(`Thread ${id} not found`);
|
|
380
|
+
}
|
|
381
|
+
const mergedMetadata = {
|
|
382
|
+
...existingThread.metadata,
|
|
383
|
+
...metadata
|
|
384
|
+
};
|
|
385
|
+
const updatedThread = {
|
|
386
|
+
...existingThread,
|
|
387
|
+
title,
|
|
388
|
+
metadata: mergedMetadata,
|
|
389
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
390
|
+
};
|
|
391
|
+
await this.db.insert({
|
|
392
|
+
table: storage.TABLE_THREADS,
|
|
393
|
+
values: [
|
|
394
|
+
{
|
|
395
|
+
...updatedThread,
|
|
396
|
+
updatedAt: updatedThread.updatedAt.toISOString()
|
|
397
|
+
}
|
|
398
|
+
],
|
|
399
|
+
format: "JSONEachRow",
|
|
400
|
+
clickhouse_settings: {
|
|
401
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
402
|
+
date_time_input_format: "best_effort",
|
|
403
|
+
use_client_time_zone: 1,
|
|
404
|
+
output_format_json_quote_64bit_integers: 0
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
return updatedThread;
|
|
408
|
+
} catch (error) {
|
|
409
|
+
console.error("Error updating thread:", error);
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
async deleteThread({ threadId }) {
|
|
414
|
+
try {
|
|
415
|
+
await this.db.command({
|
|
416
|
+
query: `DELETE FROM "${storage.TABLE_MESSAGES}" WHERE thread_id = '${threadId}';`,
|
|
417
|
+
query_params: { var_thread_id: threadId },
|
|
418
|
+
clickhouse_settings: {
|
|
419
|
+
output_format_json_quote_64bit_integers: 0
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
await this.db.command({
|
|
423
|
+
query: `DELETE FROM "${storage.TABLE_THREADS}" WHERE id = {var_id:String};`,
|
|
424
|
+
query_params: { var_id: threadId },
|
|
425
|
+
clickhouse_settings: {
|
|
426
|
+
output_format_json_quote_64bit_integers: 0
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
} catch (error) {
|
|
430
|
+
console.error("Error deleting thread:", error);
|
|
431
|
+
throw error;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
async getMessages({ threadId, selectBy }) {
|
|
435
|
+
try {
|
|
436
|
+
const messages = [];
|
|
437
|
+
const limit = typeof selectBy?.last === `number` ? selectBy.last : 40;
|
|
438
|
+
const include = selectBy?.include || [];
|
|
439
|
+
if (include.length) {
|
|
440
|
+
const includeResult = await this.db.query({
|
|
441
|
+
query: `
|
|
442
|
+
WITH ordered_messages AS (
|
|
443
|
+
SELECT
|
|
444
|
+
*,
|
|
445
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
446
|
+
toDateTime64(updatedAt, 3) as updatedAt,
|
|
447
|
+
ROW_NUMBER() OVER (ORDER BY "createdAt" DESC) as row_num
|
|
448
|
+
FROM "${storage.TABLE_MESSAGES}"
|
|
449
|
+
WHERE thread_id = {var_thread_id:String}
|
|
450
|
+
)
|
|
451
|
+
SELECT
|
|
452
|
+
m.id AS id,
|
|
453
|
+
m.content as content,
|
|
454
|
+
m.role as role,
|
|
455
|
+
m.type as type,
|
|
456
|
+
m.createdAt as createdAt,
|
|
457
|
+
m.updatedAt as updatedAt,
|
|
458
|
+
m.thread_id AS "threadId"
|
|
459
|
+
FROM ordered_messages m
|
|
460
|
+
WHERE m.id = ANY({var_include:Array(String)})
|
|
461
|
+
OR EXISTS (
|
|
462
|
+
SELECT 1 FROM ordered_messages target
|
|
463
|
+
WHERE target.id = ANY({var_include:Array(String)})
|
|
464
|
+
AND (
|
|
465
|
+
-- Get previous messages based on the max withPreviousMessages
|
|
466
|
+
(m.row_num <= target.row_num + {var_withPreviousMessages:Int64} AND m.row_num > target.row_num)
|
|
467
|
+
OR
|
|
468
|
+
-- Get next messages based on the max withNextMessages
|
|
469
|
+
(m.row_num >= target.row_num - {var_withNextMessages:Int64} AND m.row_num < target.row_num)
|
|
470
|
+
)
|
|
471
|
+
)
|
|
472
|
+
ORDER BY m."createdAt" DESC
|
|
473
|
+
`,
|
|
474
|
+
query_params: {
|
|
475
|
+
var_thread_id: threadId,
|
|
476
|
+
var_include: include.map((i) => i.id),
|
|
477
|
+
var_withPreviousMessages: Math.max(...include.map((i) => i.withPreviousMessages || 0)),
|
|
478
|
+
var_withNextMessages: Math.max(...include.map((i) => i.withNextMessages || 0))
|
|
479
|
+
},
|
|
480
|
+
clickhouse_settings: {
|
|
481
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
482
|
+
date_time_input_format: "best_effort",
|
|
483
|
+
date_time_output_format: "iso",
|
|
484
|
+
use_client_time_zone: 1,
|
|
485
|
+
output_format_json_quote_64bit_integers: 0
|
|
486
|
+
}
|
|
487
|
+
});
|
|
488
|
+
const rows2 = await includeResult.json();
|
|
489
|
+
messages.push(...transformRows(rows2.data));
|
|
490
|
+
}
|
|
491
|
+
const result = await this.db.query({
|
|
492
|
+
query: `
|
|
493
|
+
SELECT
|
|
494
|
+
id,
|
|
495
|
+
content,
|
|
496
|
+
role,
|
|
497
|
+
type,
|
|
498
|
+
toDateTime64(createdAt, 3) as createdAt,
|
|
499
|
+
thread_id AS "threadId"
|
|
500
|
+
FROM "${storage.TABLE_MESSAGES}"
|
|
501
|
+
WHERE thread_id = {threadId:String}
|
|
502
|
+
AND id NOT IN ({exclude:Array(String)})
|
|
503
|
+
ORDER BY "createdAt" DESC
|
|
504
|
+
LIMIT {limit:Int64}
|
|
505
|
+
`,
|
|
506
|
+
query_params: {
|
|
507
|
+
threadId,
|
|
508
|
+
exclude: messages.map((m) => m.id),
|
|
509
|
+
limit
|
|
510
|
+
},
|
|
511
|
+
clickhouse_settings: {
|
|
512
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
513
|
+
date_time_input_format: "best_effort",
|
|
514
|
+
date_time_output_format: "iso",
|
|
515
|
+
use_client_time_zone: 1,
|
|
516
|
+
output_format_json_quote_64bit_integers: 0
|
|
517
|
+
}
|
|
518
|
+
});
|
|
519
|
+
const rows = await result.json();
|
|
520
|
+
messages.push(...transformRows(rows.data));
|
|
521
|
+
messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
522
|
+
messages.forEach((message) => {
|
|
523
|
+
if (typeof message.content === "string") {
|
|
524
|
+
try {
|
|
525
|
+
message.content = JSON.parse(message.content);
|
|
526
|
+
} catch {
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
return messages;
|
|
531
|
+
} catch (error) {
|
|
532
|
+
console.error("Error getting messages:", error);
|
|
533
|
+
throw error;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
async saveMessages({ messages }) {
|
|
537
|
+
if (messages.length === 0) return messages;
|
|
538
|
+
try {
|
|
539
|
+
const threadId = messages[0]?.threadId;
|
|
540
|
+
if (!threadId) {
|
|
541
|
+
throw new Error("Thread ID is required");
|
|
542
|
+
}
|
|
543
|
+
const thread = await this.getThreadById({ threadId });
|
|
544
|
+
if (!thread) {
|
|
545
|
+
throw new Error(`Thread ${threadId} not found`);
|
|
546
|
+
}
|
|
547
|
+
await this.db.insert({
|
|
548
|
+
table: storage.TABLE_MESSAGES,
|
|
549
|
+
format: "JSONEachRow",
|
|
550
|
+
values: messages.map((message) => ({
|
|
551
|
+
id: message.id,
|
|
552
|
+
thread_id: threadId,
|
|
553
|
+
content: typeof message.content === "string" ? message.content : JSON.stringify(message.content),
|
|
554
|
+
createdAt: message.createdAt.toISOString(),
|
|
555
|
+
role: message.role,
|
|
556
|
+
type: message.type
|
|
557
|
+
})),
|
|
558
|
+
clickhouse_settings: {
|
|
559
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
560
|
+
date_time_input_format: "best_effort",
|
|
561
|
+
use_client_time_zone: 1,
|
|
562
|
+
output_format_json_quote_64bit_integers: 0
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
return messages;
|
|
566
|
+
} catch (error) {
|
|
567
|
+
console.error("Error saving messages:", error);
|
|
568
|
+
throw error;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
async persistWorkflowSnapshot({
|
|
572
|
+
workflowName,
|
|
573
|
+
runId,
|
|
574
|
+
snapshot
|
|
575
|
+
}) {
|
|
576
|
+
try {
|
|
577
|
+
const currentSnapshot = await this.load({
|
|
578
|
+
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
579
|
+
keys: { workflow_name: workflowName, run_id: runId }
|
|
580
|
+
});
|
|
581
|
+
const now = /* @__PURE__ */ new Date();
|
|
582
|
+
const persisting = currentSnapshot ? {
|
|
583
|
+
...currentSnapshot,
|
|
584
|
+
snapshot: JSON.stringify(snapshot),
|
|
585
|
+
updatedAt: now.toISOString()
|
|
586
|
+
} : {
|
|
587
|
+
workflow_name: workflowName,
|
|
588
|
+
run_id: runId,
|
|
589
|
+
snapshot: JSON.stringify(snapshot),
|
|
590
|
+
createdAt: now.toISOString(),
|
|
591
|
+
updatedAt: now.toISOString()
|
|
592
|
+
};
|
|
593
|
+
await this.db.insert({
|
|
594
|
+
table: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
595
|
+
format: "JSONEachRow",
|
|
596
|
+
values: [persisting],
|
|
597
|
+
clickhouse_settings: {
|
|
598
|
+
// Allows to insert serialized JS Dates (such as '2023-12-06T10:54:48.000Z')
|
|
599
|
+
date_time_input_format: "best_effort",
|
|
600
|
+
use_client_time_zone: 1,
|
|
601
|
+
output_format_json_quote_64bit_integers: 0
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
} catch (error) {
|
|
605
|
+
console.error("Error persisting workflow snapshot:", error);
|
|
606
|
+
throw error;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
async loadWorkflowSnapshot({
|
|
610
|
+
workflowName,
|
|
611
|
+
runId
|
|
612
|
+
}) {
|
|
613
|
+
try {
|
|
614
|
+
const result = await this.load({
|
|
615
|
+
tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
|
|
616
|
+
keys: {
|
|
617
|
+
workflow_name: workflowName,
|
|
618
|
+
run_id: runId
|
|
619
|
+
}
|
|
620
|
+
});
|
|
621
|
+
if (!result) {
|
|
622
|
+
return null;
|
|
623
|
+
}
|
|
624
|
+
return result.snapshot;
|
|
625
|
+
} catch (error) {
|
|
626
|
+
console.error("Error loading workflow snapshot:", error);
|
|
627
|
+
throw error;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
async close() {
|
|
631
|
+
await this.db.close();
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
|
|
635
|
+
exports.ClickhouseStore = ClickhouseStore;
|
package/dist/index.d.cts
ADDED
package/dist/index.d.ts
ADDED