@bolt-ai/providers-openai 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,200 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ buildOpenAIMessages: () => buildOpenAIMessages,
34
+ createOpenAIProvider: () => createOpenAIProvider,
35
+ fromOpenAIToolCalls: () => fromOpenAIToolCalls,
36
+ toOpenAITools: () => toOpenAITools
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+ var import_openai = __toESM(require("openai"), 1);
40
+ function createOpenAIProvider(opts = {}) {
41
+ const options = typeof opts === "string" ? { model: opts } : opts;
42
+ const apiKey = options.apiKey ?? process.env.OPENAI_API_KEY ?? "";
43
+ if (!apiKey && !options.client) throw new Error("OPENAI_API_KEY is required");
44
+ const model = options.model ?? process.env.OPENAI_MODEL ?? "gpt-4o-mini";
45
+ const temperature = options.temperature ?? 0.2;
46
+ const client = options.client ?? new import_openai.default({ apiKey });
47
+ return {
48
+ id: `openai:${model}`,
49
+ supports: ["text", "json"],
50
+ async call(args) {
51
+ const prompt = args.prompt ?? (typeof args.input === "string" ? args.input : JSON.stringify(args.input ?? ""));
52
+ const messages = buildOpenAIMessages(prompt, args.toolResults);
53
+ const tools = toOpenAITools(args.tools);
54
+ const request = buildOpenAIRequest({
55
+ model,
56
+ temperature,
57
+ messages,
58
+ tools,
59
+ kind: args.kind
60
+ });
61
+ if (args.onToken && args.kind === "text") {
62
+ const stream = await client.chat.completions.create({ ...request, stream: true });
63
+ return collectOpenAIStream(stream, args.onToken);
64
+ }
65
+ const resp = await client.chat.completions.create(request);
66
+ const raw = resp;
67
+ const message = raw.choices?.[0]?.message;
68
+ const toolCalls = fromOpenAIToolCalls(message?.tool_calls);
69
+ if (toolCalls.length) {
70
+ return { toolCalls, tokens: raw.usage?.total_tokens };
71
+ }
72
+ const content = message?.content ?? "";
73
+ const output = args.kind === "json" ? safeParseJSON(content) : content;
74
+ return { output, tokens: raw.usage?.total_tokens };
75
+ }
76
+ };
77
+ }
78
+ function toOpenAITools(tools) {
79
+ if (!tools?.length) return void 0;
80
+ return tools.map((tool) => ({
81
+ type: "function",
82
+ function: {
83
+ name: tool.id,
84
+ description: tool.description ?? tool.id,
85
+ parameters: tool.schema ?? { type: "object", properties: {} }
86
+ }
87
+ }));
88
+ }
89
+ function fromOpenAIToolCalls(toolCalls) {
90
+ if (!Array.isArray(toolCalls)) return [];
91
+ return toolCalls.map((toolCall) => {
92
+ const raw = toolCall;
93
+ const fn = raw?.function ?? {};
94
+ const toolId = String(fn.name ?? raw.toolId ?? "").trim();
95
+ if (!toolId) return null;
96
+ return {
97
+ id: raw.id ? String(raw.id) : void 0,
98
+ toolId,
99
+ args: parseToolArguments(fn.arguments)
100
+ };
101
+ }).filter((toolCall) => Boolean(toolCall));
102
+ }
103
+ function buildOpenAIMessages(prompt, toolResults) {
104
+ const messages = [{ role: "user", content: prompt }];
105
+ if (!toolResults?.length) return messages;
106
+ messages.push({
107
+ role: "assistant",
108
+ content: null,
109
+ tool_calls: toolResults.map((result) => ({
110
+ id: result.id,
111
+ type: "function",
112
+ function: {
113
+ name: result.toolId,
114
+ arguments: "{}"
115
+ }
116
+ }))
117
+ });
118
+ for (const result of toolResults) {
119
+ messages.push({
120
+ role: "tool",
121
+ tool_call_id: result.id,
122
+ content: stringifyToolOutput(result.output)
123
+ });
124
+ }
125
+ return messages;
126
+ }
127
+ function buildOpenAIRequest(args) {
128
+ return {
129
+ model: args.model,
130
+ temperature: args.temperature,
131
+ messages: args.messages,
132
+ ...args.tools?.length ? { tools: args.tools, tool_choice: "auto" } : {},
133
+ ...args.kind === "json" ? { response_format: { type: "json_object" } } : {}
134
+ };
135
+ }
136
+ async function collectOpenAIStream(stream, onToken) {
137
+ let full = "";
138
+ const toolCallByIndex = /* @__PURE__ */ new Map();
139
+ for await (const chunk of stream) {
140
+ const delta = chunk?.choices?.[0]?.delta ?? {};
141
+ const content = typeof delta.content === "string" ? delta.content : "";
142
+ if (content) {
143
+ full += content;
144
+ onToken(content);
145
+ }
146
+ for (const toolCall of delta.tool_calls ?? []) {
147
+ const index = Number.isInteger(toolCall.index) ? toolCall.index : toolCallByIndex.size;
148
+ const current = toolCallByIndex.get(index) ?? {
149
+ id: void 0,
150
+ type: "function",
151
+ function: { name: "", arguments: "" }
152
+ };
153
+ if (toolCall.id) current.id = toolCall.id;
154
+ if (toolCall.function?.name) current.function.name += toolCall.function.name;
155
+ if (toolCall.function?.arguments) current.function.arguments += toolCall.function.arguments;
156
+ toolCallByIndex.set(index, current);
157
+ }
158
+ }
159
+ const toolCalls = fromOpenAIToolCalls([...toolCallByIndex.values()]);
160
+ if (toolCalls.length) return { toolCalls };
161
+ return { output: full };
162
+ }
163
+ function safeParseJSON(s) {
164
+ try {
165
+ return JSON.parse(s);
166
+ } catch {
167
+ const m = s.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
168
+ if (m) {
169
+ try {
170
+ return JSON.parse(m[0]);
171
+ } catch {
172
+ }
173
+ }
174
+ return { raw: s };
175
+ }
176
+ }
177
+ function stringifyToolOutput(output) {
178
+ if (typeof output === "string") return output;
179
+ try {
180
+ return JSON.stringify(output);
181
+ } catch {
182
+ return String(output);
183
+ }
184
+ }
185
+ function parseToolArguments(raw) {
186
+ if (typeof raw !== "string") return raw ?? {};
187
+ if (!raw.trim()) return {};
188
+ try {
189
+ return JSON.parse(raw);
190
+ } catch {
191
+ return { raw };
192
+ }
193
+ }
194
+ // Annotate the CommonJS export names for ESM import in node:
195
+ 0 && (module.exports = {
196
+ buildOpenAIMessages,
197
+ createOpenAIProvider,
198
+ fromOpenAIToolCalls,
199
+ toOpenAITools
200
+ });
@@ -0,0 +1,29 @@
1
+ import { ModelProvider, ProviderToolDefinition, ProviderToolCall, ProviderToolResult } from '@bolt-ai/core';
2
+
3
+ type OpenAIClient = {
4
+ chat: {
5
+ completions: {
6
+ create(args: Record<string, unknown>): Promise<unknown>;
7
+ };
8
+ };
9
+ };
10
+ interface OpenAIProviderOptions {
11
+ apiKey?: string;
12
+ model?: string;
13
+ temperature?: number;
14
+ client?: OpenAIClient;
15
+ }
16
+ declare function createOpenAIProvider(model?: string): ModelProvider;
17
+ declare function createOpenAIProvider(opts?: OpenAIProviderOptions): ModelProvider;
18
+ declare function toOpenAITools(tools?: ProviderToolDefinition[]): {
19
+ type: "function";
20
+ function: {
21
+ name: string;
22
+ description: string;
23
+ parameters: any;
24
+ };
25
+ }[] | undefined;
26
+ declare function fromOpenAIToolCalls(toolCalls: unknown): ProviderToolCall[];
27
+ declare function buildOpenAIMessages(prompt: string, toolResults?: ProviderToolResult[]): any[];
28
+
29
+ export { type OpenAIProviderOptions, buildOpenAIMessages, createOpenAIProvider, fromOpenAIToolCalls, toOpenAITools };
@@ -0,0 +1,29 @@
1
+ import { ModelProvider, ProviderToolDefinition, ProviderToolCall, ProviderToolResult } from '@bolt-ai/core';
2
+
3
+ type OpenAIClient = {
4
+ chat: {
5
+ completions: {
6
+ create(args: Record<string, unknown>): Promise<unknown>;
7
+ };
8
+ };
9
+ };
10
+ interface OpenAIProviderOptions {
11
+ apiKey?: string;
12
+ model?: string;
13
+ temperature?: number;
14
+ client?: OpenAIClient;
15
+ }
16
+ declare function createOpenAIProvider(model?: string): ModelProvider;
17
+ declare function createOpenAIProvider(opts?: OpenAIProviderOptions): ModelProvider;
18
+ declare function toOpenAITools(tools?: ProviderToolDefinition[]): {
19
+ type: "function";
20
+ function: {
21
+ name: string;
22
+ description: string;
23
+ parameters: any;
24
+ };
25
+ }[] | undefined;
26
+ declare function fromOpenAIToolCalls(toolCalls: unknown): ProviderToolCall[];
27
+ declare function buildOpenAIMessages(prompt: string, toolResults?: ProviderToolResult[]): any[];
28
+
29
+ export { type OpenAIProviderOptions, buildOpenAIMessages, createOpenAIProvider, fromOpenAIToolCalls, toOpenAITools };
package/dist/index.js ADDED
@@ -0,0 +1,162 @@
1
+ // src/index.ts
2
+ import OpenAI from "openai";
3
+ function createOpenAIProvider(opts = {}) {
4
+ const options = typeof opts === "string" ? { model: opts } : opts;
5
+ const apiKey = options.apiKey ?? process.env.OPENAI_API_KEY ?? "";
6
+ if (!apiKey && !options.client) throw new Error("OPENAI_API_KEY is required");
7
+ const model = options.model ?? process.env.OPENAI_MODEL ?? "gpt-4o-mini";
8
+ const temperature = options.temperature ?? 0.2;
9
+ const client = options.client ?? new OpenAI({ apiKey });
10
+ return {
11
+ id: `openai:${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 messages = buildOpenAIMessages(prompt, args.toolResults);
16
+ const tools = toOpenAITools(args.tools);
17
+ const request = buildOpenAIRequest({
18
+ model,
19
+ temperature,
20
+ messages,
21
+ tools,
22
+ kind: args.kind
23
+ });
24
+ if (args.onToken && args.kind === "text") {
25
+ const stream = await client.chat.completions.create({ ...request, stream: true });
26
+ return collectOpenAIStream(stream, args.onToken);
27
+ }
28
+ const resp = await client.chat.completions.create(request);
29
+ const raw = resp;
30
+ const message = raw.choices?.[0]?.message;
31
+ const toolCalls = fromOpenAIToolCalls(message?.tool_calls);
32
+ if (toolCalls.length) {
33
+ return { toolCalls, tokens: raw.usage?.total_tokens };
34
+ }
35
+ const content = message?.content ?? "";
36
+ const output = args.kind === "json" ? safeParseJSON(content) : content;
37
+ return { output, tokens: raw.usage?.total_tokens };
38
+ }
39
+ };
40
+ }
41
+ function toOpenAITools(tools) {
42
+ if (!tools?.length) return void 0;
43
+ return tools.map((tool) => ({
44
+ type: "function",
45
+ function: {
46
+ name: tool.id,
47
+ description: tool.description ?? tool.id,
48
+ parameters: tool.schema ?? { type: "object", properties: {} }
49
+ }
50
+ }));
51
+ }
52
+ function fromOpenAIToolCalls(toolCalls) {
53
+ if (!Array.isArray(toolCalls)) return [];
54
+ return toolCalls.map((toolCall) => {
55
+ const raw = toolCall;
56
+ const fn = raw?.function ?? {};
57
+ const toolId = String(fn.name ?? raw.toolId ?? "").trim();
58
+ if (!toolId) return null;
59
+ return {
60
+ id: raw.id ? String(raw.id) : void 0,
61
+ toolId,
62
+ args: parseToolArguments(fn.arguments)
63
+ };
64
+ }).filter((toolCall) => Boolean(toolCall));
65
+ }
66
+ function buildOpenAIMessages(prompt, toolResults) {
67
+ const messages = [{ role: "user", content: prompt }];
68
+ if (!toolResults?.length) return messages;
69
+ messages.push({
70
+ role: "assistant",
71
+ content: null,
72
+ tool_calls: toolResults.map((result) => ({
73
+ id: result.id,
74
+ type: "function",
75
+ function: {
76
+ name: result.toolId,
77
+ arguments: "{}"
78
+ }
79
+ }))
80
+ });
81
+ for (const result of toolResults) {
82
+ messages.push({
83
+ role: "tool",
84
+ tool_call_id: result.id,
85
+ content: stringifyToolOutput(result.output)
86
+ });
87
+ }
88
+ return messages;
89
+ }
90
+ function buildOpenAIRequest(args) {
91
+ return {
92
+ model: args.model,
93
+ temperature: args.temperature,
94
+ messages: args.messages,
95
+ ...args.tools?.length ? { tools: args.tools, tool_choice: "auto" } : {},
96
+ ...args.kind === "json" ? { response_format: { type: "json_object" } } : {}
97
+ };
98
+ }
99
+ async function collectOpenAIStream(stream, onToken) {
100
+ let full = "";
101
+ const toolCallByIndex = /* @__PURE__ */ new Map();
102
+ for await (const chunk of stream) {
103
+ const delta = chunk?.choices?.[0]?.delta ?? {};
104
+ const content = typeof delta.content === "string" ? delta.content : "";
105
+ if (content) {
106
+ full += content;
107
+ onToken(content);
108
+ }
109
+ for (const toolCall of delta.tool_calls ?? []) {
110
+ const index = Number.isInteger(toolCall.index) ? toolCall.index : toolCallByIndex.size;
111
+ const current = toolCallByIndex.get(index) ?? {
112
+ id: void 0,
113
+ type: "function",
114
+ function: { name: "", arguments: "" }
115
+ };
116
+ if (toolCall.id) current.id = toolCall.id;
117
+ if (toolCall.function?.name) current.function.name += toolCall.function.name;
118
+ if (toolCall.function?.arguments) current.function.arguments += toolCall.function.arguments;
119
+ toolCallByIndex.set(index, current);
120
+ }
121
+ }
122
+ const toolCalls = fromOpenAIToolCalls([...toolCallByIndex.values()]);
123
+ if (toolCalls.length) return { toolCalls };
124
+ return { output: full };
125
+ }
126
+ function safeParseJSON(s) {
127
+ try {
128
+ return JSON.parse(s);
129
+ } catch {
130
+ const m = s.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
131
+ if (m) {
132
+ try {
133
+ return JSON.parse(m[0]);
134
+ } catch {
135
+ }
136
+ }
137
+ return { raw: s };
138
+ }
139
+ }
140
+ function stringifyToolOutput(output) {
141
+ if (typeof output === "string") return output;
142
+ try {
143
+ return JSON.stringify(output);
144
+ } catch {
145
+ return String(output);
146
+ }
147
+ }
148
+ function parseToolArguments(raw) {
149
+ if (typeof raw !== "string") return raw ?? {};
150
+ if (!raw.trim()) return {};
151
+ try {
152
+ return JSON.parse(raw);
153
+ } catch {
154
+ return { raw };
155
+ }
156
+ }
157
+ export {
158
+ buildOpenAIMessages,
159
+ createOpenAIProvider,
160
+ fromOpenAIToolCalls,
161
+ toOpenAITools
162
+ };
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@bolt-ai/providers-openai",
3
+ "version": "1.0.0",
4
+ "description": "OpenAI 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
+ "openai",
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
+ "openai": "^6.42.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
+ }