@vectorx/agent-runtime 0.0.0-beta-20251112071515

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/lib/agent.js ADDED
@@ -0,0 +1,785 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.AgentRuntime = exports.AgentEventType = exports.AgentType = void 0;
46
+ const ai_sdk_1 = require("@vectorx/ai-sdk");
47
+ const functions_framework_1 = require("@vectorx/functions-framework");
48
+ const schema_1 = require("./schema");
49
+ const sse_sender_1 = require("./sse-sender");
50
+ const agent_helper_1 = require("./utils/agent-helper");
51
+ var AgentType;
52
+ (function (AgentType) {
53
+ AgentType["AI_SDK_REQUEST_START"] = "AI_SDK_REQUEST_START";
54
+ AgentType["AI_SDK_REQUEST_SUCCESS"] = "AI_SDK_REQUEST_SUCCESS";
55
+ AgentType["AI_SDK_REQUEST_ERROR"] = "AI_SDK_REQUEST_ERROR";
56
+ AgentType["AI_SDK_CREATE_MODEL"] = "AI_SDK_CREATE_MODEL";
57
+ AgentType["AI_SDK_CREATE_RECORD_PAIR"] = "AI_SDK_CREATE_RECORD_PAIR";
58
+ AgentType["AI_SDK_GET_HISTORY_MESSAGES"] = "AI_SDK_GET_HISTORY_MESSAGES";
59
+ AgentType["AI_SDK_GET_CONVERSATIONS"] = "AI_SDK_GET_CONVERSATIONS";
60
+ AgentType["Ai_SDK_POST_KNOWLEDGE_BASE"] = "Ai_SDK_POST_KNOWLEDGE_BASE";
61
+ AgentType["AI_SDK_QUERY_TASKS"] = "AI_SDK_QUERY_TASKS";
62
+ })(AgentType || (exports.AgentType = AgentType = {}));
63
+ var AgentEventType;
64
+ (function (AgentEventType) {
65
+ AgentEventType["FRAMEWORK_EVENT"] = "FRAMEWORK_EVENT";
66
+ AgentEventType["HTTP_ACCESS"] = "HTTP_ACCESS";
67
+ })(AgentEventType || (exports.AgentEventType = AgentEventType = {}));
68
+ const safeJsonStringify = (obj) => {
69
+ try {
70
+ return JSON.stringify(obj);
71
+ }
72
+ catch (error) {
73
+ return JSON.stringify({ error: "Failed to stringify object" });
74
+ }
75
+ };
76
+ class AgentRuntime {
77
+ get agentTag() {
78
+ const url = this.context.httpContext.url;
79
+ return (0, agent_helper_1.parseAgentTag)(url);
80
+ }
81
+ get agentId() {
82
+ const url = this.context.httpContext.url;
83
+ return (0, agent_helper_1.parseAgentId)(url);
84
+ }
85
+ get version() {
86
+ return "0.0.1【TODO: 从 context header 中获取22222版本号】";
87
+ }
88
+ constructor(context) {
89
+ this.context = context;
90
+ this.sseSender = new sse_sender_1.SSESender(context);
91
+ this.request = context.request;
92
+ this.logger = context.logger;
93
+ const loggedRequest = this.createLoggedRequest(this.request, this.logger);
94
+ this.ai = (0, ai_sdk_1.createAi)({
95
+ request: loggedRequest,
96
+ getBaseUrl: () => this.context.baseUrl,
97
+ env: ai_sdk_1.AiSdkEnv.Cloud,
98
+ });
99
+ }
100
+ createLoggedRequest(originalRequest, logger) {
101
+ return {
102
+ get: (options) => __awaiter(this, void 0, void 0, function* () {
103
+ const startTime = Date.now();
104
+ const requestStartLog = safeJsonStringify({
105
+ type: AgentType.AI_SDK_REQUEST_START,
106
+ method: "GET",
107
+ url: options.url,
108
+ headers: options.headers,
109
+ data: options.data,
110
+ eventId: this.context.eventID,
111
+ timestamp: new Date().toISOString(),
112
+ });
113
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestStartLog);
114
+ try {
115
+ const response = yield originalRequest.get(options);
116
+ const requestSuccessLog = safeJsonStringify({
117
+ type: AgentType.AI_SDK_REQUEST_SUCCESS,
118
+ method: "GET",
119
+ url: options.url,
120
+ status: response.statusCode,
121
+ duration: `${Date.now() - startTime}ms`,
122
+ eventId: this.context.eventID,
123
+ timestamp: new Date().toISOString(),
124
+ });
125
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestSuccessLog);
126
+ return response;
127
+ }
128
+ catch (error) {
129
+ const requestErrorLog = safeJsonStringify({
130
+ type: AgentType.AI_SDK_REQUEST_ERROR,
131
+ method: "GET",
132
+ url: options.url,
133
+ error: error instanceof Error ? error.message : "请求失败",
134
+ stack: error instanceof Error ? error.stack : undefined,
135
+ duration: `${Date.now() - startTime}ms`,
136
+ eventId: this.context.eventID,
137
+ timestamp: new Date().toISOString(),
138
+ });
139
+ logger.logAccesslog(functions_framework_1.LogLevel.ERROR, requestErrorLog);
140
+ throw error;
141
+ }
142
+ }),
143
+ post: (options) => __awaiter(this, void 0, void 0, function* () {
144
+ const startTime = Date.now();
145
+ const requestStartLog = safeJsonStringify({
146
+ type: AgentEventType.FRAMEWORK_EVENT,
147
+ scene: AgentType.AI_SDK_REQUEST_START,
148
+ method: "POST",
149
+ url: options.url,
150
+ headers: options.headers,
151
+ data: options.data,
152
+ eventId: this.context.eventID,
153
+ timestamp: new Date().toISOString(),
154
+ });
155
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestStartLog);
156
+ try {
157
+ const response = yield originalRequest.post(options);
158
+ const requestSuccessLog = safeJsonStringify({
159
+ type: AgentEventType.FRAMEWORK_EVENT,
160
+ scene: AgentType.AI_SDK_REQUEST_SUCCESS,
161
+ method: "POST",
162
+ url: options.url,
163
+ status: response.statusCode,
164
+ duration: `${Date.now() - startTime}ms`,
165
+ eventId: this.context.eventID,
166
+ timestamp: new Date().toISOString(),
167
+ });
168
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestSuccessLog);
169
+ return response;
170
+ }
171
+ catch (error) {
172
+ const requestErrorLog = safeJsonStringify({
173
+ type: AgentEventType.FRAMEWORK_EVENT,
174
+ scene: AgentType.AI_SDK_REQUEST_ERROR,
175
+ method: "POST",
176
+ url: options.url,
177
+ error: error instanceof Error ? error.message : "请求失败",
178
+ stack: error instanceof Error ? error.stack : undefined,
179
+ duration: `${Date.now() - startTime}ms`,
180
+ eventId: this.context.eventID,
181
+ timestamp: new Date().toISOString(),
182
+ });
183
+ logger.logAccesslog(functions_framework_1.LogLevel.ERROR, requestErrorLog);
184
+ throw error;
185
+ }
186
+ }),
187
+ put: (options) => __awaiter(this, void 0, void 0, function* () {
188
+ const startTime = Date.now();
189
+ const requestStartLog = safeJsonStringify({
190
+ type: AgentEventType.FRAMEWORK_EVENT,
191
+ scene: AgentType.AI_SDK_REQUEST_START,
192
+ method: "PUT",
193
+ url: options.url,
194
+ headers: options.headers,
195
+ data: options.data,
196
+ eventId: this.context.eventID,
197
+ timestamp: new Date().toISOString(),
198
+ });
199
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestStartLog);
200
+ try {
201
+ const response = yield originalRequest.put(options);
202
+ const requestSuccessLog = safeJsonStringify({
203
+ type: AgentEventType.FRAMEWORK_EVENT,
204
+ scene: AgentType.AI_SDK_REQUEST_SUCCESS,
205
+ method: "PUT",
206
+ url: options.url,
207
+ status: response.statusCode,
208
+ duration: `${Date.now() - startTime}ms`,
209
+ eventId: this.context.eventID,
210
+ timestamp: new Date().toISOString(),
211
+ });
212
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestSuccessLog);
213
+ return response;
214
+ }
215
+ catch (error) {
216
+ const requestErrorLog = safeJsonStringify({
217
+ type: AgentEventType.FRAMEWORK_EVENT,
218
+ scene: AgentType.AI_SDK_REQUEST_ERROR,
219
+ method: "PUT",
220
+ url: options.url,
221
+ error: error instanceof Error ? error.message : "请求失败",
222
+ stack: error instanceof Error ? error.stack : undefined,
223
+ duration: `${Date.now() - startTime}ms`,
224
+ eventId: this.context.eventID,
225
+ timestamp: new Date().toISOString(),
226
+ });
227
+ logger.logAccesslog(functions_framework_1.LogLevel.ERROR, requestErrorLog);
228
+ throw error;
229
+ }
230
+ }),
231
+ upload: (options) => __awaiter(this, void 0, void 0, function* () {
232
+ const startTime = Date.now();
233
+ const requestStartLog = safeJsonStringify({
234
+ type: AgentEventType.FRAMEWORK_EVENT,
235
+ scene: AgentType.AI_SDK_REQUEST_START,
236
+ method: "UPLOAD",
237
+ url: options.url,
238
+ headers: options.headers,
239
+ eventId: this.context.eventID,
240
+ timestamp: new Date().toISOString(),
241
+ });
242
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestStartLog);
243
+ try {
244
+ const response = yield originalRequest.upload(options);
245
+ const requestSuccessLog = safeJsonStringify({
246
+ type: AgentEventType.FRAMEWORK_EVENT,
247
+ scene: AgentType.AI_SDK_REQUEST_SUCCESS,
248
+ method: "UPLOAD",
249
+ url: options.url,
250
+ status: response.statusCode,
251
+ duration: `${Date.now() - startTime}ms`,
252
+ eventId: this.context.eventID,
253
+ timestamp: new Date().toISOString(),
254
+ });
255
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestSuccessLog);
256
+ return response;
257
+ }
258
+ catch (error) {
259
+ const requestErrorLog = safeJsonStringify({
260
+ type: AgentEventType.FRAMEWORK_EVENT,
261
+ scene: AgentType.AI_SDK_REQUEST_ERROR,
262
+ method: "UPLOAD",
263
+ url: options.url,
264
+ error: error instanceof Error ? error.message : "请求失败",
265
+ stack: error instanceof Error ? error.stack : undefined,
266
+ duration: `${Date.now() - startTime}ms`,
267
+ eventId: this.context.eventID,
268
+ timestamp: new Date().toISOString(),
269
+ });
270
+ logger.logAccesslog(functions_framework_1.LogLevel.ERROR, requestErrorLog);
271
+ throw error;
272
+ }
273
+ }),
274
+ download: (options) => __awaiter(this, void 0, void 0, function* () {
275
+ const startTime = Date.now();
276
+ const requestStartLog = safeJsonStringify({
277
+ type: AgentEventType.FRAMEWORK_EVENT,
278
+ scene: AgentType.AI_SDK_REQUEST_START,
279
+ method: "DOWNLOAD",
280
+ url: options.url,
281
+ headers: options.headers,
282
+ eventId: this.context.eventID,
283
+ timestamp: new Date().toISOString(),
284
+ });
285
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestStartLog);
286
+ try {
287
+ const response = yield originalRequest.download(options);
288
+ const requestSuccessLog = safeJsonStringify({
289
+ type: AgentEventType.FRAMEWORK_EVENT,
290
+ scene: AgentType.AI_SDK_REQUEST_SUCCESS,
291
+ method: "DOWNLOAD",
292
+ url: options.url,
293
+ duration: `${Date.now() - startTime}ms`,
294
+ eventId: this.context.eventID,
295
+ timestamp: new Date().toISOString(),
296
+ });
297
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestSuccessLog);
298
+ return response;
299
+ }
300
+ catch (error) {
301
+ const requestErrorLog = safeJsonStringify({
302
+ type: AgentEventType.FRAMEWORK_EVENT,
303
+ scene: AgentType.AI_SDK_REQUEST_ERROR,
304
+ method: "DOWNLOAD",
305
+ url: options.url,
306
+ error: error instanceof Error ? error.message : "请求失败",
307
+ stack: error instanceof Error ? error.stack : undefined,
308
+ duration: `${Date.now() - startTime}ms`,
309
+ eventId: this.context.eventID,
310
+ timestamp: new Date().toISOString(),
311
+ });
312
+ logger.logAccesslog(functions_framework_1.LogLevel.ERROR, requestErrorLog);
313
+ throw error;
314
+ }
315
+ }),
316
+ fetch: (options) => __awaiter(this, void 0, void 0, function* () {
317
+ const startTime = Date.now();
318
+ const requestStartLog = safeJsonStringify({
319
+ type: AgentEventType.FRAMEWORK_EVENT,
320
+ scene: AgentType.AI_SDK_REQUEST_START,
321
+ method: "FETCH",
322
+ url: options.url,
323
+ headers: options.headers,
324
+ data: safeJsonStringify(options.body),
325
+ eventId: this.context.eventID,
326
+ timestamp: new Date().toISOString(),
327
+ });
328
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestStartLog);
329
+ try {
330
+ const response = yield originalRequest.fetch(options);
331
+ const requestSuccessLog = safeJsonStringify({
332
+ type: AgentEventType.FRAMEWORK_EVENT,
333
+ scene: AgentType.AI_SDK_REQUEST_SUCCESS,
334
+ method: "FETCH",
335
+ url: options.url,
336
+ status: response.statusCode,
337
+ duration: `${Date.now() - startTime}ms`,
338
+ eventId: this.context.eventID,
339
+ timestamp: new Date().toISOString(),
340
+ });
341
+ logger.logAccesslog(functions_framework_1.LogLevel.INFO, requestSuccessLog);
342
+ return response;
343
+ }
344
+ catch (error) {
345
+ const requestErrorLog = safeJsonStringify({
346
+ type: AgentEventType.FRAMEWORK_EVENT,
347
+ scene: AgentType.AI_SDK_REQUEST_ERROR,
348
+ method: "FETCH",
349
+ url: options.url,
350
+ error: error instanceof Error ? error.message : "请求失败",
351
+ stack: error instanceof Error ? error.stack : undefined,
352
+ duration: `${Date.now() - startTime}ms`,
353
+ eventId: this.context.eventID,
354
+ timestamp: new Date().toISOString(),
355
+ });
356
+ logger.logAccesslog(functions_framework_1.LogLevel.ERROR, requestErrorLog);
357
+ throw error;
358
+ }
359
+ }),
360
+ };
361
+ }
362
+ createModel(modelName) {
363
+ const createModelLog = safeJsonStringify({
364
+ type: AgentEventType.FRAMEWORK_EVENT,
365
+ scene: AgentType.AI_SDK_CREATE_MODEL,
366
+ modelName: modelName,
367
+ eventId: this.context.eventID,
368
+ timestamp: new Date().toISOString(),
369
+ });
370
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, createModelLog);
371
+ return this.ai.createModel(modelName);
372
+ }
373
+ createRecordPair(params) {
374
+ return __awaiter(this, void 0, void 0, function* () {
375
+ try {
376
+ const validatedParams = schema_1.createRecordPairParamsSchema.passthrough().parse(params);
377
+ const { conversation_id, user_input, assistant_output } = validatedParams;
378
+ const createRecordPairStartLog = safeJsonStringify({
379
+ type: AgentEventType.FRAMEWORK_EVENT,
380
+ scene: AgentType.AI_SDK_CREATE_RECORD_PAIR,
381
+ method: "POST",
382
+ url: `${this.context.baseUrl}/conversation/save`,
383
+ headers: {
384
+ "Content-Type": "application/json",
385
+ },
386
+ data: {
387
+ conversation_id,
388
+ user_input: JSON.stringify(user_input),
389
+ assistant_output: JSON.stringify(assistant_output),
390
+ },
391
+ eventId: this.context.eventID,
392
+ timestamp: new Date().toISOString(),
393
+ });
394
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, createRecordPairStartLog);
395
+ const response = yield this.request.post({
396
+ headers: {
397
+ "Content-Type": "application/json",
398
+ },
399
+ url: `${this.context.baseUrl}/conversation/save`,
400
+ data: {
401
+ conversation_id,
402
+ user_input: JSON.stringify(user_input),
403
+ assistant_output: JSON.stringify(assistant_output),
404
+ },
405
+ });
406
+ const createRecordPairEndLog = safeJsonStringify({
407
+ type: AgentEventType.FRAMEWORK_EVENT,
408
+ scene: AgentType.AI_SDK_CREATE_RECORD_PAIR,
409
+ method: "POST",
410
+ url: `${this.context.baseUrl}/conversation/save`,
411
+ status: response.status,
412
+ data: response.data,
413
+ eventId: this.context.eventID,
414
+ timestamp: new Date().toISOString(),
415
+ });
416
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, createRecordPairEndLog);
417
+ return response.data;
418
+ }
419
+ catch (error) {
420
+ const createRecordPairErrorLog = safeJsonStringify({
421
+ type: AgentEventType.FRAMEWORK_EVENT,
422
+ scene: AgentType.AI_SDK_CREATE_RECORD_PAIR,
423
+ method: "POST",
424
+ url: `${this.context.baseUrl}/conversation/save`,
425
+ error: error instanceof Error ? error.message : "创建对话对失败",
426
+ stack: error instanceof Error ? error.stack : undefined,
427
+ eventId: this.context.eventID,
428
+ timestamp: new Date().toISOString(),
429
+ });
430
+ this.logger.logAccesslog(functions_framework_1.LogLevel.ERROR, createRecordPairErrorLog);
431
+ return {
432
+ code: -1,
433
+ msg: error instanceof Error ? error.message : "创建对话对失败",
434
+ };
435
+ }
436
+ });
437
+ }
438
+ getHistoryMessages(params) {
439
+ return __awaiter(this, void 0, void 0, function* () {
440
+ try {
441
+ const validatedParams = schema_1.getHistoryMessagesParamsSchema.passthrough().parse(params);
442
+ const getHistoryMessagesStartLog = safeJsonStringify({
443
+ type: AgentEventType.FRAMEWORK_EVENT,
444
+ scene: AgentType.AI_SDK_GET_HISTORY_MESSAGES,
445
+ method: "GET",
446
+ url: `${this.context.baseUrl}/conversation/history`,
447
+ data: validatedParams,
448
+ eventId: this.context.eventID,
449
+ timestamp: new Date().toISOString(),
450
+ });
451
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, getHistoryMessagesStartLog);
452
+ const response = yield this.request.get({
453
+ url: `${this.context.baseUrl}/conversation/history`,
454
+ data: validatedParams,
455
+ });
456
+ const getHistoryMessagesEndLog = safeJsonStringify({
457
+ type: AgentEventType.FRAMEWORK_EVENT,
458
+ scene: AgentType.AI_SDK_GET_HISTORY_MESSAGES,
459
+ method: "GET",
460
+ url: `${this.context.baseUrl}/conversation/history`,
461
+ status: response.status,
462
+ data: response.data,
463
+ eventId: this.context.eventID,
464
+ timestamp: new Date().toISOString(),
465
+ });
466
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, getHistoryMessagesEndLog);
467
+ return response.data;
468
+ }
469
+ catch (error) {
470
+ const getHistoryMessagesErrorLog = safeJsonStringify({
471
+ type: AgentEventType.FRAMEWORK_EVENT,
472
+ scene: AgentType.AI_SDK_GET_HISTORY_MESSAGES,
473
+ method: "GET",
474
+ url: `${this.context.baseUrl}/conversation/history`,
475
+ error: error instanceof Error ? error.message : "获取历史消息失败",
476
+ stack: error instanceof Error ? error.stack : undefined,
477
+ eventId: this.context.eventID,
478
+ timestamp: new Date().toISOString(),
479
+ });
480
+ this.logger.logAccesslog(functions_framework_1.LogLevel.ERROR, getHistoryMessagesErrorLog);
481
+ return {
482
+ code: -1,
483
+ msg: error instanceof Error ? error.message : "获取历史消息失败",
484
+ data: {
485
+ message_list: [],
486
+ conversation_id: "",
487
+ participant_info_map: {},
488
+ next_cursor: 0,
489
+ has_more: false,
490
+ },
491
+ };
492
+ }
493
+ });
494
+ }
495
+ getConversations() {
496
+ return __awaiter(this, void 0, void 0, function* () {
497
+ try {
498
+ const getConversationsStartLog = safeJsonStringify({
499
+ type: AgentEventType.FRAMEWORK_EVENT,
500
+ scene: AgentType.AI_SDK_GET_CONVERSATIONS,
501
+ method: "GET",
502
+ url: `${this.context.baseUrl}/conversation/list`,
503
+ eventId: this.context.eventID,
504
+ timestamp: new Date().toISOString(),
505
+ });
506
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, getConversationsStartLog);
507
+ const response = yield this.request.get({
508
+ url: `${this.context.baseUrl}/conversation/list`,
509
+ });
510
+ const getConversationsEndLog = safeJsonStringify({
511
+ type: AgentEventType.FRAMEWORK_EVENT,
512
+ scene: AgentType.AI_SDK_GET_CONVERSATIONS,
513
+ method: "GET",
514
+ url: `${this.context.baseUrl}/conversation/list`,
515
+ status: response.status,
516
+ data: response.data,
517
+ eventId: this.context.eventID,
518
+ timestamp: new Date().toISOString(),
519
+ });
520
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, getConversationsEndLog);
521
+ return response.data;
522
+ }
523
+ catch (error) {
524
+ const getConversationsErrorLog = safeJsonStringify({
525
+ type: AgentEventType.FRAMEWORK_EVENT,
526
+ scene: AgentType.AI_SDK_GET_CONVERSATIONS,
527
+ method: "GET",
528
+ url: `${this.context.baseUrl}/conversation/list`,
529
+ error: error instanceof Error ? error.message : "获取会话列表失败",
530
+ stack: error instanceof Error ? error.stack : undefined,
531
+ eventId: this.context.eventID,
532
+ timestamp: new Date().toISOString(),
533
+ });
534
+ this.logger.logAccesslog(functions_framework_1.LogLevel.ERROR, getConversationsErrorLog);
535
+ return {
536
+ code: -1,
537
+ msg: error instanceof Error ? error.message : "获取会话列表失败",
538
+ data: {
539
+ conversations: [],
540
+ },
541
+ };
542
+ }
543
+ });
544
+ }
545
+ getAgentInfo() {
546
+ return __awaiter(this, void 0, void 0, function* () {
547
+ const response = yield this.request.get({
548
+ url: `${this.context.baseUrl}/agent/info`,
549
+ });
550
+ return response.data;
551
+ });
552
+ }
553
+ knowledgeBaseRetrieve(params) {
554
+ return __awaiter(this, void 0, void 0, function* () {
555
+ try {
556
+ const validatedParams = schema_1.knowledgeSearchInputSchema.passthrough().parse(params);
557
+ const knowledgeBaseRetrieveStartLog = safeJsonStringify({
558
+ type: AgentEventType.FRAMEWORK_EVENT,
559
+ scene: AgentType.Ai_SDK_POST_KNOWLEDGE_BASE,
560
+ method: "POST",
561
+ url: `${this.context.baseUrl}/rag/retrieve`,
562
+ data: validatedParams,
563
+ eventId: this.context.eventID,
564
+ timestamp: new Date().toISOString(),
565
+ });
566
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, knowledgeBaseRetrieveStartLog);
567
+ const response = yield this.request.post({
568
+ headers: {
569
+ "Content-Type": "application/json",
570
+ },
571
+ url: `${this.context.baseUrl}/rag/retrieve`,
572
+ data: validatedParams,
573
+ });
574
+ const knowledgeBaseRetrieveEndLog = safeJsonStringify({
575
+ type: AgentEventType.FRAMEWORK_EVENT,
576
+ scene: AgentType.Ai_SDK_POST_KNOWLEDGE_BASE,
577
+ method: "POST",
578
+ url: `${this.context.baseUrl}/rag/retrieve`,
579
+ status: response.status,
580
+ data: response.data,
581
+ eventId: this.context.eventID,
582
+ timestamp: new Date().toISOString(),
583
+ });
584
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, knowledgeBaseRetrieveEndLog);
585
+ return response.data;
586
+ }
587
+ catch (error) {
588
+ const knowledgeBaseRetrieveErrorLog = safeJsonStringify({
589
+ type: AgentEventType.FRAMEWORK_EVENT,
590
+ scene: AgentType.Ai_SDK_POST_KNOWLEDGE_BASE,
591
+ method: "POST",
592
+ url: `${this.context.baseUrl}/rag/retrieve`,
593
+ error: error instanceof Error ? error.message : "知识库检索失败",
594
+ stack: error instanceof Error ? error.stack : undefined,
595
+ eventId: this.context.eventID,
596
+ timestamp: new Date().toISOString(),
597
+ });
598
+ this.logger.logAccesslog(functions_framework_1.LogLevel.ERROR, knowledgeBaseRetrieveErrorLog);
599
+ return {
600
+ code: -1,
601
+ msg: error instanceof Error ? error.message : "知识库检索失败",
602
+ data: {
603
+ knowledge_results: [],
604
+ total_tokens: 0,
605
+ },
606
+ };
607
+ }
608
+ });
609
+ }
610
+ queryTasks(task_id) {
611
+ return __awaiter(this, void 0, void 0, function* () {
612
+ const validated = schema_1.queryTasksParamsSchema.passthrough().parse({ task_id });
613
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, safeJsonStringify({
614
+ type: AgentEventType.FRAMEWORK_EVENT,
615
+ scene: AgentType.AI_SDK_QUERY_TASKS,
616
+ method: "GET",
617
+ url: `https://dashscope.aliyuncs.com/api/v1/tasks/${validated.task_id}`,
618
+ headers: {},
619
+ data: { task_id: validated.task_id },
620
+ eventId: this.context.eventID,
621
+ timestamp: new Date().toISOString(),
622
+ }));
623
+ try {
624
+ const token = yield this.ai.tokenManager.getValidToken();
625
+ const response = yield this.request.get({
626
+ url: `https://dashscope.aliyuncs.com/api/v1/tasks/${validated.task_id}`,
627
+ headers: {
628
+ Authorization: `Bearer ${token}`,
629
+ },
630
+ });
631
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, safeJsonStringify({
632
+ type: AgentEventType.FRAMEWORK_EVENT,
633
+ scene: AgentType.AI_SDK_QUERY_TASKS,
634
+ method: "GET",
635
+ url: `https://dashscope.aliyuncs.com/api/v1/tasks/${validated.task_id}`,
636
+ status: response.status,
637
+ data: response.data,
638
+ eventId: this.context.eventID,
639
+ timestamp: new Date().toISOString(),
640
+ }));
641
+ if (response.statusCode >= 200 && response.statusCode < 300) {
642
+ return {
643
+ code: 0,
644
+ msg: "success",
645
+ data: response.data,
646
+ };
647
+ }
648
+ else {
649
+ return {
650
+ code: response.status,
651
+ msg: response.statusText || "请求失败",
652
+ data: response.data,
653
+ };
654
+ }
655
+ }
656
+ catch (error) {
657
+ this.logger.logAccesslog(functions_framework_1.LogLevel.ERROR, safeJsonStringify({
658
+ type: AgentEventType.FRAMEWORK_EVENT,
659
+ scene: AgentType.AI_SDK_QUERY_TASKS,
660
+ method: "GET",
661
+ url: `https://dashscope.aliyuncs.com/api/v1/tasks/${validated.task_id}`,
662
+ error: error instanceof Error ? error.message : "查询任务失败",
663
+ stack: error instanceof Error ? error.stack : undefined,
664
+ eventId: this.context.eventID,
665
+ timestamp: new Date().toISOString(),
666
+ }));
667
+ return {
668
+ code: -1,
669
+ msg: error instanceof Error ? error.message : "查询任务失败",
670
+ };
671
+ }
672
+ });
673
+ }
674
+ uploadFile(input) {
675
+ return __awaiter(this, void 0, void 0, function* () {
676
+ var _a, _b;
677
+ const fs = yield Promise.resolve().then(() => __importStar(require("fs")));
678
+ const path = yield Promise.resolve().then(() => __importStar(require("path")));
679
+ const os = yield Promise.resolve().then(() => __importStar(require("os")));
680
+ let tempFilePath = null;
681
+ console.log("==== input ====", input);
682
+ try {
683
+ const fileData = input.file;
684
+ const filename = fileData.name || fileData.originalFilename || fileData.newFilename || "unknown";
685
+ const purpose = input.purpose || "file-extract";
686
+ const mimeType = fileData.type || fileData.mimetype || "application/octet-stream";
687
+ console.log("==== filename ====", filename);
688
+ console.log("==== purpose ====", purpose);
689
+ console.log("==== mimeType ====", mimeType);
690
+ const fileBuffer = fileData.buffer || fileData;
691
+ if (!Buffer.isBuffer(fileBuffer)) {
692
+ throw new Error("无法从上传的文件对象中提取文件内容:buffer 不存在或格式错误");
693
+ }
694
+ const tempDir = os.tmpdir();
695
+ const timestamp = Date.now();
696
+ const randomStr = Math.random().toString(36).substring(2, 15);
697
+ tempFilePath = path.join(tempDir, `upload_${timestamp}_${randomStr}_${filename}`);
698
+ fs.writeFileSync(tempFilePath, fileBuffer);
699
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, safeJsonStringify({
700
+ type: AgentEventType.FRAMEWORK_EVENT,
701
+ scene: "AI_SDK_UPLOAD_FILE",
702
+ method: "POST",
703
+ url: "https://dashscope.aliyuncs.com/compatible-mode/v1/files",
704
+ headers: {},
705
+ data: { filename, purpose, tempFilePath },
706
+ eventId: this.context.eventID,
707
+ timestamp: new Date().toISOString(),
708
+ }));
709
+ const token = yield this.ai.tokenManager.getValidToken();
710
+ const FormData = (yield Promise.resolve().then(() => __importStar(require("form-data")))).default;
711
+ const formData = new FormData();
712
+ formData.append("file", fs.createReadStream(tempFilePath), {
713
+ filename,
714
+ contentType: mimeType,
715
+ });
716
+ formData.append("purpose", purpose);
717
+ const response = yield this.request.fetch({
718
+ url: "https://dashscope.aliyuncs.com/compatible-mode/v1/files",
719
+ headers: Object.assign({ Authorization: `Bearer ${token}` }, formData.getHeaders()),
720
+ method: "POST",
721
+ body: formData,
722
+ });
723
+ this.logger.logAccesslog(functions_framework_1.LogLevel.INFO, safeJsonStringify({
724
+ type: AgentEventType.FRAMEWORK_EVENT,
725
+ scene: "AI_SDK_UPLOAD_FILE",
726
+ method: "POST",
727
+ url: "https://dashscope.aliyuncs.com/compatible-mode/v1/files",
728
+ status: response.statusCode,
729
+ data: response.data,
730
+ eventId: this.context.eventID,
731
+ timestamp: new Date().toISOString(),
732
+ }));
733
+ if (response.statusCode >= 200 && response.statusCode < 300) {
734
+ return {
735
+ code: 0,
736
+ msg: "success",
737
+ data: response.data,
738
+ };
739
+ }
740
+ else {
741
+ return {
742
+ code: response.statusCode,
743
+ msg: ((_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.message) || "文件上传失败",
744
+ data: response.data,
745
+ };
746
+ }
747
+ }
748
+ catch (error) {
749
+ this.logger.logAccesslog(functions_framework_1.LogLevel.ERROR, safeJsonStringify({
750
+ type: AgentEventType.FRAMEWORK_EVENT,
751
+ scene: "AI_SDK_UPLOAD_FILE",
752
+ method: "POST",
753
+ url: "https://dashscope.aliyuncs.com/compatible-mode/v1/files",
754
+ error: error instanceof Error ? error.message : "文件上传失败",
755
+ stack: error instanceof Error ? error.stack : undefined,
756
+ eventId: this.context.eventID,
757
+ timestamp: new Date().toISOString(),
758
+ }));
759
+ return {
760
+ code: -1,
761
+ msg: error instanceof Error ? error.message : "文件上传失败",
762
+ };
763
+ }
764
+ finally {
765
+ if (tempFilePath) {
766
+ try {
767
+ fs.unlinkSync(tempFilePath);
768
+ }
769
+ catch (cleanupError) {
770
+ this.logger.logAccesslog(functions_framework_1.LogLevel.WARN, safeJsonStringify({
771
+ type: AgentEventType.FRAMEWORK_EVENT,
772
+ scene: "AI_SDK_UPLOAD_FILE_CLEANUP",
773
+ message: "临时文件清理失败",
774
+ tempFilePath,
775
+ error: cleanupError instanceof Error ? cleanupError.message : "未知错误",
776
+ eventId: this.context.eventID,
777
+ timestamp: new Date().toISOString(),
778
+ }));
779
+ }
780
+ }
781
+ }
782
+ });
783
+ }
784
+ }
785
+ exports.AgentRuntime = AgentRuntime;