@axiom-lattice/gateway 2.1.3 → 2.1.5
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 +10 -10
- package/CHANGELOG.md +14 -0
- package/dist/index.d.mts +65 -4
- package/dist/index.d.ts +65 -4
- package/dist/index.js +606 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +612 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/controllers/agent_task.ts +65 -0
- package/src/index.ts +30 -4
- package/src/routes/index.ts +11 -0
- package/src/schemas/index.ts +53 -0
- package/src/services/AgentManager.ts +25 -21
- package/src/services/agent_task_consumer.ts +325 -0
- package/src/services/queue_service.ts +32 -71
- package/src/services/queue_service_memory.ts +85 -0
- package/src/services/queue_service_redis.ts +116 -0
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __export = (target, all) => {
|
|
3
|
+
for (var name in all)
|
|
4
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
5
|
+
};
|
|
6
|
+
|
|
1
7
|
// src/index.ts
|
|
2
8
|
import fastify from "fastify";
|
|
3
9
|
import cors from "@fastify/cors";
|
|
@@ -509,6 +515,305 @@ var getAgentGraph = async (request, reply) => {
|
|
|
509
515
|
}
|
|
510
516
|
};
|
|
511
517
|
|
|
518
|
+
// src/services/agent_task_types.ts
|
|
519
|
+
var AGENT_TASK_EVENT = "agent:execute";
|
|
520
|
+
|
|
521
|
+
// src/services/event_bus.ts
|
|
522
|
+
import { EventEmitter } from "events";
|
|
523
|
+
|
|
524
|
+
// src/services/queue_service_memory.ts
|
|
525
|
+
var queue_service_memory_exports = {};
|
|
526
|
+
__export(queue_service_memory_exports, {
|
|
527
|
+
popAgentTaskFromQueue: () => popAgentTaskFromQueue,
|
|
528
|
+
pushAgentTaskToQueue: () => pushAgentTaskToQueue
|
|
529
|
+
});
|
|
530
|
+
var queue_name = process.env.QUEUE_NAME || "tasks";
|
|
531
|
+
var queues = /* @__PURE__ */ new Map();
|
|
532
|
+
var ensureQueue = (queueName) => {
|
|
533
|
+
if (!queues.has(queueName)) {
|
|
534
|
+
queues.set(queueName, []);
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
var sendToQueue = async (queueName, message) => {
|
|
538
|
+
try {
|
|
539
|
+
ensureQueue(queueName);
|
|
540
|
+
const queue = queues.get(queueName);
|
|
541
|
+
queue.unshift(message);
|
|
542
|
+
const result = queue.length;
|
|
543
|
+
console.log("lPush (memory)", result);
|
|
544
|
+
return { data: result, error: null };
|
|
545
|
+
} catch (error) {
|
|
546
|
+
console.error(error);
|
|
547
|
+
return { data: null, error };
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
var popFromQueue = async (queueName) => {
|
|
551
|
+
try {
|
|
552
|
+
ensureQueue(queueName);
|
|
553
|
+
const queue = queues.get(queueName);
|
|
554
|
+
const message = queue.pop();
|
|
555
|
+
if (message) {
|
|
556
|
+
return { data: message, error: null };
|
|
557
|
+
}
|
|
558
|
+
return { data: null, error: null };
|
|
559
|
+
} catch (error) {
|
|
560
|
+
console.error(error);
|
|
561
|
+
return { data: null, error };
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
var createTenantQueue = async () => {
|
|
565
|
+
try {
|
|
566
|
+
ensureQueue(queue_name);
|
|
567
|
+
const queue = queues.get(queue_name);
|
|
568
|
+
const exists = queue !== void 0;
|
|
569
|
+
return { success: true, queue_name };
|
|
570
|
+
} catch (error) {
|
|
571
|
+
console.error(error);
|
|
572
|
+
return { success: false, error };
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
var pushAgentTaskToQueue = async (agentTask) => {
|
|
576
|
+
const tenantId = agentTask["x-tenant-id"];
|
|
577
|
+
try {
|
|
578
|
+
await createTenantQueue();
|
|
579
|
+
const result = await sendToQueue(`${queue_name}`, agentTask);
|
|
580
|
+
return result;
|
|
581
|
+
} catch (error) {
|
|
582
|
+
console.error(error);
|
|
583
|
+
return null;
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
var popAgentTaskFromQueue = async () => {
|
|
587
|
+
const result = await popFromQueue(`${queue_name}`);
|
|
588
|
+
return result;
|
|
589
|
+
};
|
|
590
|
+
|
|
591
|
+
// src/services/queue_service_redis.ts
|
|
592
|
+
var queue_service_redis_exports = {};
|
|
593
|
+
__export(queue_service_redis_exports, {
|
|
594
|
+
popAgentTaskFromQueue: () => popAgentTaskFromQueue2,
|
|
595
|
+
pushAgentTaskToQueue: () => pushAgentTaskToQueue2
|
|
596
|
+
});
|
|
597
|
+
import { createClient } from "redis";
|
|
598
|
+
var queue_name2 = process.env.QUEUE_NAME || "tasks";
|
|
599
|
+
var redisClient = null;
|
|
600
|
+
var isConnecting = false;
|
|
601
|
+
var connectionPromise = null;
|
|
602
|
+
var getRedisClient = async () => {
|
|
603
|
+
if (redisClient?.isOpen) {
|
|
604
|
+
return redisClient;
|
|
605
|
+
}
|
|
606
|
+
if (isConnecting && connectionPromise) {
|
|
607
|
+
await connectionPromise;
|
|
608
|
+
if (redisClient?.isOpen) {
|
|
609
|
+
return redisClient;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
isConnecting = true;
|
|
613
|
+
connectionPromise = (async () => {
|
|
614
|
+
try {
|
|
615
|
+
const redisOptions = {
|
|
616
|
+
url: process.env.REDIS_URL || "redis://localhost:6379",
|
|
617
|
+
password: process.env.REDIS_PASSWORD
|
|
618
|
+
};
|
|
619
|
+
redisClient = createClient(redisOptions);
|
|
620
|
+
redisClient.on(
|
|
621
|
+
"error",
|
|
622
|
+
(err) => console.error("Redis Client Error", err)
|
|
623
|
+
);
|
|
624
|
+
await redisClient.connect();
|
|
625
|
+
console.log("Redis connection successful");
|
|
626
|
+
isConnecting = false;
|
|
627
|
+
} catch (error) {
|
|
628
|
+
console.error("Redis connection failed:", error);
|
|
629
|
+
isConnecting = false;
|
|
630
|
+
throw error;
|
|
631
|
+
}
|
|
632
|
+
})();
|
|
633
|
+
await connectionPromise;
|
|
634
|
+
return redisClient;
|
|
635
|
+
};
|
|
636
|
+
var sendToQueue2 = async (queueName, message) => {
|
|
637
|
+
try {
|
|
638
|
+
const client = await getRedisClient();
|
|
639
|
+
const result = await client.lPush(queueName, JSON.stringify(message));
|
|
640
|
+
console.log("lPush", result);
|
|
641
|
+
return { data: result, error: null };
|
|
642
|
+
} catch (error) {
|
|
643
|
+
console.error(error);
|
|
644
|
+
return { data: null, error };
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
var popFromQueue2 = async (queueName) => {
|
|
648
|
+
try {
|
|
649
|
+
const client = await getRedisClient();
|
|
650
|
+
const message = await client.rPop(queueName);
|
|
651
|
+
if (message) {
|
|
652
|
+
return { data: JSON.parse(message), error: null };
|
|
653
|
+
}
|
|
654
|
+
return { data: null, error: null };
|
|
655
|
+
} catch (error) {
|
|
656
|
+
console.error(error);
|
|
657
|
+
return { data: null, error };
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
var createTenantQueue2 = async () => {
|
|
661
|
+
try {
|
|
662
|
+
const client = await getRedisClient();
|
|
663
|
+
const exists = await client.exists(queue_name2);
|
|
664
|
+
return { success: true, queue_name: queue_name2 };
|
|
665
|
+
} catch (error) {
|
|
666
|
+
console.error(error);
|
|
667
|
+
return { success: false, error };
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
var pushAgentTaskToQueue2 = async (agentTask) => {
|
|
671
|
+
const tenantId = agentTask["x-tenant-id"];
|
|
672
|
+
try {
|
|
673
|
+
await createTenantQueue2();
|
|
674
|
+
const result = await sendToQueue2(`${queue_name2}`, agentTask);
|
|
675
|
+
return result;
|
|
676
|
+
} catch (error) {
|
|
677
|
+
console.error(error);
|
|
678
|
+
return null;
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
var popAgentTaskFromQueue2 = async () => {
|
|
682
|
+
const result = await popFromQueue2(`${queue_name2}`);
|
|
683
|
+
return result;
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
// src/services/queue_service.ts
|
|
687
|
+
var queueServiceType = process.env.QUEUE_SERVICE_TYPE || "memory";
|
|
688
|
+
var setQueueServiceType = (type) => {
|
|
689
|
+
queueServiceType = type;
|
|
690
|
+
console.log(`Queue service type set to: ${type}`);
|
|
691
|
+
};
|
|
692
|
+
var getQueueService = () => {
|
|
693
|
+
return queueServiceType === "redis" ? queue_service_redis_exports : queue_service_memory_exports;
|
|
694
|
+
};
|
|
695
|
+
var pushAgentTaskToQueue3 = async (agentTask) => {
|
|
696
|
+
const service = getQueueService();
|
|
697
|
+
return service.pushAgentTaskToQueue(agentTask);
|
|
698
|
+
};
|
|
699
|
+
var popAgentTaskFromQueue3 = async () => {
|
|
700
|
+
const service = getQueueService();
|
|
701
|
+
return service.popAgentTaskFromQueue();
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
// src/services/event_bus.ts
|
|
705
|
+
var EventBus = class {
|
|
706
|
+
constructor() {
|
|
707
|
+
this.emitter = new EventEmitter();
|
|
708
|
+
this.emitter.setMaxListeners(100);
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* 发布事件
|
|
712
|
+
* @param eventName 事件名称
|
|
713
|
+
* @param data 事件数据
|
|
714
|
+
*/
|
|
715
|
+
publish(eventName, data, useQueue = false) {
|
|
716
|
+
if (useQueue) {
|
|
717
|
+
pushAgentTaskToQueue3(data);
|
|
718
|
+
} else {
|
|
719
|
+
this.emitter.emit(eventName, data);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* 订阅事件
|
|
724
|
+
* @param eventName 事件名称
|
|
725
|
+
* @param callback 回调函数
|
|
726
|
+
*/
|
|
727
|
+
subscribe(eventName, callback) {
|
|
728
|
+
this.emitter.on(eventName, callback);
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* 取消订阅事件
|
|
732
|
+
* @param eventName 事件名称
|
|
733
|
+
* @param callback 回调函数
|
|
734
|
+
*/
|
|
735
|
+
unsubscribe(eventName, callback) {
|
|
736
|
+
this.emitter.off(eventName, callback);
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* 只订阅一次事件
|
|
740
|
+
* @param eventName 事件名称
|
|
741
|
+
* @param callback 回调函数
|
|
742
|
+
*/
|
|
743
|
+
subscribeOnce(eventName, callback) {
|
|
744
|
+
this.emitter.once(eventName, callback);
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
var eventBus = new EventBus();
|
|
748
|
+
var event_bus_default = eventBus;
|
|
749
|
+
|
|
750
|
+
// src/services/AgentManager.ts
|
|
751
|
+
var AgentManager = class _AgentManager {
|
|
752
|
+
constructor() {
|
|
753
|
+
this.agents = [];
|
|
754
|
+
}
|
|
755
|
+
static getInstance() {
|
|
756
|
+
if (!_AgentManager.instance) {
|
|
757
|
+
_AgentManager.instance = new _AgentManager();
|
|
758
|
+
}
|
|
759
|
+
return _AgentManager.instance;
|
|
760
|
+
}
|
|
761
|
+
callAgentInQueue(queue) {
|
|
762
|
+
return new Promise((resolve, reject) => {
|
|
763
|
+
try {
|
|
764
|
+
event_bus_default.publish(
|
|
765
|
+
AGENT_TASK_EVENT,
|
|
766
|
+
{
|
|
767
|
+
...queue
|
|
768
|
+
},
|
|
769
|
+
true
|
|
770
|
+
);
|
|
771
|
+
resolve(true);
|
|
772
|
+
} catch (error) {
|
|
773
|
+
reject(error);
|
|
774
|
+
}
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
};
|
|
778
|
+
|
|
779
|
+
// src/controllers/agent_task.ts
|
|
780
|
+
var triggerAgentTask = async (request, reply) => {
|
|
781
|
+
try {
|
|
782
|
+
const { assistant_id, thread_id, input, command } = request.body;
|
|
783
|
+
const tenant_id = request.headers["x-tenant-id"];
|
|
784
|
+
if (!assistant_id) {
|
|
785
|
+
reply.status(400).send({
|
|
786
|
+
success: false,
|
|
787
|
+
error: "assistant_id is required"
|
|
788
|
+
});
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
if (!thread_id) {
|
|
792
|
+
reply.status(400).send({
|
|
793
|
+
success: false,
|
|
794
|
+
error: "thread_id is required"
|
|
795
|
+
});
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
const agentManager = AgentManager.getInstance();
|
|
799
|
+
const result = await agentManager.callAgentInQueue({
|
|
800
|
+
assistant_id,
|
|
801
|
+
thread_id,
|
|
802
|
+
input,
|
|
803
|
+
command,
|
|
804
|
+
"x-tenant-id": tenant_id
|
|
805
|
+
});
|
|
806
|
+
reply.status(200).send({
|
|
807
|
+
success: true
|
|
808
|
+
});
|
|
809
|
+
} catch (error) {
|
|
810
|
+
reply.status(500).send({
|
|
811
|
+
success: false,
|
|
812
|
+
error: `Failed to trigger agent task: ${error.message}`
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
|
|
512
817
|
// src/schemas/index.ts
|
|
513
818
|
var getAllMemoryItemsSchema = {
|
|
514
819
|
description: "Get all memory items for an assistant thread",
|
|
@@ -626,6 +931,57 @@ var getAgentGraphSchema = {
|
|
|
626
931
|
200: {}
|
|
627
932
|
}
|
|
628
933
|
};
|
|
934
|
+
var triggerAgentTaskSchema = {
|
|
935
|
+
description: "Trigger an agent task",
|
|
936
|
+
tags: ["Agent Tasks"],
|
|
937
|
+
summary: "Trigger Agent Task",
|
|
938
|
+
body: {
|
|
939
|
+
type: "object",
|
|
940
|
+
properties: {
|
|
941
|
+
assistant_id: {
|
|
942
|
+
type: "string",
|
|
943
|
+
description: "Assistant ID"
|
|
944
|
+
},
|
|
945
|
+
thread_id: {
|
|
946
|
+
type: "string",
|
|
947
|
+
description: "Thread ID"
|
|
948
|
+
},
|
|
949
|
+
input: {
|
|
950
|
+
type: "object",
|
|
951
|
+
description: "Task input data"
|
|
952
|
+
},
|
|
953
|
+
command: {
|
|
954
|
+
type: "object",
|
|
955
|
+
description: "Command data for the task",
|
|
956
|
+
nullable: true
|
|
957
|
+
}
|
|
958
|
+
},
|
|
959
|
+
required: ["assistant_id", "thread_id"]
|
|
960
|
+
},
|
|
961
|
+
response: {
|
|
962
|
+
200: {
|
|
963
|
+
type: "object",
|
|
964
|
+
properties: {
|
|
965
|
+
success: { type: "boolean" },
|
|
966
|
+
result: { type: "object" }
|
|
967
|
+
}
|
|
968
|
+
},
|
|
969
|
+
400: {
|
|
970
|
+
type: "object",
|
|
971
|
+
properties: {
|
|
972
|
+
success: { type: "boolean" },
|
|
973
|
+
error: { type: "string" }
|
|
974
|
+
}
|
|
975
|
+
},
|
|
976
|
+
500: {
|
|
977
|
+
type: "object",
|
|
978
|
+
properties: {
|
|
979
|
+
success: { type: "boolean" },
|
|
980
|
+
error: { type: "string" }
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
};
|
|
629
985
|
|
|
630
986
|
// src/routes/index.ts
|
|
631
987
|
var registerLatticeRoutes = (app2) => {
|
|
@@ -666,6 +1022,11 @@ var registerLatticeRoutes = (app2) => {
|
|
|
666
1022
|
{ schema: getAgentGraphSchema },
|
|
667
1023
|
getAgentGraph
|
|
668
1024
|
);
|
|
1025
|
+
app2.post(
|
|
1026
|
+
"/api/agent-tasks/trigger",
|
|
1027
|
+
{ schema: triggerAgentTaskSchema },
|
|
1028
|
+
triggerAgentTask
|
|
1029
|
+
);
|
|
669
1030
|
};
|
|
670
1031
|
|
|
671
1032
|
// src/logger/Logger.ts
|
|
@@ -868,6 +1229,244 @@ var configureSwagger = async (app2, customSwaggerConfig, customSwaggerUiConfig)
|
|
|
868
1229
|
await app2.register(swaggerUi, swaggerUiConfig);
|
|
869
1230
|
};
|
|
870
1231
|
|
|
1232
|
+
// src/services/agent_task_consumer.ts
|
|
1233
|
+
var handleAgentTask = async (taskRequest, retryCount = 0) => {
|
|
1234
|
+
const {
|
|
1235
|
+
assistant_id,
|
|
1236
|
+
input = {},
|
|
1237
|
+
thread_id,
|
|
1238
|
+
"x-tenant-id": tenant_id,
|
|
1239
|
+
command,
|
|
1240
|
+
callback_event
|
|
1241
|
+
} = taskRequest;
|
|
1242
|
+
try {
|
|
1243
|
+
console.log(
|
|
1244
|
+
`\u5F00\u59CB\u5904\u7406\u4EFB\u52A1 [assistant_id: ${assistant_id}, thread_id: ${thread_id}]`
|
|
1245
|
+
);
|
|
1246
|
+
const apiUrl = AgentTaskConsumer.agent_run_endpoint;
|
|
1247
|
+
console.log(`apiUrl: ${apiUrl}`);
|
|
1248
|
+
const response = await fetch(apiUrl, {
|
|
1249
|
+
method: "POST",
|
|
1250
|
+
body: JSON.stringify({
|
|
1251
|
+
assistant_id,
|
|
1252
|
+
streaming: true,
|
|
1253
|
+
...input,
|
|
1254
|
+
thread_id,
|
|
1255
|
+
command
|
|
1256
|
+
}),
|
|
1257
|
+
headers: {
|
|
1258
|
+
"Content-Type": "application/json",
|
|
1259
|
+
"x-tenant-id": tenant_id
|
|
1260
|
+
}
|
|
1261
|
+
}).catch((err) => {
|
|
1262
|
+
console.error(`fetch\u8BF7\u6C42\u5931\u8D25: ${err.message || String(err)}`);
|
|
1263
|
+
throw new Error(`fetch\u5931\u8D25: ${err.message || String(err)}`);
|
|
1264
|
+
});
|
|
1265
|
+
if (!response.ok) {
|
|
1266
|
+
throw new Error(`API\u8BF7\u6C42\u5931\u8D25: ${response.status} ${response.statusText}`);
|
|
1267
|
+
}
|
|
1268
|
+
if (callback_event) {
|
|
1269
|
+
event_bus_default.publish(callback_event, {
|
|
1270
|
+
success: true,
|
|
1271
|
+
config: { assistant_id, thread_id, tenant_id }
|
|
1272
|
+
});
|
|
1273
|
+
}
|
|
1274
|
+
console.log(
|
|
1275
|
+
`\u4EFB\u52A1\u5904\u7406\u6210\u529F [assistant_id: ${assistant_id}, thread_id: ${thread_id}]`
|
|
1276
|
+
);
|
|
1277
|
+
return true;
|
|
1278
|
+
} catch (error) {
|
|
1279
|
+
console.error(
|
|
1280
|
+
`Agent\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${assistant_id}, \u7EBF\u7A0B: ${thread_id}`,
|
|
1281
|
+
error
|
|
1282
|
+
);
|
|
1283
|
+
const maxRetries = 0;
|
|
1284
|
+
if (retryCount < maxRetries) {
|
|
1285
|
+
const nextRetryCount = retryCount + 1;
|
|
1286
|
+
const delayMs = Math.pow(2, nextRetryCount) * 1e3;
|
|
1287
|
+
console.log(
|
|
1288
|
+
`\u5C06\u5728 ${delayMs}ms \u540E\u91CD\u8BD5\u4EFB\u52A1 (${nextRetryCount}/${maxRetries})`
|
|
1289
|
+
);
|
|
1290
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
1291
|
+
return handleAgentTask(taskRequest, nextRetryCount);
|
|
1292
|
+
}
|
|
1293
|
+
if (callback_event) {
|
|
1294
|
+
event_bus_default.publish(callback_event, {
|
|
1295
|
+
success: false,
|
|
1296
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1297
|
+
config: { assistant_id, thread_id, tenant_id }
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
console.error(
|
|
1301
|
+
`\u4EFB\u52A1\u5904\u7406\u5931\u8D25\uFF0C\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570 [assistant_id: ${assistant_id}, thread_id: ${thread_id}]`
|
|
1302
|
+
);
|
|
1303
|
+
return false;
|
|
1304
|
+
}
|
|
1305
|
+
};
|
|
1306
|
+
var _AgentTaskConsumer = class _AgentTaskConsumer {
|
|
1307
|
+
constructor(gatewayPort, pollingIntervalMs) {
|
|
1308
|
+
this.isPolling = false;
|
|
1309
|
+
this.pollingInterval = null;
|
|
1310
|
+
this.pollingIntervalMs = 5e3;
|
|
1311
|
+
// 默认5秒轮询一次
|
|
1312
|
+
this.maxConcurrentTasks = 15;
|
|
1313
|
+
// 最大并发任务数
|
|
1314
|
+
this.activeTasks = 0;
|
|
1315
|
+
// 当前活跃的任务数
|
|
1316
|
+
this.processing = false;
|
|
1317
|
+
// 是否正在处理任务批次
|
|
1318
|
+
this.immediateProcessingEnabled = true;
|
|
1319
|
+
// 是否启用即时处理模式
|
|
1320
|
+
this.gatewayPort = 4001;
|
|
1321
|
+
this.gatewayPort = gatewayPort;
|
|
1322
|
+
_AgentTaskConsumer.agent_run_endpoint = `http://localhost:${this.gatewayPort}/api/runs`;
|
|
1323
|
+
if (pollingIntervalMs) {
|
|
1324
|
+
this.pollingIntervalMs = pollingIntervalMs;
|
|
1325
|
+
}
|
|
1326
|
+
this.initialize();
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* 初始化事件监听和队列轮询
|
|
1330
|
+
*/
|
|
1331
|
+
initialize() {
|
|
1332
|
+
event_bus_default.subscribe(AGENT_TASK_EVENT, this.trigger_agent_task.bind(this));
|
|
1333
|
+
this.startPollingQueue();
|
|
1334
|
+
console.log("Agent\u4EFB\u52A1\u6D88\u8D39\u8005\u5DF2\u542F\u52A8\u5E76\u76D1\u542C\u4EFB\u52A1\u4E8B\u4EF6\u548C\u961F\u5217");
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* 启动队列轮询
|
|
1338
|
+
*/
|
|
1339
|
+
startPollingQueue() {
|
|
1340
|
+
if (this.isPolling) {
|
|
1341
|
+
return;
|
|
1342
|
+
}
|
|
1343
|
+
this.isPolling = true;
|
|
1344
|
+
this.pollingInterval = setInterval(async () => {
|
|
1345
|
+
try {
|
|
1346
|
+
if (this.processing) {
|
|
1347
|
+
console.log("\u961F\u5217\u5904\u7406\u4E2D\uFF0C\u8DF3\u8FC7\u672C\u6B21\u8F6E\u8BE2");
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
await this.consumeFromQueue();
|
|
1351
|
+
} catch (error) {
|
|
1352
|
+
console.error("\u961F\u5217\u8F6E\u8BE2\u51FA\u9519:", error);
|
|
1353
|
+
}
|
|
1354
|
+
}, this.pollingIntervalMs);
|
|
1355
|
+
console.log(
|
|
1356
|
+
`\u5F00\u59CB\u8F6E\u8BE2\u961F\u5217\uFF0C\u95F4\u9694: ${this.pollingIntervalMs}ms\uFF0C\u6700\u5927\u5E76\u53D1\u4EFB\u52A1\u6570: ${this.maxConcurrentTasks}`
|
|
1357
|
+
);
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* 停止队列轮询
|
|
1361
|
+
*/
|
|
1362
|
+
stopPollingQueue() {
|
|
1363
|
+
if (this.pollingInterval) {
|
|
1364
|
+
clearInterval(this.pollingInterval);
|
|
1365
|
+
this.pollingInterval = null;
|
|
1366
|
+
this.isPolling = false;
|
|
1367
|
+
console.log("\u5DF2\u505C\u6B62\u961F\u5217\u8F6E\u8BE2");
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* 处理单个任务并在完成后立即尝试处理下一个
|
|
1372
|
+
*/
|
|
1373
|
+
async processNextTask() {
|
|
1374
|
+
try {
|
|
1375
|
+
const queueResult = await popAgentTaskFromQueue3();
|
|
1376
|
+
if (queueResult && queueResult.data) {
|
|
1377
|
+
const taskItem = queueResult.data;
|
|
1378
|
+
if (taskItem && typeof taskItem === "object") {
|
|
1379
|
+
const taskRequest = taskItem;
|
|
1380
|
+
console.log(
|
|
1381
|
+
`\u4ECE\u961F\u5217\u4E2D\u83B7\u53D6\u5230\u4EFB\u52A1 [assistant: ${taskRequest.assistant_id}, thread: ${taskRequest.thread_id}]`
|
|
1382
|
+
);
|
|
1383
|
+
this.activeTasks++;
|
|
1384
|
+
handleAgentTask(taskRequest).then((success) => {
|
|
1385
|
+
if (!success) {
|
|
1386
|
+
console.error(`\u4EFB\u52A1 \u5904\u7406\u5931\u8D25`);
|
|
1387
|
+
} else {
|
|
1388
|
+
console.log(`\u4EFB\u52A1 \u5904\u7406\u6210\u529F`);
|
|
1389
|
+
}
|
|
1390
|
+
}).catch((error) => {
|
|
1391
|
+
console.error(`\u4EFB\u52A1 \u5904\u7406\u65F6\u51FA\u9519:`, error);
|
|
1392
|
+
}).finally(() => {
|
|
1393
|
+
this.activeTasks--;
|
|
1394
|
+
if (this.immediateProcessingEnabled && !this.processing) {
|
|
1395
|
+
this.checkQueueForTasks();
|
|
1396
|
+
}
|
|
1397
|
+
});
|
|
1398
|
+
return true;
|
|
1399
|
+
} else {
|
|
1400
|
+
console.log("\u961F\u5217\u4EFB\u52A1\u683C\u5F0F\u65E0\u6548:", taskItem);
|
|
1401
|
+
return false;
|
|
1402
|
+
}
|
|
1403
|
+
} else {
|
|
1404
|
+
return false;
|
|
1405
|
+
}
|
|
1406
|
+
} catch (error) {
|
|
1407
|
+
console.error("\u5904\u7406\u4EFB\u52A1\u5931\u8D25:", error);
|
|
1408
|
+
return false;
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
/**
|
|
1412
|
+
* 检查队列中是否有任务并处理
|
|
1413
|
+
*/
|
|
1414
|
+
async checkQueueForTasks() {
|
|
1415
|
+
if (this.processing || this.activeTasks >= this.maxConcurrentTasks) {
|
|
1416
|
+
return;
|
|
1417
|
+
}
|
|
1418
|
+
this.processing = true;
|
|
1419
|
+
try {
|
|
1420
|
+
while (this.activeTasks < this.maxConcurrentTasks) {
|
|
1421
|
+
const taskProcessed = await this.processNextTask();
|
|
1422
|
+
if (!taskProcessed) {
|
|
1423
|
+
break;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
} catch (error) {
|
|
1427
|
+
console.error("\u68C0\u67E5\u961F\u5217\u4EFB\u52A1\u5931\u8D25:", error);
|
|
1428
|
+
} finally {
|
|
1429
|
+
this.processing = false;
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* 从队列中消费任务
|
|
1434
|
+
*/
|
|
1435
|
+
async consumeFromQueue() {
|
|
1436
|
+
if (this.processing) {
|
|
1437
|
+
return;
|
|
1438
|
+
}
|
|
1439
|
+
await this.checkQueueForTasks();
|
|
1440
|
+
}
|
|
1441
|
+
/**
|
|
1442
|
+
* 处理通过事件触发的任务
|
|
1443
|
+
*/
|
|
1444
|
+
trigger_agent_task(taskRequest) {
|
|
1445
|
+
console.log(
|
|
1446
|
+
`\u901A\u8FC7\u4E8B\u4EF6\u89E6\u53D1\u4EFB\u52A1: [assistant: ${taskRequest.assistant_id}, thread: ${taskRequest.thread_id}]`
|
|
1447
|
+
);
|
|
1448
|
+
handleAgentTask(taskRequest).catch((error) => {
|
|
1449
|
+
console.error("\u5904\u7406Agent\u4EFB\u52A1\u65F6\u53D1\u751F\u672A\u6355\u83B7\u7684\u9519\u8BEF:", error);
|
|
1450
|
+
if (taskRequest.callback_event) {
|
|
1451
|
+
event_bus_default.publish(taskRequest.callback_event, {
|
|
1452
|
+
success: false,
|
|
1453
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1454
|
+
config: {
|
|
1455
|
+
assistant_id: taskRequest.assistant_id,
|
|
1456
|
+
thread_id: taskRequest.thread_id,
|
|
1457
|
+
tenant_id: taskRequest["x-tenant-id"]
|
|
1458
|
+
}
|
|
1459
|
+
});
|
|
1460
|
+
}
|
|
1461
|
+
});
|
|
1462
|
+
if (this.immediateProcessingEnabled && this.activeTasks < this.maxConcurrentTasks) {
|
|
1463
|
+
setImmediate(() => this.checkQueueForTasks());
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
};
|
|
1467
|
+
_AgentTaskConsumer.agent_run_endpoint = "http://localhost:4001/api/runs";
|
|
1468
|
+
var AgentTaskConsumer = _AgentTaskConsumer;
|
|
1469
|
+
|
|
871
1470
|
// src/index.ts
|
|
872
1471
|
process.on("unhandledRejection", (reason, promise) => {
|
|
873
1472
|
console.error("\u672A\u5904\u7406\u7684Promise\u62D2\u7EDD:", reason);
|
|
@@ -928,11 +1527,19 @@ app.setErrorHandler((error, request, reply) => {
|
|
|
928
1527
|
});
|
|
929
1528
|
});
|
|
930
1529
|
app.decorate("logger", logger);
|
|
931
|
-
var start = async (
|
|
1530
|
+
var start = async (config) => {
|
|
932
1531
|
try {
|
|
933
|
-
const target_port = port || Number(process.env.PORT) || 4001;
|
|
1532
|
+
const target_port = config?.port || Number(process.env.PORT) || 4001;
|
|
934
1533
|
await app.listen({ port: target_port, host: "0.0.0.0" });
|
|
935
|
-
logger.info(`Lattice Gateway is running on port: ${
|
|
1534
|
+
logger.info(`Lattice Gateway is running on port: ${target_port}`);
|
|
1535
|
+
const queueServiceConfig = config?.queueServiceConfig;
|
|
1536
|
+
if (queueServiceConfig) {
|
|
1537
|
+
setQueueServiceType(queueServiceConfig.type);
|
|
1538
|
+
if (queueServiceConfig.defaultStartPollingQueue) {
|
|
1539
|
+
const agentTaskConsumer = new AgentTaskConsumer(target_port);
|
|
1540
|
+
agentTaskConsumer.startPollingQueue();
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
936
1543
|
} catch (err) {
|
|
937
1544
|
logger.error("Server start failed", { error: err });
|
|
938
1545
|
process.exit(1);
|
|
@@ -942,7 +1549,8 @@ var LatticeGateway = {
|
|
|
942
1549
|
startAsHttpEndpoint: start,
|
|
943
1550
|
configureSwagger,
|
|
944
1551
|
registerLatticeRoutes,
|
|
945
|
-
app
|
|
1552
|
+
app,
|
|
1553
|
+
AgentTaskConsumer
|
|
946
1554
|
};
|
|
947
1555
|
export {
|
|
948
1556
|
LatticeGateway
|