@namzu/openai 0.0.1
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 +20 -0
- package/LICENSE.md +110 -0
- package/README.md +82 -0
- package/dist/__tests__/openai.test.d.ts +2 -0
- package/dist/__tests__/openai.test.d.ts.map +1 -0
- package/dist/__tests__/openai.test.js +64 -0
- package/dist/__tests__/openai.test.js.map +1 -0
- package/dist/client.d.ts +15 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +249 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/types.d.ts +27 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +10 -0
- package/dist/types.js.map +1 -0
- package/package.json +66 -0
- package/src/__tests__/openai.test.ts +73 -0
- package/src/client.ts +292 -0
- package/src/index.ts +32 -0
- package/src/types.ts +28 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@namzu/openai` are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.1.0] — 2026-04-15
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Initial release. OpenAI support via the official `openai` npm SDK.
|
|
13
|
+
- `OpenAIProvider` implements `LLMProvider` (chat + chatStream).
|
|
14
|
+
- `registerOpenAI()` helper for one-call provider registration.
|
|
15
|
+
- Module augmentation of @namzu/sdk's ProviderConfigRegistry for type-safe config.
|
|
16
|
+
- Tool-use + function calling via Chat Completions API.
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- Observability (OTEL spans, structured logging) excluded pending @namzu/telemetry package.
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, MIT Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-MIT
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 Cogitave
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or
|
|
34
|
+
service that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software
|
|
39
|
+
that exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee
|
|
52
|
+
using the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to
|
|
59
|
+
the infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
|
79
|
+
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the MIT license that is effective on the second anniversary of the date we make
|
|
91
|
+
the Software available. On or after that date, you may use the Software under
|
|
92
|
+
the MIT license, in which case the following will apply:
|
|
93
|
+
|
|
94
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
95
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
96
|
+
the Software without restriction, including without limitation the rights to
|
|
97
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
98
|
+
of the Software, and to permit persons to whom the Software is furnished to do
|
|
99
|
+
so, subject to the following conditions:
|
|
100
|
+
|
|
101
|
+
The above copyright notice and this permission notice shall be included in all
|
|
102
|
+
copies or substantial portions of the Software.
|
|
103
|
+
|
|
104
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
105
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
106
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
107
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
108
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
109
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
110
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# @namzu/openai
|
|
2
|
+
|
|
3
|
+
[OpenAI](https://platform.openai.com) LLM provider for [`@namzu/sdk`](https://www.npmjs.com/package/@namzu/sdk). Thin wrapper around the official [`openai`](https://www.npmjs.com/package/openai) npm SDK exposing the **Chat Completions API** (chat + streaming) with full tool-use / function-calling support, conformant to the `LLMProvider` contract.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @namzu/sdk @namzu/openai
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`@namzu/openai` declares `@namzu/sdk` as a peer dependency. Install both.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { ProviderRegistry } from '@namzu/sdk'
|
|
17
|
+
import { registerOpenAI } from '@namzu/openai'
|
|
18
|
+
|
|
19
|
+
// Register once at app startup.
|
|
20
|
+
registerOpenAI()
|
|
21
|
+
|
|
22
|
+
// Fully typed via module augmentation: ProviderConfigRegistry['openai'].
|
|
23
|
+
const { provider, capabilities } = ProviderRegistry.create({
|
|
24
|
+
type: 'openai',
|
|
25
|
+
apiKey: process.env.OPENAI_API_KEY!,
|
|
26
|
+
model: 'gpt-4o-mini', // optional default — can also be passed per-call
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
const response = await provider.chat({
|
|
30
|
+
model: 'gpt-4o-mini',
|
|
31
|
+
messages: [{ role: 'user', content: 'Hello' }],
|
|
32
|
+
})
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Streaming:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
for await (const chunk of provider.chatStream({
|
|
39
|
+
model: 'gpt-4o-mini',
|
|
40
|
+
messages: [{ role: 'user', content: 'Tell me a story' }],
|
|
41
|
+
})) {
|
|
42
|
+
if (chunk.delta.content) process.stdout.write(chunk.delta.content)
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Configuration
|
|
47
|
+
|
|
48
|
+
| Field | Description | Default |
|
|
49
|
+
|------------------|------------------------------------------------------------------------------|---------------------------------|
|
|
50
|
+
| `apiKey` | OpenAI API key (required) | — |
|
|
51
|
+
| `model` | Default model identifier (overridable per-call via `ChatCompletionParams.model`) | — |
|
|
52
|
+
| `baseURL` | Override the base URL (Azure OpenAI, Enterprise endpoints, OpenAI-compat) | `https://api.openai.com/v1` |
|
|
53
|
+
| `organization` | OpenAI Organization ID | — |
|
|
54
|
+
| `project` | OpenAI Project ID | — |
|
|
55
|
+
| `timeout` | Request timeout in ms | SDK default (600_000) |
|
|
56
|
+
| `defaultHeaders` | Custom headers appended to every request | — |
|
|
57
|
+
|
|
58
|
+
## Compatibility
|
|
59
|
+
|
|
60
|
+
Setting `baseURL` makes this provider work against any OpenAI-compatible endpoint — Azure OpenAI (with the appropriate deployment URL), self-hosted gateways, Enterprise endpoints, or local OpenAI-compatible servers.
|
|
61
|
+
|
|
62
|
+
For Azure OpenAI specifically, you can also use the official `openai` SDK's `AzureOpenAI` constructor directly; this package currently only exposes the base `OpenAI` client. For generic OpenAI-compat backends (Ollama, vLLM, LM Studio's HTTP endpoint), [`@namzu/http`](https://www.npmjs.com/package/@namzu/http) with `dialect: 'openai'` is the zero-dependency alternative.
|
|
63
|
+
|
|
64
|
+
## Capabilities
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { OPENAI_CAPABILITIES } from '@namzu/openai'
|
|
68
|
+
|
|
69
|
+
// {
|
|
70
|
+
// supportsTools: true,
|
|
71
|
+
// supportsStreaming: true,
|
|
72
|
+
// supportsFunctionCalling: true,
|
|
73
|
+
// }
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Observability
|
|
77
|
+
|
|
78
|
+
This package ships without observability hooks in `0.1.x`. OpenTelemetry span emission and structured logging are roadmapped for the forthcoming `@namzu/telemetry` package — a separate opt-in dependency that wraps any `LLMProvider` to emit GenAI semantic-convention spans. Track progress in the [Namzu roadmap](https://github.com/cogitave/namzu).
|
|
79
|
+
|
|
80
|
+
## License
|
|
81
|
+
|
|
82
|
+
FSL-1.1-MIT. Same as `@namzu/sdk`.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/openai.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { DuplicateProviderError, ProviderRegistry } from '@namzu/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it } from 'vitest';
|
|
3
|
+
import { OPENAI_CAPABILITIES, OpenAIProvider, registerOpenAI } from '../index.js';
|
|
4
|
+
// Ensure a clean slate between tests. The sdk pre-registers 'mock' on import
|
|
5
|
+
// via its sideEffects whitelist; we only need to clear 'openai' to make
|
|
6
|
+
// re-registration deterministic across tests.
|
|
7
|
+
beforeEach(() => {
|
|
8
|
+
if (ProviderRegistry.isSupported('openai')) {
|
|
9
|
+
ProviderRegistry.unregister('openai');
|
|
10
|
+
}
|
|
11
|
+
});
|
|
12
|
+
describe('@namzu/openai', () => {
|
|
13
|
+
describe('registerOpenAI()', () => {
|
|
14
|
+
it("adds 'openai' to the ProviderRegistry", () => {
|
|
15
|
+
expect(ProviderRegistry.isSupported('openai')).toBe(false);
|
|
16
|
+
registerOpenAI();
|
|
17
|
+
expect(ProviderRegistry.isSupported('openai')).toBe(true);
|
|
18
|
+
expect(ProviderRegistry.listTypes()).toContain('openai');
|
|
19
|
+
});
|
|
20
|
+
it('throws DuplicateProviderError when called twice without options', () => {
|
|
21
|
+
registerOpenAI();
|
|
22
|
+
expect(() => registerOpenAI()).toThrowError(DuplicateProviderError);
|
|
23
|
+
});
|
|
24
|
+
it('allows re-registration when { replace: true } is passed', () => {
|
|
25
|
+
registerOpenAI();
|
|
26
|
+
expect(() => registerOpenAI({ replace: true })).not.toThrow();
|
|
27
|
+
expect(ProviderRegistry.isSupported('openai')).toBe(true);
|
|
28
|
+
});
|
|
29
|
+
it('exposes capabilities through the registry after registration', () => {
|
|
30
|
+
registerOpenAI();
|
|
31
|
+
const caps = ProviderRegistry.getCapabilities('openai');
|
|
32
|
+
expect(caps).toEqual(OPENAI_CAPABILITIES);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
describe('OPENAI_CAPABILITIES', () => {
|
|
36
|
+
it('declares the expected capability flags', () => {
|
|
37
|
+
expect(OPENAI_CAPABILITIES).toEqual({
|
|
38
|
+
supportsTools: true,
|
|
39
|
+
supportsStreaming: true,
|
|
40
|
+
supportsFunctionCalling: true,
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
describe('ProviderRegistry.create({ type: "openai", ... })', () => {
|
|
45
|
+
it('narrows the config type via module augmentation and instantiates OpenAIProvider', () => {
|
|
46
|
+
registerOpenAI();
|
|
47
|
+
const { provider, capabilities } = ProviderRegistry.create({
|
|
48
|
+
type: 'openai',
|
|
49
|
+
apiKey: 'test-key',
|
|
50
|
+
model: 'gpt-4o-mini',
|
|
51
|
+
});
|
|
52
|
+
expect(provider).toBeInstanceOf(OpenAIProvider);
|
|
53
|
+
expect(capabilities).toEqual(OPENAI_CAPABILITIES);
|
|
54
|
+
});
|
|
55
|
+
it('throws when apiKey is missing', () => {
|
|
56
|
+
registerOpenAI();
|
|
57
|
+
expect(() => ProviderRegistry.create({
|
|
58
|
+
type: 'openai',
|
|
59
|
+
apiKey: '',
|
|
60
|
+
})).toThrowError(/API key is required/);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
//# sourceMappingURL=openai.test.js.map
|
|
@@ -0,0 +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;AACrE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAA;AACzD,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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AA;IACH,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,qBAAqB,EAAE,GAAG,EAAE;QACpC,EAAE,CAAC,wCAAwC,EAAE,GAAG,EAAE;YACjD,MAAM,CAAC,mBAAmB,CAAC,CAAC,OAAO,CAAC;gBACnC,aAAa,EAAE,IAAI;gBACnB,iBAAiB,EAAE,IAAI;gBACvB,uBAAuB,EAAE,IAAI;aAC7B,CAAC,CAAA;QACH,CAAC,CAAC,CAAA;IACH,CAAC,CAAC,CAAA;IAEF,QAAQ,CAAC,kDAAkD,EAAE,GAAG,EAAE;QACjE,EAAE,CAAC,iFAAiF,EAAE,GAAG,EAAE;YAC1F,cAAc,EAAE,CAAA;YAChB,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,gBAAgB,CAAC,MAAM,CAAC;gBAC1D,IAAI,EAAE,QAAQ;gBACd,MAAM,EAAE,UAAU;gBAClB,KAAK,EAAE,aAAa;aACpB,CAAC,CAAA;YACF,MAAM,CAAC,QAAQ,CAAC,CAAC,cAAc,CAAC,cAAc,CAAC,CAAA;YAC/C,MAAM,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAA;QAClD,CAAC,CAAC,CAAA;QAEF,EAAE,CAAC,+BAA+B,EAAE,GAAG,EAAE;YACxC,cAAc,EAAE,CAAA;YAChB,MAAM,CAAC,GAAG,EAAE,CACX,gBAAgB,CAAC,MAAM,CAAC;gBACvB,IAAI,EAAE,QAAQ;gBACd,MAAM,EAAE,EAAE;aACV,CAAC,CACF,CAAC,YAAY,CAAC,qBAAqB,CAAC,CAAA;QACtC,CAAC,CAAC,CAAA;IACH,CAAC,CAAC,CAAA;AACH,CAAC,CAAC,CAAA"}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ChatCompletionParams, ChatCompletionResponse, LLMProvider, ModelInfo, StreamChunk } from '@namzu/sdk';
|
|
2
|
+
import type { OpenAIConfig } from './types.js';
|
|
3
|
+
export declare class OpenAIProvider implements LLMProvider {
|
|
4
|
+
readonly id = "openai";
|
|
5
|
+
readonly name = "OpenAI";
|
|
6
|
+
private client;
|
|
7
|
+
private defaultModel?;
|
|
8
|
+
constructor(config: OpenAIConfig);
|
|
9
|
+
private resolveModel;
|
|
10
|
+
chat(params: ChatCompletionParams): Promise<ChatCompletionResponse>;
|
|
11
|
+
chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk>;
|
|
12
|
+
listModels(): Promise<ModelInfo[]>;
|
|
13
|
+
healthCheck(): Promise<boolean>;
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,oBAAoB,EACpB,sBAAsB,EACtB,WAAW,EACX,SAAS,EACT,WAAW,EAGX,MAAM,YAAY,CAAA;AAOnB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAyG9C,qBAAa,cAAe,YAAW,WAAW;IACjD,QAAQ,CAAC,EAAE,YAAW;IACtB,QAAQ,CAAC,IAAI,YAAW;IAExB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,YAAY,CAAC,CAAQ;gBAEjB,MAAM,EAAE,YAAY;IAkBhC,OAAO,CAAC,YAAY;IAUd,IAAI,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAgDlE,UAAU,CAAC,MAAM,EAAE,oBAAoB,GAAG,aAAa,CAAC,WAAW,CAAC;IAkErE,UAAU,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAclC,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAQrC"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import OpenAI from 'openai';
|
|
2
|
+
function mapFinishReason(reason) {
|
|
3
|
+
switch (reason) {
|
|
4
|
+
case 'length':
|
|
5
|
+
return 'length';
|
|
6
|
+
case 'tool_calls':
|
|
7
|
+
case 'function_call':
|
|
8
|
+
return 'tool_calls';
|
|
9
|
+
case 'content_filter':
|
|
10
|
+
return 'content_filter';
|
|
11
|
+
default:
|
|
12
|
+
return 'stop';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function parseUsage(raw) {
|
|
16
|
+
if (!raw) {
|
|
17
|
+
return {
|
|
18
|
+
promptTokens: 0,
|
|
19
|
+
completionTokens: 0,
|
|
20
|
+
totalTokens: 0,
|
|
21
|
+
cachedTokens: 0,
|
|
22
|
+
cacheWriteTokens: 0,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
const promptTokens = raw.prompt_tokens ?? 0;
|
|
26
|
+
const completionTokens = raw.completion_tokens ?? 0;
|
|
27
|
+
return {
|
|
28
|
+
promptTokens,
|
|
29
|
+
completionTokens,
|
|
30
|
+
totalTokens: raw.total_tokens ?? promptTokens + completionTokens,
|
|
31
|
+
cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? 0,
|
|
32
|
+
cacheWriteTokens: 0,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function formatToolChoice(tc) {
|
|
36
|
+
if (tc === undefined)
|
|
37
|
+
return undefined;
|
|
38
|
+
if (tc === 'auto' || tc === 'none' || tc === 'required')
|
|
39
|
+
return tc;
|
|
40
|
+
if (typeof tc === 'object' && tc.type === 'function') {
|
|
41
|
+
return { type: 'function', function: { name: tc.function.name } };
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
function toOpenAIMessages(messages) {
|
|
46
|
+
return messages.map((msg) => {
|
|
47
|
+
if (msg.role === 'system') {
|
|
48
|
+
return { role: 'system', content: msg.content };
|
|
49
|
+
}
|
|
50
|
+
if (msg.role === 'user') {
|
|
51
|
+
return { role: 'user', content: msg.content };
|
|
52
|
+
}
|
|
53
|
+
if (msg.role === 'tool') {
|
|
54
|
+
return {
|
|
55
|
+
role: 'tool',
|
|
56
|
+
content: msg.content,
|
|
57
|
+
tool_call_id: msg.toolCallId,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
// assistant
|
|
61
|
+
const assistant = {
|
|
62
|
+
role: 'assistant',
|
|
63
|
+
content: msg.content,
|
|
64
|
+
};
|
|
65
|
+
if ('toolCalls' in msg && msg.toolCalls && msg.toolCalls.length > 0) {
|
|
66
|
+
;
|
|
67
|
+
assistant.tool_calls = msg.toolCalls.map((tc) => ({
|
|
68
|
+
id: tc.id,
|
|
69
|
+
type: 'function',
|
|
70
|
+
function: {
|
|
71
|
+
name: tc.function.name,
|
|
72
|
+
arguments: tc.function.arguments,
|
|
73
|
+
},
|
|
74
|
+
}));
|
|
75
|
+
}
|
|
76
|
+
return assistant;
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
function toOpenAITools(params) {
|
|
80
|
+
if (!params.tools || params.tools.length === 0)
|
|
81
|
+
return undefined;
|
|
82
|
+
return params.tools.map((t) => ({
|
|
83
|
+
type: 'function',
|
|
84
|
+
function: {
|
|
85
|
+
name: t.function.name,
|
|
86
|
+
description: t.function.description ?? '',
|
|
87
|
+
parameters: (t.function.parameters ?? {}),
|
|
88
|
+
},
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
export class OpenAIProvider {
|
|
92
|
+
id = 'openai';
|
|
93
|
+
name = 'OpenAI';
|
|
94
|
+
client;
|
|
95
|
+
defaultModel;
|
|
96
|
+
constructor(config) {
|
|
97
|
+
if (!config.apiKey) {
|
|
98
|
+
throw new Error('OpenAI API key is required. Set OPENAI_API_KEY env variable.');
|
|
99
|
+
}
|
|
100
|
+
const clientOptions = {
|
|
101
|
+
apiKey: config.apiKey,
|
|
102
|
+
};
|
|
103
|
+
if (config.baseURL)
|
|
104
|
+
clientOptions.baseURL = config.baseURL;
|
|
105
|
+
if (config.organization)
|
|
106
|
+
clientOptions.organization = config.organization;
|
|
107
|
+
if (config.project)
|
|
108
|
+
clientOptions.project = config.project;
|
|
109
|
+
if (config.timeout !== undefined)
|
|
110
|
+
clientOptions.timeout = config.timeout;
|
|
111
|
+
if (config.defaultHeaders)
|
|
112
|
+
clientOptions.defaultHeaders = config.defaultHeaders;
|
|
113
|
+
this.client = new OpenAI(clientOptions);
|
|
114
|
+
this.defaultModel = config.model;
|
|
115
|
+
}
|
|
116
|
+
resolveModel(params) {
|
|
117
|
+
const model = params.model || this.defaultModel;
|
|
118
|
+
if (!model) {
|
|
119
|
+
throw new Error('OpenAIProvider: model is required. Pass `model` in config or on the chat call.');
|
|
120
|
+
}
|
|
121
|
+
return model;
|
|
122
|
+
}
|
|
123
|
+
async chat(params) {
|
|
124
|
+
const model = this.resolveModel(params);
|
|
125
|
+
const response = await this.client.chat.completions.create({
|
|
126
|
+
model,
|
|
127
|
+
messages: toOpenAIMessages(params.messages),
|
|
128
|
+
stream: false,
|
|
129
|
+
tools: toOpenAITools(params),
|
|
130
|
+
tool_choice: formatToolChoice(params.toolChoice),
|
|
131
|
+
parallel_tool_calls: params.parallelToolCalls,
|
|
132
|
+
temperature: params.temperature,
|
|
133
|
+
max_tokens: params.maxTokens,
|
|
134
|
+
top_p: params.topP,
|
|
135
|
+
frequency_penalty: params.frequencyPenalty,
|
|
136
|
+
presence_penalty: params.presencePenalty,
|
|
137
|
+
stop: params.stop,
|
|
138
|
+
response_format: params.responseFormat,
|
|
139
|
+
});
|
|
140
|
+
const choice = response.choices[0];
|
|
141
|
+
if (!choice) {
|
|
142
|
+
throw new Error('OpenAI returned empty choices');
|
|
143
|
+
}
|
|
144
|
+
const toolCalls = choice.message.tool_calls
|
|
145
|
+
?.filter((tc) => tc.type === 'function')
|
|
146
|
+
.map((tc) => ({
|
|
147
|
+
id: tc.id,
|
|
148
|
+
type: 'function',
|
|
149
|
+
function: {
|
|
150
|
+
name: tc.function.name,
|
|
151
|
+
arguments: tc.function.arguments,
|
|
152
|
+
},
|
|
153
|
+
}));
|
|
154
|
+
return {
|
|
155
|
+
id: response.id,
|
|
156
|
+
model: response.model,
|
|
157
|
+
message: {
|
|
158
|
+
role: 'assistant',
|
|
159
|
+
content: choice.message.content,
|
|
160
|
+
toolCalls: toolCalls && toolCalls.length > 0 ? toolCalls : undefined,
|
|
161
|
+
},
|
|
162
|
+
finishReason: mapFinishReason(choice.finish_reason),
|
|
163
|
+
usage: parseUsage(response.usage),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
async *chatStream(params) {
|
|
167
|
+
const model = this.resolveModel(params);
|
|
168
|
+
const stream = await this.client.chat.completions.create({
|
|
169
|
+
model,
|
|
170
|
+
messages: toOpenAIMessages(params.messages),
|
|
171
|
+
stream: true,
|
|
172
|
+
stream_options: { include_usage: true },
|
|
173
|
+
tools: toOpenAITools(params),
|
|
174
|
+
tool_choice: formatToolChoice(params.toolChoice),
|
|
175
|
+
parallel_tool_calls: params.parallelToolCalls,
|
|
176
|
+
temperature: params.temperature,
|
|
177
|
+
max_tokens: params.maxTokens,
|
|
178
|
+
top_p: params.topP,
|
|
179
|
+
frequency_penalty: params.frequencyPenalty,
|
|
180
|
+
presence_penalty: params.presencePenalty,
|
|
181
|
+
stop: params.stop,
|
|
182
|
+
response_format: params.responseFormat,
|
|
183
|
+
});
|
|
184
|
+
for await (const chunk of stream) {
|
|
185
|
+
try {
|
|
186
|
+
const choice = chunk.choices[0];
|
|
187
|
+
const delta = choice?.delta;
|
|
188
|
+
const toolCalls = delta?.tool_calls?.map((tc) => ({
|
|
189
|
+
index: tc.index,
|
|
190
|
+
id: tc.id,
|
|
191
|
+
type: tc.type,
|
|
192
|
+
function: tc.function
|
|
193
|
+
? {
|
|
194
|
+
name: tc.function.name,
|
|
195
|
+
arguments: tc.function.arguments,
|
|
196
|
+
}
|
|
197
|
+
: undefined,
|
|
198
|
+
}));
|
|
199
|
+
const hasDelta = (delta?.content !== undefined && delta.content !== null) ||
|
|
200
|
+
(toolCalls && toolCalls.length > 0);
|
|
201
|
+
const finishReason = choice?.finish_reason
|
|
202
|
+
? mapFinishReason(choice.finish_reason)
|
|
203
|
+
: undefined;
|
|
204
|
+
const usage = chunk.usage ? parseUsage(chunk.usage) : undefined;
|
|
205
|
+
if (!hasDelta && !finishReason && !usage)
|
|
206
|
+
continue;
|
|
207
|
+
yield {
|
|
208
|
+
id: chunk.id,
|
|
209
|
+
delta: {
|
|
210
|
+
content: delta?.content ?? undefined,
|
|
211
|
+
toolCalls,
|
|
212
|
+
},
|
|
213
|
+
finishReason,
|
|
214
|
+
usage,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
catch (parseErr) {
|
|
218
|
+
yield {
|
|
219
|
+
id: chunk.id ?? '',
|
|
220
|
+
delta: {},
|
|
221
|
+
error: `Stream parse error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async listModels() {
|
|
227
|
+
const page = await this.client.models.list();
|
|
228
|
+
return page.data.map((m) => ({
|
|
229
|
+
id: m.id,
|
|
230
|
+
name: m.id,
|
|
231
|
+
contextWindow: 0,
|
|
232
|
+
maxOutputTokens: 0,
|
|
233
|
+
inputPrice: 0,
|
|
234
|
+
outputPrice: 0,
|
|
235
|
+
supportsToolUse: true,
|
|
236
|
+
supportsStreaming: true,
|
|
237
|
+
}));
|
|
238
|
+
}
|
|
239
|
+
async healthCheck() {
|
|
240
|
+
try {
|
|
241
|
+
await this.client.models.list();
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AASA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAY3B,SAAS,eAAe,CAAC,MAA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ChB,IAAI,CAAC;YACJ,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAA;YAC/B,OAAO,IAAI,CAAA;QACZ,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,KAAK,CAAA;QACb,CAAC;IACF,CAAC;CACD"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type ProviderCapabilities, type RegisterOptions } from '@namzu/sdk';
|
|
2
|
+
import type { OpenAIProviderConfig } from './types.js';
|
|
3
|
+
declare module '@namzu/sdk' {
|
|
4
|
+
interface ProviderConfigRegistry {
|
|
5
|
+
openai: OpenAIProviderConfig;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export declare const OPENAI_CAPABILITIES: ProviderCapabilities;
|
|
9
|
+
/**
|
|
10
|
+
* Register `OpenAIProvider` under the `'openai'` type in `@namzu/sdk`'s
|
|
11
|
+
* `ProviderRegistry`. Call once at app startup before
|
|
12
|
+
* `ProviderRegistry.create({ type: 'openai', ... })`.
|
|
13
|
+
*
|
|
14
|
+
* Throws `DuplicateProviderError` if `'openai'` is already registered.
|
|
15
|
+
* Pass `{ replace: true }` to override.
|
|
16
|
+
*/
|
|
17
|
+
export declare function registerOpenAI(options?: RegisterOptions): void;
|
|
18
|
+
export { OpenAIProvider } from './client.js';
|
|
19
|
+
export type { OpenAIConfig, OpenAIProviderConfig } from './types.js';
|
|
20
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,oBAAoB,EAAoB,KAAK,eAAe,EAAE,MAAM,YAAY,CAAA;AAE9F,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,eAAO,MAAM,mBAAmB,EAAE,oBAIjC,CAAA;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAE9D;AAED,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC5C,YAAY,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
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
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Register `OpenAIProvider` under the `'openai'` type in `@namzu/sdk`'s
|
|
10
|
+
* `ProviderRegistry`. Call once at app startup before
|
|
11
|
+
* `ProviderRegistry.create({ type: 'openai', ... })`.
|
|
12
|
+
*
|
|
13
|
+
* Throws `DuplicateProviderError` if `'openai'` is already registered.
|
|
14
|
+
* Pass `{ replace: true }` to override.
|
|
15
|
+
*/
|
|
16
|
+
export function registerOpenAI(options) {
|
|
17
|
+
ProviderRegistry.register('openai', OpenAIProvider, OPENAI_CAPABILITIES, options);
|
|
18
|
+
}
|
|
19
|
+
export { OpenAIProvider } from './client.js';
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,gBAAgB,EAAwB,MAAM,YAAY,CAAA;AAC9F,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAW5C,MAAM,CAAC,MAAM,mBAAmB,GAAyB;IACxD,aAAa,EAAE,IAAI;IACnB,iBAAiB,EAAE,IAAI;IACvB,uBAAuB,EAAE,IAAI;CAC7B,CAAA;AAED;;;;;;;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,cAAc,EAAE,MAAM,aAAa,CAAA"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-specific provider config shapes.
|
|
3
|
+
*
|
|
4
|
+
* `OpenAIConfig` is the constructor input for `OpenAIProvider` (no discriminator).
|
|
5
|
+
* `OpenAIProviderConfig` is the shape the consumer passes to
|
|
6
|
+
* `ProviderRegistry.create({ type: 'openai', ... })` — it extends `OpenAIConfig`
|
|
7
|
+
* with the `type: 'openai'` discriminator for the registry's generic narrowing.
|
|
8
|
+
*/
|
|
9
|
+
export interface OpenAIConfig {
|
|
10
|
+
apiKey: string;
|
|
11
|
+
/** Default model. Can be overridden per-call via ChatCompletionParams.model. */
|
|
12
|
+
model?: string;
|
|
13
|
+
/** Override the base URL (e.g. for Azure OpenAI or Enterprise endpoints). */
|
|
14
|
+
baseURL?: string;
|
|
15
|
+
/** Organization ID. */
|
|
16
|
+
organization?: string;
|
|
17
|
+
/** Project ID. */
|
|
18
|
+
project?: string;
|
|
19
|
+
/** Request timeout in ms. */
|
|
20
|
+
timeout?: number;
|
|
21
|
+
/** Custom headers appended to every request. */
|
|
22
|
+
defaultHeaders?: Record<string, string>;
|
|
23
|
+
}
|
|
24
|
+
export interface OpenAIProviderConfig extends OpenAIConfig {
|
|
25
|
+
type: 'openai';
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,MAAM,CAAA;IACd,gFAAgF;IAChF,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,6EAA6E;IAC7E,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,uBAAuB;IACvB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,kBAAkB;IAClB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,6BAA6B;IAC7B,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,gDAAgD;IAChD,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACvC;AAED,MAAM,WAAW,oBAAqB,SAAQ,YAAY;IACzD,IAAI,EAAE,QAAQ,CAAA;CACd"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-specific provider config shapes.
|
|
3
|
+
*
|
|
4
|
+
* `OpenAIConfig` is the constructor input for `OpenAIProvider` (no discriminator).
|
|
5
|
+
* `OpenAIProviderConfig` is the shape the consumer passes to
|
|
6
|
+
* `ProviderRegistry.create({ type: 'openai', ... })` — it extends `OpenAIConfig`
|
|
7
|
+
* with the `type: 'openai'` discriminator for the registry's generic narrowing.
|
|
8
|
+
*/
|
|
9
|
+
export {};
|
|
10
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"}
|
package/package.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@namzu/openai",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "OpenAI LLM provider for @namzu/sdk via the official `openai` npm SDK. Chat Completions API with streaming + tool-use.",
|
|
5
|
+
"license": "FSL-1.1-MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"homepage": "https://github.com/cogitave/namzu#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/cogitave/namzu.git",
|
|
11
|
+
"directory": "packages/providers/openai"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/cogitave/namzu/issues"
|
|
15
|
+
},
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"import": "./dist/index.js",
|
|
21
|
+
"types": "./dist/index.d.ts"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"src",
|
|
27
|
+
"LICENSE.md",
|
|
28
|
+
"README.md",
|
|
29
|
+
"CHANGELOG.md"
|
|
30
|
+
],
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public",
|
|
34
|
+
"provenance": false
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"openai": "^6.0.0"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@namzu/sdk": "^1 || ^0.1.6"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@biomejs/biome": "^1.9.4",
|
|
44
|
+
"@types/node": "^22.19.17",
|
|
45
|
+
"typescript": "^5.5.0",
|
|
46
|
+
"vitest": "^2.0.0",
|
|
47
|
+
"@namzu/sdk": "^0.1.8"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "tsc --build",
|
|
51
|
+
"dev": "tsc --build --watch",
|
|
52
|
+
"lint": "biome check src/",
|
|
53
|
+
"lint:fix": "biome check --write src/",
|
|
54
|
+
"format": "biome format --write src/",
|
|
55
|
+
"test": "vitest run --passWithNoTests",
|
|
56
|
+
"typecheck": "tsc --noEmit",
|
|
57
|
+
"verify": "bash scripts/verify.sh",
|
|
58
|
+
"release:patch": "bash scripts/release.sh patch",
|
|
59
|
+
"release:minor": "bash scripts/release.sh minor",
|
|
60
|
+
"release:major": "bash scripts/release.sh major",
|
|
61
|
+
"release:rc": "bash scripts/release.sh rc",
|
|
62
|
+
"release:beta": "bash scripts/release.sh beta",
|
|
63
|
+
"release:stable": "bash scripts/release.sh stable",
|
|
64
|
+
"release:dry": "bash scripts/release.sh patch --dry-run"
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { DuplicateProviderError, ProviderRegistry } from '@namzu/sdk'
|
|
2
|
+
import { beforeEach, describe, expect, it } from 'vitest'
|
|
3
|
+
import { OPENAI_CAPABILITIES, OpenAIProvider, registerOpenAI } from '../index.js'
|
|
4
|
+
|
|
5
|
+
// Ensure a clean slate between tests. The sdk pre-registers 'mock' on import
|
|
6
|
+
// via its sideEffects whitelist; we only need to clear 'openai' to make
|
|
7
|
+
// re-registration deterministic across tests.
|
|
8
|
+
beforeEach(() => {
|
|
9
|
+
if (ProviderRegistry.isSupported('openai')) {
|
|
10
|
+
ProviderRegistry.unregister('openai')
|
|
11
|
+
}
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
describe('@namzu/openai', () => {
|
|
15
|
+
describe('registerOpenAI()', () => {
|
|
16
|
+
it("adds 'openai' to the ProviderRegistry", () => {
|
|
17
|
+
expect(ProviderRegistry.isSupported('openai')).toBe(false)
|
|
18
|
+
registerOpenAI()
|
|
19
|
+
expect(ProviderRegistry.isSupported('openai')).toBe(true)
|
|
20
|
+
expect(ProviderRegistry.listTypes()).toContain('openai')
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('throws DuplicateProviderError when called twice without options', () => {
|
|
24
|
+
registerOpenAI()
|
|
25
|
+
expect(() => registerOpenAI()).toThrowError(DuplicateProviderError)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('allows re-registration when { replace: true } is passed', () => {
|
|
29
|
+
registerOpenAI()
|
|
30
|
+
expect(() => registerOpenAI({ replace: true })).not.toThrow()
|
|
31
|
+
expect(ProviderRegistry.isSupported('openai')).toBe(true)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('exposes capabilities through the registry after registration', () => {
|
|
35
|
+
registerOpenAI()
|
|
36
|
+
const caps = ProviderRegistry.getCapabilities('openai')
|
|
37
|
+
expect(caps).toEqual(OPENAI_CAPABILITIES)
|
|
38
|
+
})
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
describe('OPENAI_CAPABILITIES', () => {
|
|
42
|
+
it('declares the expected capability flags', () => {
|
|
43
|
+
expect(OPENAI_CAPABILITIES).toEqual({
|
|
44
|
+
supportsTools: true,
|
|
45
|
+
supportsStreaming: true,
|
|
46
|
+
supportsFunctionCalling: true,
|
|
47
|
+
})
|
|
48
|
+
})
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
describe('ProviderRegistry.create({ type: "openai", ... })', () => {
|
|
52
|
+
it('narrows the config type via module augmentation and instantiates OpenAIProvider', () => {
|
|
53
|
+
registerOpenAI()
|
|
54
|
+
const { provider, capabilities } = ProviderRegistry.create({
|
|
55
|
+
type: 'openai',
|
|
56
|
+
apiKey: 'test-key',
|
|
57
|
+
model: 'gpt-4o-mini',
|
|
58
|
+
})
|
|
59
|
+
expect(provider).toBeInstanceOf(OpenAIProvider)
|
|
60
|
+
expect(capabilities).toEqual(OPENAI_CAPABILITIES)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('throws when apiKey is missing', () => {
|
|
64
|
+
registerOpenAI()
|
|
65
|
+
expect(() =>
|
|
66
|
+
ProviderRegistry.create({
|
|
67
|
+
type: 'openai',
|
|
68
|
+
apiKey: '',
|
|
69
|
+
}),
|
|
70
|
+
).toThrowError(/API key is required/)
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
})
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ChatCompletionParams,
|
|
3
|
+
ChatCompletionResponse,
|
|
4
|
+
LLMProvider,
|
|
5
|
+
ModelInfo,
|
|
6
|
+
StreamChunk,
|
|
7
|
+
TokenUsage,
|
|
8
|
+
ToolChoice,
|
|
9
|
+
} from '@namzu/sdk'
|
|
10
|
+
import OpenAI from 'openai'
|
|
11
|
+
import type {
|
|
12
|
+
ChatCompletionMessageParam,
|
|
13
|
+
ChatCompletionTool,
|
|
14
|
+
ChatCompletionToolChoiceOption,
|
|
15
|
+
} from 'openai/resources/chat/completions'
|
|
16
|
+
import type { OpenAIConfig } from './types.js'
|
|
17
|
+
|
|
18
|
+
type OpenAIFinishReason = 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call'
|
|
19
|
+
|
|
20
|
+
type NamzuFinishReason = ChatCompletionResponse['finishReason']
|
|
21
|
+
|
|
22
|
+
function mapFinishReason(reason: OpenAIFinishReason | null | undefined): NamzuFinishReason {
|
|
23
|
+
switch (reason) {
|
|
24
|
+
case 'length':
|
|
25
|
+
return 'length'
|
|
26
|
+
case 'tool_calls':
|
|
27
|
+
case 'function_call':
|
|
28
|
+
return 'tool_calls'
|
|
29
|
+
case 'content_filter':
|
|
30
|
+
return 'content_filter'
|
|
31
|
+
default:
|
|
32
|
+
return 'stop'
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface RawOpenAIUsage {
|
|
37
|
+
prompt_tokens?: number
|
|
38
|
+
completion_tokens?: number
|
|
39
|
+
total_tokens?: number
|
|
40
|
+
prompt_tokens_details?: { cached_tokens?: number }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function parseUsage(raw?: RawOpenAIUsage | null): TokenUsage {
|
|
44
|
+
if (!raw) {
|
|
45
|
+
return {
|
|
46
|
+
promptTokens: 0,
|
|
47
|
+
completionTokens: 0,
|
|
48
|
+
totalTokens: 0,
|
|
49
|
+
cachedTokens: 0,
|
|
50
|
+
cacheWriteTokens: 0,
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const promptTokens = raw.prompt_tokens ?? 0
|
|
54
|
+
const completionTokens = raw.completion_tokens ?? 0
|
|
55
|
+
return {
|
|
56
|
+
promptTokens,
|
|
57
|
+
completionTokens,
|
|
58
|
+
totalTokens: raw.total_tokens ?? promptTokens + completionTokens,
|
|
59
|
+
cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? 0,
|
|
60
|
+
cacheWriteTokens: 0,
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function formatToolChoice(tc: ToolChoice | undefined): ChatCompletionToolChoiceOption | undefined {
|
|
65
|
+
if (tc === undefined) return undefined
|
|
66
|
+
if (tc === 'auto' || tc === 'none' || tc === 'required') return tc
|
|
67
|
+
if (typeof tc === 'object' && tc.type === 'function') {
|
|
68
|
+
return { type: 'function', function: { name: tc.function.name } }
|
|
69
|
+
}
|
|
70
|
+
return undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function toOpenAIMessages(
|
|
74
|
+
messages: ChatCompletionParams['messages'],
|
|
75
|
+
): ChatCompletionMessageParam[] {
|
|
76
|
+
return messages.map((msg): ChatCompletionMessageParam => {
|
|
77
|
+
if (msg.role === 'system') {
|
|
78
|
+
return { role: 'system', content: msg.content }
|
|
79
|
+
}
|
|
80
|
+
if (msg.role === 'user') {
|
|
81
|
+
return { role: 'user', content: msg.content }
|
|
82
|
+
}
|
|
83
|
+
if (msg.role === 'tool') {
|
|
84
|
+
return {
|
|
85
|
+
role: 'tool',
|
|
86
|
+
content: msg.content,
|
|
87
|
+
tool_call_id: msg.toolCallId,
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
// assistant
|
|
91
|
+
const assistant: ChatCompletionMessageParam = {
|
|
92
|
+
role: 'assistant',
|
|
93
|
+
content: msg.content,
|
|
94
|
+
}
|
|
95
|
+
if ('toolCalls' in msg && msg.toolCalls && msg.toolCalls.length > 0) {
|
|
96
|
+
;(assistant as { tool_calls?: unknown }).tool_calls = msg.toolCalls.map((tc) => ({
|
|
97
|
+
id: tc.id,
|
|
98
|
+
type: 'function' as const,
|
|
99
|
+
function: {
|
|
100
|
+
name: tc.function.name,
|
|
101
|
+
arguments: tc.function.arguments,
|
|
102
|
+
},
|
|
103
|
+
}))
|
|
104
|
+
}
|
|
105
|
+
return assistant
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function toOpenAITools(params: ChatCompletionParams): ChatCompletionTool[] | undefined {
|
|
110
|
+
if (!params.tools || params.tools.length === 0) return undefined
|
|
111
|
+
return params.tools.map((t) => ({
|
|
112
|
+
type: 'function' as const,
|
|
113
|
+
function: {
|
|
114
|
+
name: t.function.name,
|
|
115
|
+
description: t.function.description ?? '',
|
|
116
|
+
parameters: (t.function.parameters ?? {}) as Record<string, unknown>,
|
|
117
|
+
},
|
|
118
|
+
}))
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export class OpenAIProvider implements LLMProvider {
|
|
122
|
+
readonly id = 'openai'
|
|
123
|
+
readonly name = 'OpenAI'
|
|
124
|
+
|
|
125
|
+
private client: OpenAI
|
|
126
|
+
private defaultModel?: string
|
|
127
|
+
|
|
128
|
+
constructor(config: OpenAIConfig) {
|
|
129
|
+
if (!config.apiKey) {
|
|
130
|
+
throw new Error('OpenAI API key is required. Set OPENAI_API_KEY env variable.')
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const clientOptions: ConstructorParameters<typeof OpenAI>[0] = {
|
|
134
|
+
apiKey: config.apiKey,
|
|
135
|
+
}
|
|
136
|
+
if (config.baseURL) clientOptions.baseURL = config.baseURL
|
|
137
|
+
if (config.organization) clientOptions.organization = config.organization
|
|
138
|
+
if (config.project) clientOptions.project = config.project
|
|
139
|
+
if (config.timeout !== undefined) clientOptions.timeout = config.timeout
|
|
140
|
+
if (config.defaultHeaders) clientOptions.defaultHeaders = config.defaultHeaders
|
|
141
|
+
|
|
142
|
+
this.client = new OpenAI(clientOptions)
|
|
143
|
+
this.defaultModel = config.model
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private resolveModel(params: ChatCompletionParams): string {
|
|
147
|
+
const model = params.model || this.defaultModel
|
|
148
|
+
if (!model) {
|
|
149
|
+
throw new Error(
|
|
150
|
+
'OpenAIProvider: model is required. Pass `model` in config or on the chat call.',
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
return model
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async chat(params: ChatCompletionParams): Promise<ChatCompletionResponse> {
|
|
157
|
+
const model = this.resolveModel(params)
|
|
158
|
+
|
|
159
|
+
const response = await this.client.chat.completions.create({
|
|
160
|
+
model,
|
|
161
|
+
messages: toOpenAIMessages(params.messages),
|
|
162
|
+
stream: false,
|
|
163
|
+
tools: toOpenAITools(params),
|
|
164
|
+
tool_choice: formatToolChoice(params.toolChoice),
|
|
165
|
+
parallel_tool_calls: params.parallelToolCalls,
|
|
166
|
+
temperature: params.temperature,
|
|
167
|
+
max_tokens: params.maxTokens,
|
|
168
|
+
top_p: params.topP,
|
|
169
|
+
frequency_penalty: params.frequencyPenalty,
|
|
170
|
+
presence_penalty: params.presencePenalty,
|
|
171
|
+
stop: params.stop,
|
|
172
|
+
response_format: params.responseFormat,
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
const choice = response.choices[0]
|
|
176
|
+
if (!choice) {
|
|
177
|
+
throw new Error('OpenAI returned empty choices')
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const toolCalls = choice.message.tool_calls
|
|
181
|
+
?.filter((tc): tc is Extract<typeof tc, { type: 'function' }> => tc.type === 'function')
|
|
182
|
+
.map((tc) => ({
|
|
183
|
+
id: tc.id,
|
|
184
|
+
type: 'function' as const,
|
|
185
|
+
function: {
|
|
186
|
+
name: tc.function.name,
|
|
187
|
+
arguments: tc.function.arguments,
|
|
188
|
+
},
|
|
189
|
+
}))
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
id: response.id,
|
|
193
|
+
model: response.model,
|
|
194
|
+
message: {
|
|
195
|
+
role: 'assistant',
|
|
196
|
+
content: choice.message.content,
|
|
197
|
+
toolCalls: toolCalls && toolCalls.length > 0 ? toolCalls : undefined,
|
|
198
|
+
},
|
|
199
|
+
finishReason: mapFinishReason(choice.finish_reason),
|
|
200
|
+
usage: parseUsage(response.usage),
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
|
|
205
|
+
const model = this.resolveModel(params)
|
|
206
|
+
|
|
207
|
+
const stream = await this.client.chat.completions.create({
|
|
208
|
+
model,
|
|
209
|
+
messages: toOpenAIMessages(params.messages),
|
|
210
|
+
stream: true,
|
|
211
|
+
stream_options: { include_usage: true },
|
|
212
|
+
tools: toOpenAITools(params),
|
|
213
|
+
tool_choice: formatToolChoice(params.toolChoice),
|
|
214
|
+
parallel_tool_calls: params.parallelToolCalls,
|
|
215
|
+
temperature: params.temperature,
|
|
216
|
+
max_tokens: params.maxTokens,
|
|
217
|
+
top_p: params.topP,
|
|
218
|
+
frequency_penalty: params.frequencyPenalty,
|
|
219
|
+
presence_penalty: params.presencePenalty,
|
|
220
|
+
stop: params.stop,
|
|
221
|
+
response_format: params.responseFormat,
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
for await (const chunk of stream) {
|
|
225
|
+
try {
|
|
226
|
+
const choice = chunk.choices[0]
|
|
227
|
+
const delta = choice?.delta
|
|
228
|
+
|
|
229
|
+
const toolCalls = delta?.tool_calls?.map((tc) => ({
|
|
230
|
+
index: tc.index,
|
|
231
|
+
id: tc.id,
|
|
232
|
+
type: tc.type,
|
|
233
|
+
function: tc.function
|
|
234
|
+
? {
|
|
235
|
+
name: tc.function.name,
|
|
236
|
+
arguments: tc.function.arguments,
|
|
237
|
+
}
|
|
238
|
+
: undefined,
|
|
239
|
+
}))
|
|
240
|
+
|
|
241
|
+
const hasDelta =
|
|
242
|
+
(delta?.content !== undefined && delta.content !== null) ||
|
|
243
|
+
(toolCalls && toolCalls.length > 0)
|
|
244
|
+
const finishReason = choice?.finish_reason
|
|
245
|
+
? mapFinishReason(choice.finish_reason)
|
|
246
|
+
: undefined
|
|
247
|
+
const usage = chunk.usage ? parseUsage(chunk.usage) : undefined
|
|
248
|
+
|
|
249
|
+
if (!hasDelta && !finishReason && !usage) continue
|
|
250
|
+
|
|
251
|
+
yield {
|
|
252
|
+
id: chunk.id,
|
|
253
|
+
delta: {
|
|
254
|
+
content: delta?.content ?? undefined,
|
|
255
|
+
toolCalls,
|
|
256
|
+
},
|
|
257
|
+
finishReason,
|
|
258
|
+
usage,
|
|
259
|
+
}
|
|
260
|
+
} catch (parseErr) {
|
|
261
|
+
yield {
|
|
262
|
+
id: chunk.id ?? '',
|
|
263
|
+
delta: {},
|
|
264
|
+
error: `Stream parse error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async listModels(): Promise<ModelInfo[]> {
|
|
271
|
+
const page = await this.client.models.list()
|
|
272
|
+
return page.data.map((m) => ({
|
|
273
|
+
id: m.id,
|
|
274
|
+
name: m.id,
|
|
275
|
+
contextWindow: 0,
|
|
276
|
+
maxOutputTokens: 0,
|
|
277
|
+
inputPrice: 0,
|
|
278
|
+
outputPrice: 0,
|
|
279
|
+
supportsToolUse: true,
|
|
280
|
+
supportsStreaming: true,
|
|
281
|
+
}))
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async healthCheck(): Promise<boolean> {
|
|
285
|
+
try {
|
|
286
|
+
await this.client.models.list()
|
|
287
|
+
return true
|
|
288
|
+
} catch {
|
|
289
|
+
return false
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type ProviderCapabilities, ProviderRegistry, type RegisterOptions } from '@namzu/sdk'
|
|
2
|
+
import { OpenAIProvider } from './client.js'
|
|
3
|
+
import type { OpenAIProviderConfig } from './types.js'
|
|
4
|
+
|
|
5
|
+
// Module augmentation: register openai's config type in the sdk's registry interface.
|
|
6
|
+
// This must live inside index.ts (not a .d.ts) so it executes when index.ts is imported.
|
|
7
|
+
declare module '@namzu/sdk' {
|
|
8
|
+
interface ProviderConfigRegistry {
|
|
9
|
+
openai: OpenAIProviderConfig
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const OPENAI_CAPABILITIES: ProviderCapabilities = {
|
|
14
|
+
supportsTools: true,
|
|
15
|
+
supportsStreaming: true,
|
|
16
|
+
supportsFunctionCalling: true,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Register `OpenAIProvider` under the `'openai'` type in `@namzu/sdk`'s
|
|
21
|
+
* `ProviderRegistry`. Call once at app startup before
|
|
22
|
+
* `ProviderRegistry.create({ type: 'openai', ... })`.
|
|
23
|
+
*
|
|
24
|
+
* Throws `DuplicateProviderError` if `'openai'` is already registered.
|
|
25
|
+
* Pass `{ replace: true }` to override.
|
|
26
|
+
*/
|
|
27
|
+
export function registerOpenAI(options?: RegisterOptions): void {
|
|
28
|
+
ProviderRegistry.register('openai', OpenAIProvider, OPENAI_CAPABILITIES, options)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export { OpenAIProvider } from './client.js'
|
|
32
|
+
export type { OpenAIConfig, OpenAIProviderConfig } from './types.js'
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-specific provider config shapes.
|
|
3
|
+
*
|
|
4
|
+
* `OpenAIConfig` is the constructor input for `OpenAIProvider` (no discriminator).
|
|
5
|
+
* `OpenAIProviderConfig` is the shape the consumer passes to
|
|
6
|
+
* `ProviderRegistry.create({ type: 'openai', ... })` — it extends `OpenAIConfig`
|
|
7
|
+
* with the `type: 'openai'` discriminator for the registry's generic narrowing.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export interface OpenAIConfig {
|
|
11
|
+
apiKey: string
|
|
12
|
+
/** Default model. Can be overridden per-call via ChatCompletionParams.model. */
|
|
13
|
+
model?: string
|
|
14
|
+
/** Override the base URL (e.g. for Azure OpenAI or Enterprise endpoints). */
|
|
15
|
+
baseURL?: string
|
|
16
|
+
/** Organization ID. */
|
|
17
|
+
organization?: string
|
|
18
|
+
/** Project ID. */
|
|
19
|
+
project?: string
|
|
20
|
+
/** Request timeout in ms. */
|
|
21
|
+
timeout?: number
|
|
22
|
+
/** Custom headers appended to every request. */
|
|
23
|
+
defaultHeaders?: Record<string, string>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface OpenAIProviderConfig extends OpenAIConfig {
|
|
27
|
+
type: 'openai'
|
|
28
|
+
}
|