@namzu/openrouter 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 +91 -0
- package/dist/__tests__/openrouter.test.d.ts +2 -0
- package/dist/__tests__/openrouter.test.d.ts.map +1 -0
- package/dist/__tests__/openrouter.test.js +58 -0
- package/dist/__tests__/openrouter.test.js.map +1 -0
- package/dist/client.d.ts +17 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +248 -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 +20 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +11 -0
- package/dist/types.js.map +1 -0
- package/package.json +64 -0
- package/src/__tests__/openrouter.test.ts +64 -0
- package/src/client.ts +330 -0
- package/src/index.ts +33 -0
- package/src/types.ts +21 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@namzu/openrouter` 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. OpenRouterProvider extracted from @namzu/sdk core per ADR-0001.
|
|
13
|
+
- OpenAI-compatible Chat Completions API (chat + chatStream) via native fetch.
|
|
14
|
+
- Tool-use + function calling support.
|
|
15
|
+
- `registerOpenRouter()` helper for one-call provider registration.
|
|
16
|
+
- Module augmentation of @namzu/sdk's ProviderConfigRegistry for type-safe config.
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- Observability (OTEL spans, structured logging) removed 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,91 @@
|
|
|
1
|
+
# @namzu/openrouter
|
|
2
|
+
|
|
3
|
+
OpenRouter LLM provider for [`@namzu/sdk`](https://www.npmjs.com/package/@namzu/sdk). Thin `fetch`-based wrapper around OpenRouter's **OpenAI-compatible Chat Completions API** (chat + streaming) with full tool-use support, conformant to the `LLMProvider` contract. Gives you access to 200+ models — Claude, GPT-4, Llama, Mixtral, Gemini, and more — through a single unified API and billing account.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @namzu/sdk @namzu/openrouter
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`@namzu/openrouter` declares `@namzu/sdk` as a peer dependency. Install both. The provider has **zero runtime dependencies** — it talks to OpenRouter with native `fetch`.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { ProviderRegistry } from '@namzu/sdk'
|
|
17
|
+
import { registerOpenRouter } from '@namzu/openrouter'
|
|
18
|
+
|
|
19
|
+
// Register once at app startup.
|
|
20
|
+
registerOpenRouter()
|
|
21
|
+
|
|
22
|
+
// Fully typed via module augmentation: ProviderConfigRegistry['openrouter'].
|
|
23
|
+
const { provider, capabilities } = ProviderRegistry.create({
|
|
24
|
+
type: 'openrouter',
|
|
25
|
+
apiKey: process.env.OPENROUTER_API_KEY!,
|
|
26
|
+
siteUrl: 'https://myapp.example', // optional — shown on OpenRouter analytics
|
|
27
|
+
siteName: 'My App', // optional — shown on OpenRouter analytics
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
const response = await provider.chat({
|
|
31
|
+
model: 'anthropic/claude-sonnet-4',
|
|
32
|
+
messages: [{ role: 'user', content: 'Hello' }],
|
|
33
|
+
})
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Streaming:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
for await (const chunk of provider.chatStream({
|
|
40
|
+
model: 'openai/gpt-4o',
|
|
41
|
+
messages: [{ role: 'user', content: 'Tell me a story' }],
|
|
42
|
+
})) {
|
|
43
|
+
if (chunk.delta.content) process.stdout.write(chunk.delta.content)
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Authentication
|
|
48
|
+
|
|
49
|
+
Get an API key at [openrouter.ai/keys](https://openrouter.ai/keys). Pass it to the provider via the `apiKey` field, or read it from `process.env.OPENROUTER_API_KEY` in your app before constructing the config.
|
|
50
|
+
|
|
51
|
+
## Models
|
|
52
|
+
|
|
53
|
+
OpenRouter exposes 200+ models from every major vendor under one unified API. See the [OpenRouter model catalog](https://openrouter.ai/models) for the full list and current pricing. Identifiers follow the `vendor/model-name` pattern:
|
|
54
|
+
|
|
55
|
+
- `anthropic/claude-sonnet-4`
|
|
56
|
+
- `anthropic/claude-haiku-4`
|
|
57
|
+
- `openai/gpt-4o`
|
|
58
|
+
- `openai/gpt-4o-mini`
|
|
59
|
+
- `meta-llama/llama-3.3-70b-instruct`
|
|
60
|
+
- `mistralai/mixtral-8x22b-instruct`
|
|
61
|
+
- `google/gemini-pro-1.5`
|
|
62
|
+
|
|
63
|
+
Pricing is per-million tokens on OpenRouter's catalog — the provider's `listModels()` returns live pricing pulled from the `/models` endpoint.
|
|
64
|
+
|
|
65
|
+
## Base URL override
|
|
66
|
+
|
|
67
|
+
The OpenRouter endpoint defaults to `https://openrouter.ai/api/v1`. Override via the `baseUrl` config field or the `OPENROUTER_BASE_URL` environment variable — useful for OpenRouter-compatible self-hosted gateways.
|
|
68
|
+
|
|
69
|
+
## Capabilities
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import { OPENROUTER_CAPABILITIES } from '@namzu/openrouter'
|
|
73
|
+
|
|
74
|
+
// {
|
|
75
|
+
// supportsTools: true,
|
|
76
|
+
// supportsStreaming: true,
|
|
77
|
+
// supportsFunctionCalling: true,
|
|
78
|
+
// }
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## OpenAI compatibility
|
|
82
|
+
|
|
83
|
+
Because OpenRouter speaks the OpenAI Chat Completions dialect, this provider can also target any OpenAI-compatible endpoint (vLLM, LM Studio, Groq, local OpenAI-compat gateways) by passing `baseUrl` pointing at the alternate endpoint. For a zero-config generic OpenAI-compatible client, use the forthcoming `@namzu/http` package instead.
|
|
84
|
+
|
|
85
|
+
## Observability
|
|
86
|
+
|
|
87
|
+
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).
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
|
|
91
|
+
FSL-1.1-MIT. Same as `@namzu/sdk`.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openrouter.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/openrouter.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { DuplicateProviderError, ProviderRegistry } from '@namzu/sdk';
|
|
2
|
+
import { beforeEach, describe, expect, it } from 'vitest';
|
|
3
|
+
import { OPENROUTER_CAPABILITIES, OpenRouterProvider, registerOpenRouter } 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 'openrouter' to make
|
|
6
|
+
// re-registration deterministic across tests.
|
|
7
|
+
beforeEach(() => {
|
|
8
|
+
if (ProviderRegistry.isSupported('openrouter')) {
|
|
9
|
+
ProviderRegistry.unregister('openrouter');
|
|
10
|
+
}
|
|
11
|
+
});
|
|
12
|
+
describe('@namzu/openrouter', () => {
|
|
13
|
+
describe('registerOpenRouter()', () => {
|
|
14
|
+
it("adds 'openrouter' to the ProviderRegistry", () => {
|
|
15
|
+
expect(ProviderRegistry.isSupported('openrouter')).toBe(false);
|
|
16
|
+
registerOpenRouter();
|
|
17
|
+
expect(ProviderRegistry.isSupported('openrouter')).toBe(true);
|
|
18
|
+
expect(ProviderRegistry.listTypes()).toContain('openrouter');
|
|
19
|
+
});
|
|
20
|
+
it('throws DuplicateProviderError when called twice without options', () => {
|
|
21
|
+
registerOpenRouter();
|
|
22
|
+
expect(() => registerOpenRouter()).toThrowError(DuplicateProviderError);
|
|
23
|
+
});
|
|
24
|
+
it('allows re-registration when { replace: true } is passed', () => {
|
|
25
|
+
registerOpenRouter();
|
|
26
|
+
expect(() => registerOpenRouter({ replace: true })).not.toThrow();
|
|
27
|
+
expect(ProviderRegistry.isSupported('openrouter')).toBe(true);
|
|
28
|
+
});
|
|
29
|
+
it('exposes capabilities through the registry after registration', () => {
|
|
30
|
+
registerOpenRouter();
|
|
31
|
+
const caps = ProviderRegistry.getCapabilities('openrouter');
|
|
32
|
+
expect(caps).toEqual(OPENROUTER_CAPABILITIES);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
describe('OPENROUTER_CAPABILITIES', () => {
|
|
36
|
+
it('declares the expected capability flags', () => {
|
|
37
|
+
expect(OPENROUTER_CAPABILITIES).toEqual({
|
|
38
|
+
supportsTools: true,
|
|
39
|
+
supportsStreaming: true,
|
|
40
|
+
supportsFunctionCalling: true,
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
describe('ProviderRegistry.create({ type: "openrouter", ... })', () => {
|
|
45
|
+
it('narrows the config type via module augmentation and instantiates OpenRouterProvider', () => {
|
|
46
|
+
registerOpenRouter();
|
|
47
|
+
const { provider, capabilities } = ProviderRegistry.create({
|
|
48
|
+
type: 'openrouter',
|
|
49
|
+
apiKey: 'test-key',
|
|
50
|
+
siteUrl: 'https://example.com',
|
|
51
|
+
siteName: 'Test',
|
|
52
|
+
});
|
|
53
|
+
expect(provider).toBeInstanceOf(OpenRouterProvider);
|
|
54
|
+
expect(capabilities).toEqual(OPENROUTER_CAPABILITIES);
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
//# sourceMappingURL=openrouter.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openrouter.test.js","sourceRoot":"","sources":["../../src/__tests__/openrouter.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AACrE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,E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ompletionParams, ChatCompletionResponse, LLMProvider, ModelInfo, StreamChunk } from '@namzu/sdk';
|
|
2
|
+
import type { OpenRouterConfig } from './types.js';
|
|
3
|
+
export declare class OpenRouterProvider implements LLMProvider {
|
|
4
|
+
readonly id = "openrouter";
|
|
5
|
+
readonly name = "OpenRouter";
|
|
6
|
+
private config;
|
|
7
|
+
private baseUrl;
|
|
8
|
+
constructor(config: OpenRouterConfig);
|
|
9
|
+
private getHeaders;
|
|
10
|
+
private formatMessages;
|
|
11
|
+
private buildRequestBody;
|
|
12
|
+
chat(params: ChatCompletionParams): Promise<ChatCompletionResponse>;
|
|
13
|
+
chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk>;
|
|
14
|
+
listModels(): Promise<ModelInfo[]>;
|
|
15
|
+
healthCheck(): Promise<boolean>;
|
|
16
|
+
}
|
|
17
|
+
//# 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;AACnB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAwClD,qBAAa,kBAAmB,YAAW,WAAW;IACrD,QAAQ,CAAC,EAAE,gBAAe;IAC1B,QAAQ,CAAC,IAAI,gBAAe;IAE5B,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,OAAO,CAAQ;gBAEX,MAAM,EAAE,gBAAgB;IAQpC,OAAO,CAAC,UAAU;IAclB,OAAO,CAAC,cAAc;IAwBtB,OAAO,CAAC,gBAAgB;IAqClB,IAAI,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,sBAAsB,CAAC;IA2DlE,UAAU,CAAC,MAAM,EAAE,oBAAoB,GAAG,aAAa,CAAC,WAAW,CAAC;IAyFrE,UAAU,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IA+BlC,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAWrC"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
const OPENROUTER_BASE_URL = process.env.OPENROUTER_BASE_URL ?? 'https://openrouter.ai/api/v1';
|
|
2
|
+
function parseUsage(raw) {
|
|
3
|
+
if (!raw) {
|
|
4
|
+
return {
|
|
5
|
+
promptTokens: 0,
|
|
6
|
+
completionTokens: 0,
|
|
7
|
+
totalTokens: 0,
|
|
8
|
+
cachedTokens: 0,
|
|
9
|
+
cacheWriteTokens: 0,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
return {
|
|
13
|
+
promptTokens: raw.prompt_tokens,
|
|
14
|
+
completionTokens: raw.completion_tokens,
|
|
15
|
+
totalTokens: raw.total_tokens,
|
|
16
|
+
cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? raw.cache_read_input_tokens ?? 0,
|
|
17
|
+
cacheWriteTokens: raw.cache_creation_input_tokens ?? 0,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function formatToolChoice(tc) {
|
|
21
|
+
if (typeof tc === 'string')
|
|
22
|
+
return tc;
|
|
23
|
+
return tc;
|
|
24
|
+
}
|
|
25
|
+
export class OpenRouterProvider {
|
|
26
|
+
id = 'openrouter';
|
|
27
|
+
name = 'OpenRouter';
|
|
28
|
+
config;
|
|
29
|
+
baseUrl;
|
|
30
|
+
constructor(config) {
|
|
31
|
+
if (!config.apiKey) {
|
|
32
|
+
throw new Error('OpenRouter API key is required. Set OPENROUTER_API_KEY env variable.');
|
|
33
|
+
}
|
|
34
|
+
this.config = config;
|
|
35
|
+
this.baseUrl = config.baseUrl ?? OPENROUTER_BASE_URL;
|
|
36
|
+
}
|
|
37
|
+
getHeaders() {
|
|
38
|
+
const headers = {
|
|
39
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
40
|
+
'Content-Type': 'application/json',
|
|
41
|
+
};
|
|
42
|
+
if (this.config.siteUrl) {
|
|
43
|
+
headers['HTTP-Referer'] = this.config.siteUrl;
|
|
44
|
+
}
|
|
45
|
+
if (this.config.siteName) {
|
|
46
|
+
headers['X-Title'] = this.config.siteName;
|
|
47
|
+
}
|
|
48
|
+
return headers;
|
|
49
|
+
}
|
|
50
|
+
formatMessages(messages) {
|
|
51
|
+
return messages.map((msg) => {
|
|
52
|
+
if (msg.role === 'tool') {
|
|
53
|
+
return {
|
|
54
|
+
role: 'tool',
|
|
55
|
+
content: msg.content,
|
|
56
|
+
tool_call_id: msg.toolCallId,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls) {
|
|
60
|
+
return {
|
|
61
|
+
role: 'assistant',
|
|
62
|
+
content: msg.content,
|
|
63
|
+
tool_calls: msg.toolCalls.map((tc) => ({
|
|
64
|
+
id: tc.id,
|
|
65
|
+
type: tc.type,
|
|
66
|
+
function: tc.function,
|
|
67
|
+
})),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
return { role: msg.role, content: msg.content };
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
buildRequestBody(params, stream) {
|
|
74
|
+
const body = {
|
|
75
|
+
model: params.model,
|
|
76
|
+
messages: this.formatMessages(params.messages),
|
|
77
|
+
stream,
|
|
78
|
+
};
|
|
79
|
+
if (params.tools && params.tools.length > 0) {
|
|
80
|
+
body.tools = params.tools;
|
|
81
|
+
}
|
|
82
|
+
if (params.toolChoice !== undefined) {
|
|
83
|
+
body.tool_choice = formatToolChoice(params.toolChoice);
|
|
84
|
+
}
|
|
85
|
+
if (params.parallelToolCalls !== undefined) {
|
|
86
|
+
body.parallel_tool_calls = params.parallelToolCalls;
|
|
87
|
+
}
|
|
88
|
+
if (params.temperature !== undefined)
|
|
89
|
+
body.temperature = params.temperature;
|
|
90
|
+
if (params.maxTokens !== undefined)
|
|
91
|
+
body.max_tokens = params.maxTokens;
|
|
92
|
+
if (params.topP !== undefined)
|
|
93
|
+
body.top_p = params.topP;
|
|
94
|
+
if (params.topK !== undefined)
|
|
95
|
+
body.top_k = params.topK;
|
|
96
|
+
if (params.frequencyPenalty !== undefined)
|
|
97
|
+
body.frequency_penalty = params.frequencyPenalty;
|
|
98
|
+
if (params.presencePenalty !== undefined)
|
|
99
|
+
body.presence_penalty = params.presencePenalty;
|
|
100
|
+
if (params.repetitionPenalty !== undefined)
|
|
101
|
+
body.repetition_penalty = params.repetitionPenalty;
|
|
102
|
+
if (params.stop)
|
|
103
|
+
body.stop = params.stop;
|
|
104
|
+
if (params.cacheControl) {
|
|
105
|
+
body.cache_control = params.cacheControl;
|
|
106
|
+
}
|
|
107
|
+
if (params.responseFormat) {
|
|
108
|
+
body.response_format = params.responseFormat;
|
|
109
|
+
}
|
|
110
|
+
return body;
|
|
111
|
+
}
|
|
112
|
+
async chat(params) {
|
|
113
|
+
const body = this.buildRequestBody(params, false);
|
|
114
|
+
const response = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
115
|
+
method: 'POST',
|
|
116
|
+
headers: this.getHeaders(),
|
|
117
|
+
body: JSON.stringify(body),
|
|
118
|
+
signal: AbortSignal.timeout(this.config.timeout ?? 120_000),
|
|
119
|
+
});
|
|
120
|
+
if (!response.ok) {
|
|
121
|
+
const errorBody = await response.text();
|
|
122
|
+
throw new Error(`OpenRouter API error (${response.status}): ${errorBody}`);
|
|
123
|
+
}
|
|
124
|
+
const data = (await response.json());
|
|
125
|
+
const choice = data.choices[0];
|
|
126
|
+
if (!choice) {
|
|
127
|
+
throw new Error('OpenRouter returned empty choices');
|
|
128
|
+
}
|
|
129
|
+
const usage = parseUsage(data.usage);
|
|
130
|
+
const result = {
|
|
131
|
+
id: data.id,
|
|
132
|
+
model: data.model,
|
|
133
|
+
message: {
|
|
134
|
+
role: 'assistant',
|
|
135
|
+
content: choice.message.content,
|
|
136
|
+
toolCalls: choice.message.tool_calls?.map((tc) => ({
|
|
137
|
+
id: tc.id,
|
|
138
|
+
type: 'function',
|
|
139
|
+
function: tc.function,
|
|
140
|
+
})),
|
|
141
|
+
},
|
|
142
|
+
finishReason: choice.finish_reason,
|
|
143
|
+
usage,
|
|
144
|
+
};
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
async *chatStream(params) {
|
|
148
|
+
const body = this.buildRequestBody(params, true);
|
|
149
|
+
const response = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
150
|
+
method: 'POST',
|
|
151
|
+
headers: this.getHeaders(),
|
|
152
|
+
body: JSON.stringify(body),
|
|
153
|
+
signal: AbortSignal.timeout(this.config.timeout ?? 120_000),
|
|
154
|
+
});
|
|
155
|
+
if (!response.ok) {
|
|
156
|
+
const errorBody = await response.text();
|
|
157
|
+
throw new Error(`OpenRouter API error (${response.status}): ${errorBody}`);
|
|
158
|
+
}
|
|
159
|
+
if (!response.body) {
|
|
160
|
+
throw new Error('OpenRouter returned no stream body');
|
|
161
|
+
}
|
|
162
|
+
const reader = response.body.getReader();
|
|
163
|
+
const decoder = new TextDecoder();
|
|
164
|
+
let buffer = '';
|
|
165
|
+
try {
|
|
166
|
+
while (true) {
|
|
167
|
+
const { done, value } = await reader.read();
|
|
168
|
+
if (done)
|
|
169
|
+
break;
|
|
170
|
+
buffer += decoder.decode(value, { stream: true });
|
|
171
|
+
const lines = buffer.split('\n');
|
|
172
|
+
buffer = lines.pop() ?? '';
|
|
173
|
+
for (const line of lines) {
|
|
174
|
+
const trimmed = line.trim();
|
|
175
|
+
if (!trimmed || !trimmed.startsWith('data: '))
|
|
176
|
+
continue;
|
|
177
|
+
const data = trimmed.slice(6);
|
|
178
|
+
if (data === '[DONE]')
|
|
179
|
+
return;
|
|
180
|
+
try {
|
|
181
|
+
const parsed = JSON.parse(data);
|
|
182
|
+
const choice = parsed.choices[0];
|
|
183
|
+
if (!choice)
|
|
184
|
+
continue;
|
|
185
|
+
yield {
|
|
186
|
+
id: parsed.id,
|
|
187
|
+
delta: {
|
|
188
|
+
content: choice.delta.content,
|
|
189
|
+
toolCalls: choice.delta.tool_calls?.map((tc) => ({
|
|
190
|
+
index: tc.index,
|
|
191
|
+
id: tc.id,
|
|
192
|
+
type: tc.type,
|
|
193
|
+
function: tc.function,
|
|
194
|
+
})),
|
|
195
|
+
},
|
|
196
|
+
finishReason: choice.finish_reason,
|
|
197
|
+
usage: parsed.usage ? parseUsage(parsed.usage) : undefined,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
catch (parseErr) {
|
|
201
|
+
yield {
|
|
202
|
+
id: '',
|
|
203
|
+
delta: { content: undefined },
|
|
204
|
+
finishReason: undefined,
|
|
205
|
+
usage: undefined,
|
|
206
|
+
error: `Stream parse error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
finally {
|
|
213
|
+
reader.releaseLock();
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
async listModels() {
|
|
217
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
218
|
+
headers: this.getHeaders(),
|
|
219
|
+
});
|
|
220
|
+
if (!response.ok) {
|
|
221
|
+
throw new Error(`Failed to list models: ${response.status}`);
|
|
222
|
+
}
|
|
223
|
+
const data = (await response.json());
|
|
224
|
+
return data.data.map((m) => ({
|
|
225
|
+
id: m.id,
|
|
226
|
+
name: m.name,
|
|
227
|
+
contextWindow: m.context_length,
|
|
228
|
+
maxOutputTokens: m.top_provider?.max_completion_tokens ?? 4096,
|
|
229
|
+
inputPrice: Number.parseFloat(m.pricing?.prompt ?? '0') * 1_000_000,
|
|
230
|
+
outputPrice: Number.parseFloat(m.pricing?.completion ?? '0') * 1_000_000,
|
|
231
|
+
supportsToolUse: true,
|
|
232
|
+
supportsStreaming: true,
|
|
233
|
+
}));
|
|
234
|
+
}
|
|
235
|
+
async healthCheck() {
|
|
236
|
+
try {
|
|
237
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
238
|
+
headers: this.getHeaders(),
|
|
239
|
+
signal: AbortSignal.timeout(5000),
|
|
240
|
+
});
|
|
241
|
+
return response.ok;
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAWA,MAAM,mBAAmB,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,8BAA8B,CAAA;AAc7F,SAAS,UAAU,CAAC,GAAc;IACjC,IAAI,CAAC,GAAG,EAAE,CAAC;QACV,OAAO;YACN,YAAY,EAAE,CAAC;YACf,gBAAgB,EAAE,CAAC;YACnB,WAAW,EAAE,CAAC;YACd,YAAY,EAAE,CAAC;YACf,gBAAgB,EAAE,CAAC;SACnB,CAAA;IACF,CAAC;IACD,OAAO;QACN,YAAY,EAAE,GAAG,CAAC,aAAa;QAC/B,gBAAgB,EAAE,GAAG,CAAC,iBAAiB;QACvC,WAAW,EAAE,GAAG,CAAC,YAAY;QAC7B,YAAY,EAAE,GAAG,CAAC,qBAAqB,EAAE,aAAa,IAAI,GAAG,CAAC,uBAAuB,IAAI,CAAC;QAC1F,gBAAgB,EAAE,GAAG,CAAC,2BAA2B,IAAI,CAAC;KACtD,CAAA;AACF,CAAC;AAED,SAAS,gBAAgB,CAAC,EAAc;IACvC,IAAI,OAAO,EAAE,KAAK,QAAQ;QAAE,OAAO,EAAE,CAAA;IACrC,OAAO,EAAE,CAAA;AACV,CAAC;AAED,MAAM,OAAO,kBAAkB;IACrB,EAAE,GAAG,YAAY,CAAA;IACjB,IAAI,GAAG,YAAY,CAAA;IAEpB,MAAM,CAAkB;IACxB,OAAO,CAAQ;IAEvB,YAAY,MAAwB;QACnC,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CAAA;QACnB,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 { OpenRouterProviderConfig } from './types.js';
|
|
3
|
+
declare module '@namzu/sdk' {
|
|
4
|
+
interface ProviderConfigRegistry {
|
|
5
|
+
openrouter: OpenRouterProviderConfig;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export declare const OPENROUTER_CAPABILITIES: ProviderCapabilities;
|
|
9
|
+
/**
|
|
10
|
+
* Register `OpenRouterProvider` under the `'openrouter'` type in `@namzu/sdk`'s
|
|
11
|
+
* `ProviderRegistry`. Call once at app startup before
|
|
12
|
+
* `ProviderRegistry.create({ type: 'openrouter', ... })`.
|
|
13
|
+
*
|
|
14
|
+
* Throws `DuplicateProviderError` if `'openrouter'` is already registered.
|
|
15
|
+
* Pass `{ replace: true }` to override.
|
|
16
|
+
*/
|
|
17
|
+
export declare function registerOpenRouter(options?: RegisterOptions): void;
|
|
18
|
+
export { OpenRouterProvider } from './client.js';
|
|
19
|
+
export type { OpenRouterConfig, OpenRouterProviderConfig } 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,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAK1D,OAAO,QAAQ,YAAY,CAAC;IAC3B,UAAU,sBAAsB;QAC/B,UAAU,EAAE,wBAAwB,CAAA;KACpC;CACD;AAED,eAAO,MAAM,uBAAuB,EAAE,oBAIrC,CAAA;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAElE;AAED,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAChD,YAAY,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ProviderRegistry } from '@namzu/sdk';
|
|
2
|
+
import { OpenRouterProvider } from './client.js';
|
|
3
|
+
export const OPENROUTER_CAPABILITIES = {
|
|
4
|
+
supportsTools: true,
|
|
5
|
+
supportsStreaming: true,
|
|
6
|
+
supportsFunctionCalling: true,
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Register `OpenRouterProvider` under the `'openrouter'` type in `@namzu/sdk`'s
|
|
10
|
+
* `ProviderRegistry`. Call once at app startup before
|
|
11
|
+
* `ProviderRegistry.create({ type: 'openrouter', ... })`.
|
|
12
|
+
*
|
|
13
|
+
* Throws `DuplicateProviderError` if `'openrouter'` is already registered.
|
|
14
|
+
* Pass `{ replace: true }` to override.
|
|
15
|
+
*/
|
|
16
|
+
export function registerOpenRouter(options) {
|
|
17
|
+
ProviderRegistry.register('openrouter', OpenRouterProvider, OPENROUTER_CAPABILITIES, options);
|
|
18
|
+
}
|
|
19
|
+
export { OpenRouterProvider } 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,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAYhD,MAAM,CAAC,MAAM,uBAAuB,GAAyB;IAC5D,aAAa,EAAE,IAAI;IACnB,iBAAiB,EAAE,IAAI;IACvB,uBAAuB,EAAE,IAAI;CAC7B,CAAA;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAyB;IAC3D,gBAAgB,CAAC,QAAQ,CAAC,YAAY,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,OAAO,CAAC,CAAA;AAC9F,CAAC;AAED,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenRouter-specific provider config shapes.
|
|
3
|
+
*
|
|
4
|
+
* `OpenRouterConfig` is the constructor input for `OpenRouterProvider` (no
|
|
5
|
+
* discriminator). `OpenRouterProviderConfig` is the shape the consumer passes
|
|
6
|
+
* to `ProviderRegistry.create({ type: 'openrouter', ... })` — it extends
|
|
7
|
+
* `OpenRouterConfig` with the `type: 'openrouter'` discriminator for the
|
|
8
|
+
* registry's generic narrowing.
|
|
9
|
+
*/
|
|
10
|
+
export interface OpenRouterConfig {
|
|
11
|
+
apiKey: string;
|
|
12
|
+
baseUrl?: string;
|
|
13
|
+
siteUrl?: string;
|
|
14
|
+
siteName?: string;
|
|
15
|
+
timeout?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface OpenRouterProviderConfig extends OpenRouterConfig {
|
|
18
|
+
type: 'openrouter';
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,OAAO,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;IACjE,IAAI,EAAE,YAAY,CAAA;CAClB"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenRouter-specific provider config shapes.
|
|
3
|
+
*
|
|
4
|
+
* `OpenRouterConfig` is the constructor input for `OpenRouterProvider` (no
|
|
5
|
+
* discriminator). `OpenRouterProviderConfig` is the shape the consumer passes
|
|
6
|
+
* to `ProviderRegistry.create({ type: 'openrouter', ... })` — it extends
|
|
7
|
+
* `OpenRouterConfig` with the `type: 'openrouter'` discriminator for the
|
|
8
|
+
* registry's generic narrowing.
|
|
9
|
+
*/
|
|
10
|
+
export {};
|
|
11
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG"}
|
package/package.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@namzu/openrouter",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "OpenRouter LLM provider for @namzu/sdk. Access to 200+ models (Claude, GPT-4, Llama, Mixtral) via OpenRouter's unified API.",
|
|
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/openrouter"
|
|
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
|
+
"peerDependencies": {
|
|
38
|
+
"@namzu/sdk": "^1 || ^0.1.6"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@biomejs/biome": "^1.9.4",
|
|
42
|
+
"@types/node": "^22.19.17",
|
|
43
|
+
"typescript": "^5.5.0",
|
|
44
|
+
"vitest": "^2.0.0",
|
|
45
|
+
"@namzu/sdk": "^0.1.8"
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "tsc --build",
|
|
49
|
+
"dev": "tsc --build --watch",
|
|
50
|
+
"lint": "biome check src/",
|
|
51
|
+
"lint:fix": "biome check --write src/",
|
|
52
|
+
"format": "biome format --write src/",
|
|
53
|
+
"test": "vitest run --passWithNoTests",
|
|
54
|
+
"typecheck": "tsc --noEmit",
|
|
55
|
+
"verify": "bash scripts/verify.sh",
|
|
56
|
+
"release:patch": "bash scripts/release.sh patch",
|
|
57
|
+
"release:minor": "bash scripts/release.sh minor",
|
|
58
|
+
"release:major": "bash scripts/release.sh major",
|
|
59
|
+
"release:rc": "bash scripts/release.sh rc",
|
|
60
|
+
"release:beta": "bash scripts/release.sh beta",
|
|
61
|
+
"release:stable": "bash scripts/release.sh stable",
|
|
62
|
+
"release:dry": "bash scripts/release.sh patch --dry-run"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { DuplicateProviderError, ProviderRegistry } from '@namzu/sdk'
|
|
2
|
+
import { beforeEach, describe, expect, it } from 'vitest'
|
|
3
|
+
import { OPENROUTER_CAPABILITIES, OpenRouterProvider, registerOpenRouter } 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 'openrouter' to make
|
|
7
|
+
// re-registration deterministic across tests.
|
|
8
|
+
beforeEach(() => {
|
|
9
|
+
if (ProviderRegistry.isSupported('openrouter')) {
|
|
10
|
+
ProviderRegistry.unregister('openrouter')
|
|
11
|
+
}
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
describe('@namzu/openrouter', () => {
|
|
15
|
+
describe('registerOpenRouter()', () => {
|
|
16
|
+
it("adds 'openrouter' to the ProviderRegistry", () => {
|
|
17
|
+
expect(ProviderRegistry.isSupported('openrouter')).toBe(false)
|
|
18
|
+
registerOpenRouter()
|
|
19
|
+
expect(ProviderRegistry.isSupported('openrouter')).toBe(true)
|
|
20
|
+
expect(ProviderRegistry.listTypes()).toContain('openrouter')
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('throws DuplicateProviderError when called twice without options', () => {
|
|
24
|
+
registerOpenRouter()
|
|
25
|
+
expect(() => registerOpenRouter()).toThrowError(DuplicateProviderError)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('allows re-registration when { replace: true } is passed', () => {
|
|
29
|
+
registerOpenRouter()
|
|
30
|
+
expect(() => registerOpenRouter({ replace: true })).not.toThrow()
|
|
31
|
+
expect(ProviderRegistry.isSupported('openrouter')).toBe(true)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('exposes capabilities through the registry after registration', () => {
|
|
35
|
+
registerOpenRouter()
|
|
36
|
+
const caps = ProviderRegistry.getCapabilities('openrouter')
|
|
37
|
+
expect(caps).toEqual(OPENROUTER_CAPABILITIES)
|
|
38
|
+
})
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
describe('OPENROUTER_CAPABILITIES', () => {
|
|
42
|
+
it('declares the expected capability flags', () => {
|
|
43
|
+
expect(OPENROUTER_CAPABILITIES).toEqual({
|
|
44
|
+
supportsTools: true,
|
|
45
|
+
supportsStreaming: true,
|
|
46
|
+
supportsFunctionCalling: true,
|
|
47
|
+
})
|
|
48
|
+
})
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
describe('ProviderRegistry.create({ type: "openrouter", ... })', () => {
|
|
52
|
+
it('narrows the config type via module augmentation and instantiates OpenRouterProvider', () => {
|
|
53
|
+
registerOpenRouter()
|
|
54
|
+
const { provider, capabilities } = ProviderRegistry.create({
|
|
55
|
+
type: 'openrouter',
|
|
56
|
+
apiKey: 'test-key',
|
|
57
|
+
siteUrl: 'https://example.com',
|
|
58
|
+
siteName: 'Test',
|
|
59
|
+
})
|
|
60
|
+
expect(provider).toBeInstanceOf(OpenRouterProvider)
|
|
61
|
+
expect(capabilities).toEqual(OPENROUTER_CAPABILITIES)
|
|
62
|
+
})
|
|
63
|
+
})
|
|
64
|
+
})
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ChatCompletionParams,
|
|
3
|
+
ChatCompletionResponse,
|
|
4
|
+
LLMProvider,
|
|
5
|
+
ModelInfo,
|
|
6
|
+
StreamChunk,
|
|
7
|
+
TokenUsage,
|
|
8
|
+
ToolChoice,
|
|
9
|
+
} from '@namzu/sdk'
|
|
10
|
+
import type { OpenRouterConfig } from './types.js'
|
|
11
|
+
|
|
12
|
+
const OPENROUTER_BASE_URL = process.env.OPENROUTER_BASE_URL ?? 'https://openrouter.ai/api/v1'
|
|
13
|
+
|
|
14
|
+
interface RawUsage {
|
|
15
|
+
prompt_tokens: number
|
|
16
|
+
completion_tokens: number
|
|
17
|
+
total_tokens: number
|
|
18
|
+
prompt_tokens_details?: {
|
|
19
|
+
cached_tokens?: number
|
|
20
|
+
}
|
|
21
|
+
cache_discount?: number
|
|
22
|
+
cache_read_input_tokens?: number
|
|
23
|
+
cache_creation_input_tokens?: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function parseUsage(raw?: RawUsage): TokenUsage {
|
|
27
|
+
if (!raw) {
|
|
28
|
+
return {
|
|
29
|
+
promptTokens: 0,
|
|
30
|
+
completionTokens: 0,
|
|
31
|
+
totalTokens: 0,
|
|
32
|
+
cachedTokens: 0,
|
|
33
|
+
cacheWriteTokens: 0,
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
promptTokens: raw.prompt_tokens,
|
|
38
|
+
completionTokens: raw.completion_tokens,
|
|
39
|
+
totalTokens: raw.total_tokens,
|
|
40
|
+
cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? raw.cache_read_input_tokens ?? 0,
|
|
41
|
+
cacheWriteTokens: raw.cache_creation_input_tokens ?? 0,
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function formatToolChoice(tc: ToolChoice): unknown {
|
|
46
|
+
if (typeof tc === 'string') return tc
|
|
47
|
+
return tc
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class OpenRouterProvider implements LLMProvider {
|
|
51
|
+
readonly id = 'openrouter'
|
|
52
|
+
readonly name = 'OpenRouter'
|
|
53
|
+
|
|
54
|
+
private config: OpenRouterConfig
|
|
55
|
+
private baseUrl: string
|
|
56
|
+
|
|
57
|
+
constructor(config: OpenRouterConfig) {
|
|
58
|
+
if (!config.apiKey) {
|
|
59
|
+
throw new Error('OpenRouter API key is required. Set OPENROUTER_API_KEY env variable.')
|
|
60
|
+
}
|
|
61
|
+
this.config = config
|
|
62
|
+
this.baseUrl = config.baseUrl ?? OPENROUTER_BASE_URL
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private getHeaders(): Record<string, string> {
|
|
66
|
+
const headers: Record<string, string> = {
|
|
67
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
68
|
+
'Content-Type': 'application/json',
|
|
69
|
+
}
|
|
70
|
+
if (this.config.siteUrl) {
|
|
71
|
+
headers['HTTP-Referer'] = this.config.siteUrl
|
|
72
|
+
}
|
|
73
|
+
if (this.config.siteName) {
|
|
74
|
+
headers['X-Title'] = this.config.siteName
|
|
75
|
+
}
|
|
76
|
+
return headers
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private formatMessages(messages: ChatCompletionParams['messages']): unknown[] {
|
|
80
|
+
return messages.map((msg) => {
|
|
81
|
+
if (msg.role === 'tool') {
|
|
82
|
+
return {
|
|
83
|
+
role: 'tool',
|
|
84
|
+
content: msg.content,
|
|
85
|
+
tool_call_id: (msg as { toolCallId?: string }).toolCallId,
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls) {
|
|
89
|
+
return {
|
|
90
|
+
role: 'assistant',
|
|
91
|
+
content: msg.content,
|
|
92
|
+
tool_calls: msg.toolCalls.map((tc) => ({
|
|
93
|
+
id: tc.id,
|
|
94
|
+
type: tc.type,
|
|
95
|
+
function: tc.function,
|
|
96
|
+
})),
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return { role: msg.role, content: msg.content }
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private buildRequestBody(params: ChatCompletionParams, stream: boolean): Record<string, unknown> {
|
|
104
|
+
const body: Record<string, unknown> = {
|
|
105
|
+
model: params.model,
|
|
106
|
+
messages: this.formatMessages(params.messages),
|
|
107
|
+
stream,
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (params.tools && params.tools.length > 0) {
|
|
111
|
+
body.tools = params.tools
|
|
112
|
+
}
|
|
113
|
+
if (params.toolChoice !== undefined) {
|
|
114
|
+
body.tool_choice = formatToolChoice(params.toolChoice)
|
|
115
|
+
}
|
|
116
|
+
if (params.parallelToolCalls !== undefined) {
|
|
117
|
+
body.parallel_tool_calls = params.parallelToolCalls
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (params.temperature !== undefined) body.temperature = params.temperature
|
|
121
|
+
if (params.maxTokens !== undefined) body.max_tokens = params.maxTokens
|
|
122
|
+
if (params.topP !== undefined) body.top_p = params.topP
|
|
123
|
+
if (params.topK !== undefined) body.top_k = params.topK
|
|
124
|
+
if (params.frequencyPenalty !== undefined) body.frequency_penalty = params.frequencyPenalty
|
|
125
|
+
if (params.presencePenalty !== undefined) body.presence_penalty = params.presencePenalty
|
|
126
|
+
if (params.repetitionPenalty !== undefined) body.repetition_penalty = params.repetitionPenalty
|
|
127
|
+
if (params.stop) body.stop = params.stop
|
|
128
|
+
|
|
129
|
+
if (params.cacheControl) {
|
|
130
|
+
body.cache_control = params.cacheControl
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (params.responseFormat) {
|
|
134
|
+
body.response_format = params.responseFormat
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return body
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async chat(params: ChatCompletionParams): Promise<ChatCompletionResponse> {
|
|
141
|
+
const body = this.buildRequestBody(params, false)
|
|
142
|
+
|
|
143
|
+
const response = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
144
|
+
method: 'POST',
|
|
145
|
+
headers: this.getHeaders(),
|
|
146
|
+
body: JSON.stringify(body),
|
|
147
|
+
signal: AbortSignal.timeout(this.config.timeout ?? 120_000),
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
if (!response.ok) {
|
|
151
|
+
const errorBody = await response.text()
|
|
152
|
+
throw new Error(`OpenRouter API error (${response.status}): ${errorBody}`)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const data = (await response.json()) as {
|
|
156
|
+
id: string
|
|
157
|
+
model: string
|
|
158
|
+
choices: Array<{
|
|
159
|
+
message: {
|
|
160
|
+
role: string
|
|
161
|
+
content: string | null
|
|
162
|
+
tool_calls?: Array<{
|
|
163
|
+
id: string
|
|
164
|
+
type: string
|
|
165
|
+
function: { name: string; arguments: string }
|
|
166
|
+
}>
|
|
167
|
+
}
|
|
168
|
+
finish_reason: string
|
|
169
|
+
}>
|
|
170
|
+
usage?: RawUsage
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const choice = data.choices[0]
|
|
174
|
+
if (!choice) {
|
|
175
|
+
throw new Error('OpenRouter returned empty choices')
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const usage = parseUsage(data.usage)
|
|
179
|
+
|
|
180
|
+
const result: ChatCompletionResponse = {
|
|
181
|
+
id: data.id,
|
|
182
|
+
model: data.model,
|
|
183
|
+
message: {
|
|
184
|
+
role: 'assistant',
|
|
185
|
+
content: choice.message.content,
|
|
186
|
+
toolCalls: choice.message.tool_calls?.map((tc) => ({
|
|
187
|
+
id: tc.id,
|
|
188
|
+
type: 'function' as const,
|
|
189
|
+
function: tc.function,
|
|
190
|
+
})),
|
|
191
|
+
},
|
|
192
|
+
finishReason: choice.finish_reason as ChatCompletionResponse['finishReason'],
|
|
193
|
+
usage,
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return result
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
|
|
200
|
+
const body = this.buildRequestBody(params, true)
|
|
201
|
+
|
|
202
|
+
const response = await fetch(`${this.baseUrl}/chat/completions`, {
|
|
203
|
+
method: 'POST',
|
|
204
|
+
headers: this.getHeaders(),
|
|
205
|
+
body: JSON.stringify(body),
|
|
206
|
+
signal: AbortSignal.timeout(this.config.timeout ?? 120_000),
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
if (!response.ok) {
|
|
210
|
+
const errorBody = await response.text()
|
|
211
|
+
throw new Error(`OpenRouter API error (${response.status}): ${errorBody}`)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (!response.body) {
|
|
215
|
+
throw new Error('OpenRouter returned no stream body')
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const reader = response.body.getReader()
|
|
219
|
+
const decoder = new TextDecoder()
|
|
220
|
+
let buffer = ''
|
|
221
|
+
|
|
222
|
+
try {
|
|
223
|
+
while (true) {
|
|
224
|
+
const { done, value } = await reader.read()
|
|
225
|
+
if (done) break
|
|
226
|
+
|
|
227
|
+
buffer += decoder.decode(value, { stream: true })
|
|
228
|
+
const lines = buffer.split('\n')
|
|
229
|
+
buffer = lines.pop() ?? ''
|
|
230
|
+
|
|
231
|
+
for (const line of lines) {
|
|
232
|
+
const trimmed = line.trim()
|
|
233
|
+
if (!trimmed || !trimmed.startsWith('data: ')) continue
|
|
234
|
+
const data = trimmed.slice(6)
|
|
235
|
+
if (data === '[DONE]') return
|
|
236
|
+
|
|
237
|
+
try {
|
|
238
|
+
const parsed = JSON.parse(data) as {
|
|
239
|
+
id: string
|
|
240
|
+
choices: Array<{
|
|
241
|
+
delta: {
|
|
242
|
+
content?: string
|
|
243
|
+
tool_calls?: Array<{
|
|
244
|
+
index: number
|
|
245
|
+
id?: string
|
|
246
|
+
type?: string
|
|
247
|
+
function?: { name?: string; arguments?: string }
|
|
248
|
+
}>
|
|
249
|
+
}
|
|
250
|
+
finish_reason?: string
|
|
251
|
+
}>
|
|
252
|
+
usage?: RawUsage
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const choice = parsed.choices[0]
|
|
256
|
+
if (!choice) continue
|
|
257
|
+
|
|
258
|
+
yield {
|
|
259
|
+
id: parsed.id,
|
|
260
|
+
delta: {
|
|
261
|
+
content: choice.delta.content,
|
|
262
|
+
toolCalls: choice.delta.tool_calls?.map((tc) => ({
|
|
263
|
+
index: tc.index,
|
|
264
|
+
id: tc.id,
|
|
265
|
+
type: tc.type as 'function' | undefined,
|
|
266
|
+
function: tc.function,
|
|
267
|
+
})),
|
|
268
|
+
},
|
|
269
|
+
finishReason: choice.finish_reason as StreamChunk['finishReason'],
|
|
270
|
+
usage: parsed.usage ? parseUsage(parsed.usage) : undefined,
|
|
271
|
+
}
|
|
272
|
+
} catch (parseErr) {
|
|
273
|
+
yield {
|
|
274
|
+
id: '',
|
|
275
|
+
delta: { content: undefined },
|
|
276
|
+
finishReason: undefined,
|
|
277
|
+
usage: undefined,
|
|
278
|
+
error: `Stream parse error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
} finally {
|
|
284
|
+
reader.releaseLock()
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async listModels(): Promise<ModelInfo[]> {
|
|
289
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
290
|
+
headers: this.getHeaders(),
|
|
291
|
+
})
|
|
292
|
+
|
|
293
|
+
if (!response.ok) {
|
|
294
|
+
throw new Error(`Failed to list models: ${response.status}`)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const data = (await response.json()) as {
|
|
298
|
+
data: Array<{
|
|
299
|
+
id: string
|
|
300
|
+
name: string
|
|
301
|
+
context_length: number
|
|
302
|
+
top_provider?: { max_completion_tokens?: number }
|
|
303
|
+
pricing?: { prompt: string; completion: string }
|
|
304
|
+
}>
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
return data.data.map((m) => ({
|
|
308
|
+
id: m.id,
|
|
309
|
+
name: m.name,
|
|
310
|
+
contextWindow: m.context_length,
|
|
311
|
+
maxOutputTokens: m.top_provider?.max_completion_tokens ?? 4096,
|
|
312
|
+
inputPrice: Number.parseFloat(m.pricing?.prompt ?? '0') * 1_000_000,
|
|
313
|
+
outputPrice: Number.parseFloat(m.pricing?.completion ?? '0') * 1_000_000,
|
|
314
|
+
supportsToolUse: true,
|
|
315
|
+
supportsStreaming: true,
|
|
316
|
+
}))
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async healthCheck(): Promise<boolean> {
|
|
320
|
+
try {
|
|
321
|
+
const response = await fetch(`${this.baseUrl}/models`, {
|
|
322
|
+
headers: this.getHeaders(),
|
|
323
|
+
signal: AbortSignal.timeout(5000),
|
|
324
|
+
})
|
|
325
|
+
return response.ok
|
|
326
|
+
} catch {
|
|
327
|
+
return false
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type ProviderCapabilities, ProviderRegistry, type RegisterOptions } from '@namzu/sdk'
|
|
2
|
+
import { OpenRouterProvider } from './client.js'
|
|
3
|
+
import type { OpenRouterProviderConfig } from './types.js'
|
|
4
|
+
|
|
5
|
+
// Module augmentation: register openrouter's config type in the sdk's registry
|
|
6
|
+
// interface. This must live inside index.ts (not a .d.ts) so it executes when
|
|
7
|
+
// index.ts is imported.
|
|
8
|
+
declare module '@namzu/sdk' {
|
|
9
|
+
interface ProviderConfigRegistry {
|
|
10
|
+
openrouter: OpenRouterProviderConfig
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const OPENROUTER_CAPABILITIES: ProviderCapabilities = {
|
|
15
|
+
supportsTools: true,
|
|
16
|
+
supportsStreaming: true,
|
|
17
|
+
supportsFunctionCalling: true,
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Register `OpenRouterProvider` under the `'openrouter'` type in `@namzu/sdk`'s
|
|
22
|
+
* `ProviderRegistry`. Call once at app startup before
|
|
23
|
+
* `ProviderRegistry.create({ type: 'openrouter', ... })`.
|
|
24
|
+
*
|
|
25
|
+
* Throws `DuplicateProviderError` if `'openrouter'` is already registered.
|
|
26
|
+
* Pass `{ replace: true }` to override.
|
|
27
|
+
*/
|
|
28
|
+
export function registerOpenRouter(options?: RegisterOptions): void {
|
|
29
|
+
ProviderRegistry.register('openrouter', OpenRouterProvider, OPENROUTER_CAPABILITIES, options)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export { OpenRouterProvider } from './client.js'
|
|
33
|
+
export type { OpenRouterConfig, OpenRouterProviderConfig } from './types.js'
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenRouter-specific provider config shapes.
|
|
3
|
+
*
|
|
4
|
+
* `OpenRouterConfig` is the constructor input for `OpenRouterProvider` (no
|
|
5
|
+
* discriminator). `OpenRouterProviderConfig` is the shape the consumer passes
|
|
6
|
+
* to `ProviderRegistry.create({ type: 'openrouter', ... })` — it extends
|
|
7
|
+
* `OpenRouterConfig` with the `type: 'openrouter'` discriminator for the
|
|
8
|
+
* registry's generic narrowing.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface OpenRouterConfig {
|
|
12
|
+
apiKey: string
|
|
13
|
+
baseUrl?: string
|
|
14
|
+
siteUrl?: string
|
|
15
|
+
siteName?: string
|
|
16
|
+
timeout?: number
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface OpenRouterProviderConfig extends OpenRouterConfig {
|
|
20
|
+
type: 'openrouter'
|
|
21
|
+
}
|