@anvia/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/LICENSE +21 -0
- package/README.md +84 -0
- package/dist/index.d.ts +120 -0
- package/dist/index.js +971 -0
- package/dist/index.js.map +1 -0
- package/package.json +35 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Indra Zulfi
|
|
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/README.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# @anvia/openai
|
|
2
|
+
|
|
3
|
+
OpenAI provider adapter for Anvia.
|
|
4
|
+
|
|
5
|
+
Use this package when you want Anvia agents, extractors, pipelines, embeddings, image generation, audio generation, or transcription to run on OpenAI models or OpenAI-compatible endpoints.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm add @anvia/openai @anvia/core
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
In this monorepo, the package is available through the workspace:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
pnpm --filter @anvia/openai build
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { AgentBuilder } from "@anvia/core";
|
|
23
|
+
import { OpenAIClient } from "@anvia/openai";
|
|
24
|
+
|
|
25
|
+
const client = new OpenAIClient({
|
|
26
|
+
apiKey,
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const model = client.completionModel("gpt-5");
|
|
30
|
+
|
|
31
|
+
const agent = new AgentBuilder("assistant", model)
|
|
32
|
+
.instructions("Answer clearly and concisely.")
|
|
33
|
+
.build();
|
|
34
|
+
|
|
35
|
+
const response = await agent.prompt("Summarize Anvia in one sentence.").send();
|
|
36
|
+
|
|
37
|
+
console.log(response.output);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## OpenAI-Compatible APIs
|
|
41
|
+
|
|
42
|
+
When `baseUrl` is provided, `OpenAIClient` uses the chat-completions-compatible adapter by default:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { OpenAIClient } from "@anvia/openai";
|
|
46
|
+
|
|
47
|
+
const client = new OpenAIClient({
|
|
48
|
+
apiKey,
|
|
49
|
+
baseUrl,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const model = client.completionModel("openai/gpt-5.2");
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
You can also force a specific completion API with `completionApi: "responses"` or `completionApi: "chat"`.
|
|
56
|
+
|
|
57
|
+
## Other Models
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const embeddingModel = client.embeddingModel("text-embedding-3-small");
|
|
61
|
+
const imageModel = client.imageGenerationModel();
|
|
62
|
+
const audioModel = client.audioGenerationModel();
|
|
63
|
+
const transcriptionModel = client.transcriptionModel();
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Exports
|
|
67
|
+
|
|
68
|
+
- `OpenAIClient`
|
|
69
|
+
- `OpenAIResponsesCompletionModel`
|
|
70
|
+
- `OpenAIChatCompletionModel`
|
|
71
|
+
- `OpenAIEmbeddingModel`
|
|
72
|
+
- `OpenAIImageGenerationModel`
|
|
73
|
+
- `OpenAIAudioGenerationModel`
|
|
74
|
+
- `OpenAITranscriptionModel`
|
|
75
|
+
- model constants such as `GPT_IMAGE_1`, `DALL_E_3`, `TTS_1`, and `WHISPER_1`
|
|
76
|
+
- `openai`
|
|
77
|
+
|
|
78
|
+
## Development
|
|
79
|
+
|
|
80
|
+
```sh
|
|
81
|
+
pnpm --filter @anvia/openai typecheck
|
|
82
|
+
pnpm --filter @anvia/openai test
|
|
83
|
+
pnpm --filter @anvia/openai build
|
|
84
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { AudioGenerationModel, AudioGenerationRequest, AudioGenerationResponse } from '@anvia/core/audio-generation';
|
|
2
|
+
import OpenAI$1, { OpenAI } from 'openai';
|
|
3
|
+
import { StreamingCompletionModel, CompletionModelCapabilities, CompletionRequest, CompletionResponse, CompletionStreamEvent } from '@anvia/core/completion';
|
|
4
|
+
import { EmbeddingModel, Embedding } from '@anvia/core/embeddings';
|
|
5
|
+
import { ImageGenerationModel, ImageGenerationRequest, ImageGenerationResponse } from '@anvia/core/image-generation';
|
|
6
|
+
import { TranscriptionModel, TranscriptionRequest, TranscriptionResponse } from '@anvia/core/transcription';
|
|
7
|
+
|
|
8
|
+
declare const TTS_1 = "tts-1";
|
|
9
|
+
declare const TTS_1_HD = "tts-1-hd";
|
|
10
|
+
declare class OpenAIAudioGenerationModel implements AudioGenerationModel {
|
|
11
|
+
private readonly client;
|
|
12
|
+
readonly defaultModel: string;
|
|
13
|
+
readonly provider = "openai";
|
|
14
|
+
constructor(client: OpenAI, defaultModel?: string);
|
|
15
|
+
audioGeneration(request: AudioGenerationRequest): Promise<AudioGenerationResponse<unknown>>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
declare class OpenAIChatCompletionModel implements StreamingCompletionModel {
|
|
19
|
+
private readonly client;
|
|
20
|
+
readonly defaultModel: string;
|
|
21
|
+
readonly provider = "openai-chat";
|
|
22
|
+
readonly capabilities: CompletionModelCapabilities;
|
|
23
|
+
constructor(client: OpenAI, defaultModel?: string);
|
|
24
|
+
completion(request: CompletionRequest): Promise<CompletionResponse>;
|
|
25
|
+
streamCompletion(request: CompletionRequest): AsyncIterable<CompletionStreamEvent>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type ProviderEmbeddingModelOptions = {
|
|
29
|
+
dimensions?: number | undefined;
|
|
30
|
+
user?: string | undefined;
|
|
31
|
+
maxBatchSize?: number | undefined;
|
|
32
|
+
};
|
|
33
|
+
declare class OpenAIEmbeddingModel implements EmbeddingModel {
|
|
34
|
+
private readonly client;
|
|
35
|
+
private readonly model;
|
|
36
|
+
readonly dimensions: number | undefined;
|
|
37
|
+
readonly maxBatchSize: number;
|
|
38
|
+
private readonly user;
|
|
39
|
+
constructor(client: OpenAI$1, model: string, options?: ProviderEmbeddingModelOptions);
|
|
40
|
+
embedTexts(texts: string[]): Promise<Embedding[]>;
|
|
41
|
+
private embedBatch;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
declare const DALL_E_2 = "dall-e-2";
|
|
45
|
+
declare const DALL_E_3 = "dall-e-3";
|
|
46
|
+
declare const GPT_IMAGE_1 = "gpt-image-1";
|
|
47
|
+
declare const GPT_IMAGE_2 = "gpt-image-2";
|
|
48
|
+
declare class OpenAIImageGenerationModel implements ImageGenerationModel {
|
|
49
|
+
private readonly client;
|
|
50
|
+
readonly defaultModel: string;
|
|
51
|
+
readonly provider = "openai";
|
|
52
|
+
constructor(client: OpenAI, defaultModel?: string);
|
|
53
|
+
imageGeneration(request: ImageGenerationRequest): Promise<ImageGenerationResponse<unknown>>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
declare const WHISPER_1 = "whisper-1";
|
|
57
|
+
declare class OpenAITranscriptionModel implements TranscriptionModel {
|
|
58
|
+
private readonly client;
|
|
59
|
+
readonly defaultModel: string;
|
|
60
|
+
readonly provider = "openai";
|
|
61
|
+
constructor(client: OpenAI, defaultModel?: string);
|
|
62
|
+
transcription(request: TranscriptionRequest): Promise<TranscriptionResponse<unknown>>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
type OpenAIClientOptions = {
|
|
66
|
+
apiKey?: string | undefined;
|
|
67
|
+
baseUrl?: string | undefined;
|
|
68
|
+
headers?: Record<string, string> | undefined;
|
|
69
|
+
completionApi?: "responses" | "chat" | undefined;
|
|
70
|
+
client?: OpenAI$1 | undefined;
|
|
71
|
+
};
|
|
72
|
+
declare class OpenAIClient {
|
|
73
|
+
readonly client: OpenAI$1;
|
|
74
|
+
private readonly completionApi;
|
|
75
|
+
constructor(options?: OpenAIClientOptions);
|
|
76
|
+
completionModel(model?: string): StreamingCompletionModel;
|
|
77
|
+
embeddingModel(model?: string, options?: ProviderEmbeddingModelOptions): OpenAIEmbeddingModel;
|
|
78
|
+
imageGenerationModel(model?: string): OpenAIImageGenerationModel;
|
|
79
|
+
audioGenerationModel(model?: string): OpenAIAudioGenerationModel;
|
|
80
|
+
transcriptionModel(model?: string): OpenAITranscriptionModel;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
declare class OpenAIResponsesCompletionModel implements StreamingCompletionModel {
|
|
84
|
+
private readonly client;
|
|
85
|
+
readonly defaultModel: string;
|
|
86
|
+
readonly provider = "openai";
|
|
87
|
+
readonly capabilities: CompletionModelCapabilities;
|
|
88
|
+
constructor(client: OpenAI, defaultModel?: string);
|
|
89
|
+
completion(request: CompletionRequest): Promise<CompletionResponse>;
|
|
90
|
+
streamCompletion(request: CompletionRequest): AsyncIterable<CompletionStreamEvent>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
declare const index_DALL_E_2: typeof DALL_E_2;
|
|
94
|
+
declare const index_DALL_E_3: typeof DALL_E_3;
|
|
95
|
+
declare const index_GPT_IMAGE_1: typeof GPT_IMAGE_1;
|
|
96
|
+
declare const index_GPT_IMAGE_2: typeof GPT_IMAGE_2;
|
|
97
|
+
type index_OpenAIAudioGenerationModel = OpenAIAudioGenerationModel;
|
|
98
|
+
declare const index_OpenAIAudioGenerationModel: typeof OpenAIAudioGenerationModel;
|
|
99
|
+
type index_OpenAIChatCompletionModel = OpenAIChatCompletionModel;
|
|
100
|
+
declare const index_OpenAIChatCompletionModel: typeof OpenAIChatCompletionModel;
|
|
101
|
+
type index_OpenAIClient = OpenAIClient;
|
|
102
|
+
declare const index_OpenAIClient: typeof OpenAIClient;
|
|
103
|
+
type index_OpenAIClientOptions = OpenAIClientOptions;
|
|
104
|
+
type index_OpenAIEmbeddingModel = OpenAIEmbeddingModel;
|
|
105
|
+
declare const index_OpenAIEmbeddingModel: typeof OpenAIEmbeddingModel;
|
|
106
|
+
type index_OpenAIImageGenerationModel = OpenAIImageGenerationModel;
|
|
107
|
+
declare const index_OpenAIImageGenerationModel: typeof OpenAIImageGenerationModel;
|
|
108
|
+
type index_OpenAIResponsesCompletionModel = OpenAIResponsesCompletionModel;
|
|
109
|
+
declare const index_OpenAIResponsesCompletionModel: typeof OpenAIResponsesCompletionModel;
|
|
110
|
+
type index_OpenAITranscriptionModel = OpenAITranscriptionModel;
|
|
111
|
+
declare const index_OpenAITranscriptionModel: typeof OpenAITranscriptionModel;
|
|
112
|
+
type index_ProviderEmbeddingModelOptions = ProviderEmbeddingModelOptions;
|
|
113
|
+
declare const index_TTS_1: typeof TTS_1;
|
|
114
|
+
declare const index_TTS_1_HD: typeof TTS_1_HD;
|
|
115
|
+
declare const index_WHISPER_1: typeof WHISPER_1;
|
|
116
|
+
declare namespace index {
|
|
117
|
+
export { index_DALL_E_2 as DALL_E_2, index_DALL_E_3 as DALL_E_3, index_GPT_IMAGE_1 as GPT_IMAGE_1, index_GPT_IMAGE_2 as GPT_IMAGE_2, index_OpenAIAudioGenerationModel as OpenAIAudioGenerationModel, index_OpenAIChatCompletionModel as OpenAIChatCompletionModel, index_OpenAIClient as OpenAIClient, type index_OpenAIClientOptions as OpenAIClientOptions, index_OpenAIEmbeddingModel as OpenAIEmbeddingModel, index_OpenAIImageGenerationModel as OpenAIImageGenerationModel, index_OpenAIResponsesCompletionModel as OpenAIResponsesCompletionModel, index_OpenAITranscriptionModel as OpenAITranscriptionModel, type index_ProviderEmbeddingModelOptions as ProviderEmbeddingModelOptions, index_TTS_1 as TTS_1, index_TTS_1_HD as TTS_1_HD, index_WHISPER_1 as WHISPER_1 };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export { DALL_E_2, DALL_E_3, GPT_IMAGE_1, GPT_IMAGE_2, OpenAIAudioGenerationModel, OpenAIChatCompletionModel, OpenAIClient, type OpenAIClientOptions, OpenAIEmbeddingModel, OpenAIImageGenerationModel, OpenAIResponsesCompletionModel, OpenAITranscriptionModel, type ProviderEmbeddingModelOptions, TTS_1, TTS_1_HD, WHISPER_1, index as openai };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,971 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __export = (target, all) => {
|
|
3
|
+
for (var name in all)
|
|
4
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
// src/openai/index.ts
|
|
8
|
+
var openai_exports = {};
|
|
9
|
+
__export(openai_exports, {
|
|
10
|
+
DALL_E_2: () => DALL_E_2,
|
|
11
|
+
DALL_E_3: () => DALL_E_3,
|
|
12
|
+
GPT_IMAGE_1: () => GPT_IMAGE_1,
|
|
13
|
+
GPT_IMAGE_2: () => GPT_IMAGE_2,
|
|
14
|
+
OpenAIAudioGenerationModel: () => OpenAIAudioGenerationModel,
|
|
15
|
+
OpenAIChatCompletionModel: () => OpenAIChatCompletionModel,
|
|
16
|
+
OpenAIClient: () => OpenAIClient,
|
|
17
|
+
OpenAIEmbeddingModel: () => OpenAIEmbeddingModel,
|
|
18
|
+
OpenAIImageGenerationModel: () => OpenAIImageGenerationModel,
|
|
19
|
+
OpenAIResponsesCompletionModel: () => OpenAIResponsesCompletionModel,
|
|
20
|
+
OpenAITranscriptionModel: () => OpenAITranscriptionModel,
|
|
21
|
+
TTS_1: () => TTS_1,
|
|
22
|
+
TTS_1_HD: () => TTS_1_HD,
|
|
23
|
+
WHISPER_1: () => WHISPER_1
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// src/utils.ts
|
|
27
|
+
function isPlainObject(value) {
|
|
28
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
29
|
+
}
|
|
30
|
+
function numberFrom(value) {
|
|
31
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
32
|
+
}
|
|
33
|
+
function stringFrom(value) {
|
|
34
|
+
return typeof value === "string" ? value : void 0;
|
|
35
|
+
}
|
|
36
|
+
function parseJsonValue(text) {
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(text);
|
|
39
|
+
} catch {
|
|
40
|
+
return text;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function schemaName(schema) {
|
|
44
|
+
return typeof schema.title === "string" ? schema.title : "response_schema";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/openai/audio-generation.ts
|
|
48
|
+
var TTS_1 = "tts-1";
|
|
49
|
+
var TTS_1_HD = "tts-1-hd";
|
|
50
|
+
var OpenAIAudioGenerationModel = class {
|
|
51
|
+
constructor(client, defaultModel = TTS_1) {
|
|
52
|
+
this.client = client;
|
|
53
|
+
this.defaultModel = defaultModel;
|
|
54
|
+
}
|
|
55
|
+
client;
|
|
56
|
+
defaultModel;
|
|
57
|
+
provider = "openai";
|
|
58
|
+
async audioGeneration(request) {
|
|
59
|
+
const params = {
|
|
60
|
+
model: this.defaultModel,
|
|
61
|
+
input: request.text,
|
|
62
|
+
voice: request.voice,
|
|
63
|
+
speed: request.speed
|
|
64
|
+
};
|
|
65
|
+
if (request.additionalParams !== void 0 && isPlainObject(request.additionalParams)) {
|
|
66
|
+
Object.assign(params, request.additionalParams);
|
|
67
|
+
}
|
|
68
|
+
const response = await this.client.audio.speech.create(params);
|
|
69
|
+
return {
|
|
70
|
+
audio: new Uint8Array(await response.arrayBuffer()),
|
|
71
|
+
mediaType: mediaTypeFromFormat(params.response_format),
|
|
72
|
+
rawResponse: response
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
function mediaTypeFromFormat(format) {
|
|
77
|
+
if (format === "wav") return "audio/wav";
|
|
78
|
+
if (format === "flac") return "audio/flac";
|
|
79
|
+
if (format === "opus") return "audio/opus";
|
|
80
|
+
if (format === "aac") return "audio/aac";
|
|
81
|
+
if (format === "pcm") return "audio/pcm";
|
|
82
|
+
return "audio/mpeg";
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/openai/chat-completion.ts
|
|
86
|
+
import {
|
|
87
|
+
AssistantContent,
|
|
88
|
+
assertCompletionRequestSupported,
|
|
89
|
+
Usage
|
|
90
|
+
} from "@anvia/core/completion";
|
|
91
|
+
|
|
92
|
+
// src/request-messages.ts
|
|
93
|
+
import {
|
|
94
|
+
Message,
|
|
95
|
+
normalizeDocuments
|
|
96
|
+
} from "@anvia/core/completion";
|
|
97
|
+
function orderedRequestMessages(request, options = {}) {
|
|
98
|
+
const messages = [];
|
|
99
|
+
if (options.includeInstructionsAsSystem === true && request.instructions !== void 0) {
|
|
100
|
+
messages.push(Message.system(request.instructions));
|
|
101
|
+
}
|
|
102
|
+
messages.push(...request.chatHistory.filter((message) => message.role === "system"));
|
|
103
|
+
const documents = normalizeDocuments(request.documents);
|
|
104
|
+
if (documents !== void 0) {
|
|
105
|
+
messages.push(documents);
|
|
106
|
+
}
|
|
107
|
+
messages.push(...request.chatHistory.filter((message) => message.role !== "system"));
|
|
108
|
+
return messages;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// src/openai/chat-completion.ts
|
|
112
|
+
var OpenAIChatCompletionModel = class {
|
|
113
|
+
constructor(client, defaultModel = "openai/gpt-5.2") {
|
|
114
|
+
this.client = client;
|
|
115
|
+
this.defaultModel = defaultModel;
|
|
116
|
+
}
|
|
117
|
+
client;
|
|
118
|
+
defaultModel;
|
|
119
|
+
provider = "openai-chat";
|
|
120
|
+
capabilities = {
|
|
121
|
+
streaming: true,
|
|
122
|
+
tools: true,
|
|
123
|
+
toolChoice: true,
|
|
124
|
+
imageInput: true,
|
|
125
|
+
documentInput: false,
|
|
126
|
+
outputSchema: true,
|
|
127
|
+
reasoning: true
|
|
128
|
+
};
|
|
129
|
+
async completion(request) {
|
|
130
|
+
assertCompletionRequestSupported(this, request);
|
|
131
|
+
const params = toOpenAIChatCompletionParams(this.defaultModel, request);
|
|
132
|
+
const response = await this.client.chat.completions.create(params);
|
|
133
|
+
return fromOpenAIChatCompletionResponse(response);
|
|
134
|
+
}
|
|
135
|
+
async *streamCompletion(request) {
|
|
136
|
+
assertCompletionRequestSupported(this, request, { streaming: true });
|
|
137
|
+
const params = {
|
|
138
|
+
...toOpenAIChatCompletionParams(this.defaultModel, request),
|
|
139
|
+
stream: true
|
|
140
|
+
};
|
|
141
|
+
const streamOptions = isPlainObject(params.stream_options) ? params.stream_options : {};
|
|
142
|
+
params.stream_options = { ...streamOptions, include_usage: true };
|
|
143
|
+
const stream = await this.client.chat.completions.create(params);
|
|
144
|
+
for await (const chunk of stream) {
|
|
145
|
+
for (const event of fromOpenAIChatCompletionStreamChunk(chunk)) {
|
|
146
|
+
yield event;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
function toOpenAIChatCompletionParams(defaultModel, request) {
|
|
152
|
+
const params = {
|
|
153
|
+
model: request.model ?? defaultModel,
|
|
154
|
+
messages: requestMessages(request).flatMap(messageToChatMessages)
|
|
155
|
+
};
|
|
156
|
+
if (request.tools.length > 0) {
|
|
157
|
+
params.tools = request.tools.map(toolDefinitionToOpenAIChatCompletion);
|
|
158
|
+
}
|
|
159
|
+
if (request.temperature !== void 0) {
|
|
160
|
+
params.temperature = request.temperature;
|
|
161
|
+
}
|
|
162
|
+
if (request.maxTokens !== void 0) {
|
|
163
|
+
params.max_tokens = request.maxTokens;
|
|
164
|
+
}
|
|
165
|
+
if (request.toolChoice !== void 0) {
|
|
166
|
+
params.tool_choice = toolChoiceToOpenAIChatCompletion(request.toolChoice);
|
|
167
|
+
}
|
|
168
|
+
if (request.outputSchema !== void 0) {
|
|
169
|
+
params.response_format = {
|
|
170
|
+
type: "json_schema",
|
|
171
|
+
json_schema: {
|
|
172
|
+
name: schemaName(request.outputSchema),
|
|
173
|
+
strict: true,
|
|
174
|
+
schema: request.outputSchema
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
if (request.additionalParams !== void 0 && isPlainObject(request.additionalParams)) {
|
|
179
|
+
Object.assign(params, request.additionalParams);
|
|
180
|
+
}
|
|
181
|
+
return params;
|
|
182
|
+
}
|
|
183
|
+
function requestMessages(request) {
|
|
184
|
+
return orderedRequestMessages(request, { includeInstructionsAsSystem: true });
|
|
185
|
+
}
|
|
186
|
+
function fromOpenAIChatCompletionResponse(response) {
|
|
187
|
+
const raw = response;
|
|
188
|
+
const choices = Array.isArray(raw.choices) ? raw.choices : [];
|
|
189
|
+
const firstChoice = choices.find(isPlainObject);
|
|
190
|
+
const message = isPlainObject(firstChoice?.message) ? firstChoice.message : {};
|
|
191
|
+
const choice = [];
|
|
192
|
+
if (typeof message.content === "string" && message.content.length > 0) {
|
|
193
|
+
choice.push(AssistantContent.text(message.content));
|
|
194
|
+
}
|
|
195
|
+
const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
|
|
196
|
+
for (const toolCall of toolCalls) {
|
|
197
|
+
if (!isPlainObject(toolCall)) {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const fn = isPlainObject(toolCall.function) ? toolCall.function : {};
|
|
201
|
+
const id = typeof toolCall.id === "string" ? toolCall.id : crypto.randomUUID();
|
|
202
|
+
const name = typeof fn.name === "string" ? fn.name : "";
|
|
203
|
+
const argsText = typeof fn.arguments === "string" ? fn.arguments : "{}";
|
|
204
|
+
choice.push(AssistantContent.toolCall(id, name, parseJsonValue(argsText)));
|
|
205
|
+
}
|
|
206
|
+
const result = {
|
|
207
|
+
choice,
|
|
208
|
+
usage: usageFromOpenAIChatCompletion(raw.usage),
|
|
209
|
+
rawResponse: response
|
|
210
|
+
};
|
|
211
|
+
if (typeof raw.id === "string") {
|
|
212
|
+
result.messageId = raw.id;
|
|
213
|
+
}
|
|
214
|
+
return result;
|
|
215
|
+
}
|
|
216
|
+
function fromOpenAIChatCompletionStreamChunk(chunk) {
|
|
217
|
+
if (!isPlainObject(chunk)) {
|
|
218
|
+
return [];
|
|
219
|
+
}
|
|
220
|
+
const events = [];
|
|
221
|
+
const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
|
|
222
|
+
for (const choice of choices) {
|
|
223
|
+
if (!isPlainObject(choice) || !isPlainObject(choice.delta)) {
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
const delta = choice.delta;
|
|
227
|
+
if (typeof delta.content === "string" && delta.content.length > 0) {
|
|
228
|
+
events.push({ type: "text_delta", delta: delta.content });
|
|
229
|
+
}
|
|
230
|
+
const reasoning = stringFrom(delta.reasoning) ?? stringFrom(delta.reasoning_content);
|
|
231
|
+
if (reasoning !== void 0 && reasoning.length > 0) {
|
|
232
|
+
events.push({ type: "reasoning_delta", delta: reasoning });
|
|
233
|
+
}
|
|
234
|
+
const toolCalls = Array.isArray(delta.tool_calls) ? delta.tool_calls : [];
|
|
235
|
+
for (const toolCall of toolCalls) {
|
|
236
|
+
if (!isPlainObject(toolCall)) {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const fn = isPlainObject(toolCall.function) ? toolCall.function : {};
|
|
240
|
+
const index = numberFrom(toolCall.index);
|
|
241
|
+
const id = `tool_${index}`;
|
|
242
|
+
events.push(
|
|
243
|
+
toolCallDelta(id, {
|
|
244
|
+
callId: stringFrom(toolCall.id),
|
|
245
|
+
name: stringFrom(fn.name),
|
|
246
|
+
argumentsDelta: stringFrom(fn.arguments)
|
|
247
|
+
})
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (typeof chunk.id === "string") {
|
|
252
|
+
events.push({ type: "message_id", id: chunk.id });
|
|
253
|
+
}
|
|
254
|
+
if (isPlainObject(chunk.usage)) {
|
|
255
|
+
const response = {
|
|
256
|
+
choice: [],
|
|
257
|
+
usage: usageFromOpenAIChatCompletion(chunk.usage),
|
|
258
|
+
rawResponse: chunk
|
|
259
|
+
};
|
|
260
|
+
if (typeof chunk.id === "string") {
|
|
261
|
+
response.messageId = chunk.id;
|
|
262
|
+
}
|
|
263
|
+
events.push({ type: "final", response });
|
|
264
|
+
}
|
|
265
|
+
return events;
|
|
266
|
+
}
|
|
267
|
+
function usageFromOpenAIChatCompletion(usage) {
|
|
268
|
+
const usageSource = isPlainObject(usage) ? usage : {};
|
|
269
|
+
const promptDetails = isPlainObject(usageSource.prompt_tokens_details) ? usageSource.prompt_tokens_details : {};
|
|
270
|
+
return {
|
|
271
|
+
...Usage.empty(),
|
|
272
|
+
inputTokens: numberFrom(usageSource.prompt_tokens),
|
|
273
|
+
outputTokens: numberFrom(usageSource.completion_tokens),
|
|
274
|
+
totalTokens: numberFrom(usageSource.total_tokens),
|
|
275
|
+
cachedInputTokens: numberFrom(promptDetails.cached_tokens)
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
function messageToChatMessages(message) {
|
|
279
|
+
if (message.role === "system") {
|
|
280
|
+
return [{ role: "system", content: message.content }];
|
|
281
|
+
}
|
|
282
|
+
if (message.role === "user") {
|
|
283
|
+
const contentParts = [];
|
|
284
|
+
for (const content of message.content) {
|
|
285
|
+
contentParts.push(...userContentToChatParts(content));
|
|
286
|
+
}
|
|
287
|
+
if (contentParts.length === 1 && contentParts[0]?.type === "text") {
|
|
288
|
+
return [{ role: "user", content: contentParts[0].text }];
|
|
289
|
+
} else if (contentParts.length > 0) {
|
|
290
|
+
return [{ role: "user", content: contentParts }];
|
|
291
|
+
}
|
|
292
|
+
return [];
|
|
293
|
+
}
|
|
294
|
+
if (message.role === "tool") {
|
|
295
|
+
return message.content.map(toolContentToChatMessage);
|
|
296
|
+
}
|
|
297
|
+
const text = message.content.flatMap((content) => content.type === "text" ? [content.text] : []).join("\n");
|
|
298
|
+
if (message.content.some((content) => content.type === "image")) {
|
|
299
|
+
throw new Error("OpenAI chat completions does not support image content in assistant history");
|
|
300
|
+
}
|
|
301
|
+
const toolCalls = message.content.filter((content) => content.type === "tool_call").map((content) => ({
|
|
302
|
+
id: content.id,
|
|
303
|
+
type: "function",
|
|
304
|
+
function: {
|
|
305
|
+
name: content.function.name,
|
|
306
|
+
arguments: JSON.stringify(content.function.arguments ?? {})
|
|
307
|
+
}
|
|
308
|
+
}));
|
|
309
|
+
const chatMessage = {
|
|
310
|
+
role: "assistant"
|
|
311
|
+
};
|
|
312
|
+
if (text.length > 0) {
|
|
313
|
+
chatMessage.content = text;
|
|
314
|
+
}
|
|
315
|
+
if (toolCalls.length > 0) {
|
|
316
|
+
chatMessage.tool_calls = toolCalls;
|
|
317
|
+
}
|
|
318
|
+
return [chatMessage];
|
|
319
|
+
}
|
|
320
|
+
function toolContentToChatMessage(content) {
|
|
321
|
+
return {
|
|
322
|
+
role: "tool",
|
|
323
|
+
tool_call_id: content.callId ?? content.id,
|
|
324
|
+
content: content.content.map((item) => item.type === "text" ? item.text : item.data).join("\n")
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
function userContentToChatParts(content) {
|
|
328
|
+
if (content.type === "text") {
|
|
329
|
+
return [{ type: "text", text: content.text }];
|
|
330
|
+
}
|
|
331
|
+
if (content.type === "image") {
|
|
332
|
+
const image_url = { url: imageUrl(content) };
|
|
333
|
+
if (content.detail !== void 0) {
|
|
334
|
+
image_url.detail = content.detail;
|
|
335
|
+
}
|
|
336
|
+
return [{ type: "image_url", image_url }];
|
|
337
|
+
}
|
|
338
|
+
if (content.type === "document") {
|
|
339
|
+
return documentToChatParts(content);
|
|
340
|
+
}
|
|
341
|
+
return [];
|
|
342
|
+
}
|
|
343
|
+
function imageUrl(image) {
|
|
344
|
+
if (image.source.type === "url") {
|
|
345
|
+
return image.source.url;
|
|
346
|
+
}
|
|
347
|
+
return `data:${image.source.mediaType};base64,${image.source.data}`;
|
|
348
|
+
}
|
|
349
|
+
function documentToChatParts(document) {
|
|
350
|
+
if (document.source.type === "text") {
|
|
351
|
+
return [{ type: "text", text: document.source.text }];
|
|
352
|
+
}
|
|
353
|
+
throw new Error("OpenAI chat completions does not support file document attachments");
|
|
354
|
+
}
|
|
355
|
+
function toolDefinitionToOpenAIChatCompletion(tool) {
|
|
356
|
+
return {
|
|
357
|
+
type: "function",
|
|
358
|
+
function: {
|
|
359
|
+
name: tool.name,
|
|
360
|
+
description: tool.description,
|
|
361
|
+
parameters: tool.parameters
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
function toolChoiceToOpenAIChatCompletion(toolChoice) {
|
|
366
|
+
if (toolChoice === "auto" || toolChoice === "required" || toolChoice === "none") {
|
|
367
|
+
return toolChoice;
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
type: "function",
|
|
371
|
+
function: {
|
|
372
|
+
name: toolChoice.name
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
function toolCallDelta(id, values) {
|
|
377
|
+
const event = { type: "tool_call_delta", id };
|
|
378
|
+
if (values.callId !== void 0) event.callId = values.callId;
|
|
379
|
+
if (values.name !== void 0) event.name = values.name;
|
|
380
|
+
if (values.argumentsDelta !== void 0) event.argumentsDelta = values.argumentsDelta;
|
|
381
|
+
return event;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// src/openai/client.ts
|
|
385
|
+
import OpenAI from "openai";
|
|
386
|
+
|
|
387
|
+
// src/openai/embedding.ts
|
|
388
|
+
var OpenAIEmbeddingModel = class {
|
|
389
|
+
constructor(client, model, options = {}) {
|
|
390
|
+
this.client = client;
|
|
391
|
+
this.model = model;
|
|
392
|
+
this.dimensions = options.dimensions;
|
|
393
|
+
this.maxBatchSize = options.maxBatchSize ?? 1024;
|
|
394
|
+
this.user = options.user;
|
|
395
|
+
}
|
|
396
|
+
client;
|
|
397
|
+
model;
|
|
398
|
+
dimensions;
|
|
399
|
+
maxBatchSize;
|
|
400
|
+
user;
|
|
401
|
+
async embedTexts(texts) {
|
|
402
|
+
const embeddings = [];
|
|
403
|
+
for (let index = 0; index < texts.length; index += this.maxBatchSize) {
|
|
404
|
+
const batch = texts.slice(index, index + this.maxBatchSize);
|
|
405
|
+
embeddings.push(...await this.embedBatch(batch));
|
|
406
|
+
}
|
|
407
|
+
return embeddings;
|
|
408
|
+
}
|
|
409
|
+
async embedBatch(texts) {
|
|
410
|
+
if (texts.length === 0) {
|
|
411
|
+
return [];
|
|
412
|
+
}
|
|
413
|
+
const params = {
|
|
414
|
+
model: this.model,
|
|
415
|
+
input: texts
|
|
416
|
+
};
|
|
417
|
+
if (this.dimensions !== void 0) {
|
|
418
|
+
params.dimensions = this.dimensions;
|
|
419
|
+
}
|
|
420
|
+
if (this.user !== void 0) {
|
|
421
|
+
params.user = this.user;
|
|
422
|
+
}
|
|
423
|
+
const response = await this.client.embeddings.create(params);
|
|
424
|
+
const data = Array.isArray(response.data) ? response.data : [];
|
|
425
|
+
if (data.length !== texts.length) {
|
|
426
|
+
throw new Error(
|
|
427
|
+
`Embedding response length ${data.length} did not match input length ${texts.length}`
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
return data.slice().sort((left, right) => left.index - right.index).map((item, index) => ({
|
|
431
|
+
document: texts[index],
|
|
432
|
+
vector: item.embedding
|
|
433
|
+
}));
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
// src/openai/image-generation.ts
|
|
438
|
+
import { Buffer as Buffer2 } from "buffer";
|
|
439
|
+
var DALL_E_2 = "dall-e-2";
|
|
440
|
+
var DALL_E_3 = "dall-e-3";
|
|
441
|
+
var GPT_IMAGE_1 = "gpt-image-1";
|
|
442
|
+
var GPT_IMAGE_2 = "gpt-image-2";
|
|
443
|
+
var OpenAIImageGenerationModel = class {
|
|
444
|
+
constructor(client, defaultModel = GPT_IMAGE_1) {
|
|
445
|
+
this.client = client;
|
|
446
|
+
this.defaultModel = defaultModel;
|
|
447
|
+
}
|
|
448
|
+
client;
|
|
449
|
+
defaultModel;
|
|
450
|
+
provider = "openai";
|
|
451
|
+
async imageGeneration(request) {
|
|
452
|
+
const params = {
|
|
453
|
+
model: this.defaultModel,
|
|
454
|
+
prompt: request.prompt,
|
|
455
|
+
size: `${request.width}x${request.height}`
|
|
456
|
+
};
|
|
457
|
+
if (this.defaultModel === DALL_E_2 || this.defaultModel === DALL_E_3) {
|
|
458
|
+
params.response_format = "b64_json";
|
|
459
|
+
}
|
|
460
|
+
if (request.additionalParams !== void 0 && isPlainObject(request.additionalParams)) {
|
|
461
|
+
Object.assign(params, request.additionalParams);
|
|
462
|
+
}
|
|
463
|
+
const response = await this.client.images.generate(params);
|
|
464
|
+
return imageResponseFromOpenAI(response);
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
function imageResponseFromOpenAI(response) {
|
|
468
|
+
const raw = response;
|
|
469
|
+
const mediaType = mediaTypeFromFormat2(
|
|
470
|
+
typeof raw.output_format === "string" ? raw.output_format : "png"
|
|
471
|
+
);
|
|
472
|
+
const images = (Array.isArray(raw.data) ? raw.data : []).flatMap((item) => {
|
|
473
|
+
if (!isPlainObject(item) || typeof item.b64_json !== "string") {
|
|
474
|
+
return [];
|
|
475
|
+
}
|
|
476
|
+
return [{ data: new Uint8Array(Buffer2.from(item.b64_json, "base64")), mediaType }];
|
|
477
|
+
});
|
|
478
|
+
const image = images[0]?.data;
|
|
479
|
+
if (image === void 0) {
|
|
480
|
+
throw new Error("OpenAI image generation response contained no base64 images.");
|
|
481
|
+
}
|
|
482
|
+
return {
|
|
483
|
+
image,
|
|
484
|
+
images,
|
|
485
|
+
mediaType,
|
|
486
|
+
rawResponse: response
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
function mediaTypeFromFormat2(format) {
|
|
490
|
+
if (format === "jpeg" || format === "jpg") {
|
|
491
|
+
return "image/jpeg";
|
|
492
|
+
}
|
|
493
|
+
if (format === "webp") {
|
|
494
|
+
return "image/webp";
|
|
495
|
+
}
|
|
496
|
+
return "image/png";
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// src/openai/responses.ts
|
|
500
|
+
import {
|
|
501
|
+
AssistantContent as AssistantContent2,
|
|
502
|
+
assertCompletionRequestSupported as assertCompletionRequestSupported2,
|
|
503
|
+
Usage as Usage2
|
|
504
|
+
} from "@anvia/core/completion";
|
|
505
|
+
var OpenAIResponsesCompletionModel = class {
|
|
506
|
+
constructor(client, defaultModel = "gpt-5") {
|
|
507
|
+
this.client = client;
|
|
508
|
+
this.defaultModel = defaultModel;
|
|
509
|
+
}
|
|
510
|
+
client;
|
|
511
|
+
defaultModel;
|
|
512
|
+
provider = "openai";
|
|
513
|
+
capabilities = {
|
|
514
|
+
streaming: true,
|
|
515
|
+
tools: true,
|
|
516
|
+
toolChoice: true,
|
|
517
|
+
imageInput: true,
|
|
518
|
+
documentInput: true,
|
|
519
|
+
outputSchema: true,
|
|
520
|
+
reasoning: true
|
|
521
|
+
};
|
|
522
|
+
async completion(request) {
|
|
523
|
+
assertCompletionRequestSupported2(this, request);
|
|
524
|
+
const params = toOpenAIResponsesParams(this.defaultModel, request);
|
|
525
|
+
const response = await this.client.responses.create(params);
|
|
526
|
+
return fromOpenAIResponse(response);
|
|
527
|
+
}
|
|
528
|
+
async *streamCompletion(request) {
|
|
529
|
+
assertCompletionRequestSupported2(this, request, { streaming: true });
|
|
530
|
+
const params = { ...toOpenAIResponsesParams(this.defaultModel, request), stream: true };
|
|
531
|
+
const stream = await this.client.responses.create(params);
|
|
532
|
+
for await (const event of stream) {
|
|
533
|
+
const mapped = fromOpenAIStreamEvent(event);
|
|
534
|
+
if (mapped !== void 0) {
|
|
535
|
+
yield mapped;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
function toOpenAIResponsesParams(defaultModel, request) {
|
|
541
|
+
const params = {
|
|
542
|
+
model: request.model ?? defaultModel,
|
|
543
|
+
input: requestMessages2(request).flatMap(messageToResponsesInput)
|
|
544
|
+
};
|
|
545
|
+
if (request.instructions !== void 0) {
|
|
546
|
+
params.instructions = request.instructions;
|
|
547
|
+
}
|
|
548
|
+
if (request.tools.length > 0) {
|
|
549
|
+
params.tools = request.tools.map(toolDefinitionToOpenAI);
|
|
550
|
+
}
|
|
551
|
+
if (request.temperature !== void 0) {
|
|
552
|
+
params.temperature = request.temperature;
|
|
553
|
+
}
|
|
554
|
+
if (request.maxTokens !== void 0) {
|
|
555
|
+
params.max_output_tokens = request.maxTokens;
|
|
556
|
+
}
|
|
557
|
+
if (request.toolChoice !== void 0) {
|
|
558
|
+
params.tool_choice = toolChoiceToOpenAI(request.toolChoice);
|
|
559
|
+
}
|
|
560
|
+
if (request.outputSchema !== void 0) {
|
|
561
|
+
params.text = {
|
|
562
|
+
format: {
|
|
563
|
+
type: "json_schema",
|
|
564
|
+
name: schemaName(request.outputSchema),
|
|
565
|
+
strict: true,
|
|
566
|
+
schema: request.outputSchema
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
if (request.additionalParams !== void 0 && isPlainObject(request.additionalParams)) {
|
|
571
|
+
Object.assign(params, request.additionalParams);
|
|
572
|
+
}
|
|
573
|
+
return params;
|
|
574
|
+
}
|
|
575
|
+
function requestMessages2(request) {
|
|
576
|
+
return orderedRequestMessages(request);
|
|
577
|
+
}
|
|
578
|
+
function fromOpenAIResponse(response) {
|
|
579
|
+
const raw = response;
|
|
580
|
+
const output = Array.isArray(raw.output) ? raw.output : [];
|
|
581
|
+
const choice = [];
|
|
582
|
+
for (const item of output) {
|
|
583
|
+
if (!isPlainObject(item)) {
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
if (item.type === "message") {
|
|
587
|
+
choice.push(...messageOutputToAssistantContent(item));
|
|
588
|
+
}
|
|
589
|
+
if (item.type === "function_call") {
|
|
590
|
+
const id = typeof item.id === "string" ? item.id : crypto.randomUUID();
|
|
591
|
+
const callId = typeof item.call_id === "string" ? item.call_id : void 0;
|
|
592
|
+
const name = typeof item.name === "string" ? item.name : "";
|
|
593
|
+
const argsText = typeof item.arguments === "string" ? item.arguments : "{}";
|
|
594
|
+
choice.push(AssistantContent2.toolCall(id, name, parseJsonValue(argsText), callId));
|
|
595
|
+
}
|
|
596
|
+
if (item.type === "reasoning") {
|
|
597
|
+
choice.push(reasoningItemToAssistantContent(item));
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
const usageSource = isPlainObject(raw.usage) ? raw.usage : {};
|
|
601
|
+
const inputTokens = numberFrom(usageSource.input_tokens);
|
|
602
|
+
const outputTokens = numberFrom(usageSource.output_tokens);
|
|
603
|
+
const totalTokens = numberFrom(usageSource.total_tokens) || inputTokens + outputTokens;
|
|
604
|
+
const details = isPlainObject(usageSource.input_tokens_details) ? usageSource.input_tokens_details : {};
|
|
605
|
+
const result = {
|
|
606
|
+
choice,
|
|
607
|
+
usage: {
|
|
608
|
+
...Usage2.empty(),
|
|
609
|
+
inputTokens,
|
|
610
|
+
outputTokens,
|
|
611
|
+
totalTokens,
|
|
612
|
+
cachedInputTokens: numberFrom(details.cached_tokens)
|
|
613
|
+
},
|
|
614
|
+
rawResponse: response
|
|
615
|
+
};
|
|
616
|
+
if (typeof raw.id === "string") {
|
|
617
|
+
result.messageId = raw.id;
|
|
618
|
+
}
|
|
619
|
+
return result;
|
|
620
|
+
}
|
|
621
|
+
function fromOpenAIStreamEvent(event) {
|
|
622
|
+
if (!isPlainObject(event) || typeof event.type !== "string") {
|
|
623
|
+
return void 0;
|
|
624
|
+
}
|
|
625
|
+
if (event.type === "response.output_text.delta" || event.type === "response.refusal.delta") {
|
|
626
|
+
return typeof event.delta === "string" ? { type: "text_delta", delta: event.delta } : void 0;
|
|
627
|
+
}
|
|
628
|
+
if (event.type === "response.reasoning_text.delta" || event.type === "response.reasoning_summary_text.delta") {
|
|
629
|
+
if (typeof event.delta !== "string") {
|
|
630
|
+
return void 0;
|
|
631
|
+
}
|
|
632
|
+
const mapped = { type: "reasoning_delta", delta: event.delta };
|
|
633
|
+
const id = stringFrom(event.item_id);
|
|
634
|
+
if (id !== void 0) {
|
|
635
|
+
mapped.id = id;
|
|
636
|
+
}
|
|
637
|
+
if (event.type === "response.reasoning_summary_text.delta") {
|
|
638
|
+
mapped.contentType = "summary";
|
|
639
|
+
} else {
|
|
640
|
+
mapped.contentType = "text";
|
|
641
|
+
}
|
|
642
|
+
return mapped;
|
|
643
|
+
}
|
|
644
|
+
if (event.type === "response.output_item.added" && isPlainObject(event.item)) {
|
|
645
|
+
const item = event.item;
|
|
646
|
+
if (item.type === "function_call") {
|
|
647
|
+
return toolCallDelta2(
|
|
648
|
+
stringFrom(item.id) ?? stringFrom(event.item_id) ?? crypto.randomUUID(),
|
|
649
|
+
{
|
|
650
|
+
callId: stringFrom(item.call_id),
|
|
651
|
+
name: stringFrom(item.name),
|
|
652
|
+
argumentsDelta: typeof item.arguments === "string" ? item.arguments : void 0
|
|
653
|
+
}
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
if (typeof item.id === "string") {
|
|
657
|
+
return { type: "message_id", id: item.id };
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
if (event.type === "response.function_call_arguments.delta" || event.type === "response.function_call_arguments.done") {
|
|
661
|
+
return toolCallDelta2(
|
|
662
|
+
stringFrom(event.item_id) ?? stringFrom(event.output_item_id) ?? crypto.randomUUID(),
|
|
663
|
+
{
|
|
664
|
+
argumentsDelta: typeof event.delta === "string" ? event.delta : typeof event.arguments === "string" ? event.arguments : void 0
|
|
665
|
+
}
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
if (event.type === "response.output_item.done" && isPlainObject(event.item)) {
|
|
669
|
+
const item = event.item;
|
|
670
|
+
if (item.type === "function_call") {
|
|
671
|
+
return {
|
|
672
|
+
type: "tool_call",
|
|
673
|
+
toolCall: AssistantContent2.toolCall(
|
|
674
|
+
stringFrom(item.id) ?? crypto.randomUUID(),
|
|
675
|
+
stringFrom(item.name) ?? "",
|
|
676
|
+
parseJsonValue(typeof item.arguments === "string" ? item.arguments : "{}"),
|
|
677
|
+
stringFrom(item.call_id)
|
|
678
|
+
)
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
if (event.type === "response.completed" && isPlainObject(event.response)) {
|
|
683
|
+
return {
|
|
684
|
+
type: "final",
|
|
685
|
+
response: fromOpenAIResponse(event.response)
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
if (event.type === "response.error") {
|
|
689
|
+
return { type: "error", error: event.error ?? event };
|
|
690
|
+
}
|
|
691
|
+
return void 0;
|
|
692
|
+
}
|
|
693
|
+
function messageToResponsesInput(message) {
|
|
694
|
+
if (message.role === "system") {
|
|
695
|
+
return [
|
|
696
|
+
{
|
|
697
|
+
role: "system",
|
|
698
|
+
content: message.content
|
|
699
|
+
}
|
|
700
|
+
];
|
|
701
|
+
}
|
|
702
|
+
if (message.role === "user") {
|
|
703
|
+
const inputContent = [];
|
|
704
|
+
for (const content of message.content) {
|
|
705
|
+
inputContent.push(...userContentToOpenAIResponsesParts(content));
|
|
706
|
+
}
|
|
707
|
+
if (inputContent.length === 1 && inputContent[0]?.type === "input_text") {
|
|
708
|
+
return [{ role: "user", content: inputContent[0].text }];
|
|
709
|
+
} else if (inputContent.length > 0) {
|
|
710
|
+
return [{ role: "user", content: inputContent }];
|
|
711
|
+
}
|
|
712
|
+
return [];
|
|
713
|
+
}
|
|
714
|
+
if (message.role === "tool") {
|
|
715
|
+
return message.content.map(toolContentToOpenAIResponsesItem);
|
|
716
|
+
}
|
|
717
|
+
const items = [];
|
|
718
|
+
const text = message.content.flatMap((content) => content.type === "text" ? [content.text] : []).join("\n");
|
|
719
|
+
if (text.length > 0) {
|
|
720
|
+
items.push({ role: "assistant", content: text });
|
|
721
|
+
}
|
|
722
|
+
for (const content of message.content) {
|
|
723
|
+
if (content.type === "reasoning" && content.id !== void 0) {
|
|
724
|
+
items.push(reasoningToOpenAIInput(content));
|
|
725
|
+
}
|
|
726
|
+
if (content.type === "tool_call") {
|
|
727
|
+
items.push({
|
|
728
|
+
type: "function_call",
|
|
729
|
+
id: content.id,
|
|
730
|
+
call_id: content.callId ?? content.id,
|
|
731
|
+
name: content.function.name,
|
|
732
|
+
arguments: JSON.stringify(content.function.arguments ?? {})
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
if (content.type === "image") {
|
|
736
|
+
throw new Error("OpenAI Responses does not support image content in assistant history");
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
return items;
|
|
740
|
+
}
|
|
741
|
+
function toolContentToOpenAIResponsesItem(content) {
|
|
742
|
+
return {
|
|
743
|
+
type: "function_call_output",
|
|
744
|
+
call_id: content.callId ?? content.id,
|
|
745
|
+
output: content.content.map((item) => item.type === "text" ? item.text : item.data).join("\n")
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
function reasoningItemToAssistantContent(item) {
|
|
749
|
+
const content = reasoningContentFromOpenAIItem(item);
|
|
750
|
+
const id = stringFrom(item.id);
|
|
751
|
+
if (content.length === 0) {
|
|
752
|
+
return AssistantContent2.reasoning("", id);
|
|
753
|
+
}
|
|
754
|
+
return AssistantContent2.reasoningFromContent(content, id);
|
|
755
|
+
}
|
|
756
|
+
function reasoningContentFromOpenAIItem(item) {
|
|
757
|
+
const content = [];
|
|
758
|
+
if (Array.isArray(item.content)) {
|
|
759
|
+
for (const part of item.content) {
|
|
760
|
+
if (!isPlainObject(part)) {
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (part.type === "reasoning_text" && typeof part.text === "string") {
|
|
764
|
+
content.push({ type: "text", text: part.text });
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
if (Array.isArray(item.summary)) {
|
|
769
|
+
for (const summary of item.summary) {
|
|
770
|
+
if (!isPlainObject(summary)) {
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
if (typeof summary.text === "string") {
|
|
774
|
+
content.push({ type: "summary", text: summary.text });
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
if (typeof item.encrypted_content === "string") {
|
|
779
|
+
content.push({ type: "encrypted", data: item.encrypted_content });
|
|
780
|
+
}
|
|
781
|
+
return content;
|
|
782
|
+
}
|
|
783
|
+
function reasoningToOpenAIInput(reasoning) {
|
|
784
|
+
const item = {
|
|
785
|
+
type: "reasoning",
|
|
786
|
+
id: reasoning.id,
|
|
787
|
+
summary: reasoning.content?.filter((content) => {
|
|
788
|
+
return content.type === "summary";
|
|
789
|
+
}).map((content) => ({ type: "summary_text", text: content.text })) ?? []
|
|
790
|
+
};
|
|
791
|
+
const textContent = reasoning.content?.flatMap(
|
|
792
|
+
(content) => content.type === "text" ? [{ type: "reasoning_text", text: content.text }] : []
|
|
793
|
+
);
|
|
794
|
+
if (textContent !== void 0 && textContent.length > 0) {
|
|
795
|
+
item.content = textContent;
|
|
796
|
+
}
|
|
797
|
+
const encrypted = reasoning.content?.find((content) => content.type === "encrypted");
|
|
798
|
+
if (encrypted?.type === "encrypted") {
|
|
799
|
+
item.encrypted_content = encrypted.data;
|
|
800
|
+
}
|
|
801
|
+
return item;
|
|
802
|
+
}
|
|
803
|
+
function userContentToOpenAIResponsesParts(content) {
|
|
804
|
+
if (content.type === "text") {
|
|
805
|
+
return [{ type: "input_text", text: content.text }];
|
|
806
|
+
}
|
|
807
|
+
if (content.type === "image") {
|
|
808
|
+
const part = { type: "input_image", image_url: imageUrl2(content) };
|
|
809
|
+
if (content.detail !== void 0) {
|
|
810
|
+
part.detail = content.detail;
|
|
811
|
+
}
|
|
812
|
+
return [part];
|
|
813
|
+
}
|
|
814
|
+
if (content.type === "document") {
|
|
815
|
+
return [documentToOpenAIResponsesPart(content)];
|
|
816
|
+
}
|
|
817
|
+
return [];
|
|
818
|
+
}
|
|
819
|
+
function imageUrl2(image) {
|
|
820
|
+
if (image.source.type === "url") {
|
|
821
|
+
return image.source.url;
|
|
822
|
+
}
|
|
823
|
+
return `data:${image.source.mediaType};base64,${image.source.data}`;
|
|
824
|
+
}
|
|
825
|
+
function documentToOpenAIResponsesPart(document) {
|
|
826
|
+
if (document.source.type === "text") {
|
|
827
|
+
return { type: "input_text", text: document.source.text };
|
|
828
|
+
}
|
|
829
|
+
if (document.source.mediaType !== "application/pdf") {
|
|
830
|
+
throw new Error(`OpenAI Responses only supports PDF document attachments`);
|
|
831
|
+
}
|
|
832
|
+
if (document.source.type === "url") {
|
|
833
|
+
return { type: "input_file", file_url: document.source.url };
|
|
834
|
+
}
|
|
835
|
+
return {
|
|
836
|
+
type: "input_file",
|
|
837
|
+
file_data: `data:${document.source.mediaType};base64,${document.source.data}`,
|
|
838
|
+
filename: document.source.filename ?? "document.pdf"
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
function toolDefinitionToOpenAI(tool) {
|
|
842
|
+
return {
|
|
843
|
+
type: "function",
|
|
844
|
+
name: tool.name,
|
|
845
|
+
description: tool.description,
|
|
846
|
+
parameters: tool.parameters
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
function toolChoiceToOpenAI(toolChoice) {
|
|
850
|
+
if (toolChoice === "auto" || toolChoice === "required" || toolChoice === "none") {
|
|
851
|
+
return toolChoice;
|
|
852
|
+
}
|
|
853
|
+
return {
|
|
854
|
+
type: "function",
|
|
855
|
+
name: toolChoice.name
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
function messageOutputToAssistantContent(item) {
|
|
859
|
+
const content = Array.isArray(item.content) ? item.content : [];
|
|
860
|
+
return content.flatMap((part) => {
|
|
861
|
+
if (!isPlainObject(part)) {
|
|
862
|
+
return [];
|
|
863
|
+
}
|
|
864
|
+
if (part.type === "output_text" && typeof part.text === "string") {
|
|
865
|
+
return [AssistantContent2.text(part.text)];
|
|
866
|
+
}
|
|
867
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
868
|
+
return [AssistantContent2.text(part.text)];
|
|
869
|
+
}
|
|
870
|
+
return [];
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
function toolCallDelta2(id, values) {
|
|
874
|
+
const event = { type: "tool_call_delta", id };
|
|
875
|
+
if (values.callId !== void 0) event.callId = values.callId;
|
|
876
|
+
if (values.name !== void 0) event.name = values.name;
|
|
877
|
+
if (values.argumentsDelta !== void 0) event.argumentsDelta = values.argumentsDelta;
|
|
878
|
+
return event;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// src/openai/transcription.ts
|
|
882
|
+
import { toFile } from "openai";
|
|
883
|
+
var WHISPER_1 = "whisper-1";
|
|
884
|
+
var OpenAITranscriptionModel = class {
|
|
885
|
+
constructor(client, defaultModel = WHISPER_1) {
|
|
886
|
+
this.client = client;
|
|
887
|
+
this.defaultModel = defaultModel;
|
|
888
|
+
}
|
|
889
|
+
client;
|
|
890
|
+
defaultModel;
|
|
891
|
+
provider = "openai";
|
|
892
|
+
async transcription(request) {
|
|
893
|
+
const params = {
|
|
894
|
+
model: this.defaultModel,
|
|
895
|
+
file: await toFile(request.data, request.filename)
|
|
896
|
+
};
|
|
897
|
+
if (request.language !== void 0) params.language = request.language;
|
|
898
|
+
if (request.prompt !== void 0) params.prompt = request.prompt;
|
|
899
|
+
if (request.temperature !== void 0) params.temperature = request.temperature;
|
|
900
|
+
if (request.additionalParams !== void 0 && isPlainObject(request.additionalParams)) {
|
|
901
|
+
Object.assign(params, request.additionalParams);
|
|
902
|
+
}
|
|
903
|
+
const response = await this.client.audio.transcriptions.create(params);
|
|
904
|
+
return {
|
|
905
|
+
text: transcriptionText(response),
|
|
906
|
+
rawResponse: response
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
};
|
|
910
|
+
function transcriptionText(response) {
|
|
911
|
+
if (typeof response === "string") {
|
|
912
|
+
return response;
|
|
913
|
+
}
|
|
914
|
+
if (isPlainObject(response) && typeof response.text === "string") {
|
|
915
|
+
return response.text;
|
|
916
|
+
}
|
|
917
|
+
throw new Error("OpenAI transcription response contained no text.");
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// src/openai/client.ts
|
|
921
|
+
var OpenAIClient = class {
|
|
922
|
+
client;
|
|
923
|
+
completionApi;
|
|
924
|
+
constructor(options = {}) {
|
|
925
|
+
this.completionApi = options.completionApi ?? (options.baseUrl === void 0 ? "responses" : "chat");
|
|
926
|
+
this.client = options.client ?? new OpenAI({
|
|
927
|
+
apiKey: requireApiKey(options.apiKey),
|
|
928
|
+
baseURL: options.baseUrl,
|
|
929
|
+
defaultHeaders: options.headers
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
completionModel(model = "gpt-5") {
|
|
933
|
+
return this.completionApi === "chat" ? new OpenAIChatCompletionModel(this.client, model) : new OpenAIResponsesCompletionModel(this.client, model);
|
|
934
|
+
}
|
|
935
|
+
embeddingModel(model = "text-embedding-3-small", options = {}) {
|
|
936
|
+
return new OpenAIEmbeddingModel(this.client, model, options);
|
|
937
|
+
}
|
|
938
|
+
imageGenerationModel(model = GPT_IMAGE_1) {
|
|
939
|
+
return new OpenAIImageGenerationModel(this.client, model);
|
|
940
|
+
}
|
|
941
|
+
audioGenerationModel(model = TTS_1) {
|
|
942
|
+
return new OpenAIAudioGenerationModel(this.client, model);
|
|
943
|
+
}
|
|
944
|
+
transcriptionModel(model = WHISPER_1) {
|
|
945
|
+
return new OpenAITranscriptionModel(this.client, model);
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
function requireApiKey(apiKey) {
|
|
949
|
+
if (apiKey === void 0 || apiKey.length === 0) {
|
|
950
|
+
throw new Error("Missing OpenAI credentials. Pass apiKey when constructing OpenAIClient.");
|
|
951
|
+
}
|
|
952
|
+
return apiKey;
|
|
953
|
+
}
|
|
954
|
+
export {
|
|
955
|
+
DALL_E_2,
|
|
956
|
+
DALL_E_3,
|
|
957
|
+
GPT_IMAGE_1,
|
|
958
|
+
GPT_IMAGE_2,
|
|
959
|
+
OpenAIAudioGenerationModel,
|
|
960
|
+
OpenAIChatCompletionModel,
|
|
961
|
+
OpenAIClient,
|
|
962
|
+
OpenAIEmbeddingModel,
|
|
963
|
+
OpenAIImageGenerationModel,
|
|
964
|
+
OpenAIResponsesCompletionModel,
|
|
965
|
+
OpenAITranscriptionModel,
|
|
966
|
+
TTS_1,
|
|
967
|
+
TTS_1_HD,
|
|
968
|
+
WHISPER_1,
|
|
969
|
+
openai_exports as openai
|
|
970
|
+
};
|
|
971
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/openai/index.ts","../src/utils.ts","../src/openai/audio-generation.ts","../src/openai/chat-completion.ts","../src/request-messages.ts","../src/openai/client.ts","../src/openai/embedding.ts","../src/openai/image-generation.ts","../src/openai/responses.ts","../src/openai/transcription.ts"],"sourcesContent":["export { OpenAIAudioGenerationModel, TTS_1, TTS_1_HD } from \"./audio-generation\";\nexport { OpenAIChatCompletionModel } from \"./chat-completion\";\nexport { OpenAIClient, type OpenAIClientOptions } from \"./client\";\nexport { OpenAIEmbeddingModel, type ProviderEmbeddingModelOptions } from \"./embedding\";\nexport {\n DALL_E_2,\n DALL_E_3,\n GPT_IMAGE_1,\n GPT_IMAGE_2,\n OpenAIImageGenerationModel,\n} from \"./image-generation\";\nexport { OpenAIResponsesCompletionModel } from \"./responses\";\nexport { OpenAITranscriptionModel, WHISPER_1 } from \"./transcription\";\n","import type { JsonObject, JsonValue } from \"@anvia/core/completion\";\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function numberFrom(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nexport function stringFrom(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport function parseJsonValue(text: string): JsonValue {\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n return text;\n }\n}\n\nexport function schemaName(schema: JsonObject): string {\n return typeof schema.title === \"string\" ? schema.title : \"response_schema\";\n}\n","import type {\n AudioGenerationModel,\n AudioGenerationRequest,\n AudioGenerationResponse,\n} from \"@anvia/core/audio-generation\";\nimport type { OpenAI } from \"openai\";\nimport { isPlainObject } from \"../utils\";\n\nexport const TTS_1 = \"tts-1\";\nexport const TTS_1_HD = \"tts-1-hd\";\n\nexport class OpenAIAudioGenerationModel implements AudioGenerationModel {\n readonly provider = \"openai\";\n\n constructor(\n private readonly client: OpenAI,\n readonly defaultModel = TTS_1,\n ) {}\n\n async audioGeneration(\n request: AudioGenerationRequest,\n ): Promise<AudioGenerationResponse<unknown>> {\n const params: Record<string, unknown> = {\n model: this.defaultModel,\n input: request.text,\n voice: request.voice,\n speed: request.speed,\n };\n\n if (request.additionalParams !== undefined && isPlainObject(request.additionalParams)) {\n Object.assign(params, request.additionalParams);\n }\n\n const response = await this.client.audio.speech.create(params as never);\n return {\n audio: new Uint8Array(await response.arrayBuffer()),\n mediaType: mediaTypeFromFormat(params.response_format),\n rawResponse: response,\n };\n }\n}\n\nfunction mediaTypeFromFormat(format: unknown): string {\n if (format === \"wav\") return \"audio/wav\";\n if (format === \"flac\") return \"audio/flac\";\n if (format === \"opus\") return \"audio/opus\";\n if (format === \"aac\") return \"audio/aac\";\n if (format === \"pcm\") return \"audio/pcm\";\n return \"audio/mpeg\";\n}\n","import {\n AssistantContent,\n type AssistantContent as AssistantContentType,\n assertCompletionRequestSupported,\n type CompletionModelCapabilities,\n type CompletionRequest,\n type CompletionResponse,\n type CompletionStreamEvent,\n type DocumentContent,\n type ImageContent,\n type Message as MessageType,\n type StreamingCompletionModel,\n type ToolChoice,\n type ToolContent,\n type ToolDefinition,\n Usage,\n type UserContent,\n} from \"@anvia/core/completion\";\nimport type { OpenAI } from \"openai\";\nimport { orderedRequestMessages } from \"../request-messages\";\nimport { isPlainObject, numberFrom, parseJsonValue, schemaName, stringFrom } from \"../utils\";\n\ntype ChatCompletionParams = Record<string, unknown>;\ntype ChatMessage = Record<string, unknown>;\n\nexport class OpenAIChatCompletionModel implements StreamingCompletionModel {\n readonly provider = \"openai-chat\";\n readonly capabilities: CompletionModelCapabilities = {\n streaming: true,\n tools: true,\n toolChoice: true,\n imageInput: true,\n documentInput: false,\n outputSchema: true,\n reasoning: true,\n };\n\n constructor(\n private readonly client: OpenAI,\n readonly defaultModel = \"openai/gpt-5.2\",\n ) {}\n\n async completion(request: CompletionRequest): Promise<CompletionResponse> {\n assertCompletionRequestSupported(this, request);\n const params = toOpenAIChatCompletionParams(this.defaultModel, request);\n const response = await this.client.chat.completions.create(params as never);\n return fromOpenAIChatCompletionResponse(response);\n }\n\n async *streamCompletion(request: CompletionRequest): AsyncIterable<CompletionStreamEvent> {\n assertCompletionRequestSupported(this, request, { streaming: true });\n const params: ChatCompletionParams = {\n ...toOpenAIChatCompletionParams(this.defaultModel, request),\n stream: true,\n };\n const streamOptions = isPlainObject(params.stream_options) ? params.stream_options : {};\n params.stream_options = { ...streamOptions, include_usage: true };\n const stream = await this.client.chat.completions.create(params as never);\n for await (const chunk of stream as unknown as AsyncIterable<unknown>) {\n for (const event of fromOpenAIChatCompletionStreamChunk(chunk)) {\n yield event;\n }\n }\n }\n}\n\nexport function toOpenAIChatCompletionParams(\n defaultModel: string,\n request: CompletionRequest,\n): ChatCompletionParams {\n const params: ChatCompletionParams = {\n model: request.model ?? defaultModel,\n messages: requestMessages(request).flatMap(messageToChatMessages),\n };\n\n if (request.tools.length > 0) {\n params.tools = request.tools.map(toolDefinitionToOpenAIChatCompletion);\n }\n\n if (request.temperature !== undefined) {\n params.temperature = request.temperature;\n }\n\n if (request.maxTokens !== undefined) {\n params.max_tokens = request.maxTokens;\n }\n\n if (request.toolChoice !== undefined) {\n params.tool_choice = toolChoiceToOpenAIChatCompletion(request.toolChoice);\n }\n\n if (request.outputSchema !== undefined) {\n params.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: schemaName(request.outputSchema),\n strict: true,\n schema: request.outputSchema,\n },\n };\n }\n\n if (request.additionalParams !== undefined && isPlainObject(request.additionalParams)) {\n Object.assign(params, request.additionalParams);\n }\n\n return params;\n}\n\nfunction requestMessages(request: CompletionRequest): MessageType[] {\n return orderedRequestMessages(request, { includeInstructionsAsSystem: true });\n}\n\nexport function fromOpenAIChatCompletionResponse(response: unknown): CompletionResponse {\n const raw = response as Record<string, unknown>;\n const choices = Array.isArray(raw.choices) ? raw.choices : [];\n const firstChoice = choices.find(isPlainObject);\n const message = isPlainObject(firstChoice?.message) ? firstChoice.message : {};\n const choice: AssistantContentType[] = [];\n\n if (typeof message.content === \"string\" && message.content.length > 0) {\n choice.push(AssistantContent.text(message.content));\n }\n\n const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];\n for (const toolCall of toolCalls) {\n if (!isPlainObject(toolCall)) {\n continue;\n }\n\n const fn = isPlainObject(toolCall.function) ? toolCall.function : {};\n const id = typeof toolCall.id === \"string\" ? toolCall.id : crypto.randomUUID();\n const name = typeof fn.name === \"string\" ? fn.name : \"\";\n const argsText = typeof fn.arguments === \"string\" ? fn.arguments : \"{}\";\n choice.push(AssistantContent.toolCall(id, name, parseJsonValue(argsText)));\n }\n\n const result: CompletionResponse = {\n choice,\n usage: usageFromOpenAIChatCompletion(raw.usage),\n rawResponse: response,\n };\n\n if (typeof raw.id === \"string\") {\n result.messageId = raw.id;\n }\n\n return result;\n}\n\nexport function fromOpenAIChatCompletionStreamChunk(chunk: unknown): CompletionStreamEvent[] {\n if (!isPlainObject(chunk)) {\n return [];\n }\n\n const events: CompletionStreamEvent[] = [];\n const choices = Array.isArray(chunk.choices) ? chunk.choices : [];\n for (const choice of choices) {\n if (!isPlainObject(choice) || !isPlainObject(choice.delta)) {\n continue;\n }\n\n const delta = choice.delta;\n if (typeof delta.content === \"string\" && delta.content.length > 0) {\n events.push({ type: \"text_delta\", delta: delta.content });\n }\n\n const reasoning = stringFrom(delta.reasoning) ?? stringFrom(delta.reasoning_content);\n if (reasoning !== undefined && reasoning.length > 0) {\n events.push({ type: \"reasoning_delta\", delta: reasoning });\n }\n\n const toolCalls = Array.isArray(delta.tool_calls) ? delta.tool_calls : [];\n for (const toolCall of toolCalls) {\n if (!isPlainObject(toolCall)) {\n continue;\n }\n const fn = isPlainObject(toolCall.function) ? toolCall.function : {};\n const index = numberFrom(toolCall.index);\n const id = `tool_${index}`;\n events.push(\n toolCallDelta(id, {\n callId: stringFrom(toolCall.id),\n name: stringFrom(fn.name),\n argumentsDelta: stringFrom(fn.arguments),\n }),\n );\n }\n }\n\n if (typeof chunk.id === \"string\") {\n events.push({ type: \"message_id\", id: chunk.id });\n }\n\n if (isPlainObject(chunk.usage)) {\n const response: CompletionResponse = {\n choice: [],\n usage: usageFromOpenAIChatCompletion(chunk.usage),\n rawResponse: chunk,\n };\n if (typeof chunk.id === \"string\") {\n response.messageId = chunk.id;\n }\n events.push({ type: \"final\", response });\n }\n\n return events;\n}\n\nfunction usageFromOpenAIChatCompletion(usage: unknown): Usage {\n const usageSource = isPlainObject(usage) ? usage : {};\n const promptDetails = isPlainObject(usageSource.prompt_tokens_details)\n ? usageSource.prompt_tokens_details\n : {};\n\n return {\n ...Usage.empty(),\n inputTokens: numberFrom(usageSource.prompt_tokens),\n outputTokens: numberFrom(usageSource.completion_tokens),\n totalTokens: numberFrom(usageSource.total_tokens),\n cachedInputTokens: numberFrom(promptDetails.cached_tokens),\n };\n}\n\nfunction messageToChatMessages(message: MessageType): ChatMessage[] {\n if (message.role === \"system\") {\n return [{ role: \"system\", content: message.content }];\n }\n\n if (message.role === \"user\") {\n const contentParts: ChatMessage[] = [];\n\n for (const content of message.content) {\n contentParts.push(...userContentToChatParts(content));\n }\n\n if (contentParts.length === 1 && contentParts[0]?.type === \"text\") {\n return [{ role: \"user\", content: contentParts[0].text }];\n } else if (contentParts.length > 0) {\n return [{ role: \"user\", content: contentParts }];\n }\n\n return [];\n }\n\n if (message.role === \"tool\") {\n return message.content.map(toolContentToChatMessage);\n }\n\n const text = message.content\n .flatMap((content) => (content.type === \"text\" ? [content.text] : []))\n .join(\"\\n\");\n if (message.content.some((content) => content.type === \"image\")) {\n throw new Error(\"OpenAI chat completions does not support image content in assistant history\");\n }\n const toolCalls = message.content\n .filter((content) => content.type === \"tool_call\")\n .map((content) => ({\n id: content.id,\n type: \"function\",\n function: {\n name: content.function.name,\n arguments: JSON.stringify(content.function.arguments ?? {}),\n },\n }));\n\n const chatMessage: ChatMessage = {\n role: \"assistant\",\n };\n if (text.length > 0) {\n chatMessage.content = text;\n }\n if (toolCalls.length > 0) {\n chatMessage.tool_calls = toolCalls;\n }\n\n return [chatMessage];\n}\n\nfunction toolContentToChatMessage(content: ToolContent): ChatMessage {\n return {\n role: \"tool\",\n tool_call_id: content.callId ?? content.id,\n content: content.content\n .map((item) => (item.type === \"text\" ? item.text : item.data))\n .join(\"\\n\"),\n };\n}\n\nfunction userContentToChatParts(content: UserContent): ChatMessage[] {\n if (content.type === \"text\") {\n return [{ type: \"text\", text: content.text }];\n }\n\n if (content.type === \"image\") {\n const image_url: ChatMessage = { url: imageUrl(content) };\n if (content.detail !== undefined) {\n image_url.detail = content.detail;\n }\n return [{ type: \"image_url\", image_url }];\n }\n\n if (content.type === \"document\") {\n return documentToChatParts(content);\n }\n\n return [];\n}\n\nfunction imageUrl(image: ImageContent): string {\n if (image.source.type === \"url\") {\n return image.source.url;\n }\n\n return `data:${image.source.mediaType};base64,${image.source.data}`;\n}\n\nfunction documentToChatParts(document: DocumentContent): ChatMessage[] {\n if (document.source.type === \"text\") {\n return [{ type: \"text\", text: document.source.text }];\n }\n\n throw new Error(\"OpenAI chat completions does not support file document attachments\");\n}\n\nfunction toolDefinitionToOpenAIChatCompletion(tool: ToolDefinition): ChatMessage {\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n };\n}\n\nfunction toolChoiceToOpenAIChatCompletion(toolChoice: ToolChoice): unknown {\n if (toolChoice === \"auto\" || toolChoice === \"required\" || toolChoice === \"none\") {\n return toolChoice;\n }\n\n return {\n type: \"function\",\n function: {\n name: toolChoice.name,\n },\n };\n}\n\nfunction toolCallDelta(\n id: string,\n values: {\n callId?: string | undefined;\n name?: string | undefined;\n argumentsDelta?: string | undefined;\n },\n): CompletionStreamEvent {\n const event: CompletionStreamEvent = { type: \"tool_call_delta\", id };\n if (values.callId !== undefined) event.callId = values.callId;\n if (values.name !== undefined) event.name = values.name;\n if (values.argumentsDelta !== undefined) event.argumentsDelta = values.argumentsDelta;\n return event;\n}\n\nexport const openAIChatCompletionMessageHelpers = {\n messageToChatMessages,\n toolDefinitionToOpenAIChatCompletion,\n};\n","import {\n type CompletionRequest,\n Message,\n type Message as MessageType,\n normalizeDocuments,\n} from \"@anvia/core/completion\";\n\nexport type OrderedRequestMessagesOptions = {\n includeInstructionsAsSystem?: boolean;\n};\n\nexport function orderedRequestMessages(\n request: CompletionRequest,\n options: OrderedRequestMessagesOptions = {},\n): MessageType[] {\n const messages: MessageType[] = [];\n if (options.includeInstructionsAsSystem === true && request.instructions !== undefined) {\n messages.push(Message.system(request.instructions));\n }\n messages.push(...request.chatHistory.filter((message) => message.role === \"system\"));\n const documents = normalizeDocuments(request.documents);\n if (documents !== undefined) {\n messages.push(documents);\n }\n messages.push(...request.chatHistory.filter((message) => message.role !== \"system\"));\n return messages;\n}\n","import type { StreamingCompletionModel } from \"@anvia/core/completion\";\nimport OpenAI from \"openai\";\nimport { OpenAIAudioGenerationModel, TTS_1 } from \"./audio-generation\";\nimport { OpenAIChatCompletionModel } from \"./chat-completion\";\nimport { OpenAIEmbeddingModel, type ProviderEmbeddingModelOptions } from \"./embedding\";\nimport { GPT_IMAGE_1, OpenAIImageGenerationModel } from \"./image-generation\";\nimport { OpenAIResponsesCompletionModel } from \"./responses\";\nimport { OpenAITranscriptionModel, WHISPER_1 } from \"./transcription\";\n\nexport type OpenAIClientOptions = {\n apiKey?: string | undefined;\n baseUrl?: string | undefined;\n headers?: Record<string, string> | undefined;\n completionApi?: \"responses\" | \"chat\" | undefined;\n client?: OpenAI | undefined;\n};\n\nexport class OpenAIClient {\n readonly client: OpenAI;\n private readonly completionApi: \"responses\" | \"chat\";\n\n constructor(options: OpenAIClientOptions = {}) {\n this.completionApi =\n options.completionApi ?? (options.baseUrl === undefined ? \"responses\" : \"chat\");\n this.client =\n options.client ??\n new OpenAI({\n apiKey: requireApiKey(options.apiKey),\n baseURL: options.baseUrl,\n defaultHeaders: options.headers,\n });\n }\n\n completionModel(model = \"gpt-5\"): StreamingCompletionModel {\n return this.completionApi === \"chat\"\n ? new OpenAIChatCompletionModel(this.client, model)\n : new OpenAIResponsesCompletionModel(this.client, model);\n }\n\n embeddingModel(\n model = \"text-embedding-3-small\",\n options: ProviderEmbeddingModelOptions = {},\n ): OpenAIEmbeddingModel {\n return new OpenAIEmbeddingModel(this.client, model, options);\n }\n\n imageGenerationModel(model = GPT_IMAGE_1): OpenAIImageGenerationModel {\n return new OpenAIImageGenerationModel(this.client, model);\n }\n\n audioGenerationModel(model = TTS_1): OpenAIAudioGenerationModel {\n return new OpenAIAudioGenerationModel(this.client, model);\n }\n\n transcriptionModel(model = WHISPER_1): OpenAITranscriptionModel {\n return new OpenAITranscriptionModel(this.client, model);\n }\n}\n\nfunction requireApiKey(apiKey: string | undefined): string {\n if (apiKey === undefined || apiKey.length === 0) {\n throw new Error(\"Missing OpenAI credentials. Pass apiKey when constructing OpenAIClient.\");\n }\n\n return apiKey;\n}\n","import type { Embedding, EmbeddingModel } from \"@anvia/core/embeddings\";\nimport type OpenAI from \"openai\";\n\nexport type ProviderEmbeddingModelOptions = {\n dimensions?: number | undefined;\n user?: string | undefined;\n maxBatchSize?: number | undefined;\n};\n\nexport class OpenAIEmbeddingModel implements EmbeddingModel {\n readonly dimensions: number | undefined;\n readonly maxBatchSize: number;\n private readonly user: string | undefined;\n\n constructor(\n private readonly client: OpenAI,\n private readonly model: string,\n options: ProviderEmbeddingModelOptions = {},\n ) {\n this.dimensions = options.dimensions;\n this.maxBatchSize = options.maxBatchSize ?? 1024;\n this.user = options.user;\n }\n\n async embedTexts(texts: string[]): Promise<Embedding[]> {\n const embeddings: Embedding[] = [];\n for (let index = 0; index < texts.length; index += this.maxBatchSize) {\n const batch = texts.slice(index, index + this.maxBatchSize);\n embeddings.push(...(await this.embedBatch(batch)));\n }\n return embeddings;\n }\n\n private async embedBatch(texts: string[]): Promise<Embedding[]> {\n if (texts.length === 0) {\n return [];\n }\n\n const params: Record<string, unknown> = {\n model: this.model,\n input: texts,\n };\n if (this.dimensions !== undefined) {\n params.dimensions = this.dimensions;\n }\n if (this.user !== undefined) {\n params.user = this.user;\n }\n\n const response = await this.client.embeddings.create(params as never);\n const data = Array.isArray(response.data) ? response.data : [];\n if (data.length !== texts.length) {\n throw new Error(\n `Embedding response length ${data.length} did not match input length ${texts.length}`,\n );\n }\n\n return data\n .slice()\n .sort((left, right) => left.index - right.index)\n .map((item, index) => ({\n document: texts[index] as string,\n vector: item.embedding,\n }));\n }\n}\n","import { Buffer } from \"node:buffer\";\nimport type {\n GeneratedImage,\n ImageGenerationModel,\n ImageGenerationRequest,\n ImageGenerationResponse,\n} from \"@anvia/core/image-generation\";\nimport type { OpenAI } from \"openai\";\nimport { isPlainObject } from \"../utils\";\n\nexport const DALL_E_2 = \"dall-e-2\";\nexport const DALL_E_3 = \"dall-e-3\";\nexport const GPT_IMAGE_1 = \"gpt-image-1\";\nexport const GPT_IMAGE_2 = \"gpt-image-2\";\n\nexport class OpenAIImageGenerationModel implements ImageGenerationModel {\n readonly provider = \"openai\";\n\n constructor(\n private readonly client: OpenAI,\n readonly defaultModel = GPT_IMAGE_1,\n ) {}\n\n async imageGeneration(\n request: ImageGenerationRequest,\n ): Promise<ImageGenerationResponse<unknown>> {\n const params: Record<string, unknown> = {\n model: this.defaultModel,\n prompt: request.prompt,\n size: `${request.width}x${request.height}`,\n };\n\n if (this.defaultModel === DALL_E_2 || this.defaultModel === DALL_E_3) {\n params.response_format = \"b64_json\";\n }\n\n if (request.additionalParams !== undefined && isPlainObject(request.additionalParams)) {\n Object.assign(params, request.additionalParams);\n }\n\n const response = await this.client.images.generate(params as never);\n return imageResponseFromOpenAI(response);\n }\n}\n\nexport function imageResponseFromOpenAI(response: unknown): ImageGenerationResponse<unknown> {\n const raw = response as Record<string, unknown>;\n const mediaType = mediaTypeFromFormat(\n typeof raw.output_format === \"string\" ? raw.output_format : \"png\",\n );\n const images = (Array.isArray(raw.data) ? raw.data : []).flatMap((item): GeneratedImage[] => {\n if (!isPlainObject(item) || typeof item.b64_json !== \"string\") {\n return [];\n }\n return [{ data: new Uint8Array(Buffer.from(item.b64_json, \"base64\")), mediaType }];\n });\n\n const image = images[0]?.data;\n if (image === undefined) {\n throw new Error(\"OpenAI image generation response contained no base64 images.\");\n }\n\n return {\n image,\n images,\n mediaType,\n rawResponse: response,\n };\n}\n\nfunction mediaTypeFromFormat(format: string): string {\n if (format === \"jpeg\" || format === \"jpg\") {\n return \"image/jpeg\";\n }\n if (format === \"webp\") {\n return \"image/webp\";\n }\n return \"image/png\";\n}\n","import {\n AssistantContent,\n type AssistantContent as AssistantContentType,\n assertCompletionRequestSupported,\n type CompletionModelCapabilities,\n type CompletionRequest,\n type CompletionResponse,\n type CompletionStreamEvent,\n type DocumentContent,\n type ImageContent,\n type Message as MessageType,\n type Reasoning,\n type ReasoningContent,\n type StreamingCompletionModel,\n type ToolChoice,\n type ToolContent,\n type ToolDefinition,\n Usage,\n type UserContent,\n} from \"@anvia/core/completion\";\nimport type { OpenAI } from \"openai\";\nimport { orderedRequestMessages } from \"../request-messages\";\nimport { isPlainObject, numberFrom, parseJsonValue, schemaName, stringFrom } from \"../utils\";\n\ntype ResponsesCreateParams = Record<string, unknown>;\ntype ResponsesInputItem = Record<string, unknown>;\n\nexport class OpenAIResponsesCompletionModel implements StreamingCompletionModel {\n readonly provider = \"openai\";\n readonly capabilities: CompletionModelCapabilities = {\n streaming: true,\n tools: true,\n toolChoice: true,\n imageInput: true,\n documentInput: true,\n outputSchema: true,\n reasoning: true,\n };\n\n constructor(\n private readonly client: OpenAI,\n readonly defaultModel = \"gpt-5\",\n ) {}\n\n async completion(request: CompletionRequest): Promise<CompletionResponse> {\n assertCompletionRequestSupported(this, request);\n const params = toOpenAIResponsesParams(this.defaultModel, request);\n const response = await this.client.responses.create(params as never);\n return fromOpenAIResponse(response);\n }\n\n async *streamCompletion(request: CompletionRequest): AsyncIterable<CompletionStreamEvent> {\n assertCompletionRequestSupported(this, request, { streaming: true });\n const params = { ...toOpenAIResponsesParams(this.defaultModel, request), stream: true };\n const stream = await this.client.responses.create(params as never);\n for await (const event of stream as unknown as AsyncIterable<unknown>) {\n const mapped = fromOpenAIStreamEvent(event);\n if (mapped !== undefined) {\n yield mapped;\n }\n }\n }\n}\n\nexport function toOpenAIResponsesParams(\n defaultModel: string,\n request: CompletionRequest,\n): ResponsesCreateParams {\n const params: ResponsesCreateParams = {\n model: request.model ?? defaultModel,\n input: requestMessages(request).flatMap(messageToResponsesInput),\n };\n\n if (request.instructions !== undefined) {\n params.instructions = request.instructions;\n }\n\n if (request.tools.length > 0) {\n params.tools = request.tools.map(toolDefinitionToOpenAI);\n }\n\n if (request.temperature !== undefined) {\n params.temperature = request.temperature;\n }\n\n if (request.maxTokens !== undefined) {\n params.max_output_tokens = request.maxTokens;\n }\n\n if (request.toolChoice !== undefined) {\n params.tool_choice = toolChoiceToOpenAI(request.toolChoice);\n }\n\n if (request.outputSchema !== undefined) {\n params.text = {\n format: {\n type: \"json_schema\",\n name: schemaName(request.outputSchema),\n strict: true,\n schema: request.outputSchema,\n },\n };\n }\n\n if (request.additionalParams !== undefined && isPlainObject(request.additionalParams)) {\n Object.assign(params, request.additionalParams);\n }\n\n return params;\n}\n\nfunction requestMessages(request: CompletionRequest): MessageType[] {\n return orderedRequestMessages(request);\n}\n\nexport function fromOpenAIResponse(response: unknown): CompletionResponse {\n const raw = response as Record<string, unknown>;\n const output = Array.isArray(raw.output) ? raw.output : [];\n const choice: AssistantContentType[] = [];\n\n for (const item of output) {\n if (!isPlainObject(item)) {\n continue;\n }\n\n if (item.type === \"message\") {\n choice.push(...messageOutputToAssistantContent(item));\n }\n\n if (item.type === \"function_call\") {\n const id = typeof item.id === \"string\" ? item.id : crypto.randomUUID();\n const callId = typeof item.call_id === \"string\" ? item.call_id : undefined;\n const name = typeof item.name === \"string\" ? item.name : \"\";\n const argsText = typeof item.arguments === \"string\" ? item.arguments : \"{}\";\n choice.push(AssistantContent.toolCall(id, name, parseJsonValue(argsText), callId));\n }\n\n if (item.type === \"reasoning\") {\n choice.push(reasoningItemToAssistantContent(item));\n }\n }\n\n const usageSource = isPlainObject(raw.usage) ? raw.usage : {};\n const inputTokens = numberFrom(usageSource.input_tokens);\n const outputTokens = numberFrom(usageSource.output_tokens);\n const totalTokens = numberFrom(usageSource.total_tokens) || inputTokens + outputTokens;\n const details = isPlainObject(usageSource.input_tokens_details)\n ? usageSource.input_tokens_details\n : {};\n\n const result: CompletionResponse = {\n choice,\n usage: {\n ...Usage.empty(),\n inputTokens,\n outputTokens,\n totalTokens,\n cachedInputTokens: numberFrom(details.cached_tokens),\n },\n rawResponse: response,\n };\n\n if (typeof raw.id === \"string\") {\n result.messageId = raw.id;\n }\n\n return result;\n}\n\nexport function fromOpenAIStreamEvent(event: unknown): CompletionStreamEvent | undefined {\n if (!isPlainObject(event) || typeof event.type !== \"string\") {\n return undefined;\n }\n\n if (event.type === \"response.output_text.delta\" || event.type === \"response.refusal.delta\") {\n return typeof event.delta === \"string\" ? { type: \"text_delta\", delta: event.delta } : undefined;\n }\n\n if (\n event.type === \"response.reasoning_text.delta\" ||\n event.type === \"response.reasoning_summary_text.delta\"\n ) {\n if (typeof event.delta !== \"string\") {\n return undefined;\n }\n const mapped: CompletionStreamEvent = { type: \"reasoning_delta\", delta: event.delta };\n const id = stringFrom(event.item_id);\n if (id !== undefined) {\n mapped.id = id;\n }\n if (event.type === \"response.reasoning_summary_text.delta\") {\n mapped.contentType = \"summary\";\n } else {\n mapped.contentType = \"text\";\n }\n return mapped;\n }\n\n if (event.type === \"response.output_item.added\" && isPlainObject(event.item)) {\n const item = event.item;\n if (item.type === \"function_call\") {\n return toolCallDelta(\n stringFrom(item.id) ?? stringFrom(event.item_id) ?? crypto.randomUUID(),\n {\n callId: stringFrom(item.call_id),\n name: stringFrom(item.name),\n argumentsDelta: typeof item.arguments === \"string\" ? item.arguments : undefined,\n },\n );\n }\n if (typeof item.id === \"string\") {\n return { type: \"message_id\", id: item.id };\n }\n }\n\n if (\n event.type === \"response.function_call_arguments.delta\" ||\n event.type === \"response.function_call_arguments.done\"\n ) {\n return toolCallDelta(\n stringFrom(event.item_id) ?? stringFrom(event.output_item_id) ?? crypto.randomUUID(),\n {\n argumentsDelta:\n typeof event.delta === \"string\"\n ? event.delta\n : typeof event.arguments === \"string\"\n ? event.arguments\n : undefined,\n },\n );\n }\n\n if (event.type === \"response.output_item.done\" && isPlainObject(event.item)) {\n const item = event.item;\n if (item.type === \"function_call\") {\n return {\n type: \"tool_call\",\n toolCall: AssistantContent.toolCall(\n stringFrom(item.id) ?? crypto.randomUUID(),\n stringFrom(item.name) ?? \"\",\n parseJsonValue(typeof item.arguments === \"string\" ? item.arguments : \"{}\"),\n stringFrom(item.call_id),\n ),\n };\n }\n }\n\n if (event.type === \"response.completed\" && isPlainObject(event.response)) {\n return {\n type: \"final\",\n response: fromOpenAIResponse(event.response),\n };\n }\n\n if (event.type === \"response.error\") {\n return { type: \"error\", error: event.error ?? event };\n }\n\n return undefined;\n}\n\nfunction messageToResponsesInput(message: MessageType): ResponsesInputItem[] {\n if (message.role === \"system\") {\n return [\n {\n role: \"system\",\n content: message.content,\n },\n ];\n }\n\n if (message.role === \"user\") {\n const inputContent: ResponsesInputItem[] = [];\n\n for (const content of message.content) {\n inputContent.push(...userContentToOpenAIResponsesParts(content));\n }\n\n if (inputContent.length === 1 && inputContent[0]?.type === \"input_text\") {\n return [{ role: \"user\", content: inputContent[0].text }];\n } else if (inputContent.length > 0) {\n return [{ role: \"user\", content: inputContent }];\n }\n\n return [];\n }\n\n if (message.role === \"tool\") {\n return message.content.map(toolContentToOpenAIResponsesItem);\n }\n\n const items: ResponsesInputItem[] = [];\n const text = message.content\n .flatMap((content) => (content.type === \"text\" ? [content.text] : []))\n .join(\"\\n\");\n if (text.length > 0) {\n items.push({ role: \"assistant\", content: text });\n }\n\n for (const content of message.content) {\n if (content.type === \"reasoning\" && content.id !== undefined) {\n items.push(reasoningToOpenAIInput(content));\n }\n if (content.type === \"tool_call\") {\n items.push({\n type: \"function_call\",\n id: content.id,\n call_id: content.callId ?? content.id,\n name: content.function.name,\n arguments: JSON.stringify(content.function.arguments ?? {}),\n });\n }\n if (content.type === \"image\") {\n throw new Error(\"OpenAI Responses does not support image content in assistant history\");\n }\n }\n\n return items;\n}\n\nfunction toolContentToOpenAIResponsesItem(content: ToolContent): ResponsesInputItem {\n return {\n type: \"function_call_output\",\n call_id: content.callId ?? content.id,\n output: content.content\n .map((item) => (item.type === \"text\" ? item.text : item.data))\n .join(\"\\n\"),\n };\n}\n\nfunction reasoningItemToAssistantContent(item: Record<string, unknown>): Reasoning {\n const content = reasoningContentFromOpenAIItem(item);\n const id = stringFrom(item.id);\n if (content.length === 0) {\n return AssistantContent.reasoning(\"\", id);\n }\n return AssistantContent.reasoningFromContent(content, id);\n}\n\nfunction reasoningContentFromOpenAIItem(item: Record<string, unknown>): ReasoningContent[] {\n const content: ReasoningContent[] = [];\n if (Array.isArray(item.content)) {\n for (const part of item.content) {\n if (!isPlainObject(part)) {\n continue;\n }\n if (part.type === \"reasoning_text\" && typeof part.text === \"string\") {\n content.push({ type: \"text\", text: part.text });\n }\n }\n }\n if (Array.isArray(item.summary)) {\n for (const summary of item.summary) {\n if (!isPlainObject(summary)) {\n continue;\n }\n if (typeof summary.text === \"string\") {\n content.push({ type: \"summary\", text: summary.text });\n }\n }\n }\n if (typeof item.encrypted_content === \"string\") {\n content.push({ type: \"encrypted\", data: item.encrypted_content });\n }\n return content;\n}\n\nfunction reasoningToOpenAIInput(reasoning: Reasoning): ResponsesInputItem {\n const item: ResponsesInputItem = {\n type: \"reasoning\",\n id: reasoning.id,\n summary:\n reasoning.content\n ?.filter((content): content is Extract<ReasoningContent, { type: \"summary\" }> => {\n return content.type === \"summary\";\n })\n .map((content) => ({ type: \"summary_text\", text: content.text })) ?? [],\n };\n const textContent = reasoning.content?.flatMap((content) =>\n content.type === \"text\" ? [{ type: \"reasoning_text\", text: content.text }] : [],\n );\n if (textContent !== undefined && textContent.length > 0) {\n item.content = textContent;\n }\n const encrypted = reasoning.content?.find((content) => content.type === \"encrypted\");\n if (encrypted?.type === \"encrypted\") {\n item.encrypted_content = encrypted.data;\n }\n return item;\n}\n\nfunction userContentToOpenAIResponsesParts(content: UserContent): ResponsesInputItem[] {\n if (content.type === \"text\") {\n return [{ type: \"input_text\", text: content.text }];\n }\n\n if (content.type === \"image\") {\n const part: ResponsesInputItem = { type: \"input_image\", image_url: imageUrl(content) };\n if (content.detail !== undefined) {\n part.detail = content.detail;\n }\n return [part];\n }\n\n if (content.type === \"document\") {\n return [documentToOpenAIResponsesPart(content)];\n }\n\n return [];\n}\n\nfunction imageUrl(image: ImageContent): string {\n if (image.source.type === \"url\") {\n return image.source.url;\n }\n\n return `data:${image.source.mediaType};base64,${image.source.data}`;\n}\n\nfunction documentToOpenAIResponsesPart(document: DocumentContent): ResponsesInputItem {\n if (document.source.type === \"text\") {\n return { type: \"input_text\", text: document.source.text };\n }\n\n if (document.source.mediaType !== \"application/pdf\") {\n throw new Error(`OpenAI Responses only supports PDF document attachments`);\n }\n\n if (document.source.type === \"url\") {\n return { type: \"input_file\", file_url: document.source.url };\n }\n\n return {\n type: \"input_file\",\n file_data: `data:${document.source.mediaType};base64,${document.source.data}`,\n filename: document.source.filename ?? \"document.pdf\",\n };\n}\n\nfunction toolDefinitionToOpenAI(tool: ToolDefinition): ResponsesInputItem {\n return {\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n };\n}\n\nfunction toolChoiceToOpenAI(toolChoice: ToolChoice): unknown {\n if (toolChoice === \"auto\" || toolChoice === \"required\" || toolChoice === \"none\") {\n return toolChoice;\n }\n\n return {\n type: \"function\",\n name: toolChoice.name,\n };\n}\n\nfunction messageOutputToAssistantContent(item: Record<string, unknown>): AssistantContentType[] {\n const content = Array.isArray(item.content) ? item.content : [];\n return content.flatMap((part): AssistantContentType[] => {\n if (!isPlainObject(part)) {\n return [];\n }\n\n if (part.type === \"output_text\" && typeof part.text === \"string\") {\n return [AssistantContent.text(part.text)];\n }\n\n if (part.type === \"text\" && typeof part.text === \"string\") {\n return [AssistantContent.text(part.text)];\n }\n\n return [];\n });\n}\n\nfunction toolCallDelta(\n id: string,\n values: {\n callId?: string | undefined;\n name?: string | undefined;\n argumentsDelta?: string | undefined;\n },\n): CompletionStreamEvent {\n const event: CompletionStreamEvent = { type: \"tool_call_delta\", id };\n if (values.callId !== undefined) event.callId = values.callId;\n if (values.name !== undefined) event.name = values.name;\n if (values.argumentsDelta !== undefined) event.argumentsDelta = values.argumentsDelta;\n return event;\n}\n\nexport const openaiMessageHelpers = {\n messageToResponsesInput,\n toolDefinitionToOpenAI,\n};\n","import type {\n TranscriptionModel,\n TranscriptionRequest,\n TranscriptionResponse,\n} from \"@anvia/core/transcription\";\nimport type { OpenAI } from \"openai\";\nimport { toFile } from \"openai\";\nimport { isPlainObject } from \"../utils\";\n\nexport const WHISPER_1 = \"whisper-1\";\n\nexport class OpenAITranscriptionModel implements TranscriptionModel {\n readonly provider = \"openai\";\n\n constructor(\n private readonly client: OpenAI,\n readonly defaultModel = WHISPER_1,\n ) {}\n\n async transcription(request: TranscriptionRequest): Promise<TranscriptionResponse<unknown>> {\n const params: Record<string, unknown> = {\n model: this.defaultModel,\n file: await toFile(request.data, request.filename),\n };\n\n if (request.language !== undefined) params.language = request.language;\n if (request.prompt !== undefined) params.prompt = request.prompt;\n if (request.temperature !== undefined) params.temperature = request.temperature;\n if (request.additionalParams !== undefined && isPlainObject(request.additionalParams)) {\n Object.assign(params, request.additionalParams);\n }\n\n const response = await this.client.audio.transcriptions.create(params as never);\n return {\n text: transcriptionText(response),\n rawResponse: response,\n };\n }\n}\n\nexport function transcriptionText(response: unknown): string {\n if (typeof response === \"string\") {\n return response;\n }\n if (isPlainObject(response) && typeof response.text === \"string\") {\n return response.text;\n }\n throw new Error(\"OpenAI transcription response contained no text.\");\n}\n"],"mappings":";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,SAAS,cAAc,OAAkD;AAC9E,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEO,SAAS,WAAW,OAAwB;AACjD,SAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEO,SAAS,WAAW,OAAoC;AAC7D,SAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEO,SAAS,eAAe,MAAyB;AACtD,MAAI;AACF,WAAO,KAAK,MAAM,I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B;AACA,QAAM,IAAI,MAAM,kDAAkD;AACpE;;;AJ/BO,IAAM,eAAN,MAAmB;AAAA,EACf;AAAA,EACQ;AAAA,EAEjB,YAAY,UAA+B,CAAC,GAAG;AAC7C,SAAK,gBACH,QAAQ,kBAAkB,QAAQ,YAAY,SAAY,cAAc;AAC1E,SAAK,SACH,QAAQ,UACR,IAAI,OAAO;AAAA,MACT,QAAQ,cAAc,QAAQ,MAAM;AAAA,MACpC,SAAS,QAAQ;AAAA,MACjB,gBAAgB,QAAQ;AAAA,IAC1B,CAAC;AAAA,EACL;AAAA,EAEA,gBAAgB,QAAQ,SAAmC;AACzD,WAAO,KAAK,kBAAkB,SAC1B,IAAI,0BAA0B,KAAK,QAAQ,KAAK,IAChD,IAAI,+BAA+B,KAAK,QAAQ,KAAK;AAAA,EAC3D;AAAA,EAEA,eACE,QAAQ,0BACR,UAAyC,CAAC,GACpB;AACtB,WAAO,IAAI,qBAAqB,KAAK,QAAQ,OAAO,OAAO;AAAA,EAC7D;AAAA,EAEA,qBAAqB,QAAQ,aAAyC;AACpE,WAAO,IAAI,2BAA2B,KAAK,QAAQ,KAAK;AAAA,EAC1D;AAAA,EAEA,qBAAqB,QAAQ,OAAmC;AAC9D,WAAO,IAAI,2BAA2B,KAAK,QAAQ,KAAK;AAAA,EAC1D;AAAA,EAEA,mBAAmB,QAAQ,WAAqC;AAC9D,WAAO,IAAI,yBAAyB,KAAK,QAAQ,KAAK;AAAA,EACxD;AACF;AAEA,SAAS,cAAc,QAAoC;AACzD,MAAI,WAAW,UAAa,OAAO,WAAW,GAAG;AAC/C,UAAM,IAAI,MAAM,yEAAyE;AAAA,EAC3F;AAEA,SAAO;AACT;","names":["Buffer","mediaTypeFromFormat","Buffer","AssistantContent","assertCompletionRequestSupported","Usage","assertCompletionRequestSupported","requestMessages","AssistantContent","Usage","toolCallDelta","imageUrl"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@anvia/openai",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "OpenAI provider adapter for Anvia.",
|
|
5
|
+
"author": "anvia",
|
|
6
|
+
"maintainer": "Indra Zulfi",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"type": "module",
|
|
12
|
+
"main": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"openai": "^6.35.0",
|
|
22
|
+
"@anvia/core": "0.1.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@types/node": "^24.9.1",
|
|
26
|
+
"tsup": "^8.5.0",
|
|
27
|
+
"typescript": "^5.9.3",
|
|
28
|
+
"vitest": "^4.0.8"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
|
|
32
|
+
"test": "vitest run",
|
|
33
|
+
"typecheck": "tsc --noEmit"
|
|
34
|
+
}
|
|
35
|
+
}
|