@zimtsui/brainswitch 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +165 -0
  2. package/README.md +164 -0
  3. package/build/adaptor.d.ts +12 -0
  4. package/build/adaptor.js +62 -0
  5. package/build/adaptor.js.map +1 -0
  6. package/build/agentloop.d.ts +12 -0
  7. package/build/agentloop.js +47 -0
  8. package/build/agentloop.js.map +1 -0
  9. package/build/api-types/base.d.ts +21 -0
  10. package/build/api-types/base.js +37 -0
  11. package/build/api-types/base.js.map +1 -0
  12. package/build/api-types/google-base.d.ts +22 -0
  13. package/build/api-types/google-base.js +142 -0
  14. package/build/api-types/google-base.js.map +1 -0
  15. package/build/api-types/google-rest.d.ts +20 -0
  16. package/build/api-types/google-rest.js +113 -0
  17. package/build/api-types/google-rest.js.map +1 -0
  18. package/build/api-types/huggingface-cerebras-qwen3-thinking.d.ts +13 -0
  19. package/build/api-types/huggingface-cerebras-qwen3-thinking.js +52 -0
  20. package/build/api-types/huggingface-cerebras-qwen3-thinking.js.map +1 -0
  21. package/build/api-types/openai-chatcompletions-base.d.ts +28 -0
  22. package/build/api-types/openai-chatcompletions-base.js +150 -0
  23. package/build/api-types/openai-chatcompletions-base.js.map +1 -0
  24. package/build/api-types/openai-chatcompletions-monolith-base.d.ts +10 -0
  25. package/build/api-types/openai-chatcompletions-monolith-base.js +85 -0
  26. package/build/api-types/openai-chatcompletions-monolith-base.js.map +1 -0
  27. package/build/api-types/openai-chatcompletions-stream-base.d.ts +11 -0
  28. package/build/api-types/openai-chatcompletions-stream-base.js +110 -0
  29. package/build/api-types/openai-chatcompletions-stream-base.js.map +1 -0
  30. package/build/api-types/openai-chatcompletions.d.ts +6 -0
  31. package/build/api-types/openai-chatcompletions.js +10 -0
  32. package/build/api-types/openai-chatcompletions.js.map +1 -0
  33. package/build/api-types/openai-responses.d.ts +30 -0
  34. package/build/api-types/openai-responses.js +216 -0
  35. package/build/api-types/openai-responses.js.map +1 -0
  36. package/build/api-types/openrouter-monolith.d.ts +21 -0
  37. package/build/api-types/openrouter-monolith.js +57 -0
  38. package/build/api-types/openrouter-monolith.js.map +1 -0
  39. package/build/api-types/openrouter-stream.d.ts +27 -0
  40. package/build/api-types/openrouter-stream.js +68 -0
  41. package/build/api-types/openrouter-stream.js.map +1 -0
  42. package/build/api-types/qwen.d.ts +11 -0
  43. package/build/api-types/qwen.js +13 -0
  44. package/build/api-types/qwen.js.map +1 -0
  45. package/build/config.d.ts +23 -0
  46. package/build/config.js +12 -0
  47. package/build/config.js.map +1 -0
  48. package/build/endpoint-spec.d.ts +19 -0
  49. package/build/endpoint-spec.js +28 -0
  50. package/build/endpoint-spec.js.map +1 -0
  51. package/build/engine.d.ts +23 -0
  52. package/build/engine.js +18 -0
  53. package/build/engine.js.map +1 -0
  54. package/build/exports.d.ts +9 -0
  55. package/build/exports.js +10 -0
  56. package/build/exports.js.map +1 -0
  57. package/build/function.d.ts +68 -0
  58. package/build/function.js +41 -0
  59. package/build/function.js.map +1 -0
  60. package/build/inference-context.d.ts +15 -0
  61. package/build/inference-context.js +4 -0
  62. package/build/inference-context.js.map +1 -0
  63. package/build/session.d.ts +55 -0
  64. package/build/session.js +78 -0
  65. package/build/session.js.map +1 -0
  66. package/build/test.d.ts +1 -0
  67. package/build/test.js +23 -0
  68. package/build/test.js.map +1 -0
  69. package/build/throttle.d.ts +14 -0
  70. package/build/throttle.js +50 -0
  71. package/build/throttle.js.map +1 -0
  72. package/build/tsconfig.tsbuildinfo +1 -0
  73. package/package.json +38 -0
  74. package/typedoc.json +8 -0
package/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ <!-- 本文档由 GPT-5 生成 -->
2
+
3
+ # Brainswitch
4
+
5
+ [![Npm package version](https://flat.badgen.net/npm/v/@zimtsui/brainswitch)](https://www.npmjs.com/package/@zimtsui/brainswitch)
6
+
7
+ Brainswitch 是一个为 AI 工作流设计的 LLM 推理 API 适配器,支持在会话中切换模型。
8
+
9
+ ## Motivation
10
+
11
+ 大多数 LLM 推理服务商不支持[严格函数调用](https://platform.openai.com/docs/guides/function-calling#strict-mode),在 AI 批处理工作流中难以达到生产级的可靠性。如果仅使用 OpenAI、Google 等支持严格函数调用的服务商,那么可选的模型型号会大幅受限。
12
+
13
+ Brainswitch 支持在一次会话中途切换模型并保持对话上下文,包括 OpenAI、Google 的深度思考模型的加密思考内容。有了 Brainswitch 就可以在会话的大量推理阶段使用最合适的模型生成自然语言结果,在最后的总结阶段切换成支持严格函数调用的模型进行结构化提交。
14
+
15
+ ## 支持服务商 API 类型
16
+
17
+ - OpenAI Chat Completions
18
+ - OpenAI Responses
19
+ - Google
20
+ - Qwen
21
+ - OpenRouter
22
+ - HuggingFace Cerebras Qwen3 Thinking
23
+
24
+ ## 安装
25
+
26
+ 环境要求:Node.js >= 22。
27
+
28
+ ```bash
29
+ npm i @zimtsui/brainswitch
30
+ ```
31
+
32
+ ## 核心概念
33
+
34
+ - `Session`:会话状态,包含开发者提示词和往返消息。
35
+ - `InferenceContext`:工作流上下文,包含 [TypeLog](https://github.com/zimtsui/typelog) Logger、`AbortSignal`、用户防止并发过载的[读写锁](https://github.com/zimtsui/coroutine-locks)。
36
+ - `Engine`:一个函数 `(ctx, session) => Promise<AIMessage>`;实现了具体服务商的请求/响应适配。
37
+ - `Endpoint`:一家服务商的某个模型的 API 端点。
38
+ - `Adaptor`:创建使用某个 Endpoint 的 `Engine`。
39
+ - `RoleMessage`:三类角色消息 `Developer`、`User`、`AI`,消息由 `Text` 与 `Function.Call/Response` 片段组成。
40
+ - `Function.Declaration.Map`:函数工具声明集合,使用 [JSON Schema](https://json-schema.org/) 描述函数参数。
41
+
42
+ ## 配置
43
+
44
+ ```ts
45
+ export type Config = {
46
+ brainswitch: {
47
+ endpoints: Record<string, {
48
+ baseUrl: string;
49
+ apiKey: string;
50
+ model: string;
51
+ name: string;
52
+ apiType: 'openai-chatcompletions' | 'openai-responses' | 'google' | 'qwen' | 'openrouter-monolith' | 'openrouter-stream' | 'huggingface-cerebras-qwen3-thinking';
53
+ proxy?: string;
54
+ inputPrice?: number; // 每百万输入 Token 人民币成本
55
+ outputPrice?: number; // 每百万输出 Token 人民币成本
56
+ cachedPrice?: number; // 每百万缓存命中 Token 人民币成本
57
+ customOptions?: Record<string, unknown>; // 直通服务商的自定义参数
58
+ rpm?: number; // 每分钟请求次数上限
59
+ tpm?: number; // 每分钟 Token 上限
60
+ timeout?: number; // 单次请求超时(毫秒)
61
+ }>;
62
+ };
63
+ }
64
+ ```
65
+
66
+ ### 计费说明
67
+
68
+ `inputPrice`/`outputPrice`/`cachedPrice` 的单位均为「人民币每百万 Token」。OpenRouter 的成本会自动按服务器返回的 USD 成本并使用固定汇率(源码中默认 8)换算为 CNY 记账。
69
+
70
+ ## 快速上手
71
+
72
+ 下面演示:定义一个工具函数,先用 Google 做推理与工具调用,再在同一会话中切换到 OpenAI Responses 做最终的结构化总结。
73
+
74
+ ```ts
75
+ import { Adaptor, agentloop, RoleMessage, Function, type InferenceContext } from '@zimtsui/brainswitch';
76
+ import { Type } from '@sinclair/typebox';
77
+ import { RWLock } from '@zimtsui/coroutine-locks';
78
+ import { Channel } from '@zimtsui/typelog';
79
+ import * as Presets from '@zimtsui/typelog/presets';
80
+
81
+ // 配置
82
+ const config: Config = {
83
+ brainswitch: {
84
+ endpoints: {
85
+ 'gpt-4o-mini': {
86
+ name: 'GPT-4o mini',
87
+ apiType: 'openai-chatcompletions',
88
+ baseUrl: 'https://api.openai.com/v1',
89
+ apiKey: process.env.OPENAI_API_KEY!,
90
+ model: 'gpt-4o-mini',
91
+ inputPrice: 5, outputPrice: 15, cachedPrice: 1,
92
+ rpm: 3000, tpm: 1_000_000, timeout: 60_000,
93
+ },
94
+ 'o4-mini': {
95
+ name: 'o4 mini',
96
+ apiType: 'openai-responses',
97
+ baseUrl: 'https://api.openai.com/v1',
98
+ apiKey: process.env.OPENAI_API_KEY!,
99
+ model: 'o4-mini',
100
+ },
101
+ 'gemini-2.0-flash': {
102
+ name: 'Gemini 2.0 Flash',
103
+ apiType: 'google',
104
+ baseUrl: 'https://generativelanguage.googleapis.com',
105
+ apiKey: process.env.GOOGLE_API_KEY!,
106
+ model: 'gemini-2.0-flash',
107
+ },
108
+ }
109
+ }
110
+ }
111
+
112
+ // 声明函数工具
113
+ const fdm = {
114
+ get_weather: {
115
+ description: '获取某城市的天气',
116
+ paraschema: Type.Object({
117
+ city: Type.String(),
118
+ unit: Type.Optional(Type.Union([Type.Literal('C'), Type.Literal('F')]))
119
+ }),
120
+ },
121
+ } satisfies Function.Declaration.Map;
122
+ type fdm = typeof fdm;
123
+
124
+ const fnm: Function.Map<fdm> = {
125
+ async get_weather({ city, unit }) {
126
+ // 实际项目中此处调用真实 API,这里仅示例
127
+ const data = { city, unit: unit ?? 'C', temperature: 26, sky: 'sunny' };
128
+ return JSON.stringify(data);
129
+ },
130
+ };
131
+
132
+ // 初始化工作流上下文
133
+ const ctx: InferenceContext = {
134
+ busy: new RWLock(),
135
+ logger: {
136
+ message: new Channel(Presets.Level),
137
+ cost(deltaCost) { console.log((-deltaCost).toFixed(2)); },
138
+ },
139
+ };
140
+
141
+ // 创建会话
142
+ const session = {
143
+ developerMessage: new RoleMessage.Developer([
144
+ new RoleMessage.Text('你是一个会使用工具的中文助理,遇到需要实时数据请调用工具,完成后用简洁中文回答。'),
145
+ ]),
146
+ chatMessages: [
147
+ new RoleMessage.User([ new RoleMessage.Text('帮我查一下明天北京的天气,并给穿衣建议。') ]),
148
+ ],
149
+ };
150
+
151
+ // 选择推理引擎
152
+ const adaptor = Adaptor.create(config);
153
+ const engineReason = adaptor.createEngine('gemini-2.0-flash', fdm, ['get_weather']);
154
+
155
+ // 使用 agentloop 驱动工具调用到完成,最多 8 轮对话
156
+ for await (const text of agentloop(ctx, session, engineReason, fnm, 8)) console.log(text);
157
+
158
+ // 在同一会话中切换到 OpenAI Responses 做结构化总结
159
+ session.chatMessages.push(new RoleMessage.User([
160
+ new RoleMessage.Text('请把以上结论整理成 JSON:{"reason": string, "advice": string}')
161
+ ]));
162
+ const engineStrict = adaptor.createEngine('gpt-4o-mini', fdm); // Responses API 在声明了工具时会强制严格模式
163
+ for await (const text of agentloop(ctx, session, engineStrict, fnm, 4)) console.log(text);
164
+ ```
@@ -0,0 +1,12 @@
1
+ import { Config } from '#config';
2
+ import { Function } from './function.ts';
3
+ import { Engine } from './engine.ts';
4
+ import { Throttle } from './throttle.ts';
5
+ export declare class Adaptor {
6
+ config: Config;
7
+ static create(config: Config): Adaptor;
8
+ protected constructor(config: Config);
9
+ private throttles;
10
+ getThrottle(endpointId: string): Throttle;
11
+ createEngine<fdm extends Function.Declaration.Map = {}>(endpoint: string, functionDeclarationMap: fdm, functionCallMode?: Function.ToolChoice<fdm>): Engine<Function.Declaration.From<fdm>>;
12
+ }
@@ -0,0 +1,62 @@
1
+ import { Config } from '#config';
2
+ import { Function } from "./function.js";
3
+ import { Engine } from "./engine.js";
4
+ import assert from 'node:assert';
5
+ import { OpenAIChatCompletionsAPI } from "./api-types/openai-chatcompletions.js";
6
+ import { GoogleRESTfulAPI } from "./api-types/google-rest.js";
7
+ import { OpenRouterMonolithAPI } from "./api-types/openrouter-monolith.js";
8
+ import { OpenRouterStreamAPI } from "./api-types/openrouter-stream.js";
9
+ import { QwenAPI } from "./api-types/qwen.js";
10
+ import { OpenAIResponsesAPI } from "./api-types/openai-responses.js";
11
+ import { HuggingFaceCerebrasQwen3ThinkingAPI } from "./api-types/huggingface-cerebras-qwen3-thinking.js";
12
+ import { Throttle } from "./throttle.js";
13
+ export class Adaptor {
14
+ config;
15
+ static create(config) {
16
+ return new Adaptor(config);
17
+ }
18
+ constructor(config) {
19
+ this.config = config;
20
+ }
21
+ throttles = new Map();
22
+ getThrottle(endpointId) {
23
+ assert(endpointId in this.config.brainswitch.endpoints);
24
+ const baseUrl = this.config.brainswitch.endpoints[endpointId].baseUrl;
25
+ const model = this.config.brainswitch.endpoints[endpointId].model;
26
+ const rpm = this.config.brainswitch.endpoints[endpointId].rpm ?? Number.POSITIVE_INFINITY;
27
+ const tpm = this.config.brainswitch.endpoints[endpointId].tpm ?? Number.POSITIVE_INFINITY;
28
+ if (!this.throttles.has(baseUrl))
29
+ this.throttles.set(baseUrl, new Map());
30
+ if (!this.throttles.get(baseUrl).has(model))
31
+ this.throttles.get(baseUrl).set(model, new Throttle(rpm, tpm));
32
+ return this.throttles.get(baseUrl).get(model);
33
+ }
34
+ createEngine(endpoint, functionDeclarationMap, functionCallMode) {
35
+ assert(endpoint in this.config.brainswitch.endpoints);
36
+ const endpointSpec = this.config.brainswitch.endpoints[endpoint];
37
+ const throttle = this.getThrottle(endpoint);
38
+ const options = {
39
+ ...endpointSpec,
40
+ functionDeclarationMap,
41
+ functionCallMode,
42
+ throttle,
43
+ };
44
+ if (endpointSpec.apiType === 'openai-responses')
45
+ return OpenAIResponsesAPI.create(options);
46
+ else if (endpointSpec.apiType === 'openai-chatcompletions')
47
+ return OpenAIChatCompletionsAPI.create(options);
48
+ else if (endpointSpec.apiType === 'google')
49
+ return GoogleRESTfulAPI.create(options);
50
+ else if (endpointSpec.apiType === 'qwen')
51
+ return QwenAPI.create(options);
52
+ else if (endpointSpec.apiType === 'openrouter-monolith')
53
+ return OpenRouterMonolithAPI.create(options);
54
+ else if (endpointSpec.apiType === 'openrouter-stream')
55
+ return OpenRouterStreamAPI.create(options);
56
+ else if (endpointSpec.apiType === 'huggingface-cerebras-qwen3-thinking')
57
+ return HuggingFaceCerebrasQwen3ThinkingAPI.create(options);
58
+ else
59
+ throw new Error();
60
+ }
61
+ }
62
+ //# sourceMappingURL=adaptor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adaptor.js","sourceRoot":"","sources":["../src/adaptor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,uCAAuC,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BA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AAK,qBAAqB;YACtD,OAAO,qBAAqB,CAAC,MAAM,CAAM,OAAO,CAAC,CAAC;aAC9C,IAAI,YAAY,CAAC,OAAO,KAAK,mBAAmB;YACpD,OAAO,mBAAmB,CAAC,MAAM,CAAM,OAAO,CAAC,CAAC;aAC5C,IAAI,YAAY,CAAC,OAAO,KAAK,qCAAqC;YACtE,OAAO,mCAAmC,CAAC,MAAM,CAAM,OAAO,CAAC,CAAC;;YAC5D,MAAM,IAAI,KAAK,EAAE,CAAC;IACxB,CAAC;CACD"}
@@ -0,0 +1,12 @@
1
+ import { type InferenceContext } from './inference-context.ts';
2
+ import { type Session } from './session.ts';
3
+ import { Function } from './function.ts';
4
+ import { Engine } from './engine.ts';
5
+ /**
6
+ * @param session mutable
7
+ */
8
+ export declare function agentloop<fdm extends Function.Declaration.Map>(ctx: InferenceContext, session: Session<Function.Declaration.From<fdm>>, engine: Engine<Function.Declaration.From<fdm>>, functionMap: Function.Map<fdm>, limit?: number): AsyncGenerator<string, void, void>;
9
+ export declare namespace agentloop {
10
+ class FunctionCallLimitExceeded extends Error {
11
+ }
12
+ }
@@ -0,0 +1,47 @@
1
+ import {} from "./inference-context.js";
2
+ import { RoleMessage } from "./session.js";
3
+ import { Function } from "./function.js";
4
+ import { Engine } from "./engine.js";
5
+ import assert from 'node:assert';
6
+ /**
7
+ * @param session mutable
8
+ */
9
+ export async function* agentloop(ctx, session, engine, functionMap, limit = Number.POSITIVE_INFINITY) {
10
+ for (let i = 0; i < limit; i++) {
11
+ const response = await Engine.apply(ctx, session, engine);
12
+ const fcs = response.getFunctionCalls();
13
+ if (fcs.length) {
14
+ const parts = [];
15
+ for (const part of response.parts) {
16
+ if (part instanceof RoleMessage.Text) {
17
+ yield part.text;
18
+ }
19
+ else if (part instanceof Function.Call) {
20
+ const fc = part;
21
+ const f = functionMap[fc.name];
22
+ assert(f);
23
+ const text = await f(fc.args);
24
+ ctx.logger.message?.debug('\n' + text);
25
+ const fr = Function.Response.create({
26
+ id: fc.id,
27
+ name: fc.name,
28
+ text,
29
+ });
30
+ parts.push(fr);
31
+ }
32
+ else
33
+ throw new Error();
34
+ }
35
+ session.chatMessages.push(new RoleMessage.User(parts));
36
+ }
37
+ else
38
+ return yield response.getOnlyText();
39
+ }
40
+ throw new agentloop.FunctionCallLimitExceeded('Function call limit exceeded.');
41
+ }
42
+ (function (agentloop) {
43
+ class FunctionCallLimitExceeded extends Error {
44
+ }
45
+ agentloop.FunctionCallLimitExceeded = FunctionCallLimitExceeded;
46
+ })(agentloop || (agentloop = {}));
47
+ //# sourceMappingURL=agentloop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agentloop.js","sourceRoot":"","sources":["../src/agentloop.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyB,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAgB,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,MAAM,MAAM,aAAa,CAAC;AAGjC;;GAEG;AACH,MAAM,CAAC,KAAK,SAAU,CAAC,CAAA,SAAS,CAC/B,GAAqB,EACrB,OAAgD,EAChD,MAA8C,EAC9C,WAA8B,EAC9B,KAAK,GAAG,MAAM,CAAC,iBAAiB;IAEhC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;QAChC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QAC1D,MAAM,GAAG,GAAG,QAAQ,CAAC,gBAAgB,EAAE,CAAC;QACxC,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;YAChB,MAAM,KAAK,GAAqE,EAAE,CAAC;YACnF,KAAK,MAAM,IAAI,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;gBACnC,IAAI,IAAI,YAAY,WAAW,CAAC,IAAI,EAAE,CAAC;oBACtC,MAAM,IAAI,CAAC,IAAI,CAAC;gBACjB,CAAC;qBAAM,IAAI,IAAI,YAAY,QAAQ,CAAC,IAAI,EAAE,CAAC;oBAC1C,MAAM,EAAE,GAAG,IAAkE,CAAC;oBAC9E,MAAM,CAAC,GAAG,WAAW,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;oBAC/B,MAAM,CAAC,CAAC,CAAC,CAAC;oBACV,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;oBAC9B,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,GAAC,IAAI,CAAC,CAAC;oBACrC,MAAM,EAAE,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;wBACnC,EAAE,EAAE,EAAE,CAAC,EAAE;wBACT,IAAI,EAAE,EAAE,CAAC,IAAI;wBACb,IAAI;qBACgE,CAAC,CAAC;oBACvE,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBAChB,CAAC;;oBAAM,MAAM,IAAI,KAAK,EAAE,CAAC;YAC1B,CAAC;YACD,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,IAAI,CAAiC,KAAK,CAAC,CAAC,CAAC;QACxF,CAAC;;YAAM,OAAO,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC;IAC5C,CAAC;IACD,MAAM,IAAI,SAAS,CAAC,yBAAyB,CAAC,+BAA+B,CAAC,CAAC;AAChF,CAAC;AAED,WAAiB,SAAS;IACzB,MAAa,yBAA0B,SAAQ,KAAK;KAAG;IAA1C,mCAAyB,4BAAiB,CAAA;AACxD,CAAC,EAFgB,SAAS,KAAT,SAAS,QAEzB"}
@@ -0,0 +1,21 @@
1
+ import { Function } from '../function.ts';
2
+ import { Engine } from '../engine.ts';
3
+ import { Throttle } from '../throttle.ts';
4
+ export declare abstract class APIBase<in out fdm extends Function.Declaration.Map = {}> {
5
+ protected baseUrl: string;
6
+ protected apiKey: string;
7
+ protected model: string;
8
+ protected inputPrice: number;
9
+ protected outputPrice: number;
10
+ protected cachedPrice: number;
11
+ protected functionDeclarationMap: fdm;
12
+ protected toolChoice: Function.ToolChoice<fdm>;
13
+ protected customOptions?: Record<string, unknown>;
14
+ protected throttle: Throttle;
15
+ protected timeout?: number;
16
+ constructor(options: Engine.Options<fdm>);
17
+ }
18
+ export declare class TransientError extends Error {
19
+ }
20
+ export declare class RetryLimitError extends Error {
21
+ }
@@ -0,0 +1,37 @@
1
+ import { Function } from "../function.js";
2
+ import { Engine } from "../engine.js";
3
+ import { Throttle } from "../throttle.js";
4
+ export class APIBase {
5
+ baseUrl;
6
+ apiKey;
7
+ model;
8
+ inputPrice;
9
+ outputPrice;
10
+ cachedPrice;
11
+ functionDeclarationMap;
12
+ toolChoice;
13
+ customOptions;
14
+ throttle;
15
+ timeout;
16
+ constructor(options) {
17
+ this.baseUrl = options.baseUrl;
18
+ this.apiKey = options.apiKey;
19
+ this.model = options.model;
20
+ this.inputPrice = options.inputPrice ?? 0;
21
+ this.outputPrice = options.outputPrice ?? 0;
22
+ this.cachedPrice = options.cachedPrice ?? this.inputPrice;
23
+ this.functionDeclarationMap = options.functionDeclarationMap;
24
+ if (Object.keys(this.functionDeclarationMap).length)
25
+ this.toolChoice = options.functionCallMode ?? Function.ToolChoice.AUTO;
26
+ else
27
+ this.toolChoice = Function.ToolChoice.NONE;
28
+ this.customOptions = options.customOptions;
29
+ this.throttle = options.throttle;
30
+ this.timeout = options.timeout;
31
+ }
32
+ }
33
+ export class TransientError extends Error {
34
+ }
35
+ export class RetryLimitError extends Error {
36
+ }
37
+ //# sourceMappingURL=base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../src/api-types/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,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AQ,KAAK;CAAG;AAC5C,MAAM,OAAO,eAAgB,SAAQ,KAAK;CAAG"}
@@ -0,0 +1,22 @@
1
+ import { Engine } from '../engine.ts';
2
+ import { RoleMessage, type ChatMessage } from '../session.ts';
3
+ import { Function } from '../function.ts';
4
+ import * as Google from '@google/genai';
5
+ import { APIBase } from './base.ts';
6
+ export declare abstract class GoogleAPIBase<in out fdm extends Function.Declaration.Map = {}> extends APIBase<fdm> {
7
+ protected constructor(options: Engine.Options<fdm>);
8
+ protected convertFromFunctionCall(fc: Function.Call.Distributive<Function.Declaration.From<fdm>>): Google.FunctionCall;
9
+ protected convertToFunctionCall(googlefc: Google.FunctionCall): Function.Call.Distributive<Function.Declaration.From<fdm>>;
10
+ protected convertFromUserMessage(userMessage: RoleMessage.User<Function.Declaration.From<fdm>>): Google.Content;
11
+ protected convertFromAIMessage(aiMessage: RoleMessage.AI<Function.Declaration.From<fdm>>): Google.Content;
12
+ protected convertFromDeveloperMessage(developerMessage: RoleMessage.Developer): Google.Content;
13
+ protected convertFromChatMessages(chatMessages: ChatMessage<Function.Declaration.From<fdm>>[]): Google.Content[];
14
+ protected convertToAIMessage(content: Google.Content): GoogleAIMessage<Function.Declaration.From<fdm>>;
15
+ protected convertFromFunctionDeclarationEntry(fdentry: Function.Declaration.Entry.From<fdm>): Google.FunctionDeclaration;
16
+ protected convertFromFunctionCallMode(mode: Function.ToolChoice<fdm>): Google.FunctionCallingConfig;
17
+ protected validateFunctionCallByToolChoice(aiMessage: RoleMessage.AI<Function.Declaration.From<fdm>>): void;
18
+ }
19
+ export declare class GoogleAIMessage<out fdu extends Function.Declaration> extends RoleMessage.AI<fdu> {
20
+ raw: Google.Content;
21
+ constructor(parts: RoleMessage.AI.Part<fdu>[], raw: Google.Content);
22
+ }