@ruixutong.manee/agent-framework 1.0.0

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.js ADDED
@@ -0,0 +1,881 @@
1
+ import { z as e } from "zod";
2
+ import t from "openai";
3
+ import { zodToJsonSchema as n } from "zod-to-json-schema";
4
+ import { createReadStream as r } from "node:fs";
5
+ //#region src/agent/decorators/index.ts
6
+ var i = Symbol.for("@manee/agent-framework/toolDefinitions");
7
+ function a(e) {
8
+ return function(t, n) {
9
+ if (n.kind !== "method" || typeof t != "function") throw Error("@Tool can only decorate methods.");
10
+ let r = t;
11
+ s(n.metadata, { ...e }), n.addInitializer(function() {
12
+ if (typeof this != "object" || this === null) return;
13
+ let t = this;
14
+ t.tools ??= [], t.tools.push({
15
+ ...e,
16
+ handler: r.bind(t)
17
+ });
18
+ });
19
+ };
20
+ }
21
+ function o(e) {
22
+ let t = e[c()]?.[i];
23
+ return Array.isArray(t) ? t.map((e) => ({ ...e })) : [];
24
+ }
25
+ function s(e, t) {
26
+ let n = Object.prototype.hasOwnProperty.call(e, i), r = e[i], a = n && Array.isArray(r) ? r : Array.isArray(r) ? [...r] : [];
27
+ a.push(t), e[i] = a;
28
+ }
29
+ function c() {
30
+ return Symbol.metadata ?? Symbol.for("Symbol.metadata");
31
+ }
32
+ //#endregion
33
+ //#region src/agent/schema.ts
34
+ var l = e.object({});
35
+ function u() {
36
+ return l;
37
+ }
38
+ //#endregion
39
+ //#region src/agent/index.ts
40
+ var d, f, p, m;
41
+ function h(e, t, n, r, i, a) {
42
+ var o, s, c, l, u, d, f, p = Symbol.metadata || Symbol.for("Symbol.metadata"), m = Object.defineProperty, h = Object.create, _ = [h(null), h(null)], b = t.length;
43
+ function x(t, n, r) {
44
+ return function(i, a) {
45
+ n && (a = i, i = e);
46
+ for (var o = 0; o < t.length; o++) a = t[o].apply(i, r ? [a] : []);
47
+ return r ? a : i;
48
+ };
49
+ }
50
+ function S(e, t, n, r) {
51
+ if (typeof e != "function" && (r || e !== void 0)) throw TypeError(t + " must " + (n || "be") + " a function" + (r ? "" : " or undefined"));
52
+ return e;
53
+ }
54
+ function C(e, t, n, r, i, a, c, l, u, d, f) {
55
+ function p(e) {
56
+ if (!f(e)) throw TypeError("Attempted to access private element on non-instance");
57
+ }
58
+ var h = [].concat(t[0]), g = t[3], y = !c, b = i === 1, C = i === 3, w = i === 4, T = i === 2;
59
+ function E(t, n, r) {
60
+ return function(i, a) {
61
+ return n && (a = i, i = e), r && r(i), D[t].call(i, a);
62
+ };
63
+ }
64
+ if (!y) {
65
+ var D = {}, O = [], k = C ? "get" : w || b ? "set" : "value";
66
+ if (u ? (d || b ? D = {
67
+ get: v(function() {
68
+ return g(this);
69
+ }, r, "get"),
70
+ set: function(e) {
71
+ t[4](this, e);
72
+ }
73
+ } : D[k] = g, d || v(D[k], r, T ? "" : k)) : d || (D = Object.getOwnPropertyDescriptor(e, r)), !d && !u) {
74
+ if ((s = _[+l][r]) && (s ^ i) !== 7) throw Error("Decorating two elements with the same name (" + D[k].name + ") is not supported yet");
75
+ _[+l][r] = i < 3 ? 1 : i;
76
+ }
77
+ }
78
+ for (var A = e, j = h.length - 1; j >= 0; j -= n ? 2 : 1) {
79
+ var M = S(h[j], "A decorator", "be", !0), N = n ? h[j - 1] : void 0, P = {}, F = {
80
+ kind: [
81
+ "field",
82
+ "accessor",
83
+ "method",
84
+ "getter",
85
+ "setter",
86
+ "class"
87
+ ][i],
88
+ name: r,
89
+ metadata: o,
90
+ addInitializer: function(e, t) {
91
+ if (e.v) throw TypeError("attempted to call addInitializer after decoration was finished");
92
+ S(t, "An initializer", "be", !0), a.push(t);
93
+ }.bind(null, P)
94
+ };
95
+ if (y) s = M.call(N, A, F), P.v = 1, S(s, "class decorators", "return") && (A = s);
96
+ else if (F.static = l, F.private = u, s = F.access = { has: u ? f.bind() : function(e) {
97
+ return r in e;
98
+ } }, w || (s.get = u ? T ? function(e) {
99
+ return p(e), D.value;
100
+ } : E("get", 0, p) : function(e) {
101
+ return e[r];
102
+ }), T || C || (s.set = u ? E("set", 0, p) : function(e, t) {
103
+ e[r] = t;
104
+ }), A = M.call(N, b ? {
105
+ get: D.get,
106
+ set: D.set
107
+ } : D[k], F), P.v = 1, b) {
108
+ if (typeof A == "object" && A) (s = S(A.get, "accessor.get")) && (D.get = s), (s = S(A.set, "accessor.set")) && (D.set = s), (s = S(A.init, "accessor.init")) && O.unshift(s);
109
+ else if (A !== void 0) throw TypeError("accessor decorators must return an object with get, set, or init properties or undefined");
110
+ } else S(A, (d ? "field" : "method") + " decorators", "return") && (d ? O.unshift(A) : D[k] = A);
111
+ }
112
+ return i < 2 && c.push(x(O, l, 1), x(a, l, 0)), d || y || (u ? b ? c.splice(-1, 0, E("get", l), E("set", l)) : c.push(T ? D[k] : S.call.bind(D[k])) : m(e, r, D)), A;
113
+ }
114
+ function w(e) {
115
+ return m(e, p, {
116
+ configurable: !0,
117
+ enumerable: !0,
118
+ value: o
119
+ });
120
+ }
121
+ return a !== void 0 && (o = a[p]), o = h(o ?? null), u = [], d = function(e) {
122
+ e && u.push(x(e));
123
+ }, f = function(t, r) {
124
+ for (var a = 0; a < n.length; a++) {
125
+ var o = n[a], s = o[1], d = 7 & s;
126
+ if ((8 & s) == t && !d == r) {
127
+ var f = o[2], p = !!o[3], m = 16 & s;
128
+ C(t ? e : e.prototype, o, m, p ? "#" + f : g(f), d, d < 2 ? [] : t ? l ||= [] : c ||= [], u, !!t, p, r, t && p ? function(t) {
129
+ return y(t) === e;
130
+ } : i);
131
+ }
132
+ }
133
+ }, f(8, 0), f(0, 0), f(8, 1), f(0, 1), d(c), d(l), s = u, b || w(e), {
134
+ e: s,
135
+ get c() {
136
+ var n = [];
137
+ return b && [w(e = C(e, [t], r, e.name, 5, n)), x(n, 1)];
138
+ }
139
+ };
140
+ }
141
+ function g(e) {
142
+ var t = _(e, "string");
143
+ return typeof t == "symbol" ? t : t + "";
144
+ }
145
+ function _(e, t) {
146
+ if (typeof e != "object" || !e) return e;
147
+ var n = e[Symbol.toPrimitive];
148
+ if (n !== void 0) {
149
+ var r = n.call(e, t || "default");
150
+ if (typeof r != "object") return r;
151
+ throw TypeError("@@toPrimitive must return a primitive value.");
152
+ }
153
+ return (t === "string" ? String : Number)(e);
154
+ }
155
+ function v(e, t, n) {
156
+ typeof t == "symbol" && (t = (t = t.description) ? "[" + t + "]" : "");
157
+ try {
158
+ Object.defineProperty(e, "name", {
159
+ configurable: !0,
160
+ value: n ? n + " " + t : t
161
+ });
162
+ } catch {}
163
+ return e;
164
+ }
165
+ function y(e) {
166
+ if (Object(e) !== e) throw TypeError("right-hand side of 'in' should be an object, got " + (e === null ? "null" : typeof e));
167
+ return e;
168
+ }
169
+ var b = "函数调用的前置工作出现异常,异常为:", x = "框架约束:当任务完成时,必须单独调用 end-agent 工具结束任务;不能仅用自然语言回答表示结束,也不能把 end-agent 与其他工具放在同一轮调用。", S = Symbol("agent.tools"), C = class {
170
+ static {
171
+ [f, p, m, d] = h(this, [], [
172
+ [
173
+ a({
174
+ name: "agent",
175
+ description: ({ subAgents: e }) => [
176
+ "这是一个子代理调度工具,当你需要调用一个子代理来完成某个任务时,请使用这个工具。调用时请在参数中说明需要调用的子代理名称和输入子代理的内容。",
177
+ "每次调度同一子代理都是全新的代理,并且可以同时调度多个相同子代理。",
178
+ "调度子代理时,需要指定任务的描述,以及需要子代理最后汇报你的东西的描述。比如如果是一个任务,那需要汇报你任务的报告;如果是需要一个问题的答案,则是问题的回答。",
179
+ "以下是当前可用的子代理列表:",
180
+ e.length === 0 ? "当前没有可调度的子代理。" : e.map(j).join("\n\n")
181
+ ].join("\n\n"),
182
+ parameters: e.object({
183
+ agentName: e.string().describe("要调用的子代理名称"),
184
+ input: e.string().describe("输入子代理的内容"),
185
+ outputDescription: e.string().describe("需要让子代理最后交付你的东西的描述,比如任务的报告、问题的回答")
186
+ })
187
+ }),
188
+ 2,
189
+ "toolSubAgent",
190
+ async function(t) {
191
+ let n, r, { agentName: i, input: o, outputDescription: s } = t, c = this.subAgents.find((e) => e.name === i);
192
+ if (!c) return `没有找到名称为 ${i} 的子代理。`;
193
+ let l, u = c;
194
+ class d extends u {
195
+ static {
196
+ [r, n] = h(this, [], [[
197
+ a({
198
+ name: "agent-result",
199
+ description: "这是一个结果汇报工具,你需要在完成任务后调用这个工具把结果汇报回来",
200
+ parameters: e.object({ result: e.string().describe(s) })
201
+ }),
202
+ 2,
203
+ "reportResult",
204
+ function(e) {
205
+ let { result: t } = e;
206
+ return l = t, t;
207
+ }
208
+ ]], 0, (e) => #j in e, u).e;
209
+ }
210
+ constructor(...e) {
211
+ super(...e), n(this);
212
+ }
213
+ #j = r;
214
+ }
215
+ let f = new d({
216
+ llm: this.#o,
217
+ systemPrompts: [
218
+ `你现在是被主代理调度的子代理:${i}。`,
219
+ `主代理输入给你的任务:\n${o}`,
220
+ ["完成任务后,调用 end-agent 前必须先调用 agent-result 工具把结果汇报回来。", `agent-result.result 必须满足如下交付描述:\n${s}`].join("\n")
221
+ ]
222
+ });
223
+ return f.init(), await f.agent(o), l ?? "子代理已结束但未通过 agent-result 汇报结果。";
224
+ }
225
+ ],
226
+ [
227
+ a({
228
+ name: "get-skill",
229
+ description: "获取指定下标的技能手册完整内容。",
230
+ parameters: e.object({ index: e.number().int().nonnegative() })
231
+ }),
232
+ 2,
233
+ "getSkill",
234
+ function(e) {
235
+ let { index: t } = e, n = this.#n[t];
236
+ return n ? [
237
+ `手册标题:${n.name}`,
238
+ `手册描述:${n.description}`,
239
+ n.systemContent ? `全局适用内容:${n.systemContent}` : "",
240
+ ...(n.sops ?? []).map((e, t) => [`工作流${t + 1}:${e.description}`, `执行流程:\n${e.content}`].join("\n"))
241
+ ].filter((e) => e.length > 0).join("\n\n") : `没有找到下标为 ${t} 的技能手册。`;
242
+ }
243
+ ],
244
+ [
245
+ a({
246
+ name: "end-agent",
247
+ description: "当你认为你已经彻底完成了用户交代的任务,并且不需要更多信息时,请调用这个工具。该工具必须在任务确定结束时单独调用,不能跟其他工具一起调用。"
248
+ }),
249
+ 2,
250
+ "endAgent",
251
+ function() {
252
+ return this.#A("ended"), "Agent 已结束。";
253
+ }
254
+ ]
255
+ ], 0, (e) => #p in e).e;
256
+ }
257
+ get tools() {
258
+ return k(this);
259
+ }
260
+ set tools(e) {
261
+ A(this, e);
262
+ }
263
+ #e = (d(this), []);
264
+ #t = [];
265
+ #n = [];
266
+ #r = [];
267
+ #i = "idle";
268
+ #a;
269
+ #o;
270
+ #s = !1;
271
+ #c = [];
272
+ #l = [];
273
+ #u = [];
274
+ #d = [];
275
+ #f = [];
276
+ #p = [];
277
+ static description;
278
+ subAgents = [];
279
+ static get toolsDefinition() {
280
+ return o(this);
281
+ }
282
+ constructor(e) {
283
+ if (this.#o = e.llm, this.#a = e.maxIterations, this.#t = [...e.initContext ?? e.initRawContext ?? []], this.#e = [...e.initRawContext ?? e.initContext ?? []], this.tools ??= [], this.subAgents = [...e.subAgents ?? []], this.#a !== void 0 && (this.#a < 1 || !Number.isInteger(this.#a))) throw Error("maxIterations must be a positive integer.");
284
+ this.addSkill(...e.skills ?? []), this.addSystemPrompts(...e.systemPrompts ?? []);
285
+ }
286
+ getHistory() {
287
+ return [...this.#e];
288
+ }
289
+ getContext() {
290
+ return [...this.#t];
291
+ }
292
+ init() {
293
+ return this.#s = !1, this.#m(), this.#h(), this.#s = !0, this;
294
+ }
295
+ addSystemPrompts(...e) {
296
+ for (let t of e) t.trim().length > 0 && this.#r.push(t);
297
+ return this;
298
+ }
299
+ addSkill(...e) {
300
+ return this.#n.push(...e), this;
301
+ }
302
+ appendContext(e) {
303
+ return this.#D(e), this;
304
+ }
305
+ onModelResponse(e) {
306
+ return w(this.#f, e);
307
+ }
308
+ onBeforeToolCall(e, t, n) {
309
+ return w(this.#c, {
310
+ toolName: e,
311
+ callback: t,
312
+ options: T(n)
313
+ });
314
+ }
315
+ onAfterToolCall(e, t, n) {
316
+ return w(this.#l, {
317
+ toolName: e,
318
+ callback: t,
319
+ options: T(n)
320
+ });
321
+ }
322
+ onToolCallError(e) {
323
+ return w(this.#u, e);
324
+ }
325
+ onAgentStatusChanged(e, t) {
326
+ return w(this.#d, {
327
+ status: e,
328
+ callback: t
329
+ });
330
+ }
331
+ onAgentError(e) {
332
+ return w(this.#p, e);
333
+ }
334
+ async toolCall(e) {
335
+ this.#g();
336
+ let t = this.tools.find((t) => t.name === e.name), n = {};
337
+ if (!t) {
338
+ let t = /* @__PURE__ */ Error(`Unknown tool: ${e.name}`);
339
+ return await this.#T(e.name, "calling", t, n, e), this.#O(this.#k(e.id, D(t)));
340
+ }
341
+ let r = await this.#x(t, e);
342
+ if (!r.ok) return this.#O(this.#k(e.id, r.message));
343
+ let i = r.parameters, a = await this.#S(t.name, i, e);
344
+ if (a.canceled) return this.#O(this.#k(e.id, `${b}${D(a.error)}`));
345
+ let o;
346
+ try {
347
+ o = await t.handler(i);
348
+ } catch (n) {
349
+ return await this.#T(t.name, "calling", n, i, e), this.#O(this.#k(e.id, D(n)));
350
+ }
351
+ let s = this.#O(this.#k(e.id, E(o)));
352
+ return await this.#C(t.name, i, e, o), s;
353
+ }
354
+ async agent(e, t = !1) {
355
+ let n = !0;
356
+ try {
357
+ if (this.#g(), this.#i === "running") throw n = !1, Error("Agent is already running.");
358
+ if (t) throw Error("Agent streaming is not supported in this version.");
359
+ this.#D(this.#o.buildUserMessage(typeof e == "string" ? { content: [{
360
+ type: "text",
361
+ text: e
362
+ }] } : e)), this.#A("running");
363
+ for (let e = 0; this.#a === void 0 || e < this.#a; e += 1) {
364
+ let e = await this.#b();
365
+ await this.#w(e.messages);
366
+ for (let t of e.messages) this.#D(t);
367
+ for (let t of this.#o.parseToolCalls(e.messages)) await this.toolCall(t);
368
+ if (this.#i === "ended") return [...this.#t];
369
+ }
370
+ throw Error(`Agent exceeded maxIterations: ${this.#a}.`);
371
+ } catch (e) {
372
+ let t = O(e);
373
+ throw n && this.#i !== "ended" && this.#A("failed"), this.#E(t), e instanceof Error ? e : t;
374
+ }
375
+ }
376
+ #m() {
377
+ this.tools ??= [];
378
+ let e = /* @__PURE__ */ new Set();
379
+ for (let t of this.tools) {
380
+ if (e.has(t.name)) throw Error(`Duplicate tool name: ${t.name}`);
381
+ e.add(t.name);
382
+ }
383
+ }
384
+ #h() {
385
+ let e = /* @__PURE__ */ new Set();
386
+ for (let t of this.subAgents) {
387
+ if (e.has(t.name)) throw Error(`Duplicate sub-agent name: ${t.name}`);
388
+ e.add(t.name);
389
+ }
390
+ }
391
+ #g() {
392
+ if (!this.#s) throw Error("Agent has not been initialized. Call init() before agent().");
393
+ }
394
+ #_() {
395
+ return [...[
396
+ x,
397
+ this.#v(),
398
+ ...this.#r
399
+ ].map((e) => this.#o.buildSystemMessage({ content: e })), ...this.#t];
400
+ }
401
+ #v() {
402
+ return ["框架技能约束:当正在执行的任务匹配到如下技能手册描述时,必须先调用 get-skill 工具获取对应下标的完整手册内容,然后检查手册内是否有具体工作流;如果匹配到具体工作流,必须按照该工作流执行。", this.#n.length === 0 ? "当前没有可查询的技能手册,不要调用 get-skill。" : this.#n.map((e, t) => `技能手册${t}:\n名称:${e.name}\n描述:${e.description}`).join("\n\n")].join("\n\n");
403
+ }
404
+ #y() {
405
+ return this.tools.map((e) => {
406
+ let t = { name: e.name };
407
+ e.parameters && (t.parameters = e.parameters), e.strict !== void 0 && (t.strict = e.strict);
408
+ let n = typeof e.description == "function" ? e.description({
409
+ skills: [...this.#n],
410
+ subAgents: [...this.subAgents],
411
+ context: [...this.#t],
412
+ history: [...this.#e],
413
+ systemPrompts: [...this.#r],
414
+ tool: t
415
+ }) : e.description;
416
+ return this.#o.buildToolMessage({
417
+ name: e.name,
418
+ description: n,
419
+ parameters: e.parameters ?? u(),
420
+ ...e.strict === void 0 ? {} : { strict: e.strict }
421
+ });
422
+ });
423
+ }
424
+ async #b() {
425
+ let e = "Model returned no messages.";
426
+ for (let t = 0; t <= 3; t += 1) {
427
+ let n = await this.#o.generate({
428
+ context: this.#_(),
429
+ tools: this.#y()
430
+ });
431
+ if (n.messages.length > 0) return n;
432
+ e = `Model returned no messages after ${t + 1} attempt(s).`;
433
+ }
434
+ throw Error(e);
435
+ }
436
+ async #x(e, t) {
437
+ let n;
438
+ try {
439
+ n = t.arguments.trim().length > 0 ? JSON.parse(t.arguments) : {};
440
+ } catch (n) {
441
+ return await this.#T(e.name, "calling", n, {}, t), {
442
+ ok: !1,
443
+ message: D(n)
444
+ };
445
+ }
446
+ let r = (e.parameters ?? u()).safeParse(n);
447
+ return r.success ? {
448
+ ok: !0,
449
+ parameters: r.data
450
+ } : (await this.#T(e.name, "calling", r.error, n, t), {
451
+ ok: !1,
452
+ message: D(r.error)
453
+ });
454
+ }
455
+ async #S(e, t, n) {
456
+ for (let r of this.#c.filter((t) => t.toolName === e)) try {
457
+ let i = r.callback(t, n);
458
+ r.options.await ? await i : Promise.resolve(i).catch((r) => {
459
+ this.#T(e, "before", r, t, n);
460
+ });
461
+ } catch (i) {
462
+ if (await this.#T(e, "before", i, t, n), r.options.errorCancel) return {
463
+ canceled: !0,
464
+ error: i
465
+ };
466
+ }
467
+ return { canceled: !1 };
468
+ }
469
+ async #C(e, t, n, r) {
470
+ for (let i of this.#l.filter((t) => t.toolName === e)) try {
471
+ let a = i.callback(t, n, r);
472
+ i.options.await ? await a : Promise.resolve(a).catch((i) => {
473
+ this.#T(e, "after", i, t, n, r);
474
+ });
475
+ } catch (i) {
476
+ await this.#T(e, "after", i, t, n, r);
477
+ }
478
+ }
479
+ async #w(e) {
480
+ for (let t of this.#f) try {
481
+ await t(e);
482
+ } catch {}
483
+ }
484
+ async #T(e, t, n, r, i, a) {
485
+ for (let o of this.#u) try {
486
+ await o(e, t, n, r, i, a);
487
+ } catch {}
488
+ }
489
+ #E(e) {
490
+ for (let t of this.#p) try {
491
+ let n = t(e);
492
+ Promise.resolve(n).catch((e) => {});
493
+ } catch {}
494
+ }
495
+ #D(e) {
496
+ this.#e.push(e), this.#t.push(e);
497
+ }
498
+ #O(e) {
499
+ return this.#D(e), e;
500
+ }
501
+ #k(e, t) {
502
+ return this.#o.buildToolCallOutputMessage({
503
+ callId: e,
504
+ output: t
505
+ });
506
+ }
507
+ #A(e) {
508
+ if (this.#i !== e) {
509
+ this.#i = e;
510
+ for (let t of this.#d.filter((t) => t.status === e)) Promise.resolve(t.callback([...this.#e], [...this.#t])).catch(() => {});
511
+ }
512
+ }
513
+ };
514
+ function w(e, t) {
515
+ return e.push(t), () => {
516
+ let n = e.indexOf(t);
517
+ n >= 0 && e.splice(n, 1);
518
+ };
519
+ }
520
+ function T(e) {
521
+ return {
522
+ await: e?.await ?? !1,
523
+ errorCancel: e?.errorCancel ?? !1
524
+ };
525
+ }
526
+ function E(e) {
527
+ if (typeof e == "string") return e;
528
+ if (e === void 0) return "";
529
+ try {
530
+ return JSON.stringify(e);
531
+ } catch {
532
+ return String(e);
533
+ }
534
+ }
535
+ function D(e) {
536
+ return e instanceof Error ? e.message : E(e);
537
+ }
538
+ function O(e) {
539
+ return e instanceof Error ? e : Error(String(e));
540
+ }
541
+ function k(e) {
542
+ let t = e;
543
+ return t[S] ??= [], t[S];
544
+ }
545
+ function A(e, t) {
546
+ let n = e;
547
+ n[S] = t;
548
+ }
549
+ function j(e, t) {
550
+ let n = e.toolsDefinition.length === 0 ? " 当前子代理没有声明工具能力。" : e.toolsDefinition.map(M).join("\n");
551
+ return [
552
+ `子代理${t + 1}:`,
553
+ ` 名称:${e.name || "未命名代理"}`,
554
+ ` 描述:${e.description ?? "未提供描述。"}`,
555
+ " 工具能力:",
556
+ n
557
+ ].join("\n");
558
+ }
559
+ function M(e, t) {
560
+ return [` - 工具${t + 1}:${e.name}`, ` 描述:${typeof e.description == "function" ? "动态描述,运行时生成。" : e.description}`].join("\n");
561
+ }
562
+ //#endregion
563
+ //#region src/llm/base/index.ts
564
+ var N = class {};
565
+ //#endregion
566
+ //#region src/llm/openai-schema.ts
567
+ function P(e) {
568
+ let t = L(F(e));
569
+ if (t) return t;
570
+ let n = L(I(e));
571
+ if (n) return n;
572
+ throw Error("Tool parameters must resolve to a JSON object schema.");
573
+ }
574
+ function F(e) {
575
+ try {
576
+ return n(e, { target: "openAi" });
577
+ } catch {
578
+ return null;
579
+ }
580
+ }
581
+ function I(t) {
582
+ try {
583
+ return e.toJSONSchema(t);
584
+ } catch {
585
+ return null;
586
+ }
587
+ }
588
+ function L(e) {
589
+ if (!V(e)) return null;
590
+ let t = B(R(B(e)));
591
+ return t.type === "object" ? t : null;
592
+ }
593
+ function R(e) {
594
+ let t = e.$ref;
595
+ if (typeof t != "string" || !t.startsWith("#/")) return e;
596
+ let n = z(e, t);
597
+ if (!n) return e;
598
+ let r = { ...n };
599
+ return V(e.definitions) && !("definitions" in r) && (r.definitions = e.definitions), V(e.$defs) && !("$defs" in r) && (r.$defs = e.$defs), r;
600
+ }
601
+ function z(e, t) {
602
+ let n = t.slice(2).split("/").map((e) => e.replace(/~1/g, "/").replace(/~0/g, "~")), r = e;
603
+ for (let e of n) {
604
+ if (!V(r)) return null;
605
+ r = r[e];
606
+ }
607
+ return V(r) ? r : null;
608
+ }
609
+ function B(e) {
610
+ let t = { ...e };
611
+ return delete t.$schema, t;
612
+ }
613
+ function V(e) {
614
+ return typeof e == "object" && !!e && !Array.isArray(e);
615
+ }
616
+ //#endregion
617
+ //#region src/llm/chat/index.ts
618
+ var H = class extends N {
619
+ #e;
620
+ #t;
621
+ #n;
622
+ constructor(e) {
623
+ super();
624
+ let { client: n, model: r, defaultParams: i, ...a } = e;
625
+ this.#t = r, this.#n = i, this.#e = n ?? new t(a);
626
+ }
627
+ async generate(e) {
628
+ let t = {
629
+ ...this.#n,
630
+ model: this.#t,
631
+ messages: e.context
632
+ };
633
+ e.tools.length > 0 && (t.tools = e.tools);
634
+ let n = await this.#e.chat.completions.create(t), r = n.choices[0]?.message;
635
+ return {
636
+ messages: r ? [r] : [],
637
+ raw: n
638
+ };
639
+ }
640
+ buildUserMessage(e) {
641
+ return {
642
+ role: "user",
643
+ content: e.content.map((e) => e.type === "text" ? {
644
+ type: "text",
645
+ text: e.text
646
+ } : e),
647
+ ..."name" in e && e.name ? { name: e.name } : {}
648
+ };
649
+ }
650
+ buildSystemMessage(e) {
651
+ return {
652
+ role: "system",
653
+ content: e.content,
654
+ ..."name" in e && e.name ? { name: e.name } : {}
655
+ };
656
+ }
657
+ buildToolCallOutputMessage(e) {
658
+ return {
659
+ role: "tool",
660
+ tool_call_id: e.callId,
661
+ content: e.output
662
+ };
663
+ }
664
+ buildToolMessage(e) {
665
+ return {
666
+ type: "function",
667
+ function: {
668
+ name: e.name,
669
+ description: e.description,
670
+ parameters: P(e.parameters ?? u()),
671
+ ...e.strict === void 0 ? {} : { strict: e.strict }
672
+ }
673
+ };
674
+ }
675
+ parseUserMessages(e) {
676
+ return e.flatMap((e) => e.role === "user" ? [{
677
+ message: {
678
+ content: U(e.content),
679
+ ...e.name ? { name: e.name } : {}
680
+ },
681
+ sourceMessage: e
682
+ }] : []);
683
+ }
684
+ parseSystemMessages(e) {
685
+ return e.flatMap((e) => e.role === "system" ? [{
686
+ message: {
687
+ content: W(e.content),
688
+ ...e.name ? { name: e.name } : {}
689
+ },
690
+ sourceMessage: e
691
+ }] : []);
692
+ }
693
+ parseAssistantMessages(e) {
694
+ return e.flatMap((e) => {
695
+ if (e.role !== "assistant") return [];
696
+ let t = G(e.content);
697
+ return [{
698
+ message: {
699
+ content: t.content,
700
+ ...t.refusals.length > 0 ? { refusals: t.refusals } : {},
701
+ ...e.refusal === void 0 ? {} : { refusal: e.refusal }
702
+ },
703
+ sourceMessage: e
704
+ }];
705
+ });
706
+ }
707
+ parseToolCalls(e) {
708
+ return e.flatMap((e) => e.role === "assistant" ? (e.tool_calls ?? []).flatMap((t) => t.type === "function" ? [{
709
+ id: t.id,
710
+ name: t.function.name,
711
+ arguments: t.function.arguments,
712
+ sourceMessage: e,
713
+ sourceCall: t
714
+ }] : []) : []);
715
+ }
716
+ parseToolCallOutputMessages(e) {
717
+ return e.flatMap((e) => e.role === "tool" ? [{
718
+ message: {
719
+ callId: e.tool_call_id,
720
+ output: W(e.content)
721
+ },
722
+ sourceMessage: e
723
+ }] : []);
724
+ }
725
+ };
726
+ function U(e) {
727
+ return typeof e == "string" ? [{
728
+ type: "text",
729
+ text: e
730
+ }] : e.map((e) => e.type === "text" ? {
731
+ type: "text",
732
+ text: e.text
733
+ } : e);
734
+ }
735
+ function W(e) {
736
+ return typeof e == "string" ? e : e.map((e) => e.text).join("");
737
+ }
738
+ function G(e) {
739
+ return typeof e == "string" ? {
740
+ content: [{
741
+ type: "text",
742
+ text: e
743
+ }],
744
+ refusals: []
745
+ } : e ? {
746
+ content: e.flatMap((e) => e.type === "text" ? [{
747
+ type: "text",
748
+ text: e.text
749
+ }] : []),
750
+ refusals: e.flatMap((e) => e.type === "refusal" ? [e.refusal] : [])
751
+ } : {
752
+ content: [],
753
+ refusals: []
754
+ };
755
+ }
756
+ //#endregion
757
+ //#region src/llm/responses/index.ts
758
+ var K = class extends N {
759
+ #e;
760
+ #t;
761
+ #n;
762
+ constructor(e) {
763
+ super();
764
+ let { client: n, model: r, defaultParams: i, ...a } = e;
765
+ this.#t = r, this.#n = i, this.#e = n ?? new t(a);
766
+ }
767
+ async generate(e) {
768
+ let t = {
769
+ ...this.#n,
770
+ model: this.#t,
771
+ input: e.context
772
+ };
773
+ e.tools.length > 0 && (t.tools = e.tools);
774
+ let n = await this.#e.responses.create(t);
775
+ return {
776
+ messages: n.output,
777
+ raw: n
778
+ };
779
+ }
780
+ buildUserMessage(e) {
781
+ return {
782
+ role: "user",
783
+ content: e.content.map((e) => e.type === "text" ? {
784
+ type: "input_text",
785
+ text: e.text
786
+ } : e)
787
+ };
788
+ }
789
+ buildSystemMessage(e) {
790
+ return {
791
+ role: "system",
792
+ content: [{
793
+ type: "input_text",
794
+ text: e.content
795
+ }]
796
+ };
797
+ }
798
+ buildToolCallOutputMessage(e) {
799
+ return {
800
+ type: "function_call_output",
801
+ call_id: e.callId,
802
+ output: e.output
803
+ };
804
+ }
805
+ buildToolMessage(e) {
806
+ return {
807
+ type: "function",
808
+ name: e.name,
809
+ description: e.description,
810
+ parameters: P(e.parameters ?? u()),
811
+ ...e.strict === void 0 ? {} : { strict: e.strict }
812
+ };
813
+ }
814
+ parseUserMessages(e) {
815
+ return e.flatMap((e) => Y(e, "user") ? [{
816
+ message: { content: q(e.content) },
817
+ sourceMessage: e
818
+ }] : []);
819
+ }
820
+ parseSystemMessages(e) {
821
+ return e.flatMap((e) => Y(e, "system") ? [{
822
+ message: { content: J(e.content) },
823
+ sourceMessage: e
824
+ }] : []);
825
+ }
826
+ parseAssistantMessages(e) {
827
+ return e.flatMap((e) => e.type !== "message" || e.role !== "assistant" || !("id" in e) ? [] : [{
828
+ message: {
829
+ content: e.content.flatMap((e) => e.type === "output_text" ? [{
830
+ type: "text",
831
+ text: e.text
832
+ }] : []),
833
+ refusals: e.content.flatMap((e) => e.type === "refusal" ? [e.refusal] : [])
834
+ },
835
+ sourceMessage: e
836
+ }]);
837
+ }
838
+ parseToolCalls(e) {
839
+ return e.flatMap((e) => e.type === "function_call" ? [{
840
+ id: e.call_id,
841
+ name: e.name,
842
+ arguments: e.arguments,
843
+ sourceMessage: e,
844
+ sourceCall: e
845
+ }] : []);
846
+ }
847
+ parseToolCallOutputMessages(e) {
848
+ return e.flatMap((e) => e.type === "function_call_output" ? [{
849
+ message: {
850
+ callId: e.call_id,
851
+ output: e.output
852
+ },
853
+ sourceMessage: e
854
+ }] : []);
855
+ }
856
+ async uploadFile(e, t = {}) {
857
+ return this.#e.files.create({
858
+ file: r(e),
859
+ purpose: t.purpose ?? "user_data"
860
+ });
861
+ }
862
+ };
863
+ function q(e) {
864
+ return typeof e == "string" ? [{
865
+ type: "text",
866
+ text: e
867
+ }] : e.map((e) => e.type === "input_text" ? {
868
+ type: "text",
869
+ text: e.text
870
+ } : e);
871
+ }
872
+ function J(e) {
873
+ return typeof e == "string" ? e : e.flatMap((e) => e.type === "input_text" ? [e.text] : []).join("\n");
874
+ }
875
+ function Y(e, t) {
876
+ return "role" in e && e.role === t && !("id" in e);
877
+ }
878
+ //#endregion
879
+ export { C as Agent, N as Model, H as OpenAIChatModel, K as OpenAIResponsesModel, a as Tool };
880
+
881
+ //# sourceMappingURL=index.js.map