shengsuanyun-gemini-api 1.38.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,424 @@
1
+ # 胜算云 Gemini API(适用于 TypeScript 和 JavaScript)
2
+
3
+ [![NPM 下载量](https://img.shields.io/npm/dw/shengsuanyun-gemini-api)](https://www.npmjs.com/package/shengsuanyun-gemini-api)
4
+ [![Node 当前版本](https://img.shields.io/node/v/shengsuanyun-gemini-api)](https://www.npmjs.com/package/shengsuanyun-gemini-api)
5
+
6
+ ----------------------
7
+
8
+ 胜算云 Gemini API JavaScript SDK 专为 TypeScript 和 JavaScript 开发者设计,用于构建由 Gemini 驱动的应用程序。
9
+
10
+ > [!CAUTION]
11
+ > **API 密钥安全提示:** 切勿在客户端代码中暴露 API 密钥。
12
+ > 在生产环境中,请使用服务端实现。
13
+
14
+ ## 安装
15
+
16
+ 要安装 SDK,请运行以下命令:
17
+
18
+ ```shell
19
+ npm install shengsuanyun-gemini-api
20
+ ```
21
+
22
+ ## 快速入门
23
+
24
+ 最简单的入门方式是使用从 [胜算云]() 获取的 API 密钥:
25
+
26
+ ```typescript
27
+ import { GoogleGenAI } from 'shengsuanyun-gemini-api';
28
+ const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
29
+
30
+ const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
31
+
32
+ async function main() {
33
+ const response = await ai.models.generateContent({
34
+ model: 'google/gemini-2.5-flash',
35
+ contents: '为什么天空是蓝色的?',
36
+ });
37
+ console.log(response.text);
38
+ }
39
+
40
+ main();
41
+ ```
42
+
43
+ ### 查询 API Key 额度与使用情况
44
+
45
+ ```typescript
46
+ import { GoogleGenAI } from 'shengsuanyun-gemini-api';
47
+
48
+ const client = new GoogleGenAI({ apiKey: 'YOUR_API_KEY' });
49
+ // 自动使用 Bearer Token 请求 /v1/key
50
+ const quota = await client.quota.getQuota();
51
+ console.log(quota);
52
+ ```
53
+
54
+ ## GoogleGenAI 概览
55
+
56
+ 所有 API 功能都通过 `GoogleGenAI` 类的实例访问。子模块将相关 API 方法分组如下:
57
+
58
+ - [`ai.models`](https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html):
59
+ 用于查询模型(`generateContent`、`generateImages` 等)或查看其元数据。
60
+ - [`ai.caches`](https://googleapis.github.io/js-genai/release_docs/classes/caches.Caches.html):
61
+ 创建和管理 `caches`,在重复使用相同大型提示前缀时降低成本。
62
+ - [`ai.chats`](https://googleapis.github.io/js-genai/release_docs/classes/chats.Chats.html):
63
+ 创建本地有状态的 `chat` 对象,简化多轮对话交互。
64
+ - [`ai.files`](https://googleapis.github.io/js-genai/release_docs/classes/files.Files.html):
65
+ 将 `files` 上传到 API 并在提示中引用,减少带宽消耗(尤其适用于多次使用的大文件)。
66
+ - [`ai.live`](https://googleapis.github.io/js-genai/release_docs/classes/live.Live.html):
67
+ 启动 `live` 会话进行实时交互,支持文本 + 音频 + 视频输入,以及文本或音频输出。
68
+
69
+ ### 流式响应
70
+
71
+ 为获得更快、更响应式的 API 交互,可使用 `generateContentStream` 方法,它会在生成时逐块返回内容:
72
+
73
+ ```typescript
74
+ import { GoogleGenAI } from '@google/genai';
75
+ const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
76
+
77
+ const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
78
+
79
+ async function main() {
80
+ const response = await ai.models.generateContentStream({
81
+ model: 'google/gemini-2.5-flash',
82
+ contents: '写一首 100 字的诗。',
83
+ });
84
+ for await (const chunk of response) {
85
+ console.log(chunk.text);
86
+ }
87
+ }
88
+
89
+ main();
90
+ ```
91
+
92
+ ### 函数调用
93
+
94
+ 要让 Gemini 与外部系统交互,您可以提供 `functionDeclaration` 对象作为 `tools`。使用这些工具需遵循以下四步流程:
95
+
96
+ 1. **声明函数名称、描述和参数 JSON Schema**
97
+ 2. **调用 `generateContent` 并启用函数调用**
98
+ 3. **使用返回的 `FunctionCall` 参数调用实际函数**
99
+ 4. **将结果作为 `FunctionResponse` 发回给模型(推荐在 `ai.chat` 中使用历史记录)**
100
+
101
+ ```typescript
102
+ import { GoogleGenAI, FunctionCallingConfigMode, FunctionDeclaration, Type } from '@google/genai';
103
+ const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
104
+
105
+ async function main() {
106
+ const controlLightDeclaration: FunctionDeclaration = {
107
+ name: 'controlLight',
108
+ parametersJsonSchema: {
109
+ type: 'object',
110
+ properties: {
111
+ brightness: { type: 'number' },
112
+ colorTemperature: { type: 'string' },
113
+ },
114
+ required: ['brightness', 'colorTemperature'],
115
+ },
116
+ };
117
+
118
+ const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
119
+ const response = await ai.models.generateContent({
120
+ model: 'google/gemini-2.5-flash',
121
+ contents: '把灯调暗一点,让房间感觉温馨又温暖。',
122
+ config: {
123
+ toolConfig: {
124
+ functionCallingConfig: {
125
+ mode: FunctionCallingConfigMode.ANY,
126
+ allowedFunctionNames: ['controlLight'],
127
+ }
128
+ },
129
+ tools: [{ functionDeclarations: [controlLightDeclaration] }]
130
+ }
131
+ });
132
+
133
+ console.log(response.functionCalls);
134
+ }
135
+
136
+ main();
137
+ ```
138
+
139
+ #### 模型上下文协议(MCP)支持(实验性)
140
+
141
+ 内置 [MCP](https://modelcontextprotocol.io/introduction) 支持是一项实验性功能。您可以直接将本地 MCP 服务器作为工具传入。
142
+
143
+ ```javascript
144
+ import { GoogleGenAI, FunctionCallingConfigMode, mcpToTool } from '@google/genai';
145
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
146
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
147
+
148
+ // 创建 stdio 连接的服务器参数
149
+ const serverParams = new StdioClientTransport({
150
+ command: "npx",
151
+ args: ["-y", "@philschmid/weather-mcp"] // MCP 服务器
152
+ });
153
+
154
+ const client = new Client({ name: "example-client", version: "1.0.0" });
155
+
156
+ // 配置客户端
157
+ const ai = new GoogleGenAI({});
158
+
159
+ // 初始化客户端与服务器的连接
160
+ await client.connect(serverParams);
161
+
162
+ // 使用 MCP 工具向模型发送请求
163
+ const response = await ai.models.generateContent({
164
+ model: "google/gemini-2.5-flash",
165
+ contents: `今天 ${new Date().toLocaleDateString()} 伦敦的天气如何?`,
166
+ config: {
167
+ tools: [mcpToTool(client)], // 使用会话,将自动调用工具
168
+ },
169
+ });
170
+ console.log(response.text);
171
+
172
+ // 关闭连接
173
+ await client.close();
174
+ ```
175
+
176
+ ### 内容生成
177
+
178
+ #### 如何构造 `generateContent` 的 `contents` 参数
179
+
180
+ SDK 允许您在 `contents` 参数中指定以下类型:
181
+
182
+ ##### Content 类型
183
+ - `Content`:SDK 会将单个 `Content` 实例包装为仅包含该实例的数组。
184
+ - `Content[]`:不做任何转换。
185
+
186
+ ##### Part 类型
187
+
188
+ Part 会被聚合到一个角色为 `'user'` 的 `Content` 中:
189
+ - `Part | string`:SDK 会将 `string` 或 `Part` 包装为角色为 `'user'` 的 `Content` 实例。
190
+ - `Part[] | string[]`:SDK 会将整个列表包装为一个角色为 `'user'` 的 `Content`。
191
+
192
+ **_注意:_** 此规则不适用于 `FunctionCall` 和 `FunctionResponse` 类型的 Part。如果您使用这些类型,必须显式提供完整的 `Content[]` 结构,明确指出哪些 Part 是由模型或用户“说出”的。否则 SDK 会抛出异常。
193
+
194
+ ## 错误处理
195
+
196
+ 为处理 API 抛出的错误,SDK 提供了 [ApiError](https://github.com/googleapis/js-genai/blob/main/src/errors.ts) 类。
197
+
198
+ ```typescript
199
+ import { GoogleGenAI } from '@google/genai';
200
+ const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
201
+
202
+ const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
203
+
204
+ async function main() {
205
+ await ai.models.generateContent({
206
+ model: 'non-existent-model',
207
+ contents: '写一首 100 字的诗。',
208
+ }).catch((e) => {
209
+ console.error('错误名称:', e.name);
210
+ console.error('错误信息:', e.message);
211
+ console.error('HTTP 状态码:', e.status);
212
+ });
213
+ }
214
+
215
+ main();
216
+ ```
217
+
218
+ ## Interactions(交互)(预览版)
219
+
220
+ > **警告:** Interactions API 目前处于 **Beta 阶段**。这是一个实验性功能的预览版,其功能和结构可能随时发生 **破坏性变更**。
221
+
222
+ Interactions API 是与 Gemini 模型和智能体交互的统一接口,简化了状态管理、工具编排和长时间运行任务。
223
+
224
+ 更多详情请参见 [官方文档](https://ai.google.dev/gemini-api/docs/interactions)。
225
+
226
+ ### 基础交互
227
+
228
+ ```typescript
229
+ const interaction = await ai.interactions.create({
230
+ model: 'google/gemini-2.5-flash',
231
+ input: '你好,你怎么样?',
232
+ });
233
+ console.debug(interaction);
234
+ ```
235
+
236
+ ### 有状态对话
237
+
238
+ Interactions API 支持服务端状态管理。您可以通过引用 `previous_interaction_id` 继续对话。
239
+
240
+ ```typescript
241
+ // 第一轮
242
+ const interaction1 = await ai.interactions.create({
243
+ model: 'google/gemini-2.5-flash',
244
+ input: '你好,我叫 Amir。',
245
+ });
246
+ console.debug(interaction1);
247
+
248
+ // 第二轮(传入 previous_interaction_id)
249
+ const interaction2 = await ai.interactions.create({
250
+ model: 'google/gemini-2.5-flash',
251
+ input: '我叫什么名字?',
252
+ previous_interaction_id: interaction1.id,
253
+ });
254
+ console.debug(interaction2);
255
+ ```
256
+
257
+ ### 智能体(深度研究)
258
+
259
+ 您可以使用如 `deep-research-pro-preview-12-2025` 等专用智能体执行复杂任务。
260
+
261
+ ```typescript
262
+ function sleep(ms: number): Promise<void> {
263
+ return new Promise(resolve => setTimeout(resolve, ms));
264
+ }
265
+
266
+ // 1. 启动深度研究智能体
267
+ const initialInteraction = await ai.interactions.create({
268
+ input: '研究 Google TPU 的历史,重点关注 2025 和 2026 年。',
269
+ agent: 'deep-research-pro-preview-12-2025',
270
+ background: true,
271
+ });
272
+
273
+ console.log(`研究已启动。交互 ID:${initialInteraction.id}`);
274
+
275
+ // 2. 轮询结果
276
+ while (true) {
277
+ const interaction = await ai.interactions.get(initialInteraction.id);
278
+ console.log(`状态:${interaction.status}`);
279
+
280
+ if (interaction.status === 'completed') {
281
+ console.debug('\n最终报告:\n', interaction.outputs);
282
+ break;
283
+ } else if (['failed', 'cancelled'].includes(interaction.status)) {
284
+ console.log(`失败,状态:${interaction.status}`);
285
+ break;
286
+ }
287
+
288
+ await sleep(10000); // 等待 10 秒
289
+ }
290
+ ```
291
+
292
+ ### 多模态输入
293
+
294
+ 您可以在输入列表中提供多模态数据(文本、图像、音频等)。
295
+
296
+ ```typescript
297
+ // 假设您有一个 base64 字符串
298
+ // const base64Image = ...;
299
+
300
+ const interaction = await ai.interactions.create({
301
+ model: 'google/gemini-2.5-flash',
302
+ input: [
303
+ { type: 'text', text: '描述这张图片。' },
304
+ { type: 'image', data: base64Image, mime_type: 'image/png' },
305
+ ],
306
+ });
307
+
308
+ console.debug(interaction);
309
+ ```
310
+
311
+ ### 函数调用
312
+
313
+ 您可以定义自定义函数供模型使用。Interactions API 负责工具选择,您只需将执行结果返回给模型。
314
+
315
+ ```typescript
316
+ // 1. 定义工具
317
+ const getWeather = (location: string) => {
318
+ /* 获取指定位置的天气 */
319
+ return `目前 ${location} 的天气是晴天。`;
320
+ };
321
+
322
+ // 2. 带工具发送请求
323
+ let interaction = await ai.interactions.create({
324
+ model: 'google/gemini-2.5-flash',
325
+ input: 'Mountain View, CA 的天气如何?',
326
+ tools: [
327
+ {
328
+ type: 'function',
329
+ name: 'get_weather',
330
+ description: '获取指定位置的天气。',
331
+ parameters: {
332
+ type: 'object',
333
+ properties: {
334
+ location: {
335
+ type: 'string',
336
+ description: '城市和州,例如 San Francisco, CA',
337
+ },
338
+ },
339
+ required: ['location'],
340
+ },
341
+ },
342
+ ],
343
+ });
344
+
345
+ // 3. 处理工具调用
346
+ for (const output of interaction.outputs!) {
347
+ if (output.type === 'function_call') {
348
+ console.log(`工具调用:${output.name}(${JSON.stringify(output.arguments)})`);
349
+
350
+ // 在此处执行实际函数
351
+ const result = getWeather(output.arguments.location);
352
+
353
+ // 将结果发回模型
354
+ interaction = await ai.interactions.create({
355
+ model: 'google/gemini-2.5-flash',
356
+ previous_interaction_id: interaction.id,
357
+ input: [
358
+ {
359
+ type: 'function_result',
360
+ name: output.name,
361
+ call_id: output.id,
362
+ result: result,
363
+ },
364
+ ],
365
+ });
366
+
367
+ console.debug(`响应:${JSON.stringify(interaction)}`);
368
+ }
369
+ }
370
+ ```
371
+
372
+ ### 内置工具
373
+
374
+ 您也可以使用 Google 的内置工具,如 **Google 搜索** 或 **代码执行**。
375
+
376
+ #### 使用 Google 搜索进行事实核查
377
+
378
+ ```typescript
379
+ const interaction = await ai.interactions.create({
380
+ model: 'google/gemini-2.5-flash',
381
+ input: '上一届超级碗谁赢了?',
382
+ tools: [{ type: 'google_search' }],
383
+ });
384
+
385
+ console.debug(interaction);
386
+ ```
387
+
388
+ #### 代码执行
389
+
390
+ ```typescript
391
+ const interaction = await ai.interactions.create({
392
+ model: 'google/gemini-2.5-flash',
393
+ input: '计算第 50 个斐波那契数。',
394
+ tools: [{ type: 'code_execution' }],
395
+ });
396
+
397
+ console.debug(interaction);
398
+ ```
399
+
400
+ ### 多模态输出
401
+
402
+ Interactions API 可生成多模态输出(如图像),但您必须指定 `response_modalities`。
403
+
404
+ ```typescript
405
+ import * as fs from 'fs';
406
+
407
+ const interaction = await ai.interactions.create({
408
+ model: 'google/gemini-3-pro-image-preview',
409
+ input: '生成一张未来城市的图像。',
410
+ response_modalities: ['image'],
411
+ });
412
+
413
+ for (const output of interaction.outputs!) {
414
+ if (output.type === 'image') {
415
+ console.log(`已生成图像,MIME 类型:${output.mime_type}`);
416
+ // 保存图像
417
+ fs.writeFileSync(
418
+ 'generated_city.png',
419
+ Buffer.from(output.data!, 'base64')
420
+ );
421
+ }
422
+ }
423
+ ```
424
+