@aigne/openai 0.1.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.
@@ -0,0 +1,415 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ROLE_MAP = exports.OpenAIChatModel = exports.openAIChatModelOptionsSchema = void 0;
7
+ exports.contentsFromInputMessages = contentsFromInputMessages;
8
+ exports.toolsFromInputTools = toolsFromInputTools;
9
+ exports.jsonSchemaToOpenAIJsonSchema = jsonSchemaToOpenAIJsonSchema;
10
+ const core_1 = require("@aigne/core");
11
+ const json_schema_js_1 = require("@aigne/core/utils/json-schema.js");
12
+ const model_utils_js_1 = require("@aigne/core/utils/model-utils.js");
13
+ const prompts_js_1 = require("@aigne/core/utils/prompts.js");
14
+ const stream_utils_js_1 = require("@aigne/core/utils/stream-utils.js");
15
+ const type_utils_js_1 = require("@aigne/core/utils/type-utils.js");
16
+ const nanoid_1 = require("nanoid");
17
+ const openai_1 = __importDefault(require("openai"));
18
+ const zod_1 = require("zod");
19
+ const CHAT_MODEL_OPENAI_DEFAULT_MODEL = "gpt-4o-mini";
20
+ const OPENAI_CHAT_MODEL_CAPABILITIES = {
21
+ "o4-mini": { supportsParallelToolCalls: false, supportsTemperature: false },
22
+ "o3-mini": { supportsParallelToolCalls: false, supportsTemperature: false },
23
+ };
24
+ /**
25
+ * @hidden
26
+ */
27
+ exports.openAIChatModelOptionsSchema = zod_1.z.object({
28
+ apiKey: zod_1.z.string().optional(),
29
+ baseURL: zod_1.z.string().optional(),
30
+ model: zod_1.z.string().optional(),
31
+ modelOptions: zod_1.z
32
+ .object({
33
+ model: zod_1.z.string().optional(),
34
+ temperature: zod_1.z.number().optional(),
35
+ topP: zod_1.z.number().optional(),
36
+ frequencyPenalty: zod_1.z.number().optional(),
37
+ presencePenalty: zod_1.z.number().optional(),
38
+ parallelToolCalls: zod_1.z.boolean().optional().default(true),
39
+ })
40
+ .optional(),
41
+ });
42
+ /**
43
+ * Implementation of the ChatModel interface for OpenAI's API
44
+ *
45
+ * This model provides access to OpenAI's capabilities including:
46
+ * - Text generation
47
+ * - Tool use with parallel tool calls
48
+ * - JSON structured output
49
+ * - Image understanding
50
+ *
51
+ * Default model: 'gpt-4o-mini'
52
+ *
53
+ * @example
54
+ * Here's how to create and use an OpenAI chat model:
55
+ * {@includeCode ../test/openai-chat-model.test.ts#example-openai-chat-model}
56
+ *
57
+ * @example
58
+ * Here's an example with streaming response:
59
+ * {@includeCode ../test/openai-chat-model.test.ts#example-openai-chat-model-streaming}
60
+ */
61
+ class OpenAIChatModel extends core_1.ChatModel {
62
+ options;
63
+ constructor(options) {
64
+ super();
65
+ this.options = options;
66
+ if (options)
67
+ (0, type_utils_js_1.checkArguments)(this.name, exports.openAIChatModelOptionsSchema, options);
68
+ const preset = options?.model ? OPENAI_CHAT_MODEL_CAPABILITIES[options.model] : undefined;
69
+ Object.assign(this, preset);
70
+ }
71
+ /**
72
+ * @hidden
73
+ */
74
+ _client;
75
+ apiKeyEnvName = "OPENAI_API_KEY";
76
+ apiKeyDefault;
77
+ supportsNativeStructuredOutputs = true;
78
+ supportsEndWithSystemMessage = true;
79
+ supportsToolsUseWithJsonSchema = true;
80
+ supportsParallelToolCalls = true;
81
+ supportsToolsEmptyParameters = true;
82
+ supportsToolStreaming = true;
83
+ supportsTemperature = true;
84
+ get client() {
85
+ const apiKey = this.options?.apiKey || process.env[this.apiKeyEnvName] || this.apiKeyDefault;
86
+ if (!apiKey)
87
+ throw new Error(`Api Key is required for ${this.name}`);
88
+ this._client ??= new openai_1.default({
89
+ baseURL: this.options?.baseURL,
90
+ apiKey,
91
+ });
92
+ return this._client;
93
+ }
94
+ get modelOptions() {
95
+ return this.options?.modelOptions;
96
+ }
97
+ /**
98
+ * Process the input and generate a response
99
+ * @param input The input to process
100
+ * @returns The generated response
101
+ */
102
+ process(input) {
103
+ return this._process(input);
104
+ }
105
+ async _process(input) {
106
+ const messages = await this.getRunMessages(input);
107
+ const body = {
108
+ model: this.options?.model || CHAT_MODEL_OPENAI_DEFAULT_MODEL,
109
+ temperature: this.supportsTemperature
110
+ ? (input.modelOptions?.temperature ?? this.modelOptions?.temperature)
111
+ : undefined,
112
+ top_p: input.modelOptions?.topP ?? this.modelOptions?.topP,
113
+ frequency_penalty: input.modelOptions?.frequencyPenalty ?? this.modelOptions?.frequencyPenalty,
114
+ presence_penalty: input.modelOptions?.presencePenalty ?? this.modelOptions?.presencePenalty,
115
+ messages,
116
+ stream_options: {
117
+ include_usage: true,
118
+ },
119
+ stream: true,
120
+ };
121
+ const { jsonMode, responseFormat } = await this.getRunResponseFormat(input);
122
+ const stream = await this.client.chat.completions.create({
123
+ ...body,
124
+ tools: toolsFromInputTools(input.tools, {
125
+ addTypeToEmptyParameters: !this.supportsToolsEmptyParameters,
126
+ }),
127
+ tool_choice: input.toolChoice,
128
+ parallel_tool_calls: this.getParallelToolCalls(input),
129
+ response_format: responseFormat,
130
+ });
131
+ if (input.responseFormat?.type !== "json_schema") {
132
+ return await this.extractResultFromStream(stream, false, true);
133
+ }
134
+ const result = await this.extractResultFromStream(stream, jsonMode);
135
+ if (!this.supportsToolsUseWithJsonSchema &&
136
+ !result.toolCalls?.length &&
137
+ input.responseFormat?.type === "json_schema" &&
138
+ result.text) {
139
+ const output = await this.requestStructuredOutput(body, input.responseFormat);
140
+ return { ...output, usage: (0, model_utils_js_1.mergeUsage)(result.usage, output.usage) };
141
+ }
142
+ return result;
143
+ }
144
+ getParallelToolCalls(input) {
145
+ if (!this.supportsParallelToolCalls)
146
+ return undefined;
147
+ if (!input.tools?.length)
148
+ return undefined;
149
+ return input.modelOptions?.parallelToolCalls ?? this.modelOptions?.parallelToolCalls;
150
+ }
151
+ async getRunMessages(input) {
152
+ const messages = await contentsFromInputMessages(input.messages);
153
+ if (!this.supportsEndWithSystemMessage && messages.at(-1)?.role !== "user") {
154
+ messages.push({ role: "user", content: "" });
155
+ }
156
+ if (!this.supportsToolsUseWithJsonSchema && input.tools?.length)
157
+ return messages;
158
+ if (this.supportsNativeStructuredOutputs)
159
+ return messages;
160
+ if (input.responseFormat?.type === "json_schema") {
161
+ messages.unshift({
162
+ role: "system",
163
+ content: (0, prompts_js_1.getJsonOutputPrompt)(input.responseFormat.jsonSchema.schema),
164
+ });
165
+ }
166
+ return messages;
167
+ }
168
+ async getRunResponseFormat(input) {
169
+ if (!this.supportsToolsUseWithJsonSchema && input.tools?.length)
170
+ return { jsonMode: false, responseFormat: undefined };
171
+ if (!this.supportsNativeStructuredOutputs) {
172
+ const jsonMode = input.responseFormat?.type === "json_schema";
173
+ return { jsonMode, responseFormat: jsonMode ? { type: "json_object" } : undefined };
174
+ }
175
+ if (input.responseFormat?.type === "json_schema") {
176
+ return {
177
+ jsonMode: true,
178
+ responseFormat: {
179
+ type: "json_schema",
180
+ json_schema: {
181
+ ...input.responseFormat.jsonSchema,
182
+ schema: jsonSchemaToOpenAIJsonSchema(input.responseFormat.jsonSchema.schema),
183
+ },
184
+ },
185
+ };
186
+ }
187
+ return { jsonMode: false, responseFormat: undefined };
188
+ }
189
+ async requestStructuredOutput(body, responseFormat) {
190
+ if (responseFormat?.type !== "json_schema") {
191
+ throw new Error("Expected json_schema response format");
192
+ }
193
+ const { jsonMode, responseFormat: resolvedResponseFormat } = await this.getRunResponseFormat({
194
+ responseFormat,
195
+ });
196
+ const res = await this.client.chat.completions.create({
197
+ ...body,
198
+ response_format: resolvedResponseFormat,
199
+ });
200
+ return this.extractResultFromStream(res, jsonMode);
201
+ }
202
+ async extractResultFromStream(stream, jsonMode, streaming) {
203
+ const result = new ReadableStream({
204
+ start: async (controller) => {
205
+ try {
206
+ let text = "";
207
+ let refusal = "";
208
+ const toolCalls = [];
209
+ let model;
210
+ for await (const chunk of stream) {
211
+ const choice = chunk.choices?.[0];
212
+ if (!model) {
213
+ model = chunk.model;
214
+ controller.enqueue({
215
+ delta: {
216
+ json: {
217
+ model,
218
+ },
219
+ },
220
+ });
221
+ }
222
+ if (choice?.delta.tool_calls?.length) {
223
+ for (const call of choice.delta.tool_calls) {
224
+ if (this.supportsToolStreaming && call.index !== undefined) {
225
+ handleToolCallDelta(toolCalls, call);
226
+ }
227
+ else {
228
+ handleCompleteToolCall(toolCalls, call);
229
+ }
230
+ }
231
+ }
232
+ if (choice?.delta.content) {
233
+ text += choice.delta.content;
234
+ if (!jsonMode) {
235
+ controller.enqueue({
236
+ delta: {
237
+ text: {
238
+ text: choice.delta.content,
239
+ },
240
+ },
241
+ });
242
+ }
243
+ }
244
+ if (choice?.delta.refusal) {
245
+ refusal += choice.delta.refusal;
246
+ if (!jsonMode) {
247
+ controller.enqueue({
248
+ delta: {
249
+ text: { text: choice.delta.refusal },
250
+ },
251
+ });
252
+ }
253
+ }
254
+ if (chunk.usage) {
255
+ controller.enqueue({
256
+ delta: {
257
+ json: {
258
+ usage: {
259
+ inputTokens: chunk.usage.prompt_tokens,
260
+ outputTokens: chunk.usage.completion_tokens,
261
+ },
262
+ },
263
+ },
264
+ });
265
+ }
266
+ }
267
+ text = text || refusal;
268
+ if (jsonMode && text) {
269
+ controller.enqueue({
270
+ delta: {
271
+ json: {
272
+ json: (0, json_schema_js_1.parseJSON)(text),
273
+ },
274
+ },
275
+ });
276
+ }
277
+ if (toolCalls.length) {
278
+ controller.enqueue({
279
+ delta: {
280
+ json: {
281
+ toolCalls: toolCalls.map(({ args, ...c }) => ({
282
+ ...c,
283
+ function: { ...c.function, arguments: (0, json_schema_js_1.parseJSON)(args) },
284
+ })),
285
+ },
286
+ },
287
+ });
288
+ }
289
+ controller.close();
290
+ }
291
+ catch (error) {
292
+ controller.error(error);
293
+ }
294
+ },
295
+ });
296
+ return streaming ? result : await (0, stream_utils_js_1.agentResponseStreamToObject)(result);
297
+ }
298
+ }
299
+ exports.OpenAIChatModel = OpenAIChatModel;
300
+ /**
301
+ * @hidden
302
+ */
303
+ exports.ROLE_MAP = {
304
+ system: "system",
305
+ user: "user",
306
+ agent: "assistant",
307
+ tool: "tool",
308
+ };
309
+ /**
310
+ * @hidden
311
+ */
312
+ async function contentsFromInputMessages(messages) {
313
+ return messages.map((i) => ({
314
+ role: exports.ROLE_MAP[i.role],
315
+ content: typeof i.content === "string"
316
+ ? i.content
317
+ : i.content
318
+ ?.map((c) => {
319
+ if (c.type === "text") {
320
+ return { type: "text", text: c.text };
321
+ }
322
+ if (c.type === "image_url") {
323
+ return {
324
+ type: "image_url",
325
+ image_url: { url: c.url },
326
+ };
327
+ }
328
+ })
329
+ .filter(type_utils_js_1.isNonNullable),
330
+ tool_calls: i.toolCalls?.map((i) => ({
331
+ ...i,
332
+ function: {
333
+ ...i.function,
334
+ arguments: JSON.stringify(i.function.arguments),
335
+ },
336
+ })),
337
+ tool_call_id: i.toolCallId,
338
+ name: i.name,
339
+ }));
340
+ }
341
+ /**
342
+ * @hidden
343
+ */
344
+ function toolsFromInputTools(tools, options) {
345
+ return tools?.length
346
+ ? tools.map((i) => {
347
+ const parameters = i.function.parameters;
348
+ if (options?.addTypeToEmptyParameters && Object.keys(parameters).length === 0) {
349
+ parameters.type = "object";
350
+ }
351
+ return {
352
+ type: "function",
353
+ function: {
354
+ name: i.function.name,
355
+ description: i.function.description,
356
+ parameters,
357
+ },
358
+ };
359
+ })
360
+ : undefined;
361
+ }
362
+ /**
363
+ * @hidden
364
+ */
365
+ function jsonSchemaToOpenAIJsonSchema(schema) {
366
+ if (schema?.type === "object") {
367
+ const { required, properties } = schema;
368
+ return {
369
+ ...schema,
370
+ properties: Object.fromEntries(Object.entries(properties).map(([key, value]) => {
371
+ const valueSchema = jsonSchemaToOpenAIJsonSchema(value);
372
+ // NOTE: All fields must be required https://platform.openai.com/docs/guides/structured-outputs/all-fields-must-be-required
373
+ return [
374
+ key,
375
+ required?.includes(key) ? valueSchema : { anyOf: [valueSchema, { type: ["null"] }] },
376
+ ];
377
+ })),
378
+ required: Object.keys(properties),
379
+ };
380
+ }
381
+ if (schema?.type === "array") {
382
+ const { items } = schema;
383
+ return {
384
+ ...schema,
385
+ items: jsonSchemaToOpenAIJsonSchema(items),
386
+ };
387
+ }
388
+ return schema;
389
+ }
390
+ function handleToolCallDelta(toolCalls, call) {
391
+ toolCalls[call.index] ??= {
392
+ id: call.id || (0, nanoid_1.nanoid)(),
393
+ type: "function",
394
+ function: { name: "", arguments: {} },
395
+ args: "",
396
+ };
397
+ const c = toolCalls[call.index];
398
+ if (!c)
399
+ throw new Error("Tool call not found");
400
+ if (call.type)
401
+ c.type = call.type;
402
+ c.function.name = c.function.name + (call.function?.name || "");
403
+ c.args = c.args.concat(call.function?.arguments || "");
404
+ }
405
+ function handleCompleteToolCall(toolCalls, call) {
406
+ toolCalls.push({
407
+ id: call.id || (0, nanoid_1.nanoid)(),
408
+ type: "function",
409
+ function: {
410
+ name: call.function?.name || "",
411
+ arguments: (0, json_schema_js_1.parseJSON)(call.function?.arguments || "{}"),
412
+ },
413
+ args: call.function?.arguments || "",
414
+ });
415
+ }
@@ -0,0 +1 @@
1
+ {"type": "commonjs"}
@@ -0,0 +1 @@
1
+ export * from "./openai-chat-model.js";
@@ -0,0 +1,165 @@
1
+ import { type AgentProcessResult, ChatModel, type ChatModelInput, type ChatModelInputMessage, type ChatModelInputTool, type ChatModelOptions, type ChatModelOutput, type Role } from "@aigne/core";
2
+ import { type PromiseOrValue } from "@aigne/core/utils/type-utils.js";
3
+ import OpenAI from "openai";
4
+ import type { ChatCompletionMessageParam, ChatCompletionTool } from "openai/resources";
5
+ import { z } from "zod";
6
+ export interface OpenAIChatModelCapabilities {
7
+ supportsNativeStructuredOutputs: boolean;
8
+ supportsEndWithSystemMessage: boolean;
9
+ supportsToolsUseWithJsonSchema: boolean;
10
+ supportsParallelToolCalls: boolean;
11
+ supportsToolsEmptyParameters: boolean;
12
+ supportsToolStreaming: boolean;
13
+ supportsTemperature: boolean;
14
+ }
15
+ /**
16
+ * Configuration options for OpenAI Chat Model
17
+ */
18
+ export interface OpenAIChatModelOptions {
19
+ /**
20
+ * API key for OpenAI API
21
+ *
22
+ * If not provided, will look for OPENAI_API_KEY in environment variables
23
+ */
24
+ apiKey?: string;
25
+ /**
26
+ * Base URL for OpenAI API
27
+ *
28
+ * Useful for proxies or alternate endpoints
29
+ */
30
+ baseURL?: string;
31
+ /**
32
+ * OpenAI model to use
33
+ *
34
+ * Defaults to 'gpt-4o-mini'
35
+ */
36
+ model?: string;
37
+ /**
38
+ * Additional model options to control behavior
39
+ */
40
+ modelOptions?: ChatModelOptions;
41
+ }
42
+ /**
43
+ * @hidden
44
+ */
45
+ export declare const openAIChatModelOptionsSchema: z.ZodObject<{
46
+ apiKey: z.ZodOptional<z.ZodString>;
47
+ baseURL: z.ZodOptional<z.ZodString>;
48
+ model: z.ZodOptional<z.ZodString>;
49
+ modelOptions: z.ZodOptional<z.ZodObject<{
50
+ model: z.ZodOptional<z.ZodString>;
51
+ temperature: z.ZodOptional<z.ZodNumber>;
52
+ topP: z.ZodOptional<z.ZodNumber>;
53
+ frequencyPenalty: z.ZodOptional<z.ZodNumber>;
54
+ presencePenalty: z.ZodOptional<z.ZodNumber>;
55
+ parallelToolCalls: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
56
+ }, "strip", z.ZodTypeAny, {
57
+ parallelToolCalls: boolean;
58
+ model?: string | undefined;
59
+ temperature?: number | undefined;
60
+ topP?: number | undefined;
61
+ frequencyPenalty?: number | undefined;
62
+ presencePenalty?: number | undefined;
63
+ }, {
64
+ model?: string | undefined;
65
+ temperature?: number | undefined;
66
+ topP?: number | undefined;
67
+ frequencyPenalty?: number | undefined;
68
+ presencePenalty?: number | undefined;
69
+ parallelToolCalls?: boolean | undefined;
70
+ }>>;
71
+ }, "strip", z.ZodTypeAny, {
72
+ apiKey?: string | undefined;
73
+ baseURL?: string | undefined;
74
+ model?: string | undefined;
75
+ modelOptions?: {
76
+ parallelToolCalls: boolean;
77
+ model?: string | undefined;
78
+ temperature?: number | undefined;
79
+ topP?: number | undefined;
80
+ frequencyPenalty?: number | undefined;
81
+ presencePenalty?: number | undefined;
82
+ } | undefined;
83
+ }, {
84
+ apiKey?: string | undefined;
85
+ baseURL?: string | undefined;
86
+ model?: string | undefined;
87
+ modelOptions?: {
88
+ model?: string | undefined;
89
+ temperature?: number | undefined;
90
+ topP?: number | undefined;
91
+ frequencyPenalty?: number | undefined;
92
+ presencePenalty?: number | undefined;
93
+ parallelToolCalls?: boolean | undefined;
94
+ } | undefined;
95
+ }>;
96
+ /**
97
+ * Implementation of the ChatModel interface for OpenAI's API
98
+ *
99
+ * This model provides access to OpenAI's capabilities including:
100
+ * - Text generation
101
+ * - Tool use with parallel tool calls
102
+ * - JSON structured output
103
+ * - Image understanding
104
+ *
105
+ * Default model: 'gpt-4o-mini'
106
+ *
107
+ * @example
108
+ * Here's how to create and use an OpenAI chat model:
109
+ * {@includeCode ../test/openai-chat-model.test.ts#example-openai-chat-model}
110
+ *
111
+ * @example
112
+ * Here's an example with streaming response:
113
+ * {@includeCode ../test/openai-chat-model.test.ts#example-openai-chat-model-streaming}
114
+ */
115
+ export declare class OpenAIChatModel extends ChatModel {
116
+ options?: OpenAIChatModelOptions | undefined;
117
+ constructor(options?: OpenAIChatModelOptions | undefined);
118
+ /**
119
+ * @hidden
120
+ */
121
+ protected _client?: OpenAI;
122
+ protected apiKeyEnvName: string;
123
+ protected apiKeyDefault: string | undefined;
124
+ protected supportsNativeStructuredOutputs: boolean;
125
+ protected supportsEndWithSystemMessage: boolean;
126
+ protected supportsToolsUseWithJsonSchema: boolean;
127
+ protected supportsParallelToolCalls: boolean;
128
+ protected supportsToolsEmptyParameters: boolean;
129
+ protected supportsToolStreaming: boolean;
130
+ protected supportsTemperature: boolean;
131
+ get client(): OpenAI;
132
+ get modelOptions(): ChatModelOptions | undefined;
133
+ /**
134
+ * Process the input and generate a response
135
+ * @param input The input to process
136
+ * @returns The generated response
137
+ */
138
+ process(input: ChatModelInput): PromiseOrValue<AgentProcessResult<ChatModelOutput>>;
139
+ private _process;
140
+ private getParallelToolCalls;
141
+ private getRunMessages;
142
+ private getRunResponseFormat;
143
+ private requestStructuredOutput;
144
+ private extractResultFromStream;
145
+ }
146
+ /**
147
+ * @hidden
148
+ */
149
+ export declare const ROLE_MAP: {
150
+ [key in Role]: ChatCompletionMessageParam["role"];
151
+ };
152
+ /**
153
+ * @hidden
154
+ */
155
+ export declare function contentsFromInputMessages(messages: ChatModelInputMessage[]): Promise<ChatCompletionMessageParam[]>;
156
+ /**
157
+ * @hidden
158
+ */
159
+ export declare function toolsFromInputTools(tools?: ChatModelInputTool[], options?: {
160
+ addTypeToEmptyParameters?: boolean;
161
+ }): ChatCompletionTool[] | undefined;
162
+ /**
163
+ * @hidden
164
+ */
165
+ export declare function jsonSchemaToOpenAIJsonSchema(schema: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1 @@
1
+ export * from "./openai-chat-model.js";
@@ -0,0 +1 @@
1
+ export * from "./openai-chat-model.js";