@agentic-kit/openai 1.2.1 → 1.2.2
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/esm/index.js +1 -173
- package/index.d.ts +1 -181
- package/index.js +24 -196
- package/package.json +5 -2
package/esm/index.js
CHANGED
|
@@ -1,81 +1,8 @@
|
|
|
1
|
+
import { calculateUsageCost, clone, createAssistantMessage, DefaultAssistantMessageEventStream, normalizeBaseUrl, parsePartialJson, } from '@agentic-kit/protocol';
|
|
1
2
|
// Use the runtime's native fetch. Node 18.17+ (engine requirement),
|
|
2
3
|
// browsers, Bun, and Deno all provide it with a Web ReadableStream body —
|
|
3
4
|
// which is what SSE parsing here requires.
|
|
4
5
|
const fetch = globalThis.fetch.bind(globalThis);
|
|
5
|
-
class EventStream {
|
|
6
|
-
isTerminal;
|
|
7
|
-
extractResult;
|
|
8
|
-
queue = [];
|
|
9
|
-
waiting = [];
|
|
10
|
-
done = false;
|
|
11
|
-
finalResultPromise;
|
|
12
|
-
resolveFinalResult;
|
|
13
|
-
constructor(isTerminal, extractResult) {
|
|
14
|
-
this.isTerminal = isTerminal;
|
|
15
|
-
this.extractResult = extractResult;
|
|
16
|
-
this.finalResultPromise = new Promise((resolve) => {
|
|
17
|
-
this.resolveFinalResult = resolve;
|
|
18
|
-
});
|
|
19
|
-
}
|
|
20
|
-
push(event) {
|
|
21
|
-
if (this.done) {
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
|
-
if (this.isTerminal(event)) {
|
|
25
|
-
this.done = true;
|
|
26
|
-
this.resolveFinalResult(this.extractResult(event));
|
|
27
|
-
}
|
|
28
|
-
const waiter = this.waiting.shift();
|
|
29
|
-
if (waiter) {
|
|
30
|
-
waiter({ value: event, done: false });
|
|
31
|
-
return;
|
|
32
|
-
}
|
|
33
|
-
this.queue.push(event);
|
|
34
|
-
}
|
|
35
|
-
end(result) {
|
|
36
|
-
this.done = true;
|
|
37
|
-
if (result !== undefined) {
|
|
38
|
-
this.resolveFinalResult(result);
|
|
39
|
-
}
|
|
40
|
-
while (this.waiting.length > 0) {
|
|
41
|
-
this.waiting.shift()({ value: undefined, done: true });
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
async *[Symbol.asyncIterator]() {
|
|
45
|
-
while (true) {
|
|
46
|
-
if (this.queue.length > 0) {
|
|
47
|
-
yield this.queue.shift();
|
|
48
|
-
continue;
|
|
49
|
-
}
|
|
50
|
-
if (this.done) {
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
const next = await new Promise((resolve) => {
|
|
54
|
-
this.waiting.push(resolve);
|
|
55
|
-
});
|
|
56
|
-
if (next.done) {
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
yield next.value;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
result() {
|
|
63
|
-
return this.finalResultPromise;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
class DefaultAssistantMessageEventStream extends EventStream {
|
|
67
|
-
constructor() {
|
|
68
|
-
super((event) => event.type === 'done' || event.type === 'error', (event) => {
|
|
69
|
-
if (event.type === 'done') {
|
|
70
|
-
return event.message;
|
|
71
|
-
}
|
|
72
|
-
if (event.type === 'error') {
|
|
73
|
-
return event.error;
|
|
74
|
-
}
|
|
75
|
-
throw new Error('Unexpected terminal event');
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
6
|
export const OPENAI_COMPATIBLE_MODELS = [
|
|
80
7
|
{
|
|
81
8
|
id: 'gpt-5.4',
|
|
@@ -493,34 +420,6 @@ function toOpenAIMessage(message, compat) {
|
|
|
493
420
|
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
494
421
|
};
|
|
495
422
|
}
|
|
496
|
-
function createAssistantMessage(model) {
|
|
497
|
-
return {
|
|
498
|
-
role: 'assistant',
|
|
499
|
-
api: model.api,
|
|
500
|
-
provider: model.provider,
|
|
501
|
-
model: model.id,
|
|
502
|
-
content: [],
|
|
503
|
-
usage: {
|
|
504
|
-
input: 0,
|
|
505
|
-
output: 0,
|
|
506
|
-
reasoning: 0,
|
|
507
|
-
cacheRead: 0,
|
|
508
|
-
cacheWrite: 0,
|
|
509
|
-
totalTokens: 0,
|
|
510
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
511
|
-
},
|
|
512
|
-
stopReason: 'stop',
|
|
513
|
-
timestamp: Date.now(),
|
|
514
|
-
};
|
|
515
|
-
}
|
|
516
|
-
function calculateUsageCost(model, usage) {
|
|
517
|
-
usage.cost.input = ((model.cost?.input ?? 0) / 1_000_000) * usage.input;
|
|
518
|
-
usage.cost.output = ((model.cost?.output ?? 0) / 1_000_000) * usage.output;
|
|
519
|
-
usage.cost.cacheRead = ((model.cost?.cacheRead ?? 0) / 1_000_000) * usage.cacheRead;
|
|
520
|
-
usage.cost.cacheWrite = ((model.cost?.cacheWrite ?? 0) / 1_000_000) * usage.cacheWrite;
|
|
521
|
-
usage.cost.total =
|
|
522
|
-
usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
523
|
-
}
|
|
524
423
|
function applyUsage(usage, model, payload) {
|
|
525
424
|
const cachedTokens = payload.prompt_tokens_details?.cached_tokens ?? 0;
|
|
526
425
|
const reasoningTokens = payload.completion_tokens_details?.reasoning_tokens ?? 0;
|
|
@@ -565,77 +464,6 @@ function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinking
|
|
|
565
464
|
});
|
|
566
465
|
}
|
|
567
466
|
}
|
|
568
|
-
function normalizeBaseUrl(baseUrl) {
|
|
569
|
-
const trimmed = baseUrl.replace(/\/+$/, '');
|
|
570
|
-
if (/\/v\d+$/.test(trimmed)) {
|
|
571
|
-
return trimmed;
|
|
572
|
-
}
|
|
573
|
-
return `${trimmed}/v1`;
|
|
574
|
-
}
|
|
575
|
-
function parsePartialJson(raw) {
|
|
576
|
-
const trimmed = raw.trim();
|
|
577
|
-
if (!trimmed) {
|
|
578
|
-
return {};
|
|
579
|
-
}
|
|
580
|
-
try {
|
|
581
|
-
return JSON.parse(trimmed);
|
|
582
|
-
}
|
|
583
|
-
catch {
|
|
584
|
-
// continue
|
|
585
|
-
}
|
|
586
|
-
const completed = completePartialJson(trimmed);
|
|
587
|
-
if (!completed) {
|
|
588
|
-
return {};
|
|
589
|
-
}
|
|
590
|
-
try {
|
|
591
|
-
return JSON.parse(completed);
|
|
592
|
-
}
|
|
593
|
-
catch {
|
|
594
|
-
return {};
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
function completePartialJson(input) {
|
|
598
|
-
let output = input;
|
|
599
|
-
let inString = false;
|
|
600
|
-
let escaping = false;
|
|
601
|
-
const stack = [];
|
|
602
|
-
for (const char of input) {
|
|
603
|
-
if (escaping) {
|
|
604
|
-
escaping = false;
|
|
605
|
-
continue;
|
|
606
|
-
}
|
|
607
|
-
if (char === '\\') {
|
|
608
|
-
escaping = true;
|
|
609
|
-
continue;
|
|
610
|
-
}
|
|
611
|
-
if (char === '"') {
|
|
612
|
-
inString = !inString;
|
|
613
|
-
continue;
|
|
614
|
-
}
|
|
615
|
-
if (inString) {
|
|
616
|
-
continue;
|
|
617
|
-
}
|
|
618
|
-
if (char === '{') {
|
|
619
|
-
stack.push('}');
|
|
620
|
-
}
|
|
621
|
-
else if (char === '[') {
|
|
622
|
-
stack.push(']');
|
|
623
|
-
}
|
|
624
|
-
else if (char === '}' || char === ']') {
|
|
625
|
-
stack.pop();
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
if (inString) {
|
|
629
|
-
output += '"';
|
|
630
|
-
}
|
|
631
|
-
while (stack.length > 0) {
|
|
632
|
-
output += stack.pop();
|
|
633
|
-
}
|
|
634
|
-
return output;
|
|
635
|
-
}
|
|
636
|
-
function clone(value) {
|
|
637
|
-
return JSON.parse(JSON.stringify(value));
|
|
638
|
-
}
|
|
639
467
|
function firstNonEmpty(...values) {
|
|
640
468
|
return values.find((value) => typeof value === 'string' && value.length > 0);
|
|
641
469
|
}
|
package/index.d.ts
CHANGED
|
@@ -1,184 +1,4 @@
|
|
|
1
|
-
type
|
|
2
|
-
type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
|
|
3
|
-
interface JsonObject {
|
|
4
|
-
[key: string]: JsonValue | undefined;
|
|
5
|
-
}
|
|
6
|
-
interface JsonSchema {
|
|
7
|
-
additionalProperties?: boolean | JsonSchema;
|
|
8
|
-
description?: string;
|
|
9
|
-
enum?: JsonValue[];
|
|
10
|
-
items?: JsonSchema | JsonSchema[];
|
|
11
|
-
properties?: Record<string, JsonSchema>;
|
|
12
|
-
required?: string[];
|
|
13
|
-
type?: string | string[];
|
|
14
|
-
}
|
|
15
|
-
interface OpenAICompatibleCompat {
|
|
16
|
-
maxTokensField?: 'max_completion_tokens' | 'max_tokens';
|
|
17
|
-
reasoningFormat?: 'none' | 'openai';
|
|
18
|
-
supportsReasoningEffort?: boolean;
|
|
19
|
-
supportsStrictToolSchema?: boolean;
|
|
20
|
-
supportsUsageInStreaming?: boolean;
|
|
21
|
-
toolCallIdFormat?: 'passthrough' | 'safe64' | 'mistral9';
|
|
22
|
-
requiresToolResultName?: boolean;
|
|
23
|
-
}
|
|
24
|
-
interface ModelDescriptor {
|
|
25
|
-
id: string;
|
|
26
|
-
name: string;
|
|
27
|
-
api: string;
|
|
28
|
-
provider: string;
|
|
29
|
-
baseUrl: string;
|
|
30
|
-
input: Array<'text' | 'image'>;
|
|
31
|
-
reasoning: boolean;
|
|
32
|
-
tools?: boolean;
|
|
33
|
-
contextWindow?: number;
|
|
34
|
-
maxOutputTokens?: number;
|
|
35
|
-
cost?: {
|
|
36
|
-
input?: number;
|
|
37
|
-
output?: number;
|
|
38
|
-
cacheRead?: number;
|
|
39
|
-
cacheWrite?: number;
|
|
40
|
-
};
|
|
41
|
-
headers?: Record<string, string>;
|
|
42
|
-
compat?: OpenAICompatibleCompat;
|
|
43
|
-
}
|
|
44
|
-
interface TextContent {
|
|
45
|
-
type: 'text';
|
|
46
|
-
text: string;
|
|
47
|
-
}
|
|
48
|
-
interface ImageContent {
|
|
49
|
-
type: 'image';
|
|
50
|
-
data: string;
|
|
51
|
-
mimeType: string;
|
|
52
|
-
}
|
|
53
|
-
interface ThinkingContent {
|
|
54
|
-
type: 'thinking';
|
|
55
|
-
thinking: string;
|
|
56
|
-
signature?: string;
|
|
57
|
-
}
|
|
58
|
-
interface ToolCallContent {
|
|
59
|
-
type: 'toolCall';
|
|
60
|
-
id: string;
|
|
61
|
-
name: string;
|
|
62
|
-
arguments: Record<string, JsonValue | undefined>;
|
|
63
|
-
rawArguments?: string;
|
|
64
|
-
}
|
|
65
|
-
type Message = {
|
|
66
|
-
role: 'user';
|
|
67
|
-
content: string | Array<TextContent | ImageContent>;
|
|
68
|
-
timestamp: number;
|
|
69
|
-
} | {
|
|
70
|
-
role: 'assistant';
|
|
71
|
-
content: Array<TextContent | ThinkingContent | ToolCallContent>;
|
|
72
|
-
api: string;
|
|
73
|
-
provider: string;
|
|
74
|
-
model: string;
|
|
75
|
-
usage: Usage;
|
|
76
|
-
stopReason: 'stop' | 'length' | 'toolUse' | 'error' | 'aborted';
|
|
77
|
-
errorMessage?: string;
|
|
78
|
-
timestamp: number;
|
|
79
|
-
} | {
|
|
80
|
-
role: 'toolResult';
|
|
81
|
-
toolCallId: string;
|
|
82
|
-
toolName: string;
|
|
83
|
-
content: Array<TextContent | ImageContent>;
|
|
84
|
-
isError: boolean;
|
|
85
|
-
details?: unknown;
|
|
86
|
-
timestamp: number;
|
|
87
|
-
};
|
|
88
|
-
interface ToolDefinition {
|
|
89
|
-
name: string;
|
|
90
|
-
description: string;
|
|
91
|
-
parameters: JsonSchema;
|
|
92
|
-
}
|
|
93
|
-
interface Context {
|
|
94
|
-
systemPrompt?: string;
|
|
95
|
-
messages: Message[];
|
|
96
|
-
tools?: ToolDefinition[];
|
|
97
|
-
}
|
|
98
|
-
interface StreamOptions {
|
|
99
|
-
apiKey?: string;
|
|
100
|
-
headers?: Record<string, string>;
|
|
101
|
-
maxTokens?: number;
|
|
102
|
-
onPayload?: (payload: unknown) => void;
|
|
103
|
-
reasoning?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
|
|
104
|
-
signal?: AbortSignal;
|
|
105
|
-
temperature?: number;
|
|
106
|
-
}
|
|
107
|
-
interface Usage {
|
|
108
|
-
input: number;
|
|
109
|
-
output: number;
|
|
110
|
-
reasoning: number;
|
|
111
|
-
cacheRead: number;
|
|
112
|
-
cacheWrite: number;
|
|
113
|
-
totalTokens: number;
|
|
114
|
-
cost: {
|
|
115
|
-
input: number;
|
|
116
|
-
output: number;
|
|
117
|
-
cacheRead: number;
|
|
118
|
-
cacheWrite: number;
|
|
119
|
-
total: number;
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
type AssistantMessage = Extract<Message, {
|
|
123
|
-
role: 'assistant';
|
|
124
|
-
}>;
|
|
125
|
-
type AssistantMessageEvent = {
|
|
126
|
-
type: 'start';
|
|
127
|
-
partial: AssistantMessage;
|
|
128
|
-
} | {
|
|
129
|
-
type: 'text_start';
|
|
130
|
-
contentIndex: number;
|
|
131
|
-
partial: AssistantMessage;
|
|
132
|
-
} | {
|
|
133
|
-
type: 'text_delta';
|
|
134
|
-
contentIndex: number;
|
|
135
|
-
delta: string;
|
|
136
|
-
partial: AssistantMessage;
|
|
137
|
-
} | {
|
|
138
|
-
type: 'text_end';
|
|
139
|
-
contentIndex: number;
|
|
140
|
-
content: string;
|
|
141
|
-
partial: AssistantMessage;
|
|
142
|
-
} | {
|
|
143
|
-
type: 'thinking_start';
|
|
144
|
-
contentIndex: number;
|
|
145
|
-
partial: AssistantMessage;
|
|
146
|
-
} | {
|
|
147
|
-
type: 'thinking_delta';
|
|
148
|
-
contentIndex: number;
|
|
149
|
-
delta: string;
|
|
150
|
-
partial: AssistantMessage;
|
|
151
|
-
} | {
|
|
152
|
-
type: 'thinking_end';
|
|
153
|
-
contentIndex: number;
|
|
154
|
-
content: string;
|
|
155
|
-
partial: AssistantMessage;
|
|
156
|
-
} | {
|
|
157
|
-
type: 'toolcall_start';
|
|
158
|
-
contentIndex: number;
|
|
159
|
-
partial: AssistantMessage;
|
|
160
|
-
} | {
|
|
161
|
-
type: 'toolcall_delta';
|
|
162
|
-
contentIndex: number;
|
|
163
|
-
delta: string;
|
|
164
|
-
partial: AssistantMessage;
|
|
165
|
-
} | {
|
|
166
|
-
type: 'toolcall_end';
|
|
167
|
-
contentIndex: number;
|
|
168
|
-
toolCall: ToolCallContent;
|
|
169
|
-
partial: AssistantMessage;
|
|
170
|
-
} | {
|
|
171
|
-
type: 'done';
|
|
172
|
-
reason: 'stop' | 'length' | 'toolUse';
|
|
173
|
-
message: AssistantMessage;
|
|
174
|
-
} | {
|
|
175
|
-
type: 'error';
|
|
176
|
-
reason: 'error' | 'aborted';
|
|
177
|
-
error: AssistantMessage;
|
|
178
|
-
};
|
|
179
|
-
interface AssistantMessageEventStream extends AsyncIterable<AssistantMessageEvent> {
|
|
180
|
-
result(): Promise<AssistantMessage>;
|
|
181
|
-
}
|
|
1
|
+
import { type AssistantMessageEventStream, type Context, type ModelDescriptor, type OpenAICompatibleCompat, type StreamOptions } from '@agentic-kit/protocol';
|
|
182
2
|
interface OpenAIModelDefinition extends ModelDescriptor {
|
|
183
3
|
}
|
|
184
4
|
export interface OpenAIOptions {
|
package/index.js
CHANGED
|
@@ -1,84 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.OpenAIAdapter = exports.OPENAI_COMPATIBLE_MODELS = void 0;
|
|
4
|
+
const protocol_1 = require("@agentic-kit/protocol");
|
|
4
5
|
// Use the runtime's native fetch. Node 18.17+ (engine requirement),
|
|
5
6
|
// browsers, Bun, and Deno all provide it with a Web ReadableStream body —
|
|
6
7
|
// which is what SSE parsing here requires.
|
|
7
8
|
const fetch = globalThis.fetch.bind(globalThis);
|
|
8
|
-
class EventStream {
|
|
9
|
-
isTerminal;
|
|
10
|
-
extractResult;
|
|
11
|
-
queue = [];
|
|
12
|
-
waiting = [];
|
|
13
|
-
done = false;
|
|
14
|
-
finalResultPromise;
|
|
15
|
-
resolveFinalResult;
|
|
16
|
-
constructor(isTerminal, extractResult) {
|
|
17
|
-
this.isTerminal = isTerminal;
|
|
18
|
-
this.extractResult = extractResult;
|
|
19
|
-
this.finalResultPromise = new Promise((resolve) => {
|
|
20
|
-
this.resolveFinalResult = resolve;
|
|
21
|
-
});
|
|
22
|
-
}
|
|
23
|
-
push(event) {
|
|
24
|
-
if (this.done) {
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
|
-
if (this.isTerminal(event)) {
|
|
28
|
-
this.done = true;
|
|
29
|
-
this.resolveFinalResult(this.extractResult(event));
|
|
30
|
-
}
|
|
31
|
-
const waiter = this.waiting.shift();
|
|
32
|
-
if (waiter) {
|
|
33
|
-
waiter({ value: event, done: false });
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
this.queue.push(event);
|
|
37
|
-
}
|
|
38
|
-
end(result) {
|
|
39
|
-
this.done = true;
|
|
40
|
-
if (result !== undefined) {
|
|
41
|
-
this.resolveFinalResult(result);
|
|
42
|
-
}
|
|
43
|
-
while (this.waiting.length > 0) {
|
|
44
|
-
this.waiting.shift()({ value: undefined, done: true });
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
async *[Symbol.asyncIterator]() {
|
|
48
|
-
while (true) {
|
|
49
|
-
if (this.queue.length > 0) {
|
|
50
|
-
yield this.queue.shift();
|
|
51
|
-
continue;
|
|
52
|
-
}
|
|
53
|
-
if (this.done) {
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
const next = await new Promise((resolve) => {
|
|
57
|
-
this.waiting.push(resolve);
|
|
58
|
-
});
|
|
59
|
-
if (next.done) {
|
|
60
|
-
return;
|
|
61
|
-
}
|
|
62
|
-
yield next.value;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
result() {
|
|
66
|
-
return this.finalResultPromise;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
class DefaultAssistantMessageEventStream extends EventStream {
|
|
70
|
-
constructor() {
|
|
71
|
-
super((event) => event.type === 'done' || event.type === 'error', (event) => {
|
|
72
|
-
if (event.type === 'done') {
|
|
73
|
-
return event.message;
|
|
74
|
-
}
|
|
75
|
-
if (event.type === 'error') {
|
|
76
|
-
return event.error;
|
|
77
|
-
}
|
|
78
|
-
throw new Error('Unexpected terminal event');
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
9
|
exports.OPENAI_COMPATIBLE_MODELS = [
|
|
83
10
|
{
|
|
84
11
|
id: 'gpt-5.4',
|
|
@@ -161,7 +88,7 @@ class OpenAIAdapter {
|
|
|
161
88
|
constructor(options) {
|
|
162
89
|
const normalized = typeof options === 'string' ? { apiKey: options } : options ?? {};
|
|
163
90
|
this.apiKey = normalized.apiKey;
|
|
164
|
-
this.baseUrl = normalizeBaseUrl(normalized.baseUrl ?? 'https://api.openai.com/v1');
|
|
91
|
+
this.baseUrl = (0, protocol_1.normalizeBaseUrl)(normalized.baseUrl ?? 'https://api.openai.com/v1');
|
|
165
92
|
this.provider = normalized.provider ?? 'openai';
|
|
166
93
|
this.name = this.provider;
|
|
167
94
|
this.defaultHeaders = normalized.headers;
|
|
@@ -227,8 +154,8 @@ class OpenAIAdapter {
|
|
|
227
154
|
}
|
|
228
155
|
}
|
|
229
156
|
stream(model, context, options) {
|
|
230
|
-
const stream = new DefaultAssistantMessageEventStream();
|
|
231
|
-
const output = createAssistantMessage(model);
|
|
157
|
+
const stream = new protocol_1.DefaultAssistantMessageEventStream();
|
|
158
|
+
const output = (0, protocol_1.createAssistantMessage)(model);
|
|
232
159
|
void (async () => {
|
|
233
160
|
let textIndex;
|
|
234
161
|
let thinkingIndex;
|
|
@@ -250,7 +177,7 @@ class OpenAIAdapter {
|
|
|
250
177
|
const text = await response.text().catch(() => '');
|
|
251
178
|
throw new Error(`OpenAI error ${response.status}: ${text}`);
|
|
252
179
|
}
|
|
253
|
-
stream.push({ type: 'start', partial: clone(output) });
|
|
180
|
+
stream.push({ type: 'start', partial: (0, protocol_1.clone)(output) });
|
|
254
181
|
const reader = response.body?.getReader();
|
|
255
182
|
if (!reader) {
|
|
256
183
|
throw new Error('No response body');
|
|
@@ -276,8 +203,8 @@ class OpenAIAdapter {
|
|
|
276
203
|
}
|
|
277
204
|
if (payload === '[DONE]') {
|
|
278
205
|
emitFinalBlockEvents(stream, output, toolIndexMap, textIndex, thinkingIndex);
|
|
279
|
-
calculateUsageCost(model, output.usage);
|
|
280
|
-
stream.push({ type: 'done', reason: doneReason, message: clone(output) });
|
|
206
|
+
(0, protocol_1.calculateUsageCost)(model, output.usage);
|
|
207
|
+
stream.push({ type: 'done', reason: doneReason, message: (0, protocol_1.clone)(output) });
|
|
281
208
|
stream.end(output);
|
|
282
209
|
return;
|
|
283
210
|
}
|
|
@@ -305,7 +232,7 @@ class OpenAIAdapter {
|
|
|
305
232
|
stream.push({
|
|
306
233
|
type: 'thinking_start',
|
|
307
234
|
contentIndex: thinkingIndex,
|
|
308
|
-
partial: clone(output),
|
|
235
|
+
partial: (0, protocol_1.clone)(output),
|
|
309
236
|
});
|
|
310
237
|
}
|
|
311
238
|
const block = output.content[thinkingIndex];
|
|
@@ -314,7 +241,7 @@ class OpenAIAdapter {
|
|
|
314
241
|
type: 'thinking_delta',
|
|
315
242
|
contentIndex: thinkingIndex,
|
|
316
243
|
delta: reasoningDelta,
|
|
317
|
-
partial: clone(output),
|
|
244
|
+
partial: (0, protocol_1.clone)(output),
|
|
318
245
|
});
|
|
319
246
|
}
|
|
320
247
|
if (typeof delta.content === 'string' && delta.content.length > 0) {
|
|
@@ -323,7 +250,7 @@ class OpenAIAdapter {
|
|
|
323
250
|
stream.push({
|
|
324
251
|
type: 'text_start',
|
|
325
252
|
contentIndex: textIndex,
|
|
326
|
-
partial: clone(output),
|
|
253
|
+
partial: (0, protocol_1.clone)(output),
|
|
327
254
|
});
|
|
328
255
|
}
|
|
329
256
|
const block = output.content[textIndex];
|
|
@@ -332,7 +259,7 @@ class OpenAIAdapter {
|
|
|
332
259
|
type: 'text_delta',
|
|
333
260
|
contentIndex: textIndex,
|
|
334
261
|
delta: delta.content,
|
|
335
|
-
partial: clone(output),
|
|
262
|
+
partial: (0, protocol_1.clone)(output),
|
|
336
263
|
});
|
|
337
264
|
}
|
|
338
265
|
for (const toolDelta of delta.tool_calls ?? []) {
|
|
@@ -351,7 +278,7 @@ class OpenAIAdapter {
|
|
|
351
278
|
stream.push({
|
|
352
279
|
type: 'toolcall_start',
|
|
353
280
|
contentIndex,
|
|
354
|
-
partial: clone(output),
|
|
281
|
+
partial: (0, protocol_1.clone)(output),
|
|
355
282
|
});
|
|
356
283
|
}
|
|
357
284
|
const block = output.content[contentIndex];
|
|
@@ -363,31 +290,31 @@ class OpenAIAdapter {
|
|
|
363
290
|
}
|
|
364
291
|
if (toolDelta.function?.arguments) {
|
|
365
292
|
block.rawArguments = `${block.rawArguments ?? ''}${toolDelta.function.arguments}`;
|
|
366
|
-
block.arguments = parsePartialJson(block.rawArguments);
|
|
293
|
+
block.arguments = (0, protocol_1.parsePartialJson)(block.rawArguments);
|
|
367
294
|
stream.push({
|
|
368
295
|
type: 'toolcall_delta',
|
|
369
296
|
contentIndex,
|
|
370
297
|
delta: toolDelta.function.arguments,
|
|
371
|
-
partial: clone(output),
|
|
298
|
+
partial: (0, protocol_1.clone)(output),
|
|
372
299
|
});
|
|
373
300
|
}
|
|
374
301
|
}
|
|
375
302
|
}
|
|
376
303
|
}
|
|
377
304
|
emitFinalBlockEvents(stream, output, toolIndexMap, textIndex, thinkingIndex);
|
|
378
|
-
calculateUsageCost(model, output.usage);
|
|
379
|
-
stream.push({ type: 'done', reason: doneReason, message: clone(output) });
|
|
305
|
+
(0, protocol_1.calculateUsageCost)(model, output.usage);
|
|
306
|
+
stream.push({ type: 'done', reason: doneReason, message: (0, protocol_1.clone)(output) });
|
|
380
307
|
stream.end(output);
|
|
381
308
|
}
|
|
382
309
|
catch (error) {
|
|
383
310
|
emitFinalBlockEvents(stream, output, toolIndexMap, textIndex, thinkingIndex);
|
|
384
311
|
output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
|
|
385
312
|
output.errorMessage = error instanceof Error ? error.message : String(error);
|
|
386
|
-
calculateUsageCost(model, output.usage);
|
|
313
|
+
(0, protocol_1.calculateUsageCost)(model, output.usage);
|
|
387
314
|
stream.push({
|
|
388
315
|
type: 'error',
|
|
389
316
|
reason: output.stopReason === 'aborted' ? 'aborted' : 'error',
|
|
390
|
-
error: clone(output),
|
|
317
|
+
error: (0, protocol_1.clone)(output),
|
|
391
318
|
});
|
|
392
319
|
stream.end(output);
|
|
393
320
|
}
|
|
@@ -497,34 +424,6 @@ function toOpenAIMessage(message, compat) {
|
|
|
497
424
|
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
498
425
|
};
|
|
499
426
|
}
|
|
500
|
-
function createAssistantMessage(model) {
|
|
501
|
-
return {
|
|
502
|
-
role: 'assistant',
|
|
503
|
-
api: model.api,
|
|
504
|
-
provider: model.provider,
|
|
505
|
-
model: model.id,
|
|
506
|
-
content: [],
|
|
507
|
-
usage: {
|
|
508
|
-
input: 0,
|
|
509
|
-
output: 0,
|
|
510
|
-
reasoning: 0,
|
|
511
|
-
cacheRead: 0,
|
|
512
|
-
cacheWrite: 0,
|
|
513
|
-
totalTokens: 0,
|
|
514
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
515
|
-
},
|
|
516
|
-
stopReason: 'stop',
|
|
517
|
-
timestamp: Date.now(),
|
|
518
|
-
};
|
|
519
|
-
}
|
|
520
|
-
function calculateUsageCost(model, usage) {
|
|
521
|
-
usage.cost.input = ((model.cost?.input ?? 0) / 1_000_000) * usage.input;
|
|
522
|
-
usage.cost.output = ((model.cost?.output ?? 0) / 1_000_000) * usage.output;
|
|
523
|
-
usage.cost.cacheRead = ((model.cost?.cacheRead ?? 0) / 1_000_000) * usage.cacheRead;
|
|
524
|
-
usage.cost.cacheWrite = ((model.cost?.cacheWrite ?? 0) / 1_000_000) * usage.cacheWrite;
|
|
525
|
-
usage.cost.total =
|
|
526
|
-
usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
527
|
-
}
|
|
528
427
|
function applyUsage(usage, model, payload) {
|
|
529
428
|
const cachedTokens = payload.prompt_tokens_details?.cached_tokens ?? 0;
|
|
530
429
|
const reasoningTokens = payload.completion_tokens_details?.reasoning_tokens ?? 0;
|
|
@@ -534,7 +433,7 @@ function applyUsage(usage, model, payload) {
|
|
|
534
433
|
usage.cacheRead = cachedTokens;
|
|
535
434
|
usage.cacheWrite = 0;
|
|
536
435
|
usage.totalTokens = payload.total_tokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
|
|
537
|
-
calculateUsageCost(model, usage);
|
|
436
|
+
(0, protocol_1.calculateUsageCost)(model, usage);
|
|
538
437
|
}
|
|
539
438
|
function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinkingIndex) {
|
|
540
439
|
const textBlock = textIndex !== undefined ? message.content[textIndex] : undefined;
|
|
@@ -543,7 +442,7 @@ function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinking
|
|
|
543
442
|
type: 'text_end',
|
|
544
443
|
contentIndex: textIndex,
|
|
545
444
|
content: textBlock.text,
|
|
546
|
-
partial: clone(message),
|
|
445
|
+
partial: (0, protocol_1.clone)(message),
|
|
547
446
|
});
|
|
548
447
|
}
|
|
549
448
|
const thinkingBlock = thinkingIndex !== undefined ? message.content[thinkingIndex] : undefined;
|
|
@@ -552,7 +451,7 @@ function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinking
|
|
|
552
451
|
type: 'thinking_end',
|
|
553
452
|
contentIndex: thinkingIndex,
|
|
554
453
|
content: thinkingBlock.thinking,
|
|
555
|
-
partial: clone(message),
|
|
454
|
+
partial: (0, protocol_1.clone)(message),
|
|
556
455
|
});
|
|
557
456
|
}
|
|
558
457
|
for (const contentIndex of toolIndexMap.values()) {
|
|
@@ -560,86 +459,15 @@ function emitFinalBlockEvents(stream, message, toolIndexMap, textIndex, thinking
|
|
|
560
459
|
if (!toolCall) {
|
|
561
460
|
continue;
|
|
562
461
|
}
|
|
563
|
-
toolCall.arguments = parsePartialJson(toolCall.rawArguments ?? '');
|
|
462
|
+
toolCall.arguments = (0, protocol_1.parsePartialJson)(toolCall.rawArguments ?? '');
|
|
564
463
|
stream.push({
|
|
565
464
|
type: 'toolcall_end',
|
|
566
465
|
contentIndex,
|
|
567
|
-
toolCall: clone(toolCall),
|
|
568
|
-
partial: clone(message),
|
|
466
|
+
toolCall: (0, protocol_1.clone)(toolCall),
|
|
467
|
+
partial: (0, protocol_1.clone)(message),
|
|
569
468
|
});
|
|
570
469
|
}
|
|
571
470
|
}
|
|
572
|
-
function normalizeBaseUrl(baseUrl) {
|
|
573
|
-
const trimmed = baseUrl.replace(/\/+$/, '');
|
|
574
|
-
if (/\/v\d+$/.test(trimmed)) {
|
|
575
|
-
return trimmed;
|
|
576
|
-
}
|
|
577
|
-
return `${trimmed}/v1`;
|
|
578
|
-
}
|
|
579
|
-
function parsePartialJson(raw) {
|
|
580
|
-
const trimmed = raw.trim();
|
|
581
|
-
if (!trimmed) {
|
|
582
|
-
return {};
|
|
583
|
-
}
|
|
584
|
-
try {
|
|
585
|
-
return JSON.parse(trimmed);
|
|
586
|
-
}
|
|
587
|
-
catch {
|
|
588
|
-
// continue
|
|
589
|
-
}
|
|
590
|
-
const completed = completePartialJson(trimmed);
|
|
591
|
-
if (!completed) {
|
|
592
|
-
return {};
|
|
593
|
-
}
|
|
594
|
-
try {
|
|
595
|
-
return JSON.parse(completed);
|
|
596
|
-
}
|
|
597
|
-
catch {
|
|
598
|
-
return {};
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
function completePartialJson(input) {
|
|
602
|
-
let output = input;
|
|
603
|
-
let inString = false;
|
|
604
|
-
let escaping = false;
|
|
605
|
-
const stack = [];
|
|
606
|
-
for (const char of input) {
|
|
607
|
-
if (escaping) {
|
|
608
|
-
escaping = false;
|
|
609
|
-
continue;
|
|
610
|
-
}
|
|
611
|
-
if (char === '\\') {
|
|
612
|
-
escaping = true;
|
|
613
|
-
continue;
|
|
614
|
-
}
|
|
615
|
-
if (char === '"') {
|
|
616
|
-
inString = !inString;
|
|
617
|
-
continue;
|
|
618
|
-
}
|
|
619
|
-
if (inString) {
|
|
620
|
-
continue;
|
|
621
|
-
}
|
|
622
|
-
if (char === '{') {
|
|
623
|
-
stack.push('}');
|
|
624
|
-
}
|
|
625
|
-
else if (char === '[') {
|
|
626
|
-
stack.push(']');
|
|
627
|
-
}
|
|
628
|
-
else if (char === '}' || char === ']') {
|
|
629
|
-
stack.pop();
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
if (inString) {
|
|
633
|
-
output += '"';
|
|
634
|
-
}
|
|
635
|
-
while (stack.length > 0) {
|
|
636
|
-
output += stack.pop();
|
|
637
|
-
}
|
|
638
|
-
return output;
|
|
639
|
-
}
|
|
640
|
-
function clone(value) {
|
|
641
|
-
return JSON.parse(JSON.stringify(value));
|
|
642
|
-
}
|
|
643
471
|
function firstNonEmpty(...values) {
|
|
644
472
|
return values.find((value) => typeof value === 'string' && value.length > 0);
|
|
645
473
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentic-kit/openai",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.2",
|
|
4
4
|
"author": "Dan Lynch <pyramation@gmail.com>",
|
|
5
5
|
"description": "OpenAI (and OpenAI-compatible) adapter for agentic-kit",
|
|
6
6
|
"main": "index.js",
|
|
@@ -39,6 +39,9 @@
|
|
|
39
39
|
"test:live:smoke": "node ./scripts/run-live-tests.js smoke",
|
|
40
40
|
"test:live:extended": "node ./scripts/run-live-tests.js extended"
|
|
41
41
|
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@agentic-kit/protocol": "1.1.0"
|
|
44
|
+
},
|
|
42
45
|
"keywords": [],
|
|
43
|
-
"gitHead": "
|
|
46
|
+
"gitHead": "fbf34d1146e8543664d904f75e5b3440f2b1d2a4"
|
|
44
47
|
}
|