@bolt-ai/providers-gemini 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Bolt AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ buildGeminiContents: () => buildGeminiContents,
24
+ createGeminiProvider: () => createGeminiProvider,
25
+ fromGeminiFunctionCalls: () => fromGeminiFunctionCalls,
26
+ toGeminiFunctionName: () => toGeminiFunctionName,
27
+ toGeminiTools: () => toGeminiTools
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+ var import_genai = require("@google/genai");
31
+ function createGeminiProvider(opts = {}) {
32
+ const options = typeof opts === "string" ? { model: opts } : opts;
33
+ const apiKey = options.apiKey ?? process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY ?? "";
34
+ if (!apiKey && !options.client) throw new Error("GEMINI_API_KEY or GOOGLE_API_KEY is required");
35
+ const model = options.model ?? process.env.GEMINI_MODEL ?? "gemini-2.5-flash";
36
+ const temperature = options.temperature ?? 0.2;
37
+ const client = options.client ?? new import_genai.GoogleGenAI({ apiKey });
38
+ return {
39
+ id: `gemini:${model}`,
40
+ supports: ["text", "json"],
41
+ async call(args) {
42
+ const prompt = args.prompt ?? (typeof args.input === "string" ? args.input : JSON.stringify(args.input ?? ""));
43
+ const contents = buildGeminiContents(prompt, args.toolResults);
44
+ const request = buildGeminiRequest({
45
+ model,
46
+ temperature,
47
+ contents,
48
+ tools: args.tools,
49
+ kind: args.kind,
50
+ schema: args.schema
51
+ });
52
+ if (args.onToken && args.kind === "text" && client.models.generateContentStream) {
53
+ const stream = await client.models.generateContentStream(request);
54
+ return collectGeminiStream(stream, args.onToken, args.tools);
55
+ }
56
+ const resp = await client.models.generateContent(request);
57
+ const raw = resp;
58
+ const toolCalls = fromGeminiFunctionCalls(extractGeminiFunctionCalls(raw), args.tools);
59
+ if (toolCalls.length) {
60
+ return { toolCalls, tokens: raw.usageMetadata?.totalTokenCount };
61
+ }
62
+ const content = extractGeminiText(raw);
63
+ const output = args.kind === "json" ? safeParseJSON(content) : content;
64
+ return { output, tokens: raw.usageMetadata?.totalTokenCount };
65
+ }
66
+ };
67
+ }
68
+ function toGeminiFunctionName(toolId) {
69
+ const normalized = toolId.replace(/[^A-Za-z0-9_]/g, "_");
70
+ if (/^[A-Za-z_]/.test(normalized)) return normalized.slice(0, 64);
71
+ return `tool_${normalized}`.slice(0, 64);
72
+ }
73
+ function toGeminiTools(tools) {
74
+ if (!tools?.length) return void 0;
75
+ return [
76
+ {
77
+ functionDeclarations: tools.map((tool) => ({
78
+ name: toGeminiFunctionName(tool.id),
79
+ description: tool.description ?? tool.id,
80
+ parametersJsonSchema: tool.schema ?? { type: "object", properties: {} }
81
+ }))
82
+ }
83
+ ];
84
+ }
85
+ function fromGeminiFunctionCalls(functionCalls, tools) {
86
+ if (!Array.isArray(functionCalls)) return [];
87
+ const providerNameToToolId = new Map(
88
+ (tools ?? []).map((tool) => [toGeminiFunctionName(tool.id), tool.id])
89
+ );
90
+ return functionCalls.map((functionCall) => {
91
+ const raw = functionCall;
92
+ const name = String(raw?.name ?? "").trim();
93
+ if (!name) return null;
94
+ return {
95
+ id: raw.id ? String(raw.id) : void 0,
96
+ toolId: providerNameToToolId.get(name) ?? name,
97
+ args: raw.args ?? {}
98
+ };
99
+ }).filter((toolCall) => Boolean(toolCall));
100
+ }
101
+ function buildGeminiContents(prompt, toolResults) {
102
+ const contents = [{ role: "user", parts: [{ text: prompt }] }];
103
+ if (!toolResults?.length) return contents;
104
+ contents.push({
105
+ role: "user",
106
+ parts: toolResults.map((result) => ({
107
+ functionResponse: {
108
+ id: result.id,
109
+ name: toGeminiFunctionName(result.toolId),
110
+ response: normalizeGeminiFunctionResponse(result.output)
111
+ }
112
+ }))
113
+ });
114
+ return contents;
115
+ }
116
+ function buildGeminiRequest(args) {
117
+ const tools = toGeminiTools(args.tools);
118
+ const config = {
119
+ temperature: args.temperature,
120
+ ...args.kind === "json" ? { responseMimeType: "application/json" } : {},
121
+ ...args.kind === "json" && args.schema ? { responseSchema: args.schema } : {},
122
+ ...tools?.length ? { tools, toolConfig: { functionCallingConfig: { mode: "AUTO" } } } : {}
123
+ };
124
+ return {
125
+ model: args.model,
126
+ contents: args.contents,
127
+ config
128
+ };
129
+ }
130
+ async function collectGeminiStream(stream, onToken, tools) {
131
+ let full = "";
132
+ const functionCalls = [];
133
+ for await (const chunk of stream) {
134
+ const text = extractGeminiText(chunk);
135
+ if (text) {
136
+ full += text;
137
+ onToken(text);
138
+ }
139
+ functionCalls.push(...extractGeminiFunctionCalls(chunk));
140
+ }
141
+ const toolCalls = fromGeminiFunctionCalls(functionCalls, tools);
142
+ if (toolCalls.length) return { toolCalls };
143
+ return { output: full };
144
+ }
145
+ function extractGeminiText(response) {
146
+ if (typeof response?.text === "string") return response.text;
147
+ if (typeof response?.text === "function") return response.text();
148
+ const parts = response?.candidates?.[0]?.content?.parts ?? response?.content?.parts ?? [];
149
+ return parts.map((part) => typeof part?.text === "string" ? part.text : "").join("");
150
+ }
151
+ function extractGeminiFunctionCalls(response) {
152
+ if (Array.isArray(response?.functionCalls)) return response.functionCalls;
153
+ const parts = response?.candidates?.[0]?.content?.parts ?? response?.content?.parts ?? [];
154
+ return parts.map((part) => part?.functionCall).filter(Boolean);
155
+ }
156
+ function normalizeGeminiFunctionResponse(output) {
157
+ if (output && typeof output === "object" && !Array.isArray(output)) return output;
158
+ return { result: output };
159
+ }
160
+ function safeParseJSON(s) {
161
+ try {
162
+ return JSON.parse(s);
163
+ } catch {
164
+ const m = s.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
165
+ if (m) {
166
+ try {
167
+ return JSON.parse(m[0]);
168
+ } catch {
169
+ }
170
+ }
171
+ return { raw: s };
172
+ }
173
+ }
174
+ // Annotate the CommonJS export names for ESM import in node:
175
+ 0 && (module.exports = {
176
+ buildGeminiContents,
177
+ createGeminiProvider,
178
+ fromGeminiFunctionCalls,
179
+ toGeminiFunctionName,
180
+ toGeminiTools
181
+ });
@@ -0,0 +1,28 @@
1
+ import { ModelProvider, ProviderToolDefinition, ProviderToolCall, ProviderToolResult } from '@bolt-ai/core';
2
+
3
+ type GeminiClient = {
4
+ models: {
5
+ generateContent(args: Record<string, unknown>): Promise<unknown>;
6
+ generateContentStream?(args: Record<string, unknown>): Promise<unknown>;
7
+ };
8
+ };
9
+ interface GeminiProviderOptions {
10
+ apiKey?: string;
11
+ model?: string;
12
+ temperature?: number;
13
+ client?: GeminiClient;
14
+ }
15
+ declare function createGeminiProvider(model?: string): ModelProvider;
16
+ declare function createGeminiProvider(opts?: GeminiProviderOptions): ModelProvider;
17
+ declare function toGeminiFunctionName(toolId: string): string;
18
+ declare function toGeminiTools(tools?: ProviderToolDefinition[]): {
19
+ functionDeclarations: {
20
+ name: string;
21
+ description: string;
22
+ parametersJsonSchema: any;
23
+ }[];
24
+ }[] | undefined;
25
+ declare function fromGeminiFunctionCalls(functionCalls: unknown, tools?: ProviderToolDefinition[]): ProviderToolCall[];
26
+ declare function buildGeminiContents(prompt: string, toolResults?: ProviderToolResult[]): any[];
27
+
28
+ export { type GeminiProviderOptions, buildGeminiContents, createGeminiProvider, fromGeminiFunctionCalls, toGeminiFunctionName, toGeminiTools };
@@ -0,0 +1,28 @@
1
+ import { ModelProvider, ProviderToolDefinition, ProviderToolCall, ProviderToolResult } from '@bolt-ai/core';
2
+
3
+ type GeminiClient = {
4
+ models: {
5
+ generateContent(args: Record<string, unknown>): Promise<unknown>;
6
+ generateContentStream?(args: Record<string, unknown>): Promise<unknown>;
7
+ };
8
+ };
9
+ interface GeminiProviderOptions {
10
+ apiKey?: string;
11
+ model?: string;
12
+ temperature?: number;
13
+ client?: GeminiClient;
14
+ }
15
+ declare function createGeminiProvider(model?: string): ModelProvider;
16
+ declare function createGeminiProvider(opts?: GeminiProviderOptions): ModelProvider;
17
+ declare function toGeminiFunctionName(toolId: string): string;
18
+ declare function toGeminiTools(tools?: ProviderToolDefinition[]): {
19
+ functionDeclarations: {
20
+ name: string;
21
+ description: string;
22
+ parametersJsonSchema: any;
23
+ }[];
24
+ }[] | undefined;
25
+ declare function fromGeminiFunctionCalls(functionCalls: unknown, tools?: ProviderToolDefinition[]): ProviderToolCall[];
26
+ declare function buildGeminiContents(prompt: string, toolResults?: ProviderToolResult[]): any[];
27
+
28
+ export { type GeminiProviderOptions, buildGeminiContents, createGeminiProvider, fromGeminiFunctionCalls, toGeminiFunctionName, toGeminiTools };
package/dist/index.js ADDED
@@ -0,0 +1,152 @@
1
+ // src/index.ts
2
+ import { GoogleGenAI } from "@google/genai";
3
+ function createGeminiProvider(opts = {}) {
4
+ const options = typeof opts === "string" ? { model: opts } : opts;
5
+ const apiKey = options.apiKey ?? process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY ?? "";
6
+ if (!apiKey && !options.client) throw new Error("GEMINI_API_KEY or GOOGLE_API_KEY is required");
7
+ const model = options.model ?? process.env.GEMINI_MODEL ?? "gemini-2.5-flash";
8
+ const temperature = options.temperature ?? 0.2;
9
+ const client = options.client ?? new GoogleGenAI({ apiKey });
10
+ return {
11
+ id: `gemini:${model}`,
12
+ supports: ["text", "json"],
13
+ async call(args) {
14
+ const prompt = args.prompt ?? (typeof args.input === "string" ? args.input : JSON.stringify(args.input ?? ""));
15
+ const contents = buildGeminiContents(prompt, args.toolResults);
16
+ const request = buildGeminiRequest({
17
+ model,
18
+ temperature,
19
+ contents,
20
+ tools: args.tools,
21
+ kind: args.kind,
22
+ schema: args.schema
23
+ });
24
+ if (args.onToken && args.kind === "text" && client.models.generateContentStream) {
25
+ const stream = await client.models.generateContentStream(request);
26
+ return collectGeminiStream(stream, args.onToken, args.tools);
27
+ }
28
+ const resp = await client.models.generateContent(request);
29
+ const raw = resp;
30
+ const toolCalls = fromGeminiFunctionCalls(extractGeminiFunctionCalls(raw), args.tools);
31
+ if (toolCalls.length) {
32
+ return { toolCalls, tokens: raw.usageMetadata?.totalTokenCount };
33
+ }
34
+ const content = extractGeminiText(raw);
35
+ const output = args.kind === "json" ? safeParseJSON(content) : content;
36
+ return { output, tokens: raw.usageMetadata?.totalTokenCount };
37
+ }
38
+ };
39
+ }
40
+ function toGeminiFunctionName(toolId) {
41
+ const normalized = toolId.replace(/[^A-Za-z0-9_]/g, "_");
42
+ if (/^[A-Za-z_]/.test(normalized)) return normalized.slice(0, 64);
43
+ return `tool_${normalized}`.slice(0, 64);
44
+ }
45
+ function toGeminiTools(tools) {
46
+ if (!tools?.length) return void 0;
47
+ return [
48
+ {
49
+ functionDeclarations: tools.map((tool) => ({
50
+ name: toGeminiFunctionName(tool.id),
51
+ description: tool.description ?? tool.id,
52
+ parametersJsonSchema: tool.schema ?? { type: "object", properties: {} }
53
+ }))
54
+ }
55
+ ];
56
+ }
57
+ function fromGeminiFunctionCalls(functionCalls, tools) {
58
+ if (!Array.isArray(functionCalls)) return [];
59
+ const providerNameToToolId = new Map(
60
+ (tools ?? []).map((tool) => [toGeminiFunctionName(tool.id), tool.id])
61
+ );
62
+ return functionCalls.map((functionCall) => {
63
+ const raw = functionCall;
64
+ const name = String(raw?.name ?? "").trim();
65
+ if (!name) return null;
66
+ return {
67
+ id: raw.id ? String(raw.id) : void 0,
68
+ toolId: providerNameToToolId.get(name) ?? name,
69
+ args: raw.args ?? {}
70
+ };
71
+ }).filter((toolCall) => Boolean(toolCall));
72
+ }
73
+ function buildGeminiContents(prompt, toolResults) {
74
+ const contents = [{ role: "user", parts: [{ text: prompt }] }];
75
+ if (!toolResults?.length) return contents;
76
+ contents.push({
77
+ role: "user",
78
+ parts: toolResults.map((result) => ({
79
+ functionResponse: {
80
+ id: result.id,
81
+ name: toGeminiFunctionName(result.toolId),
82
+ response: normalizeGeminiFunctionResponse(result.output)
83
+ }
84
+ }))
85
+ });
86
+ return contents;
87
+ }
88
+ function buildGeminiRequest(args) {
89
+ const tools = toGeminiTools(args.tools);
90
+ const config = {
91
+ temperature: args.temperature,
92
+ ...args.kind === "json" ? { responseMimeType: "application/json" } : {},
93
+ ...args.kind === "json" && args.schema ? { responseSchema: args.schema } : {},
94
+ ...tools?.length ? { tools, toolConfig: { functionCallingConfig: { mode: "AUTO" } } } : {}
95
+ };
96
+ return {
97
+ model: args.model,
98
+ contents: args.contents,
99
+ config
100
+ };
101
+ }
102
+ async function collectGeminiStream(stream, onToken, tools) {
103
+ let full = "";
104
+ const functionCalls = [];
105
+ for await (const chunk of stream) {
106
+ const text = extractGeminiText(chunk);
107
+ if (text) {
108
+ full += text;
109
+ onToken(text);
110
+ }
111
+ functionCalls.push(...extractGeminiFunctionCalls(chunk));
112
+ }
113
+ const toolCalls = fromGeminiFunctionCalls(functionCalls, tools);
114
+ if (toolCalls.length) return { toolCalls };
115
+ return { output: full };
116
+ }
117
+ function extractGeminiText(response) {
118
+ if (typeof response?.text === "string") return response.text;
119
+ if (typeof response?.text === "function") return response.text();
120
+ const parts = response?.candidates?.[0]?.content?.parts ?? response?.content?.parts ?? [];
121
+ return parts.map((part) => typeof part?.text === "string" ? part.text : "").join("");
122
+ }
123
+ function extractGeminiFunctionCalls(response) {
124
+ if (Array.isArray(response?.functionCalls)) return response.functionCalls;
125
+ const parts = response?.candidates?.[0]?.content?.parts ?? response?.content?.parts ?? [];
126
+ return parts.map((part) => part?.functionCall).filter(Boolean);
127
+ }
128
+ function normalizeGeminiFunctionResponse(output) {
129
+ if (output && typeof output === "object" && !Array.isArray(output)) return output;
130
+ return { result: output };
131
+ }
132
+ function safeParseJSON(s) {
133
+ try {
134
+ return JSON.parse(s);
135
+ } catch {
136
+ const m = s.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
137
+ if (m) {
138
+ try {
139
+ return JSON.parse(m[0]);
140
+ } catch {
141
+ }
142
+ }
143
+ return { raw: s };
144
+ }
145
+ }
146
+ export {
147
+ buildGeminiContents,
148
+ createGeminiProvider,
149
+ fromGeminiFunctionCalls,
150
+ toGeminiFunctionName,
151
+ toGeminiTools
152
+ };
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@bolt-ai/providers-gemini",
3
+ "version": "1.0.0",
4
+ "description": "Gemini model provider adapter for Bolt AI agents.",
5
+ "license": "MIT",
6
+ "author": "Bolt AI",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/TheCypher/Bolt-Agentic.git"
10
+ },
11
+ "homepage": "https://github.com/TheCypher/Bolt-Agentic#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/TheCypher/Bolt-Agentic/issues"
14
+ },
15
+ "keywords": [
16
+ "ai",
17
+ "agents",
18
+ "gemini",
19
+ "providers",
20
+ "bolt"
21
+ ],
22
+ "type": "module",
23
+ "main": "dist/index.cjs",
24
+ "module": "dist/index.js",
25
+ "types": "dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js",
30
+ "require": "./dist/index.cjs"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "engines": {
37
+ "node": ">=20.0.0"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "peerDependencies": {
43
+ "@bolt-ai/core": ">=1.0.0"
44
+ },
45
+ "peerDependenciesMeta": {
46
+ "@bolt-ai/core": {
47
+ "optional": false
48
+ }
49
+ },
50
+ "dependencies": {
51
+ "@google/genai": "^1.52.0"
52
+ },
53
+ "devDependencies": {
54
+ "tsup": "^8.5.0",
55
+ "typescript": "^5.5.0",
56
+ "rimraf": "^6.0.1",
57
+ "@bolt-ai/core": "1.0.0"
58
+ },
59
+ "scripts": {
60
+ "build": "tsup src/index.ts --dts --format esm,cjs --tsconfig tsconfig.json",
61
+ "clean": "rimraf dist"
62
+ }
63
+ }