@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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0](https://github.com/AIGNE-io/aigne-framework/compare/openai-v0.0.1...openai-v0.1.0) (2025-05-23)
4
+
5
+
6
+ ### Features
7
+
8
+ * **models:** publish model adapters as standalone packages ([#126](https://github.com/AIGNE-io/aigne-framework/issues/126)) ([588b8ae](https://github.com/AIGNE-io/aigne-framework/commit/588b8aea6abcee5fa87def1358bf51f84021c6ef))
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @aigne/core bumped to 1.16.0
16
+ * devDependencies
17
+ * @aigne/test-utils bumped to 0.3.0
package/LICENSE.md ADDED
@@ -0,0 +1,93 @@
1
+ Elastic License 2.0
2
+
3
+ URL: https://www.elastic.co/licensing/elastic-license
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject to
14
+ the limitations and conditions below.
15
+
16
+ ## Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set of
20
+ the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
27
+ of the licensor in the software. Any use of the licensor’s trademarks is subject
28
+ to applicable law.
29
+
30
+ ## Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software. If you or your company make any written claim that the software
38
+ infringes or contributes to infringement of any patent, your patent license for
39
+ the software granted under these terms ends immediately. If your company makes
40
+ such a claim, your patent license ends immediately for work on behalf of your
41
+ company.
42
+
43
+ ## Notices
44
+
45
+ You must ensure that anyone who gets a copy of any part of the software from you
46
+ also gets a copy of these terms.
47
+
48
+ If you modify the software, you must include in any modified copies of the
49
+ software prominent notices stating that you have modified the software.
50
+
51
+ ## No Other Rights
52
+
53
+ These terms do not imply any licenses other than those expressly granted in
54
+ these terms.
55
+
56
+ ## Termination
57
+
58
+ If you use the software in violation of these terms, such use is not licensed,
59
+ and your licenses will automatically terminate. If the licensor provides you
60
+ with a notice of your violation, and you cease all violation of this license no
61
+ later than 30 days after you receive that notice, your licenses will be
62
+ reinstated retroactively. However, if you violate these terms after such
63
+ reinstatement, any additional violation of these terms will cause your licenses
64
+ to terminate automatically and permanently.
65
+
66
+ ## No Liability
67
+
68
+ *As far as the law allows, the software comes as is, without any warranty or
69
+ condition, and the licensor will not be liable to you for any damages arising
70
+ out of these terms or the use or nature of the software, under any kind of
71
+ legal claim.*
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the entity offering these terms, and the **software** is the
76
+ software the licensor makes available under these terms, including any portion
77
+ of it.
78
+
79
+ **you** refers to the individual or entity agreeing to these terms.
80
+
81
+ **your company** is any legal entity, sole proprietorship, or other kind of
82
+ organization that you work for, plus all organizations that have control over,
83
+ are under the control of, or are under common control with that
84
+ organization. **control** means ownership of substantially all the assets of an
85
+ entity, or the power to direct its management and policies by vote, contract, or
86
+ otherwise. Control can be direct or indirect.
87
+
88
+ **your licenses** are all the licenses granted to you for the software under
89
+ these terms.
90
+
91
+ **use** means anything you do with the software requiring one of your licenses.
92
+
93
+ **trademark** means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # @aigne/openai
2
+
3
+ [![GitHub star chart](https://img.shields.io/github/stars/AIGNE-io/aigne-framework?style=flat-square)](https://star-history.com/#AIGNE-io/aigne-framework)
4
+ [![Open Issues](https://img.shields.io/github/issues-raw/AIGNE-io/aigne-framework?style=flat-square)](https://github.com/AIGNE-io/aigne-framework/issues)
5
+ [![codecov](https://codecov.io/gh/AIGNE-io/aigne-framework/graph/badge.svg?token=DO07834RQL)](https://codecov.io/gh/AIGNE-io/aigne-framework)
6
+ [![NPM Version](https://img.shields.io/npm/v/@aigne/openai)](https://www.npmjs.com/package/@aigne/openai)
7
+ [![Elastic-2.0 licensed](https://img.shields.io/npm/l/@aigne/openai)](https://github.com/AIGNE-io/aigne-framework/blob/main/LICENSE.md)
8
+
9
+ **English** | [中文](README.zh.md)
10
+
11
+ AIGNE OpenAI SDK for integrating with OpenAI's GPT models and API services within the [AIGNE Framework](https://github.com/AIGNE-io/aigne-framework).
12
+
13
+ ## Introduction
14
+
15
+ `@aigne/openai` provides a seamless integration between the AIGNE Framework and OpenAI's powerful language models and APIs. This package enables developers to easily leverage OpenAI's GPT models in their AIGNE applications, providing a consistent interface across the framework while taking advantage of OpenAI's advanced AI capabilities.
16
+
17
+ ## Features
18
+
19
+ * **OpenAI API Integration**: Direct connection to OpenAI's API services using the official SDK
20
+ * **Chat Completions**: Support for OpenAI's chat completions API with all available models
21
+ * **Function Calling**: Built-in support for OpenAI's function calling capability
22
+ * **Streaming Responses**: Support for streaming responses for more responsive applications
23
+ * **Type-Safe**: Comprehensive TypeScript typings for all APIs and models
24
+ * **Consistent Interface**: Compatible with the AIGNE Framework's model interface
25
+ * **Error Handling**: Robust error handling and retry mechanisms
26
+ * **Full Configuration**: Extensive configuration options for fine-tuning behavior
27
+
28
+ ## Installation
29
+
30
+ ### Using npm
31
+
32
+ ```bash
33
+ npm install @aigne/openai @aigne/core
34
+ ```
35
+
36
+ ### Using yarn
37
+
38
+ ```bash
39
+ yarn add @aigne/openai @aigne/core
40
+ ```
41
+
42
+ ### Using pnpm
43
+
44
+ ```bash
45
+ pnpm add @aigne/openai @aigne/core
46
+ ```
47
+
48
+ ## Basic Usage
49
+
50
+ ```typescript file="test/openai-chat-model.test.ts" region="example-openai-chat-model"
51
+ import { OpenAIChatModel } from "@aigne/openai";
52
+
53
+ const model = new OpenAIChatModel({
54
+ // Provide API key directly or use environment variable OPENAI_API_KEY
55
+ apiKey: "your-api-key", // Optional if set in env variables
56
+ model: "gpt-4o", // Defaults to "gpt-4o-mini" if not specified
57
+ modelOptions: {
58
+ temperature: 0.7,
59
+ },
60
+ });
61
+
62
+ const result = await model.invoke({
63
+ messages: [{ role: "user", content: "Hello, who are you?" }],
64
+ });
65
+
66
+ console.log(result);
67
+ /* Output:
68
+ {
69
+ text: "Hello! How can I assist you today?",
70
+ model: "gpt-4o",
71
+ usage: {
72
+ inputTokens: 10,
73
+ outputTokens: 9
74
+ }
75
+ }
76
+ */
77
+ ```
78
+
79
+ ## Streaming Responses
80
+
81
+ ```typescript file="test/openai-chat-model.test.ts" region="example-openai-chat-model-stream"
82
+ import { OpenAIChatModel } from "@aigne/openai";
83
+
84
+ const model = new OpenAIChatModel({
85
+ apiKey: "your-api-key",
86
+ model: "gpt-4o",
87
+ });
88
+
89
+ const stream = await model.invoke(
90
+ {
91
+ messages: [{ role: "user", content: "Hello, who are you?" }],
92
+ },
93
+ undefined,
94
+ { streaming: true },
95
+ );
96
+
97
+ let fullText = "";
98
+ const json = {};
99
+
100
+ for await (const chunk of stream) {
101
+ const text = chunk.delta.text?.text;
102
+ if (text) fullText += text;
103
+ if (chunk.delta.json) Object.assign(json, chunk.delta.json);
104
+ }
105
+
106
+ console.log(fullText); // Output: "Hello! How can I assist you today?"
107
+ console.log(json); // { model: "gpt-4o", usage: { inputTokens: 10, outputTokens: 9 } }
108
+ ```
109
+
110
+ ## License
111
+
112
+ Elastic-2.0
package/README.zh.md ADDED
@@ -0,0 +1,112 @@
1
+ # @aigne/openai
2
+
3
+ [![GitHub star chart](https://img.shields.io/github/stars/AIGNE-io/aigne-framework?style=flat-square)](https://star-history.com/#AIGNE-io/aigne-framework)
4
+ [![Open Issues](https://img.shields.io/github/issues-raw/AIGNE-io/aigne-framework?style=flat-square)](https://github.com/AIGNE-io/aigne-framework/issues)
5
+ [![codecov](https://codecov.io/gh/AIGNE-io/aigne-framework/graph/badge.svg?token=DO07834RQL)](https://codecov.io/gh/AIGNE-io/aigne-framework)
6
+ [![NPM Version](https://img.shields.io/npm/v/@aigne/openai)](https://www.npmjs.com/package/@aigne/openai)
7
+ [![Elastic-2.0 licensed](https://img.shields.io/npm/l/@aigne/openai)](https://github.com/AIGNE-io/aigne-framework/blob/main/LICENSE.md)
8
+
9
+ [English](README.md) | **中文**
10
+
11
+ AIGNE OpenAI SDK,用于在 [AIGNE 框架](https://github.com/AIGNE-io/aigne-framework) 中集成 OpenAI 的 GPT 模型和 API 服务。
12
+
13
+ ## 简介
14
+
15
+ `@aigne/openai` 提供了 AIGNE 框架与 OpenAI 强大的语言模型和 API 之间的无缝集成。该包使开发者能够在 AIGNE 应用程序中轻松利用 OpenAI 的 GPT 模型,同时提供框架内一致的接口,充分发挥 OpenAI 先进的 AI 能力。
16
+
17
+ ## 特性
18
+
19
+ * **OpenAI API 集成**:使用官方 SDK 直接连接到 OpenAI 的 API 服务
20
+ * **聊天完成**:支持 OpenAI 的聊天完成 API 和所有可用模型
21
+ * **函数调用**:内置支持 OpenAI 的函数调用功能
22
+ * **流式响应**:支持流式响应,提供更高响应性的应用程序体验
23
+ * **类型安全**:为所有 API 和模型提供全面的 TypeScript 类型定义
24
+ * **一致接口**:兼容 AIGNE 框架的模型接口
25
+ * **错误处理**:健壮的错误处理和重试机制
26
+ * **完整配置**:丰富的配置选项用于微调行为
27
+
28
+ ## 安装
29
+
30
+ ### 使用 npm
31
+
32
+ ```bash
33
+ npm install @aigne/openai @aigne/core
34
+ ```
35
+
36
+ ### 使用 yarn
37
+
38
+ ```bash
39
+ yarn add @aigne/openai @aigne/core
40
+ ```
41
+
42
+ ### 使用 pnpm
43
+
44
+ ```bash
45
+ pnpm add @aigne/openai @aigne/core
46
+ ```
47
+
48
+ ## 基本用法
49
+
50
+ ```typescript file="test/openai-chat-model.test.ts" region="example-openai-chat-model"
51
+ import { OpenAIChatModel } from "@aigne/openai";
52
+
53
+ const model = new OpenAIChatModel({
54
+ // Provide API key directly or use environment variable OPENAI_API_KEY
55
+ apiKey: "your-api-key", // Optional if set in env variables
56
+ model: "gpt-4o", // Defaults to "gpt-4o-mini" if not specified
57
+ modelOptions: {
58
+ temperature: 0.7,
59
+ },
60
+ });
61
+
62
+ const result = await model.invoke({
63
+ messages: [{ role: "user", content: "Hello, who are you?" }],
64
+ });
65
+
66
+ console.log(result);
67
+ /* Output:
68
+ {
69
+ text: "Hello! How can I assist you today?",
70
+ model: "gpt-4o",
71
+ usage: {
72
+ inputTokens: 10,
73
+ outputTokens: 9
74
+ }
75
+ }
76
+ */
77
+ ```
78
+
79
+ ## 流式响应
80
+
81
+ ```typescript file="test/openai-chat-model.test.ts" region="example-openai-chat-model-stream"
82
+ import { OpenAIChatModel } from "@aigne/openai";
83
+
84
+ const model = new OpenAIChatModel({
85
+ apiKey: "your-api-key",
86
+ model: "gpt-4o",
87
+ });
88
+
89
+ const stream = await model.invoke(
90
+ {
91
+ messages: [{ role: "user", content: "Hello, who are you?" }],
92
+ },
93
+ undefined,
94
+ { streaming: true },
95
+ );
96
+
97
+ let fullText = "";
98
+ const json = {};
99
+
100
+ for await (const chunk of stream) {
101
+ const text = chunk.delta.text?.text;
102
+ if (text) fullText += text;
103
+ if (chunk.delta.json) Object.assign(json, chunk.delta.json);
104
+ }
105
+
106
+ console.log(fullText); // Output: "Hello! How can I assist you today?"
107
+ console.log(json); // { model: "gpt-4o", usage: { inputTokens: 10, outputTokens: 9 } }
108
+ ```
109
+
110
+ ## 许可证
111
+
112
+ Elastic-2.0
@@ -0,0 +1 @@
1
+ export * from "./openai-chat-model.js";
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./openai-chat-model.js"), exports);
@@ -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>;