@namzu/openai 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +44 -0
- package/dist/__tests__/error-taxonomy.test.d.ts +14 -0
- package/dist/__tests__/error-taxonomy.test.d.ts.map +1 -0
- package/dist/__tests__/error-taxonomy.test.js +203 -0
- package/dist/__tests__/error-taxonomy.test.js.map +1 -0
- package/dist/__tests__/openai.test.js +47 -0
- package/dist/__tests__/openai.test.js.map +1 -1
- package/dist/client.d.ts +10 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +117 -61
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -7
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/__tests__/error-taxonomy.test.ts +234 -0
- package/src/__tests__/openai.test.ts +54 -0
- package/src/client.ts +123 -66
- package/src/index.ts +3 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,49 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 3fd2524: Normalize request-start and mid-stream failures across all seven provider
|
|
8
|
+
drivers with the new public `ProviderRequestError` taxonomy. Errors expose
|
|
9
|
+
`kind` (`throttle`, `network`, `auth`, `context_overflow`, `bad_request`, or
|
|
10
|
+
`server`), `providerId`, and optional `status` / `retryAfterMs`, with
|
|
11
|
+
`isProviderRequestError` available for structural narrowing across package
|
|
12
|
+
copies.
|
|
13
|
+
|
|
14
|
+
Provider error messages and metadata deliberately omit vendor response bodies,
|
|
15
|
+
URLs, messages, and causes because upstream errors can echo credentials. HTTP
|
|
16
|
+
dialect-mismatch diagnostics now keep only the endpoint origin and status.
|
|
17
|
+
Caller-owned aborts remain unchanged instead of being reclassified.
|
|
18
|
+
|
|
19
|
+
The runtime preserves the classified error through streaming and publishes its
|
|
20
|
+
safe metadata as `Run.lastProviderError` and
|
|
21
|
+
`run_failed.providerError`. Bedrock stream-exception events and provider
|
|
22
|
+
iterator/SSE failures no longer appear as clean end-of-stream.
|
|
23
|
+
|
|
24
|
+
`retryAfterMs` is metadata only; this change does not add retries or alter vendor
|
|
25
|
+
SDK retry settings. Provider packages now require `@namzu/sdk >=1.3.0`, the
|
|
26
|
+
first SDK release containing these runtime helpers and types.
|
|
27
|
+
|
|
28
|
+
Ollama now maps `done_reason: "length"` truthfully so runtime continuation can
|
|
29
|
+
run. LM Studio treats content-free `contextLengthReached` as context overflow,
|
|
30
|
+
while preserving `"length"` after partial content, and creates its WebSocket
|
|
31
|
+
client lazily on first use.
|
|
32
|
+
|
|
33
|
+
## 1.0.2
|
|
34
|
+
|
|
35
|
+
### Patch Changes
|
|
36
|
+
|
|
37
|
+
- f1f000c: Map user-message image attachments to OpenAI `image_url` content parts.
|
|
38
|
+
|
|
39
|
+
`toOpenAIMessages` now converts `UserMessage.attachments` into
|
|
40
|
+
multimodal content parts (text first, then each image as an
|
|
41
|
+
`image_url` part carrying a `data:<mediaType>;base64,<data>` URI),
|
|
42
|
+
mirroring the Anthropic driver's image-block mapping. Previously
|
|
43
|
+
attachments were silently dropped. The driver declares
|
|
44
|
+
`supportsVision: true` and exposes its capabilities on the provider
|
|
45
|
+
instance for the SDK's capability negotiation.
|
|
46
|
+
|
|
3
47
|
## 1.0.1
|
|
4
48
|
|
|
5
49
|
### Patch Changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider error taxonomy — OpenAI driver.
|
|
3
|
+
*
|
|
4
|
+
* Like the Anthropic driver, this one lets the vendor SDK's own error type
|
|
5
|
+
* escape verbatim (`RateLimitError`, `BadRequestError`, …). Those carry a
|
|
6
|
+
* status but are vendor classes, so no caller can classify them without
|
|
7
|
+
* importing `openai` — and their `message` interpolates the response body.
|
|
8
|
+
*
|
|
9
|
+
* Transport seam: `OpenAIConfig.baseURL` — a loopback server answering
|
|
10
|
+
* with a scripted status/headers/body, so the REAL vendor client runs
|
|
11
|
+
* (including its internal retries, which this group must not disturb).
|
|
12
|
+
*/
|
|
13
|
+
export {};
|
|
14
|
+
//# sourceMappingURL=error-taxonomy.test.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-taxonomy.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/error-taxonomy.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG"}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider error taxonomy — OpenAI driver.
|
|
3
|
+
*
|
|
4
|
+
* Like the Anthropic driver, this one lets the vendor SDK's own error type
|
|
5
|
+
* escape verbatim (`RateLimitError`, `BadRequestError`, …). Those carry a
|
|
6
|
+
* status but are vendor classes, so no caller can classify them without
|
|
7
|
+
* importing `openai` — and their `message` interpolates the response body.
|
|
8
|
+
*
|
|
9
|
+
* Transport seam: `OpenAIConfig.baseURL` — a loopback server answering
|
|
10
|
+
* with a scripted status/headers/body, so the REAL vendor client runs
|
|
11
|
+
* (including its internal retries, which this group must not disturb).
|
|
12
|
+
*/
|
|
13
|
+
import { createServer } from 'node:http';
|
|
14
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
15
|
+
import { OpenAIProvider } from '../client.js';
|
|
16
|
+
/** Obviously fake, non-functional token — present only as a leak probe. */
|
|
17
|
+
const FAKE_CREDENTIAL = 'sk-ant-FAKE-DO-NOT-USE-0000';
|
|
18
|
+
let server;
|
|
19
|
+
afterEach(async () => {
|
|
20
|
+
if (server) {
|
|
21
|
+
await new Promise((resolve) => server?.close(() => resolve()));
|
|
22
|
+
server = undefined;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
async function startEndpoint(reply) {
|
|
26
|
+
server = createServer((_req, res) => {
|
|
27
|
+
res.writeHead(reply.status, {
|
|
28
|
+
'Content-Type': 'application/json',
|
|
29
|
+
...(reply.headers ?? {}),
|
|
30
|
+
});
|
|
31
|
+
res.end(reply.body);
|
|
32
|
+
});
|
|
33
|
+
await new Promise((resolve) => server?.listen(0, '127.0.0.1', () => resolve()));
|
|
34
|
+
const { port } = server.address();
|
|
35
|
+
return `http://127.0.0.1:${port}/v1`;
|
|
36
|
+
}
|
|
37
|
+
async function captureChatStreamError(reply) {
|
|
38
|
+
const baseURL = await startEndpoint(reply);
|
|
39
|
+
// maxRetries is deliberately NOT set: this group classifies errors and
|
|
40
|
+
// must leave the vendor SDK's own retry behaviour exactly as it is.
|
|
41
|
+
const provider = new OpenAIProvider({
|
|
42
|
+
apiKey: 'test-key',
|
|
43
|
+
model: 'gpt-4o-mini',
|
|
44
|
+
baseURL,
|
|
45
|
+
});
|
|
46
|
+
try {
|
|
47
|
+
for await (const _chunk of provider.chatStream({
|
|
48
|
+
model: 'gpt-4o-mini',
|
|
49
|
+
messages: [{ role: 'user', content: 'hi' }],
|
|
50
|
+
})) {
|
|
51
|
+
// drain
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
return err;
|
|
56
|
+
}
|
|
57
|
+
throw new Error('expected chatStream to throw');
|
|
58
|
+
}
|
|
59
|
+
async function captureProviderError(provider, signal) {
|
|
60
|
+
try {
|
|
61
|
+
for await (const _chunk of provider.chatStream({
|
|
62
|
+
model: 'gpt-4o-mini',
|
|
63
|
+
messages: [{ role: 'user', content: 'hi' }],
|
|
64
|
+
signal,
|
|
65
|
+
})) {
|
|
66
|
+
// drain
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
return err;
|
|
71
|
+
}
|
|
72
|
+
throw new Error('expected chatStream to throw');
|
|
73
|
+
}
|
|
74
|
+
describe('@namzu/openai — provider error taxonomy', () => {
|
|
75
|
+
it('(a) 429 with `retry-after: 2` throws a throttle-classified error carrying retryAfterMs', async () => {
|
|
76
|
+
const err = await captureChatStreamError({
|
|
77
|
+
status: 429,
|
|
78
|
+
headers: { 'retry-after': '2' },
|
|
79
|
+
body: JSON.stringify({
|
|
80
|
+
error: { message: 'Rate limit reached', type: 'rate_limit_error' },
|
|
81
|
+
}),
|
|
82
|
+
});
|
|
83
|
+
expect(err).toMatchObject({
|
|
84
|
+
name: 'ProviderRequestError',
|
|
85
|
+
kind: 'throttle',
|
|
86
|
+
status: 429,
|
|
87
|
+
retryAfterMs: 2000,
|
|
88
|
+
providerId: 'openai',
|
|
89
|
+
});
|
|
90
|
+
}, 60_000);
|
|
91
|
+
it("(c) 400 whose body reports a context-length overflow classifies as 'context_overflow'", async () => {
|
|
92
|
+
const err = await captureChatStreamError({
|
|
93
|
+
status: 400,
|
|
94
|
+
body: JSON.stringify({
|
|
95
|
+
error: {
|
|
96
|
+
message: "This model's maximum context length is 128000 tokens. However, your messages resulted in 190210 tokens.",
|
|
97
|
+
type: 'invalid_request_error',
|
|
98
|
+
code: 'context_length_exceeded',
|
|
99
|
+
},
|
|
100
|
+
}),
|
|
101
|
+
});
|
|
102
|
+
expect(err).toMatchObject({
|
|
103
|
+
name: 'ProviderRequestError',
|
|
104
|
+
kind: 'context_overflow',
|
|
105
|
+
status: 400,
|
|
106
|
+
providerId: 'openai',
|
|
107
|
+
});
|
|
108
|
+
}, 30_000);
|
|
109
|
+
it("(c) 400 that is not an overflow classifies as 'bad_request'", async () => {
|
|
110
|
+
const err = await captureChatStreamError({
|
|
111
|
+
status: 400,
|
|
112
|
+
body: JSON.stringify({
|
|
113
|
+
error: {
|
|
114
|
+
message: "Unrecognized request argument: 'temperture'",
|
|
115
|
+
type: 'invalid_request_error',
|
|
116
|
+
},
|
|
117
|
+
}),
|
|
118
|
+
});
|
|
119
|
+
expect(err).toMatchObject({
|
|
120
|
+
name: 'ProviderRequestError',
|
|
121
|
+
kind: 'bad_request',
|
|
122
|
+
status: 400,
|
|
123
|
+
providerId: 'openai',
|
|
124
|
+
});
|
|
125
|
+
}, 30_000);
|
|
126
|
+
it("(auth) 401 classifies as 'auth'", async () => {
|
|
127
|
+
const err = await captureChatStreamError({
|
|
128
|
+
status: 401,
|
|
129
|
+
body: JSON.stringify({
|
|
130
|
+
error: {
|
|
131
|
+
message: 'Incorrect API key provided',
|
|
132
|
+
type: 'invalid_request_error',
|
|
133
|
+
},
|
|
134
|
+
}),
|
|
135
|
+
});
|
|
136
|
+
expect(err).toMatchObject({
|
|
137
|
+
name: 'ProviderRequestError',
|
|
138
|
+
kind: 'auth',
|
|
139
|
+
status: 401,
|
|
140
|
+
providerId: 'openai',
|
|
141
|
+
});
|
|
142
|
+
}, 30_000);
|
|
143
|
+
it('(d) SECURITY: a credential echoed back in a 401 body never reaches the thrown message', async () => {
|
|
144
|
+
const err = await captureChatStreamError({
|
|
145
|
+
status: 401,
|
|
146
|
+
body: JSON.stringify({
|
|
147
|
+
error: { message: `Incorrect API key provided: ${FAKE_CREDENTIAL}` },
|
|
148
|
+
}),
|
|
149
|
+
});
|
|
150
|
+
expect(err.message).not.toContain(FAKE_CREDENTIAL);
|
|
151
|
+
expect(JSON.stringify(err)).not.toContain(FAKE_CREDENTIAL);
|
|
152
|
+
expect('cause' in err).toBe(false);
|
|
153
|
+
}, 30_000);
|
|
154
|
+
it('classifies and sanitizes an SDK failure thrown after streaming began', async () => {
|
|
155
|
+
const vendor = Object.assign(new Error(`overloaded_error ${FAKE_CREDENTIAL}`), {
|
|
156
|
+
name: 'APIError',
|
|
157
|
+
});
|
|
158
|
+
const provider = new OpenAIProvider({
|
|
159
|
+
apiKey: 'test-key',
|
|
160
|
+
model: 'gpt-4o-mini',
|
|
161
|
+
});
|
|
162
|
+
const stream = {
|
|
163
|
+
async *[Symbol.asyncIterator]() {
|
|
164
|
+
yield {
|
|
165
|
+
id: 'chatcmpl-1',
|
|
166
|
+
choices: [{ delta: { content: 'partial' }, finish_reason: null }],
|
|
167
|
+
usage: null,
|
|
168
|
+
};
|
|
169
|
+
throw vendor;
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
provider.client = {
|
|
173
|
+
chat: { completions: { create: async () => stream } },
|
|
174
|
+
};
|
|
175
|
+
const err = await captureProviderError(provider);
|
|
176
|
+
expect(err).toMatchObject({
|
|
177
|
+
name: 'ProviderRequestError',
|
|
178
|
+
kind: 'server',
|
|
179
|
+
providerId: 'openai',
|
|
180
|
+
});
|
|
181
|
+
expect(err.message).not.toContain(FAKE_CREDENTIAL);
|
|
182
|
+
expect('cause' in err).toBe(false);
|
|
183
|
+
});
|
|
184
|
+
it('preserves the caller abort reason when the SDK replaces the error object', async () => {
|
|
185
|
+
const controller = new AbortController();
|
|
186
|
+
const reason = new Error('user stopped');
|
|
187
|
+
const sdkAbort = Object.assign(new Error('request aborted'), {
|
|
188
|
+
name: 'APIUserAbortError',
|
|
189
|
+
});
|
|
190
|
+
controller.abort(reason);
|
|
191
|
+
const provider = new OpenAIProvider({
|
|
192
|
+
apiKey: 'test-key',
|
|
193
|
+
model: 'gpt-4o-mini',
|
|
194
|
+
});
|
|
195
|
+
provider.client = {
|
|
196
|
+
chat: { completions: { create: async () => Promise.reject(sdkAbort) } },
|
|
197
|
+
};
|
|
198
|
+
const err = await captureProviderError(provider, controller.signal);
|
|
199
|
+
expect(sdkAbort).not.toBe(reason);
|
|
200
|
+
expect(err).toBe(reason);
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
//# sourceMappingURL=error-taxonomy.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-taxonomy.test.js","sourceRoot":"","sources":["../../src/__tests__/error-taxonomy.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAe,YAAY,EAAE,MAAM,WAAW,CAAA;AAErD,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAA;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAE7C,2EAA2E;AAC3E,MAAM,eAAe,G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K,EAAE,aAAa;SACpB,CAAC,CACD;QAAC,QAA2C,CAAC,MAAM,GAAG;YACtD,IAAI,EAAE,EAAE,WAAW,EAAE,EAAE,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,EAAE;SACvE,CAAA;QAED,MAAM,GAAG,GAAG,MAAM,oBAAoB,CAAC,QAAQ,EAAE,UAAU,CAAC,MAAM,CAAC,CAAA;QAEnE,MAAM,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;QACjC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IACzB,CAAC,CAAC,CAAA;AACH,CAAC,CAAC,CAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { DuplicateProviderError, ProviderRegistry } from '@namzu/sdk';
|
|
2
2
|
import { beforeEach, describe, expect, it } from 'vitest';
|
|
3
|
+
import { toOpenAIMessages } from '../client.js';
|
|
3
4
|
import { OPENAI_CAPABILITIES, OpenAIProvider, registerOpenAI } from '../index.js';
|
|
4
5
|
// Ensure a clean slate between tests. The sdk pre-registers 'mock' on import
|
|
5
6
|
// via its sideEffects whitelist; we only need to clear 'openai' to make
|
|
@@ -38,8 +39,13 @@ describe('@namzu/openai', () => {
|
|
|
38
39
|
supportsTools: true,
|
|
39
40
|
supportsStreaming: true,
|
|
40
41
|
supportsFunctionCalling: true,
|
|
42
|
+
supportsVision: true,
|
|
41
43
|
});
|
|
42
44
|
});
|
|
45
|
+
it('is exposed on the provider instance for runtime negotiation', () => {
|
|
46
|
+
const provider = new OpenAIProvider({ apiKey: 'test-key' });
|
|
47
|
+
expect(provider.capabilities).toEqual(OPENAI_CAPABILITIES);
|
|
48
|
+
});
|
|
43
49
|
});
|
|
44
50
|
describe('ProviderRegistry.create({ type: "openai", ... })', () => {
|
|
45
51
|
it('narrows the config type via module augmentation and instantiates OpenAIProvider', () => {
|
|
@@ -60,5 +66,46 @@ describe('@namzu/openai', () => {
|
|
|
60
66
|
})).toThrowError(/API key is required/);
|
|
61
67
|
});
|
|
62
68
|
});
|
|
69
|
+
describe('toOpenAIMessages image attachments', () => {
|
|
70
|
+
it('maps user-message attachments to image_url content parts with base64 data URIs', () => {
|
|
71
|
+
const messages = [
|
|
72
|
+
{
|
|
73
|
+
role: 'user',
|
|
74
|
+
content: 'what is in this image?',
|
|
75
|
+
attachments: [
|
|
76
|
+
{ data: 'aGVsbG8=', mediaType: 'image/png' },
|
|
77
|
+
{ data: 'd29ybGQ=', mediaType: 'image/jpeg' },
|
|
78
|
+
],
|
|
79
|
+
},
|
|
80
|
+
];
|
|
81
|
+
const [mapped] = toOpenAIMessages(messages);
|
|
82
|
+
expect(mapped).toEqual({
|
|
83
|
+
role: 'user',
|
|
84
|
+
content: [
|
|
85
|
+
{ type: 'text', text: 'what is in this image?' },
|
|
86
|
+
{ type: 'image_url', image_url: { url: 'data:image/png;base64,aGVsbG8=' } },
|
|
87
|
+
{ type: 'image_url', image_url: { url: 'data:image/jpeg;base64,d29ybGQ=' } },
|
|
88
|
+
],
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
it('omits the text part when the user message is empty but keeps the images', () => {
|
|
92
|
+
const messages = [
|
|
93
|
+
{
|
|
94
|
+
role: 'user',
|
|
95
|
+
content: '',
|
|
96
|
+
attachments: [{ data: 'aGVsbG8=', mediaType: 'image/webp' }],
|
|
97
|
+
},
|
|
98
|
+
];
|
|
99
|
+
const [mapped] = toOpenAIMessages(messages);
|
|
100
|
+
expect(mapped).toEqual({
|
|
101
|
+
role: 'user',
|
|
102
|
+
content: [{ type: 'image_url', image_url: { url: 'data:image/webp;base64,aGVsbG8=' } }],
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
it('keeps plain text-only user messages in string form (no content parts)', () => {
|
|
106
|
+
const messages = [{ role: 'user', content: 'hello' }];
|
|
107
|
+
expect(toOpenAIMessages(messages)).toEqual([{ role: 'user', content: 'hello' }]);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
63
110
|
});
|
|
64
111
|
//# sourceMappingURL=openai.test.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai.test.js","sourceRoot":"","sources":["../../src/__tests__/openai.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;
|
|
1
|
+
{"version":3,"file":"openai.test.js","sourceRoot":"","sources":["../../src/__tests__/openai.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAErE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAA;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAA;AAC/C,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEjF,6EAA6E;AAC7E,wEAAwE;AACxE,8CAA8C;AAC9C,UAAU,CAAC,GAAG,EAAE;IACf,IAAI,gBAAgB,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5C,gBAAgB,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;IACtC,CAAC;AACF,CAAC,CAAC,CAAA;AAEF,QAAQ,CAAC,eAAe,EAAE,GAAG,EAAE;IAC9B,QAAQ,CAAC,kBAAkB,EAAE,GAAG,EAAE;QACjC,EAAE,CAAC,uCAAuC,EAAE,GAAG,EAAE;YAChD,MAAM,CAAC,gBAAgB,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;YAC1D,cAAc,EAAE,CAAA;YAChB,MAAM,CAAC,gBAAgB,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;YACzD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AI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC,CAAA;QACjF,CAAC,CAAC,CAAA;IACH,CAAC,CAAC,CAAA;AACH,CAAC,CAAC,CAAA"}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
|
-
import type { ChatCompletionParams, LLMProvider, ModelInfo, StreamChunk } from '@namzu/sdk';
|
|
1
|
+
import type { ChatCompletionParams, LLMProvider, ModelInfo, ProviderCapabilities, StreamChunk } from '@namzu/sdk';
|
|
2
|
+
import type { ChatCompletionMessageParam } from 'openai/resources/chat/completions';
|
|
2
3
|
import type { OpenAIConfig } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* Full capability set — this driver maps tools (`toOpenAITools`), streams
|
|
6
|
+
* natively, and maps user-message image `attachments` into `image_url`
|
|
7
|
+
* content parts with base64 data URIs (`toOpenAIMessages`).
|
|
8
|
+
*/
|
|
9
|
+
export declare const OPENAI_CAPABILITIES: ProviderCapabilities;
|
|
10
|
+
export declare function toOpenAIMessages(messages: ChatCompletionParams['messages']): ChatCompletionMessageParam[];
|
|
3
11
|
export declare class OpenAIProvider implements LLMProvider {
|
|
4
12
|
readonly id = "openai";
|
|
5
13
|
readonly name = "OpenAI";
|
|
14
|
+
readonly capabilities: ProviderCapabilities;
|
|
6
15
|
private client;
|
|
7
16
|
private defaultModel?;
|
|
8
17
|
constructor(config: OpenAIConfig);
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,oBAAoB,EAEpB,WAAW,EACX,SAAS,EACT,WAAW,EAGX,MAAM,YAAY,CAAA;
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,oBAAoB,EAEpB,WAAW,EACX,SAAS,EACT,oBAAoB,EACpB,WAAW,EAGX,MAAM,YAAY,CAAA;AAQnB,OAAO,KAAK,EAEX,0BAA0B,EAG1B,MAAM,mCAAmC,CAAA;AAC1C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE9C;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,EAAE,oBAKjC,CAAA;AAyDD,wBAAgB,gBAAgB,CAC/B,QAAQ,EAAE,oBAAoB,CAAC,UAAU,CAAC,GACxC,0BAA0B,EAAE,CAiD9B;AAcD,qBAAa,cAAe,YAAW,WAAW;IACjD,QAAQ,CAAC,EAAE,YAAW;IACtB,QAAQ,CAAC,IAAI,YAAW;IACxB,QAAQ,CAAC,YAAY,uBAAsB;IAE3C,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,YAAY,CAAC,CAAQ;gBAEjB,MAAM,EAAE,YAAY;IAkBhC,OAAO,CAAC,YAAY;IAUb,UAAU,CAAC,MAAM,EAAE,oBAAoB,GAAG,aAAa,CAAC,WAAW,CAAC;IA4FrE,UAAU,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAclC,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAQrC"}
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
|
+
import { ProviderRequestError, isCallerAbortError, isProviderRequestError, providerVendorError, } from '@namzu/sdk';
|
|
1
2
|
import OpenAI from 'openai';
|
|
3
|
+
/**
|
|
4
|
+
* Full capability set — this driver maps tools (`toOpenAITools`), streams
|
|
5
|
+
* natively, and maps user-message image `attachments` into `image_url`
|
|
6
|
+
* content parts with base64 data URIs (`toOpenAIMessages`).
|
|
7
|
+
*/
|
|
8
|
+
export const OPENAI_CAPABILITIES = {
|
|
9
|
+
supportsTools: true,
|
|
10
|
+
supportsStreaming: true,
|
|
11
|
+
supportsFunctionCalling: true,
|
|
12
|
+
supportsVision: true,
|
|
13
|
+
};
|
|
2
14
|
function mapFinishReason(reason) {
|
|
3
15
|
switch (reason) {
|
|
4
16
|
case 'length':
|
|
@@ -42,12 +54,29 @@ function formatToolChoice(tc) {
|
|
|
42
54
|
}
|
|
43
55
|
return undefined;
|
|
44
56
|
}
|
|
45
|
-
function toOpenAIMessages(messages) {
|
|
57
|
+
export function toOpenAIMessages(messages) {
|
|
46
58
|
return messages.map((msg) => {
|
|
47
59
|
if (msg.role === 'system') {
|
|
48
60
|
return { role: 'system', content: msg.content };
|
|
49
61
|
}
|
|
50
62
|
if (msg.role === 'user') {
|
|
63
|
+
// User message with image attachments → multimodal content parts
|
|
64
|
+
// (text first, then each image as an `image_url` part carrying a
|
|
65
|
+
// base64 data URI). Mirrors the Anthropic driver's image-block
|
|
66
|
+
// mapping; plain text-only user messages keep the string form.
|
|
67
|
+
if (msg.attachments && msg.attachments.length > 0) {
|
|
68
|
+
const parts = [];
|
|
69
|
+
if (msg.content.length > 0) {
|
|
70
|
+
parts.push({ type: 'text', text: msg.content });
|
|
71
|
+
}
|
|
72
|
+
for (const att of msg.attachments) {
|
|
73
|
+
parts.push({
|
|
74
|
+
type: 'image_url',
|
|
75
|
+
image_url: { url: `data:${att.mediaType};base64,${att.data}` },
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return { role: 'user', content: parts };
|
|
79
|
+
}
|
|
51
80
|
return { role: 'user', content: msg.content };
|
|
52
81
|
}
|
|
53
82
|
if (msg.role === 'tool') {
|
|
@@ -91,6 +120,7 @@ function toOpenAITools(params) {
|
|
|
91
120
|
export class OpenAIProvider {
|
|
92
121
|
id = 'openai';
|
|
93
122
|
name = 'OpenAI';
|
|
123
|
+
capabilities = OPENAI_CAPABILITIES;
|
|
94
124
|
client;
|
|
95
125
|
defaultModel;
|
|
96
126
|
constructor(config) {
|
|
@@ -122,68 +152,94 @@ export class OpenAIProvider {
|
|
|
122
152
|
}
|
|
123
153
|
async *chatStream(params) {
|
|
124
154
|
const model = this.resolveModel(params);
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
155
|
+
let stream;
|
|
156
|
+
try {
|
|
157
|
+
stream = await this.client.chat.completions.create({
|
|
158
|
+
model,
|
|
159
|
+
messages: toOpenAIMessages(params.messages),
|
|
160
|
+
stream: true,
|
|
161
|
+
stream_options: { include_usage: true },
|
|
162
|
+
tools: toOpenAITools(params),
|
|
163
|
+
tool_choice: formatToolChoice(params.toolChoice),
|
|
164
|
+
parallel_tool_calls: params.parallelToolCalls,
|
|
165
|
+
temperature: params.temperature,
|
|
166
|
+
max_tokens: params.maxTokens,
|
|
167
|
+
top_p: params.topP,
|
|
168
|
+
frequency_penalty: params.frequencyPenalty,
|
|
169
|
+
presence_penalty: params.presencePenalty,
|
|
170
|
+
stop: params.stop,
|
|
171
|
+
response_format: params.responseFormat,
|
|
172
|
+
},
|
|
173
|
+
// Per-request abort: a Stop tears the in-flight SSE request down.
|
|
174
|
+
{ signal: params.signal });
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
// The vendor SDK builds its error message FROM the response body, so a
|
|
178
|
+
// credential the upstream echoed back is already inside `err.message`
|
|
179
|
+
// before this code runs (proven with a planted fake token). Classify from
|
|
180
|
+
// the status and drop the vendor error entirely — no re-throw, no
|
|
181
|
+
// `cause`, because a `cause` is exactly what a structured logger walks.
|
|
182
|
+
if (isCallerAbortError(err, params.signal))
|
|
183
|
+
throw params.signal?.reason ?? err;
|
|
184
|
+
if (isProviderRequestError(err))
|
|
185
|
+
throw err;
|
|
186
|
+
throw providerVendorError({ providerId: 'openai', error: err });
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
for await (const chunk of stream) {
|
|
190
|
+
// Stop pulling promptly on abort; `for await` calls the stream's
|
|
191
|
+
// `.return()` on this throw, releasing the connection.
|
|
192
|
+
params.signal?.throwIfAborted();
|
|
193
|
+
try {
|
|
194
|
+
const choice = chunk.choices[0];
|
|
195
|
+
const delta = choice?.delta;
|
|
196
|
+
const toolCalls = delta?.tool_calls?.map((tc) => ({
|
|
197
|
+
index: tc.index,
|
|
198
|
+
id: tc.id,
|
|
199
|
+
type: tc.type,
|
|
200
|
+
function: tc.function
|
|
201
|
+
? {
|
|
202
|
+
name: tc.function.name,
|
|
203
|
+
arguments: tc.function.arguments,
|
|
204
|
+
}
|
|
205
|
+
: undefined,
|
|
206
|
+
}));
|
|
207
|
+
const hasDelta = (delta?.content !== undefined && delta.content !== null) ||
|
|
208
|
+
(toolCalls && toolCalls.length > 0);
|
|
209
|
+
const finishReason = choice?.finish_reason
|
|
210
|
+
? mapFinishReason(choice.finish_reason)
|
|
211
|
+
: undefined;
|
|
212
|
+
const usage = chunk.usage ? parseUsage(chunk.usage) : undefined;
|
|
213
|
+
if (!hasDelta && !finishReason && !usage)
|
|
214
|
+
continue;
|
|
215
|
+
yield {
|
|
216
|
+
id: chunk.id,
|
|
217
|
+
delta: {
|
|
218
|
+
content: delta?.content ?? undefined,
|
|
219
|
+
toolCalls,
|
|
220
|
+
},
|
|
221
|
+
finishReason,
|
|
222
|
+
usage,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
catch (parseErr) {
|
|
226
|
+
if (isProviderRequestError(parseErr))
|
|
227
|
+
throw parseErr;
|
|
228
|
+
throw new ProviderRequestError({
|
|
229
|
+
kind: 'server',
|
|
230
|
+
providerId: 'openai',
|
|
231
|
+
detail: 'the provider stream returned malformed data',
|
|
232
|
+
});
|
|
233
|
+
}
|
|
185
234
|
}
|
|
186
235
|
}
|
|
236
|
+
catch (err) {
|
|
237
|
+
if (isCallerAbortError(err, params.signal))
|
|
238
|
+
throw params.signal?.reason ?? err;
|
|
239
|
+
if (isProviderRequestError(err))
|
|
240
|
+
throw err;
|
|
241
|
+
throw providerVendorError({ providerId: 'openai', error: err });
|
|
242
|
+
}
|
|
187
243
|
}
|
|
188
244
|
async listModels() {
|
|
189
245
|
const page = await this.client.models.list();
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAUA,OAAO,EACN,oBAAoB,EACpB,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,GACnB,MAAM,YAAY,CAAA;AACnB,OAAO,MAAM,MAAM,QAAQ,CAAA;AAS3B;;;;GAIG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAyB;IACxD,aAAa,EAAE,IAAI;IACnB,iBAAiB,EAAE,IAAI;IACvB,uBAAuB,EAAE,IAAI;IAC7B,cAAc,EAAE,IAAI;CACpB,CAAA;AAMD,SAAS,eAAe,CAAC,MAA6C;IACrE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,QAAQ;YACZ,OAAO,QAAQ,CAAA;QAChB,KAAK,YAAY,CAAC;QAClB,KAAK,eAAe;YACnB,OAAO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ACb,CAAC;IACF,CAAC;CACD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type RegisterOptions } from '@namzu/sdk';
|
|
2
2
|
import type { OpenAIProviderConfig } from './types.js';
|
|
3
3
|
declare module '@namzu/sdk' {
|
|
4
4
|
interface ProviderConfigRegistry {
|
|
5
5
|
openai: OpenAIProviderConfig;
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
|
-
export declare const OPENAI_CAPABILITIES: ProviderCapabilities;
|
|
9
8
|
/**
|
|
10
9
|
* Register `OpenAIProvider` under the `'openai'` type in `@namzu/sdk`'s
|
|
11
10
|
* `ProviderRegistry`. Call once at app startup before
|
|
@@ -15,6 +14,6 @@ export declare const OPENAI_CAPABILITIES: ProviderCapabilities;
|
|
|
15
14
|
* Pass `{ replace: true }` to override.
|
|
16
15
|
*/
|
|
17
16
|
export declare function registerOpenAI(options?: RegisterOptions): void;
|
|
18
|
-
export { OpenAIProvider } from './client.js';
|
|
17
|
+
export { OPENAI_CAPABILITIES, OpenAIProvider } from './client.js';
|
|
19
18
|
export type { OpenAIConfig, OpenAIProviderConfig } from './types.js';
|
|
20
19
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,eAAe,EAAE,MAAM,YAAY,CAAA;AAEnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA;AAItD,OAAO,QAAQ,YAAY,CAAC;IAC3B,UAAU,sBAAsB;QAC/B,MAAM,EAAE,oBAAoB,CAAA;KAC5B;CACD;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAE9D;AAED,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AACjE,YAAY,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,5 @@
|
|
|
1
1
|
import { ProviderRegistry } from '@namzu/sdk';
|
|
2
|
-
import { OpenAIProvider } from './client.js';
|
|
3
|
-
export const OPENAI_CAPABILITIES = {
|
|
4
|
-
supportsTools: true,
|
|
5
|
-
supportsStreaming: true,
|
|
6
|
-
supportsFunctionCalling: true,
|
|
7
|
-
};
|
|
2
|
+
import { OPENAI_CAPABILITIES, OpenAIProvider } from './client.js';
|
|
8
3
|
/**
|
|
9
4
|
* Register `OpenAIProvider` under the `'openai'` type in `@namzu/sdk`'s
|
|
10
5
|
* `ProviderRegistry`. Call once at app startup before
|
|
@@ -16,5 +11,5 @@ export const OPENAI_CAPABILITIES = {
|
|
|
16
11
|
export function registerOpenAI(options) {
|
|
17
12
|
ProviderRegistry.register('openai', OpenAIProvider, OPENAI_CAPABILITIES, options);
|
|
18
13
|
}
|
|
19
|
-
export { OpenAIProvider } from './client.js';
|
|
14
|
+
export { OPENAI_CAPABILITIES, OpenAIProvider } from './client.js';
|
|
20
15
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAwB,MAAM,YAAY,CAAA;AACnE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAWjE;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAAC,OAAyB;IACvD,gBAAgB,CAAC,QAAQ,CAAC,QAAQ,EAAE,cAAc,EAAE,mBAAmB,EAAE,OAAO,CAAC,CAAA;AAClF,CAAC;AAED,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@namzu/openai",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.3",
|
|
4
4
|
"description": "OpenAI LLM provider for @namzu/sdk via the official `openai` npm SDK. Chat Completions API with streaming + tool-use.",
|
|
5
5
|
"license": "FSL-1.1-MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -37,14 +37,14 @@
|
|
|
37
37
|
"openai": "^6.0.0"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
|
-
"@namzu/sdk": ">=1.
|
|
40
|
+
"@namzu/sdk": ">=1.3.0"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@biomejs/biome": "^1.9.4",
|
|
44
44
|
"@types/node": "^22.19.17",
|
|
45
45
|
"typescript": "^5.5.0",
|
|
46
46
|
"vitest": "^2.0.0",
|
|
47
|
-
"@namzu/sdk": "^1.
|
|
47
|
+
"@namzu/sdk": "^1.4.0"
|
|
48
48
|
},
|
|
49
49
|
"scripts": {
|
|
50
50
|
"build": "tsc --build",
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider error taxonomy — OpenAI driver.
|
|
3
|
+
*
|
|
4
|
+
* Like the Anthropic driver, this one lets the vendor SDK's own error type
|
|
5
|
+
* escape verbatim (`RateLimitError`, `BadRequestError`, …). Those carry a
|
|
6
|
+
* status but are vendor classes, so no caller can classify them without
|
|
7
|
+
* importing `openai` — and their `message` interpolates the response body.
|
|
8
|
+
*
|
|
9
|
+
* Transport seam: `OpenAIConfig.baseURL` — a loopback server answering
|
|
10
|
+
* with a scripted status/headers/body, so the REAL vendor client runs
|
|
11
|
+
* (including its internal retries, which this group must not disturb).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { type Server, createServer } from 'node:http'
|
|
15
|
+
import type { AddressInfo } from 'node:net'
|
|
16
|
+
import { afterEach, describe, expect, it } from 'vitest'
|
|
17
|
+
import { OpenAIProvider } from '../client.js'
|
|
18
|
+
|
|
19
|
+
/** Obviously fake, non-functional token — present only as a leak probe. */
|
|
20
|
+
const FAKE_CREDENTIAL = 'sk-ant-FAKE-DO-NOT-USE-0000'
|
|
21
|
+
|
|
22
|
+
interface ScriptedReply {
|
|
23
|
+
status: number
|
|
24
|
+
body: string
|
|
25
|
+
headers?: Record<string, string>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
let server: Server | undefined
|
|
29
|
+
|
|
30
|
+
afterEach(async () => {
|
|
31
|
+
if (server) {
|
|
32
|
+
await new Promise<void>((resolve) => server?.close(() => resolve()))
|
|
33
|
+
server = undefined
|
|
34
|
+
}
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
async function startEndpoint(reply: ScriptedReply): Promise<string> {
|
|
38
|
+
server = createServer((_req, res) => {
|
|
39
|
+
res.writeHead(reply.status, {
|
|
40
|
+
'Content-Type': 'application/json',
|
|
41
|
+
...(reply.headers ?? {}),
|
|
42
|
+
})
|
|
43
|
+
res.end(reply.body)
|
|
44
|
+
})
|
|
45
|
+
await new Promise<void>((resolve) => server?.listen(0, '127.0.0.1', () => resolve()))
|
|
46
|
+
const { port } = server.address() as AddressInfo
|
|
47
|
+
return `http://127.0.0.1:${port}/v1`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function captureChatStreamError(reply: ScriptedReply): Promise<unknown> {
|
|
51
|
+
const baseURL = await startEndpoint(reply)
|
|
52
|
+
// maxRetries is deliberately NOT set: this group classifies errors and
|
|
53
|
+
// must leave the vendor SDK's own retry behaviour exactly as it is.
|
|
54
|
+
const provider = new OpenAIProvider({
|
|
55
|
+
apiKey: 'test-key',
|
|
56
|
+
model: 'gpt-4o-mini',
|
|
57
|
+
baseURL,
|
|
58
|
+
})
|
|
59
|
+
try {
|
|
60
|
+
for await (const _chunk of provider.chatStream({
|
|
61
|
+
model: 'gpt-4o-mini',
|
|
62
|
+
messages: [{ role: 'user', content: 'hi' }],
|
|
63
|
+
})) {
|
|
64
|
+
// drain
|
|
65
|
+
}
|
|
66
|
+
} catch (err) {
|
|
67
|
+
return err
|
|
68
|
+
}
|
|
69
|
+
throw new Error('expected chatStream to throw')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function captureProviderError(
|
|
73
|
+
provider: OpenAIProvider,
|
|
74
|
+
signal?: AbortSignal,
|
|
75
|
+
): Promise<unknown> {
|
|
76
|
+
try {
|
|
77
|
+
for await (const _chunk of provider.chatStream({
|
|
78
|
+
model: 'gpt-4o-mini',
|
|
79
|
+
messages: [{ role: 'user', content: 'hi' }],
|
|
80
|
+
signal,
|
|
81
|
+
})) {
|
|
82
|
+
// drain
|
|
83
|
+
}
|
|
84
|
+
} catch (err) {
|
|
85
|
+
return err
|
|
86
|
+
}
|
|
87
|
+
throw new Error('expected chatStream to throw')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
describe('@namzu/openai — provider error taxonomy', () => {
|
|
91
|
+
it('(a) 429 with `retry-after: 2` throws a throttle-classified error carrying retryAfterMs', async () => {
|
|
92
|
+
const err = await captureChatStreamError({
|
|
93
|
+
status: 429,
|
|
94
|
+
headers: { 'retry-after': '2' },
|
|
95
|
+
body: JSON.stringify({
|
|
96
|
+
error: { message: 'Rate limit reached', type: 'rate_limit_error' },
|
|
97
|
+
}),
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
expect(err).toMatchObject({
|
|
101
|
+
name: 'ProviderRequestError',
|
|
102
|
+
kind: 'throttle',
|
|
103
|
+
status: 429,
|
|
104
|
+
retryAfterMs: 2000,
|
|
105
|
+
providerId: 'openai',
|
|
106
|
+
})
|
|
107
|
+
}, 60_000)
|
|
108
|
+
|
|
109
|
+
it("(c) 400 whose body reports a context-length overflow classifies as 'context_overflow'", async () => {
|
|
110
|
+
const err = await captureChatStreamError({
|
|
111
|
+
status: 400,
|
|
112
|
+
body: JSON.stringify({
|
|
113
|
+
error: {
|
|
114
|
+
message:
|
|
115
|
+
"This model's maximum context length is 128000 tokens. However, your messages resulted in 190210 tokens.",
|
|
116
|
+
type: 'invalid_request_error',
|
|
117
|
+
code: 'context_length_exceeded',
|
|
118
|
+
},
|
|
119
|
+
}),
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
expect(err).toMatchObject({
|
|
123
|
+
name: 'ProviderRequestError',
|
|
124
|
+
kind: 'context_overflow',
|
|
125
|
+
status: 400,
|
|
126
|
+
providerId: 'openai',
|
|
127
|
+
})
|
|
128
|
+
}, 30_000)
|
|
129
|
+
|
|
130
|
+
it("(c) 400 that is not an overflow classifies as 'bad_request'", async () => {
|
|
131
|
+
const err = await captureChatStreamError({
|
|
132
|
+
status: 400,
|
|
133
|
+
body: JSON.stringify({
|
|
134
|
+
error: {
|
|
135
|
+
message: "Unrecognized request argument: 'temperture'",
|
|
136
|
+
type: 'invalid_request_error',
|
|
137
|
+
},
|
|
138
|
+
}),
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
expect(err).toMatchObject({
|
|
142
|
+
name: 'ProviderRequestError',
|
|
143
|
+
kind: 'bad_request',
|
|
144
|
+
status: 400,
|
|
145
|
+
providerId: 'openai',
|
|
146
|
+
})
|
|
147
|
+
}, 30_000)
|
|
148
|
+
|
|
149
|
+
it("(auth) 401 classifies as 'auth'", async () => {
|
|
150
|
+
const err = await captureChatStreamError({
|
|
151
|
+
status: 401,
|
|
152
|
+
body: JSON.stringify({
|
|
153
|
+
error: {
|
|
154
|
+
message: 'Incorrect API key provided',
|
|
155
|
+
type: 'invalid_request_error',
|
|
156
|
+
},
|
|
157
|
+
}),
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
expect(err).toMatchObject({
|
|
161
|
+
name: 'ProviderRequestError',
|
|
162
|
+
kind: 'auth',
|
|
163
|
+
status: 401,
|
|
164
|
+
providerId: 'openai',
|
|
165
|
+
})
|
|
166
|
+
}, 30_000)
|
|
167
|
+
|
|
168
|
+
it('(d) SECURITY: a credential echoed back in a 401 body never reaches the thrown message', async () => {
|
|
169
|
+
const err = await captureChatStreamError({
|
|
170
|
+
status: 401,
|
|
171
|
+
body: JSON.stringify({
|
|
172
|
+
error: { message: `Incorrect API key provided: ${FAKE_CREDENTIAL}` },
|
|
173
|
+
}),
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
expect((err as Error).message).not.toContain(FAKE_CREDENTIAL)
|
|
177
|
+
expect(JSON.stringify(err)).not.toContain(FAKE_CREDENTIAL)
|
|
178
|
+
expect('cause' in (err as object)).toBe(false)
|
|
179
|
+
}, 30_000)
|
|
180
|
+
|
|
181
|
+
it('classifies and sanitizes an SDK failure thrown after streaming began', async () => {
|
|
182
|
+
const vendor = Object.assign(new Error(`overloaded_error ${FAKE_CREDENTIAL}`), {
|
|
183
|
+
name: 'APIError',
|
|
184
|
+
})
|
|
185
|
+
const provider = new OpenAIProvider({
|
|
186
|
+
apiKey: 'test-key',
|
|
187
|
+
model: 'gpt-4o-mini',
|
|
188
|
+
})
|
|
189
|
+
const stream = {
|
|
190
|
+
async *[Symbol.asyncIterator]() {
|
|
191
|
+
yield {
|
|
192
|
+
id: 'chatcmpl-1',
|
|
193
|
+
choices: [{ delta: { content: 'partial' }, finish_reason: null }],
|
|
194
|
+
usage: null,
|
|
195
|
+
}
|
|
196
|
+
throw vendor
|
|
197
|
+
},
|
|
198
|
+
}
|
|
199
|
+
;(provider as unknown as { client: unknown }).client = {
|
|
200
|
+
chat: { completions: { create: async () => stream } },
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const err = await captureProviderError(provider)
|
|
204
|
+
|
|
205
|
+
expect(err).toMatchObject({
|
|
206
|
+
name: 'ProviderRequestError',
|
|
207
|
+
kind: 'server',
|
|
208
|
+
providerId: 'openai',
|
|
209
|
+
})
|
|
210
|
+
expect((err as Error).message).not.toContain(FAKE_CREDENTIAL)
|
|
211
|
+
expect('cause' in (err as object)).toBe(false)
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
it('preserves the caller abort reason when the SDK replaces the error object', async () => {
|
|
215
|
+
const controller = new AbortController()
|
|
216
|
+
const reason = new Error('user stopped')
|
|
217
|
+
const sdkAbort = Object.assign(new Error('request aborted'), {
|
|
218
|
+
name: 'APIUserAbortError',
|
|
219
|
+
})
|
|
220
|
+
controller.abort(reason)
|
|
221
|
+
const provider = new OpenAIProvider({
|
|
222
|
+
apiKey: 'test-key',
|
|
223
|
+
model: 'gpt-4o-mini',
|
|
224
|
+
})
|
|
225
|
+
;(provider as unknown as { client: unknown }).client = {
|
|
226
|
+
chat: { completions: { create: async () => Promise.reject(sdkAbort) } },
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const err = await captureProviderError(provider, controller.signal)
|
|
230
|
+
|
|
231
|
+
expect(sdkAbort).not.toBe(reason)
|
|
232
|
+
expect(err).toBe(reason)
|
|
233
|
+
})
|
|
234
|
+
})
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { DuplicateProviderError, ProviderRegistry } from '@namzu/sdk'
|
|
2
|
+
import type { ChatCompletionParams } from '@namzu/sdk'
|
|
2
3
|
import { beforeEach, describe, expect, it } from 'vitest'
|
|
4
|
+
import { toOpenAIMessages } from '../client.js'
|
|
3
5
|
import { OPENAI_CAPABILITIES, OpenAIProvider, registerOpenAI } from '../index.js'
|
|
4
6
|
|
|
5
7
|
// Ensure a clean slate between tests. The sdk pre-registers 'mock' on import
|
|
@@ -44,8 +46,14 @@ describe('@namzu/openai', () => {
|
|
|
44
46
|
supportsTools: true,
|
|
45
47
|
supportsStreaming: true,
|
|
46
48
|
supportsFunctionCalling: true,
|
|
49
|
+
supportsVision: true,
|
|
47
50
|
})
|
|
48
51
|
})
|
|
52
|
+
|
|
53
|
+
it('is exposed on the provider instance for runtime negotiation', () => {
|
|
54
|
+
const provider = new OpenAIProvider({ apiKey: 'test-key' })
|
|
55
|
+
expect(provider.capabilities).toEqual(OPENAI_CAPABILITIES)
|
|
56
|
+
})
|
|
49
57
|
})
|
|
50
58
|
|
|
51
59
|
describe('ProviderRegistry.create({ type: "openai", ... })', () => {
|
|
@@ -70,4 +78,50 @@ describe('@namzu/openai', () => {
|
|
|
70
78
|
).toThrowError(/API key is required/)
|
|
71
79
|
})
|
|
72
80
|
})
|
|
81
|
+
|
|
82
|
+
describe('toOpenAIMessages image attachments', () => {
|
|
83
|
+
it('maps user-message attachments to image_url content parts with base64 data URIs', () => {
|
|
84
|
+
const messages: ChatCompletionParams['messages'] = [
|
|
85
|
+
{
|
|
86
|
+
role: 'user',
|
|
87
|
+
content: 'what is in this image?',
|
|
88
|
+
attachments: [
|
|
89
|
+
{ data: 'aGVsbG8=', mediaType: 'image/png' },
|
|
90
|
+
{ data: 'd29ybGQ=', mediaType: 'image/jpeg' },
|
|
91
|
+
],
|
|
92
|
+
},
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
const [mapped] = toOpenAIMessages(messages)
|
|
96
|
+
expect(mapped).toEqual({
|
|
97
|
+
role: 'user',
|
|
98
|
+
content: [
|
|
99
|
+
{ type: 'text', text: 'what is in this image?' },
|
|
100
|
+
{ type: 'image_url', image_url: { url: 'data:image/png;base64,aGVsbG8=' } },
|
|
101
|
+
{ type: 'image_url', image_url: { url: 'data:image/jpeg;base64,d29ybGQ=' } },
|
|
102
|
+
],
|
|
103
|
+
})
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it('omits the text part when the user message is empty but keeps the images', () => {
|
|
107
|
+
const messages: ChatCompletionParams['messages'] = [
|
|
108
|
+
{
|
|
109
|
+
role: 'user',
|
|
110
|
+
content: '',
|
|
111
|
+
attachments: [{ data: 'aGVsbG8=', mediaType: 'image/webp' }],
|
|
112
|
+
},
|
|
113
|
+
]
|
|
114
|
+
|
|
115
|
+
const [mapped] = toOpenAIMessages(messages)
|
|
116
|
+
expect(mapped).toEqual({
|
|
117
|
+
role: 'user',
|
|
118
|
+
content: [{ type: 'image_url', image_url: { url: 'data:image/webp;base64,aGVsbG8=' } }],
|
|
119
|
+
})
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
it('keeps plain text-only user messages in string form (no content parts)', () => {
|
|
123
|
+
const messages: ChatCompletionParams['messages'] = [{ role: 'user', content: 'hello' }]
|
|
124
|
+
expect(toOpenAIMessages(messages)).toEqual([{ role: 'user', content: 'hello' }])
|
|
125
|
+
})
|
|
126
|
+
})
|
|
73
127
|
})
|
package/src/client.ts
CHANGED
|
@@ -3,18 +3,38 @@ import type {
|
|
|
3
3
|
ChatCompletionResponse,
|
|
4
4
|
LLMProvider,
|
|
5
5
|
ModelInfo,
|
|
6
|
+
ProviderCapabilities,
|
|
6
7
|
StreamChunk,
|
|
7
8
|
TokenUsage,
|
|
8
9
|
ToolChoice,
|
|
9
10
|
} from '@namzu/sdk'
|
|
11
|
+
import {
|
|
12
|
+
ProviderRequestError,
|
|
13
|
+
isCallerAbortError,
|
|
14
|
+
isProviderRequestError,
|
|
15
|
+
providerVendorError,
|
|
16
|
+
} from '@namzu/sdk'
|
|
10
17
|
import OpenAI from 'openai'
|
|
11
18
|
import type {
|
|
19
|
+
ChatCompletionContentPart,
|
|
12
20
|
ChatCompletionMessageParam,
|
|
13
21
|
ChatCompletionTool,
|
|
14
22
|
ChatCompletionToolChoiceOption,
|
|
15
23
|
} from 'openai/resources/chat/completions'
|
|
16
24
|
import type { OpenAIConfig } from './types.js'
|
|
17
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Full capability set — this driver maps tools (`toOpenAITools`), streams
|
|
28
|
+
* natively, and maps user-message image `attachments` into `image_url`
|
|
29
|
+
* content parts with base64 data URIs (`toOpenAIMessages`).
|
|
30
|
+
*/
|
|
31
|
+
export const OPENAI_CAPABILITIES: ProviderCapabilities = {
|
|
32
|
+
supportsTools: true,
|
|
33
|
+
supportsStreaming: true,
|
|
34
|
+
supportsFunctionCalling: true,
|
|
35
|
+
supportsVision: true,
|
|
36
|
+
}
|
|
37
|
+
|
|
18
38
|
type OpenAIFinishReason = 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call'
|
|
19
39
|
|
|
20
40
|
type NamzuFinishReason = ChatCompletionResponse['finishReason']
|
|
@@ -70,7 +90,7 @@ function formatToolChoice(tc: ToolChoice | undefined): ChatCompletionToolChoiceO
|
|
|
70
90
|
return undefined
|
|
71
91
|
}
|
|
72
92
|
|
|
73
|
-
function toOpenAIMessages(
|
|
93
|
+
export function toOpenAIMessages(
|
|
74
94
|
messages: ChatCompletionParams['messages'],
|
|
75
95
|
): ChatCompletionMessageParam[] {
|
|
76
96
|
return messages.map((msg): ChatCompletionMessageParam => {
|
|
@@ -78,6 +98,23 @@ function toOpenAIMessages(
|
|
|
78
98
|
return { role: 'system', content: msg.content }
|
|
79
99
|
}
|
|
80
100
|
if (msg.role === 'user') {
|
|
101
|
+
// User message with image attachments → multimodal content parts
|
|
102
|
+
// (text first, then each image as an `image_url` part carrying a
|
|
103
|
+
// base64 data URI). Mirrors the Anthropic driver's image-block
|
|
104
|
+
// mapping; plain text-only user messages keep the string form.
|
|
105
|
+
if (msg.attachments && msg.attachments.length > 0) {
|
|
106
|
+
const parts: ChatCompletionContentPart[] = []
|
|
107
|
+
if (msg.content.length > 0) {
|
|
108
|
+
parts.push({ type: 'text', text: msg.content })
|
|
109
|
+
}
|
|
110
|
+
for (const att of msg.attachments) {
|
|
111
|
+
parts.push({
|
|
112
|
+
type: 'image_url',
|
|
113
|
+
image_url: { url: `data:${att.mediaType};base64,${att.data}` },
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
return { role: 'user', content: parts }
|
|
117
|
+
}
|
|
81
118
|
return { role: 'user', content: msg.content }
|
|
82
119
|
}
|
|
83
120
|
if (msg.role === 'tool') {
|
|
@@ -121,6 +158,7 @@ function toOpenAITools(params: ChatCompletionParams): ChatCompletionTool[] | und
|
|
|
121
158
|
export class OpenAIProvider implements LLMProvider {
|
|
122
159
|
readonly id = 'openai'
|
|
123
160
|
readonly name = 'OpenAI'
|
|
161
|
+
readonly capabilities = OPENAI_CAPABILITIES
|
|
124
162
|
|
|
125
163
|
private client: OpenAI
|
|
126
164
|
private defaultModel?: string
|
|
@@ -156,73 +194,92 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
156
194
|
async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
|
|
157
195
|
const model = this.resolveModel(params)
|
|
158
196
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
//
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
finishReason
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
197
|
+
let stream: Awaited<ReturnType<typeof this.client.chat.completions.create>>
|
|
198
|
+
try {
|
|
199
|
+
stream = await this.client.chat.completions.create(
|
|
200
|
+
{
|
|
201
|
+
model,
|
|
202
|
+
messages: toOpenAIMessages(params.messages),
|
|
203
|
+
stream: true,
|
|
204
|
+
stream_options: { include_usage: true },
|
|
205
|
+
tools: toOpenAITools(params),
|
|
206
|
+
tool_choice: formatToolChoice(params.toolChoice),
|
|
207
|
+
parallel_tool_calls: params.parallelToolCalls,
|
|
208
|
+
temperature: params.temperature,
|
|
209
|
+
max_tokens: params.maxTokens,
|
|
210
|
+
top_p: params.topP,
|
|
211
|
+
frequency_penalty: params.frequencyPenalty,
|
|
212
|
+
presence_penalty: params.presencePenalty,
|
|
213
|
+
stop: params.stop,
|
|
214
|
+
response_format: params.responseFormat,
|
|
215
|
+
},
|
|
216
|
+
// Per-request abort: a Stop tears the in-flight SSE request down.
|
|
217
|
+
{ signal: params.signal },
|
|
218
|
+
)
|
|
219
|
+
} catch (err) {
|
|
220
|
+
// The vendor SDK builds its error message FROM the response body, so a
|
|
221
|
+
// credential the upstream echoed back is already inside `err.message`
|
|
222
|
+
// before this code runs (proven with a planted fake token). Classify from
|
|
223
|
+
// the status and drop the vendor error entirely — no re-throw, no
|
|
224
|
+
// `cause`, because a `cause` is exactly what a structured logger walks.
|
|
225
|
+
if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
|
|
226
|
+
if (isProviderRequestError(err)) throw err
|
|
227
|
+
throw providerVendorError({ providerId: 'openai', error: err })
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
try {
|
|
231
|
+
for await (const chunk of stream) {
|
|
232
|
+
// Stop pulling promptly on abort; `for await` calls the stream's
|
|
233
|
+
// `.return()` on this throw, releasing the connection.
|
|
234
|
+
params.signal?.throwIfAborted()
|
|
235
|
+
try {
|
|
236
|
+
const choice = chunk.choices[0]
|
|
237
|
+
const delta = choice?.delta
|
|
238
|
+
|
|
239
|
+
const toolCalls = delta?.tool_calls?.map((tc) => ({
|
|
240
|
+
index: tc.index,
|
|
241
|
+
id: tc.id,
|
|
242
|
+
type: tc.type,
|
|
243
|
+
function: tc.function
|
|
244
|
+
? {
|
|
245
|
+
name: tc.function.name,
|
|
246
|
+
arguments: tc.function.arguments,
|
|
247
|
+
}
|
|
248
|
+
: undefined,
|
|
249
|
+
}))
|
|
250
|
+
|
|
251
|
+
const hasDelta =
|
|
252
|
+
(delta?.content !== undefined && delta.content !== null) ||
|
|
253
|
+
(toolCalls && toolCalls.length > 0)
|
|
254
|
+
const finishReason = choice?.finish_reason
|
|
255
|
+
? mapFinishReason(choice.finish_reason)
|
|
256
|
+
: undefined
|
|
257
|
+
const usage = chunk.usage ? parseUsage(chunk.usage) : undefined
|
|
258
|
+
|
|
259
|
+
if (!hasDelta && !finishReason && !usage) continue
|
|
260
|
+
|
|
261
|
+
yield {
|
|
262
|
+
id: chunk.id,
|
|
263
|
+
delta: {
|
|
264
|
+
content: delta?.content ?? undefined,
|
|
265
|
+
toolCalls,
|
|
266
|
+
},
|
|
267
|
+
finishReason,
|
|
268
|
+
usage,
|
|
269
|
+
}
|
|
270
|
+
} catch (parseErr) {
|
|
271
|
+
if (isProviderRequestError(parseErr)) throw parseErr
|
|
272
|
+
throw new ProviderRequestError({
|
|
273
|
+
kind: 'server',
|
|
274
|
+
providerId: 'openai',
|
|
275
|
+
detail: 'the provider stream returned malformed data',
|
|
276
|
+
})
|
|
224
277
|
}
|
|
225
278
|
}
|
|
279
|
+
} catch (err) {
|
|
280
|
+
if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
|
|
281
|
+
if (isProviderRequestError(err)) throw err
|
|
282
|
+
throw providerVendorError({ providerId: 'openai', error: err })
|
|
226
283
|
}
|
|
227
284
|
}
|
|
228
285
|
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { OpenAIProvider } from './client.js'
|
|
1
|
+
import { ProviderRegistry, type RegisterOptions } from '@namzu/sdk'
|
|
2
|
+
import { OPENAI_CAPABILITIES, OpenAIProvider } from './client.js'
|
|
3
3
|
import type { OpenAIProviderConfig } from './types.js'
|
|
4
4
|
|
|
5
5
|
// Module augmentation: register openai's config type in the sdk's registry interface.
|
|
@@ -10,12 +10,6 @@ declare module '@namzu/sdk' {
|
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
export const OPENAI_CAPABILITIES: ProviderCapabilities = {
|
|
14
|
-
supportsTools: true,
|
|
15
|
-
supportsStreaming: true,
|
|
16
|
-
supportsFunctionCalling: true,
|
|
17
|
-
}
|
|
18
|
-
|
|
19
13
|
/**
|
|
20
14
|
* Register `OpenAIProvider` under the `'openai'` type in `@namzu/sdk`'s
|
|
21
15
|
* `ProviderRegistry`. Call once at app startup before
|
|
@@ -28,5 +22,5 @@ export function registerOpenAI(options?: RegisterOptions): void {
|
|
|
28
22
|
ProviderRegistry.register('openai', OpenAIProvider, OPENAI_CAPABILITIES, options)
|
|
29
23
|
}
|
|
30
24
|
|
|
31
|
-
export { OpenAIProvider } from './client.js'
|
|
25
|
+
export { OPENAI_CAPABILITIES, OpenAIProvider } from './client.js'
|
|
32
26
|
export type { OpenAIConfig, OpenAIProviderConfig } from './types.js'
|