@axiom-lattice/gateway 1.0.11

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/index.mjs ADDED
@@ -0,0 +1,659 @@
1
+ // src/index.ts
2
+ import fastify from "fastify";
3
+ import cors from "@fastify/cors";
4
+ import sensible from "@fastify/sensible";
5
+
6
+ // src/services/agent_service.ts
7
+ import {
8
+ filterMessages,
9
+ HumanMessage
10
+ } from "@langchain/core/messages";
11
+ import { Command } from "@langchain/langgraph";
12
+ import { v4 } from "uuid";
13
+ import { getAgentClient, getAgentLattice } from "@axiom-lattice/core";
14
+ async function agent_invoke({
15
+ input,
16
+ thread_id,
17
+ assistant_id,
18
+ tenant_id,
19
+ command,
20
+ run_id
21
+ }) {
22
+ const runnable_agent = getAgentLattice(assistant_id)?.client;
23
+ const { files, message, ...rest } = input;
24
+ const humanMessage = new HumanMessage(message || "");
25
+ humanMessage.additional_kwargs = { files };
26
+ const messages = [humanMessage];
27
+ if (!runnable_agent) {
28
+ throw new Error(`Agent ${assistant_id} not found`);
29
+ }
30
+ const result = await runnable_agent.invoke(
31
+ command ? new Command(command) : { ...rest, messages, "x-tenant-id": tenant_id },
32
+ {
33
+ configurable: {
34
+ thread_id,
35
+ run_id: run_id || v4(),
36
+ recursionLimit: 200,
37
+ "x-tenant-id": tenant_id,
38
+ "x-request-id": run_id,
39
+ "x-thread-id": thread_id
40
+ }
41
+ }
42
+ );
43
+ return result;
44
+ }
45
+ async function agent_stream({
46
+ input,
47
+ thread_id,
48
+ command,
49
+ tenant_id,
50
+ assistant_id,
51
+ run_id
52
+ }) {
53
+ const runnable_agent = getAgentClient(assistant_id);
54
+ const { files, message, ...rest } = input;
55
+ let messages = [];
56
+ if (!command) {
57
+ const humanMessage = new HumanMessage(message);
58
+ humanMessage.additional_kwargs = { files };
59
+ messages = [humanMessage];
60
+ }
61
+ try {
62
+ if (!runnable_agent) {
63
+ throw new Error(`Agent ${assistant_id} not found`);
64
+ }
65
+ const agentStream = await runnable_agent.stream(
66
+ command ? new Command(command) : {
67
+ ...rest,
68
+ messages,
69
+ "x-tenant-id": tenant_id
70
+ },
71
+ {
72
+ configurable: {
73
+ thread_id,
74
+ run_id: run_id || v4(),
75
+ "x-tenant-id": tenant_id,
76
+ "x-request-id": run_id,
77
+ "x-thread-id": thread_id
78
+ },
79
+ streamMode: ["updates", "messages"],
80
+ subgraphs: false
81
+ }
82
+ );
83
+ return {
84
+ [Symbol.asyncIterator]: async function* () {
85
+ try {
86
+ for await (const chunk of agentStream) {
87
+ let data;
88
+ if (chunk[0] === "updates") {
89
+ const update = chunk[1];
90
+ const values = Object.values(update);
91
+ const messages2 = values[0].messages;
92
+ if (messages2?.[0]?.tool_call_id) {
93
+ data = messages2[0].toDict();
94
+ }
95
+ } else if (chunk[0] === "messages") {
96
+ const messages2 = chunk[1];
97
+ data = messages2?.[0]?.toDict();
98
+ }
99
+ if (chunk?.[1]?.__interrupt__) {
100
+ data = chunk?.[1]?.[0]?.toDict();
101
+ }
102
+ if (data) {
103
+ yield data;
104
+ }
105
+ }
106
+ } catch (error) {
107
+ console.error("Stream error:", error);
108
+ throw error;
109
+ }
110
+ }
111
+ };
112
+ } catch (error) {
113
+ throw error;
114
+ }
115
+ }
116
+ async function agent_state({
117
+ thread_id,
118
+ assistant_id
119
+ }) {
120
+ const runnable_agent = getAgentClient(assistant_id);
121
+ if (!runnable_agent) {
122
+ throw new Error(`Agent ${assistant_id} not found`);
123
+ }
124
+ const state = await runnable_agent.getState({
125
+ configurable: { thread_id, subgraphs: false }
126
+ });
127
+ return state;
128
+ }
129
+ async function agent_messages({
130
+ thread_id,
131
+ tenant_id,
132
+ assistant_id
133
+ }) {
134
+ const runnable_agent = getAgentClient(assistant_id);
135
+ if (!runnable_agent) {
136
+ throw new Error(`Agent ${assistant_id} not found`);
137
+ }
138
+ const state = await runnable_agent.getState({
139
+ configurable: { thread_id, subgraphs: false }
140
+ });
141
+ const messages = state.values.messages || [];
142
+ const filteredMessages = filterMessages(messages, {
143
+ includeTypes: ["ai", "human", "tool"]
144
+ //["human", "ai", "tool"],
145
+ });
146
+ let messagesArray = filteredMessages.map((message) => ({
147
+ id: message.id,
148
+ role: message.getType(),
149
+ content: message.content,
150
+ files: message.additional_kwargs.files,
151
+ ...message.lc_kwargs
152
+ }));
153
+ const action_messages = state.tasks.flatMap((task) => {
154
+ return task.interrupts.map((interrupt) => {
155
+ return {
156
+ role: "ai",
157
+ content: interrupt.value,
158
+ type: "action"
159
+ };
160
+ });
161
+ });
162
+ const new_messages = [...messagesArray, ...action_messages];
163
+ return new_messages;
164
+ }
165
+ async function draw_graph(assistant_id) {
166
+ const runnable_agent = getAgentClient(assistant_id);
167
+ if (!runnable_agent) {
168
+ throw new Error(`Agent ${assistant_id} not found`);
169
+ }
170
+ const drawableGraph = await runnable_agent.getGraphAsync();
171
+ const image = await drawableGraph.drawMermaid();
172
+ return image;
173
+ }
174
+
175
+ // src/controllers/run.ts
176
+ import { v4 as v42 } from "uuid";
177
+ var createRun = async (request, reply) => {
178
+ try {
179
+ const {
180
+ assistant_id,
181
+ thread_id,
182
+ command,
183
+ streaming,
184
+ background,
185
+ ...input
186
+ } = request.body;
187
+ const tenant_id = request.headers["x-tenant-id"];
188
+ const x_request_id = request.headers["x-request-id"] || v42();
189
+ if (!assistant_id) {
190
+ reply.status(400).send({
191
+ success: false,
192
+ error: "\u52A9\u624BID\u662F\u5FC5\u9700\u7684"
193
+ });
194
+ return;
195
+ }
196
+ if (streaming) {
197
+ const stream = await agent_stream({
198
+ assistant_id,
199
+ input,
200
+ thread_id,
201
+ command,
202
+ tenant_id,
203
+ run_id: x_request_id
204
+ });
205
+ reply.raw.writeHead(200, {
206
+ "Content-Type": "text/event-stream",
207
+ "Cache-Control": "no-cache",
208
+ Connection: "keep-alive",
209
+ "Access-Control-Allow-Origin": "*"
210
+ });
211
+ try {
212
+ for await (const chunk of stream) {
213
+ reply.raw.write(`data: ${JSON.stringify(chunk)}
214
+
215
+ `);
216
+ }
217
+ } catch (error) {
218
+ } finally {
219
+ reply.raw.end();
220
+ return reply.hijack();
221
+ }
222
+ } else {
223
+ const result = await agent_invoke({
224
+ assistant_id,
225
+ input,
226
+ command,
227
+ thread_id,
228
+ tenant_id,
229
+ run_id: x_request_id
230
+ });
231
+ reply.status(200).send(result);
232
+ }
233
+ } catch (error) {
234
+ reply.status(500).send({
235
+ success: false,
236
+ error: `\u521B\u5EFA\u8FD0\u884C\u65F6\u53D1\u751F\u9519\u8BEF: ${error.message}`
237
+ });
238
+ }
239
+ };
240
+
241
+ // src/controllers/memory.ts
242
+ var setMemoryItem = async (request, reply) => {
243
+ try {
244
+ const { assistantId, key } = request.params;
245
+ const value = request.body;
246
+ if (!assistantId || !key) {
247
+ reply.status(400).send({
248
+ success: false,
249
+ error: "\u52A9\u624BID\u548C\u952E\u662F\u5FC5\u9700\u7684"
250
+ });
251
+ return;
252
+ }
253
+ if (value === void 0) {
254
+ reply.status(400).send({
255
+ success: false,
256
+ error: "\u503C\u662F\u5FC5\u9700\u7684"
257
+ });
258
+ return;
259
+ }
260
+ reply.status(500).send();
261
+ return;
262
+ } catch (error) {
263
+ reply.status(500).send({
264
+ success: false,
265
+ error: `\u8BBE\u7F6E\u5185\u5B58\u9879\u65F6\u53D1\u751F\u9519\u8BEF: ${error.message}`
266
+ });
267
+ }
268
+ };
269
+ var getMemoryItem = async (request, reply) => {
270
+ try {
271
+ const { assistantId, key } = request.params;
272
+ if (!assistantId || !key) {
273
+ reply.status(400).send({
274
+ success: false,
275
+ error: "\u52A9\u624BID\u548C\u952E\u662F\u5FC5\u9700\u7684"
276
+ });
277
+ return;
278
+ }
279
+ reply.status(404).send();
280
+ return;
281
+ } catch (error) {
282
+ reply.status(500).send({
283
+ success: false,
284
+ error: `\u83B7\u53D6\u5185\u5B58\u9879\u65F6\u53D1\u751F\u9519\u8BEF: ${error.message}`
285
+ });
286
+ }
287
+ };
288
+ var getAllMemoryItems = async (request, reply) => {
289
+ try {
290
+ const { assistantId, thread_id } = request.params;
291
+ const tenant_id = request.headers["x-tenant-id"];
292
+ if (!thread_id) {
293
+ reply.status(400).send({
294
+ success: false,
295
+ error: "\u7EBF\u7A0BID\u662F\u5FC5\u9700\u7684"
296
+ });
297
+ return;
298
+ }
299
+ if (!assistantId) {
300
+ reply.status(400).send({
301
+ success: false,
302
+ error: "\u52A9\u624BID\u662F\u5FC5\u9700\u7684"
303
+ });
304
+ return;
305
+ }
306
+ const result = await agent_messages({
307
+ assistant_id: assistantId,
308
+ thread_id,
309
+ tenant_id
310
+ });
311
+ if (!result) {
312
+ reply.status(500).send(result);
313
+ return;
314
+ }
315
+ reply.send(result);
316
+ } catch (error) {
317
+ reply.status(500).send({
318
+ success: false,
319
+ error: `\u83B7\u53D6\u6240\u6709\u5185\u5B58\u9879\u65F6\u53D1\u751F\u9519\u8BEF: ${error.message}`
320
+ });
321
+ }
322
+ };
323
+ var getAgentState = async (request, reply) => {
324
+ try {
325
+ const { assistantId, thread_id } = request.params;
326
+ if (!thread_id) {
327
+ reply.status(400).send({
328
+ success: false,
329
+ error: "\u7EBF\u7A0BID\u662F\u5FC5\u9700\u7684"
330
+ });
331
+ return;
332
+ }
333
+ if (!assistantId) {
334
+ reply.status(400).send({
335
+ success: false,
336
+ error: "\u52A9\u624BID\u662F\u5FC5\u9700\u7684"
337
+ });
338
+ return;
339
+ }
340
+ const result = await agent_state({
341
+ assistant_id: assistantId,
342
+ thread_id
343
+ });
344
+ if (!result) {
345
+ reply.status(500).send(result);
346
+ return;
347
+ }
348
+ reply.send(result);
349
+ } catch (error) {
350
+ reply.status(500).send({
351
+ success: false,
352
+ error: `\u83B7\u53D6\u52A9\u624B\u72B6\u6001\u65F6\u53D1\u751F\u9519\u8BEF: ${error.message}`
353
+ });
354
+ }
355
+ };
356
+ var deleteMemoryItem = async (request, reply) => {
357
+ try {
358
+ const { assistantId, key } = request.params;
359
+ if (!assistantId || !key) {
360
+ reply.status(400).send({
361
+ success: false,
362
+ error: "\u52A9\u624BID\u548C\u952E\u662F\u5FC5\u9700\u7684"
363
+ });
364
+ return;
365
+ }
366
+ reply.status(500).send();
367
+ return;
368
+ reply.status(204).send();
369
+ } catch (error) {
370
+ reply.status(500).send({
371
+ success: false,
372
+ error: `\u5220\u9664\u5185\u5B58\u9879\u65F6\u53D1\u751F\u9519\u8BEF: ${error.message}`
373
+ });
374
+ }
375
+ };
376
+ var clearMemory = async (request, reply) => {
377
+ try {
378
+ const { assistantId } = request.params;
379
+ if (!assistantId) {
380
+ reply.status(400).send({
381
+ success: false,
382
+ error: "\u52A9\u624BID\u662F\u5FC5\u9700\u7684"
383
+ });
384
+ return;
385
+ }
386
+ let result;
387
+ if (!result.success) {
388
+ reply.status(500).send(result);
389
+ return;
390
+ }
391
+ reply.status(204).send();
392
+ } catch (error) {
393
+ reply.status(500).send({
394
+ success: false,
395
+ error: `\u6E05\u9664\u5185\u5B58\u65F6\u53D1\u751F\u9519\u8BEF: ${error.message}`
396
+ });
397
+ }
398
+ };
399
+
400
+ // src/controllers/assistant.ts
401
+ var getAgentGraph = async (request, reply) => {
402
+ try {
403
+ const { assistantId } = request.params;
404
+ const imageData = await draw_graph(assistantId);
405
+ reply.header("Content-Type", "application/json").send({
406
+ image: imageData
407
+ });
408
+ } catch (error) {
409
+ reply.status(500).send({
410
+ success: false,
411
+ error: error.message || "\u83B7\u53D6\u4EE3\u7406\u56FE\u8868\u5931\u8D25"
412
+ });
413
+ }
414
+ };
415
+
416
+ // src/routes/index.ts
417
+ var registerRoutes = (app2) => {
418
+ app2.post("/api/runs", createRun);
419
+ app2.get(
420
+ "/api/assistants/:assistantId/:thread_id/memory",
421
+ getAllMemoryItems
422
+ );
423
+ app2.get(
424
+ "/api/assistants/:assistantId/:thread_id/state",
425
+ getAgentState
426
+ );
427
+ app2.get(
428
+ "/api/assistants/:assistantId/memory/:key",
429
+ getMemoryItem
430
+ );
431
+ app2.put(
432
+ "/api/assistants/:assistantId/memory/:key",
433
+ setMemoryItem
434
+ );
435
+ app2.delete(
436
+ "/api/assistants/:assistantId/memory/:key",
437
+ deleteMemoryItem
438
+ );
439
+ app2.delete("/api/assistants/:assistantId/memory", clearMemory);
440
+ app2.get("/api/assistants/:assistantId/graph", getAgentGraph);
441
+ };
442
+
443
+ // src/logger/Logger.ts
444
+ import pino from "pino";
445
+ import "pino-pretty";
446
+ import "pino-roll";
447
+ var PinoLoggerFactory = class _PinoLoggerFactory {
448
+ constructor() {
449
+ const isProd = process.env.NODE_ENV === "production";
450
+ const loggerConfig = {
451
+ // 自定义时间戳格式
452
+ timestamp: () => `,"@timestamp":"${(/* @__PURE__ */ new Date()).toISOString()}"`,
453
+ // 关闭默认的时间戳键
454
+ base: {
455
+ "@version": "1",
456
+ app_name: "lattice",
457
+ service_name: "lattice/graph-server",
458
+ thread_name: "main",
459
+ logger_name: "lattice-graph-logger"
460
+ },
461
+ formatters: {
462
+ level: (label, number) => {
463
+ return {
464
+ level: label.toUpperCase(),
465
+ level_value: number * 1e3
466
+ };
467
+ }
468
+ }
469
+ };
470
+ if (isProd) {
471
+ try {
472
+ this.pinoLogger = pino(
473
+ loggerConfig,
474
+ pino.transport({
475
+ target: "pino-roll",
476
+ options: {
477
+ file: "./logs/fin_ai_graph_server",
478
+ frequency: "daily",
479
+ mkdir: true
480
+ }
481
+ })
482
+ );
483
+ } catch (error) {
484
+ console.error(
485
+ "\u65E0\u6CD5\u521D\u59CB\u5316 pino-roll \u65E5\u5FD7\u8BB0\u5F55\u5668\uFF0C\u56DE\u9000\u5230\u63A7\u5236\u53F0\u65E5\u5FD7",
486
+ error
487
+ );
488
+ this.pinoLogger = pino({
489
+ ...loggerConfig,
490
+ transport: {
491
+ target: "pino-pretty",
492
+ options: {
493
+ colorize: true
494
+ }
495
+ }
496
+ });
497
+ }
498
+ } else {
499
+ this.pinoLogger = pino({
500
+ ...loggerConfig,
501
+ transport: {
502
+ target: "pino-pretty",
503
+ options: {
504
+ colorize: true
505
+ }
506
+ }
507
+ });
508
+ }
509
+ }
510
+ static getInstance() {
511
+ if (!_PinoLoggerFactory.instance) {
512
+ _PinoLoggerFactory.instance = new _PinoLoggerFactory();
513
+ }
514
+ return _PinoLoggerFactory.instance;
515
+ }
516
+ getPinoLogger() {
517
+ return this.pinoLogger;
518
+ }
519
+ };
520
+ var Logger = class _Logger {
521
+ constructor(options) {
522
+ this.context = options?.context || {};
523
+ this.name = options?.name || "lattice-graph-logger";
524
+ this.serviceName = options?.serviceName || "lattice/graph-server";
525
+ }
526
+ /**
527
+ * 获取合并了上下文的日志对象
528
+ * @param additionalContext 额外的上下文数据
529
+ * @returns 带有上下文的pino日志对象
530
+ */
531
+ getContextualLogger(additionalContext) {
532
+ const pinoLogger = PinoLoggerFactory.getInstance().getPinoLogger();
533
+ const contextObj = {
534
+ "x-user-id": this.context["x-user-id"] || "",
535
+ "x-tenant-id": this.context["x-tenant-id"] || "",
536
+ "x-request-id": this.context["x-request-id"] || "",
537
+ "x-task-id": this.context["x-task-id"] || "",
538
+ "x-thread-id": this.context["x-thread-id"] || "",
539
+ service_name: this.serviceName,
540
+ logger_name: this.name,
541
+ ...additionalContext
542
+ };
543
+ return pinoLogger.child(contextObj);
544
+ }
545
+ info(msg, obj) {
546
+ this.getContextualLogger(obj).info(msg);
547
+ }
548
+ error(msg, obj) {
549
+ this.getContextualLogger(obj).error(msg);
550
+ }
551
+ warn(msg, obj) {
552
+ this.getContextualLogger(obj).warn(msg);
553
+ }
554
+ debug(msg, obj) {
555
+ this.getContextualLogger(obj).debug(msg);
556
+ }
557
+ /**
558
+ * 更新Logger实例的上下文
559
+ */
560
+ updateContext(context) {
561
+ this.context = {
562
+ ...this.context,
563
+ ...context
564
+ };
565
+ }
566
+ /**
567
+ * 创建一个新的Logger实例,继承当前Logger的上下文
568
+ */
569
+ child(options) {
570
+ return new _Logger({
571
+ name: options.name || this.name,
572
+ serviceName: options.serviceName || this.serviceName,
573
+ context: {
574
+ ...this.context,
575
+ ...options.context
576
+ }
577
+ });
578
+ }
579
+ };
580
+
581
+ // src/index.ts
582
+ process.on("unhandledRejection", (reason, promise) => {
583
+ console.error("\u672A\u5904\u7406\u7684Promise\u62D2\u7EDD:", reason);
584
+ });
585
+ var logger = new Logger({
586
+ serviceName: "lattice-gateway",
587
+ name: "fastify-server"
588
+ });
589
+ var app = fastify({
590
+ logger: false
591
+ // 禁用内置日志记录器
592
+ });
593
+ app.addHook("onRequest", (request, reply, done) => {
594
+ const context = {
595
+ "x-tenant-id": request.headers["x-tenant-id"],
596
+ "x-request-id": request.headers["x-request-id"]
597
+ };
598
+ done();
599
+ });
600
+ app.addHook("onResponse", (request, reply, done) => {
601
+ const context = {
602
+ "x-tenant-id": request.headers["x-tenant-id"],
603
+ "x-request-id": request.headers["x-request-id"]
604
+ };
605
+ done();
606
+ });
607
+ app.register(cors, {
608
+ origin: true,
609
+ methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
610
+ allowedHeaders: [
611
+ "Content-Type",
612
+ "Authorization",
613
+ "X-Requested-With",
614
+ "x-tenant-id",
615
+ "x-request-id"
616
+ ],
617
+ exposedHeaders: ["Content-Type"],
618
+ credentials: true
619
+ });
620
+ app.register(sensible);
621
+ app.setErrorHandler((error, request, reply) => {
622
+ const context = {
623
+ "x-tenant-id": request.headers["x-tenant-id"],
624
+ "x-request-id": request.headers["x-request-id"]
625
+ };
626
+ logger.error(
627
+ `\u8BF7\u6C42\u9519\u8BEF: ${request.method} ${request.url} error:${error.message}`,
628
+ {
629
+ ...context,
630
+ error: error.message,
631
+ stack: error.stack,
632
+ statusCode: error.statusCode || 500
633
+ }
634
+ );
635
+ reply.status(error.statusCode || 500).send({
636
+ success: false,
637
+ error: error.message || "\u670D\u52A1\u5668\u5185\u90E8\u9519\u8BEF"
638
+ });
639
+ });
640
+ app.decorate("logger", logger);
641
+ registerRoutes(app);
642
+ var start = async ({ port }) => {
643
+ try {
644
+ const target_port = port || Number(process.env.PORT) || 4001;
645
+ await app.listen({ port: target_port, host: "0.0.0.0" });
646
+ logger.info(`Lattice Gateway is running on port: ${port}`);
647
+ } catch (err) {
648
+ logger.error("Server start failed", { error: err });
649
+ process.exit(1);
650
+ }
651
+ };
652
+ var LatticeGateway = {
653
+ startAsHttpEndpoint: start,
654
+ app
655
+ };
656
+ export {
657
+ LatticeGateway
658
+ };
659
+ //# sourceMappingURL=index.mjs.map