@kindgi/adapter-model-openai-compat 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kindgi Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # `@kindgi/adapter-model-openai-compat`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenAI-compatible `ModelProvider` for [`@kindgi/capabilities`](../../capabilities/). Wraps the official `openai` SDK client behind the framework's provider-neutral interface and works against any endpoint that speaks the Chat Completions wire format — OpenAI, Ollama, vLLM, llama-server, LM Studio, OpenRouter, Groq, Together, Fireworks, DeepInfra, or a LiteLLM proxy. One adapter, many backends: `baseURL` selects the endpoint.
4
+
5
+ ## Purpose
6
+
7
+ Translate between the framework's `ModelCallInput` / `ModelCallResult` and a non-streaming `chat.completions.create` call:
8
+
9
+ - Messages map role for role. Assistant `toolCalls` become `tool_calls` with JSON-encoded arguments; `tool` messages carry `tool_call_id`.
10
+ - `tools` become `function` tools; `structuredOutput` becomes `response_format: { type: 'json_schema', json_schema: { name, schema, strict: true } }`; `temperature` and `maxOutputTokens` (as `max_tokens`) are sent only when set.
11
+ - Chat Completions endpoints reject `.` in function names, so tool names are encoded `.` → `__` on send and decoded on receive (`acme.orders.lookup` ↔ `acme__orders__lookup`). Tool ids must not contain a literal `__`. Tool-call arguments that are not valid JSON decode to `{}`.
12
+ - `finish_reason` maps `tool_calls` / `function_call` → `tool-use`, `content_filter` → `content-filter`, `length` → `length`, anything else → `stop`.
13
+ - `costUsd` is computed from the matching `ModelInfo.cost`: prompt and completion tokens, each per 1K tokens. The wire format carries no pricing, so rates come from the caller.
14
+
15
+ ## Exports
16
+
17
+ - **`createOpenAICompatModelProvider(options)`** — returns a `ModelProvider` whose `metadata` is `options.metadata` unchanged. The SDK client is created on the first `invoke()` and reused while the key stays the same. `invoke()` throws when `input.model` is not one of `metadata.models[].name`, and passes the turn's `abortSignal` to the request, so a cancelled turn cancels the call.
18
+ - **`OpenAICompatProviderOptions`**:
19
+ - `baseURL: string` — endpoint root, e.g. `BASE_URLS.OLLAMA_LOCAL`.
20
+ - `apiKey: string | (() => string | Promise<string>)` — a static key, or a resolver called on every `invoke()`: a rotated key takes effect on the next call. Local runners that ignore keys still need a non-empty string such as `'unused'`.
21
+ - `metadata: ProviderMetadata` — surfaced to the router. `models[]` must list every model invoked through this connection, with its per-1K-token cost.
22
+ - `clientOptions?` — other `openai` client options (`timeout`, `maxRetries`, `defaultHeaders`, `fetch`, …); `apiKey` and `baseURL` are excluded.
23
+ - `extraBody?` — fields merged into every request body: settings an endpoint takes that the OpenAI format has no field for. A Qwen thinking model served by vLLM, SGLang or llama-server needs `{ chat_template_kwargs: { enable_thinking: false } }`, or its answer starts with its thinking and a typed (JSON) answer fails. The fields the adapter sets (`EXTRA_BODY_RESERVED`: `model`, `messages`, `tools`, `response_format`, `temperature`, `max_tokens`, `stream`) are refused.
24
+ - **`openAICompatAdapterFactory`** (`OPENAI_COMPAT_ADAPTER_ID`) — the `AdapterFactory` a runtime registers. A provider registration names its endpoint in `adapter_config.baseURL` (an http(s) URL; `openAICompatBaseUrl` reads and checks it), any extra request fields as `extraBody.*` keys (`adapter_config` is flat, so one key per field and dots nest: `"extraBody.chat_template_kwargs.enable_thinking": false`; `openAICompatExtraBody` expands and checks them), and, for an endpoint that needs a key, its secret in `secret_ref`; without one the adapter sends `'unused'`, as local runners expect.
25
+ - **`BASE_URLS`** — well-known endpoints: `OPENAI`, `OLLAMA_LOCAL`, `VLLM_LOCAL`, `LLAMA_SERVER_LOCAL`, `LM_STUDIO_LOCAL`, `OPENROUTER`, `GROQ`, `TOGETHER`, `FIREWORKS`, `DEEPINFRA`, `LITELLM_LOCAL`. Any other URL works too.
26
+ - **`ModelProvider`** — type re-export from `@kindgi/capabilities`.
27
+
28
+ ## Example
29
+
30
+ ```ts
31
+ import { createProviderRegistry } from '@kindgi/capabilities';
32
+ import { BASE_URLS, createOpenAICompatModelProvider } from '@kindgi/adapter-model-openai-compat';
33
+
34
+ const apiKey = process.env.OPENAI_API_KEY;
35
+ if (apiKey === undefined) throw new Error('OPENAI_API_KEY is not set');
36
+
37
+ const openai = createOpenAICompatModelProvider({
38
+ baseURL: BASE_URLS.OPENAI,
39
+ apiKey,
40
+ metadata: {
41
+ id: 'openai',
42
+ region: 'us',
43
+ models: [
44
+ {
45
+ name: 'gpt-4o-mini',
46
+ contextWindow: 128_000,
47
+ features: ['tool-use', 'structured-output'],
48
+ // Rates from the provider's published pricing.
49
+ cost: { promptUsdPer1kTokens: 0.00015, completionUsdPer1kTokens: 0.0006 },
50
+ },
51
+ ],
52
+ },
53
+ clientOptions: { timeout: 30_000 },
54
+ });
55
+
56
+ const { registry } = createProviderRegistry();
57
+ registry.register(tenantId, openai);
58
+
59
+ const result = await openai.invoke({
60
+ model: 'gpt-4o-mini',
61
+ messages: [{ role: 'user', content: 'What is the status of order 1042?' }],
62
+ tools: [
63
+ {
64
+ name: 'acme.orders.lookup',
65
+ description: 'Fetch an order by id.',
66
+ inputSchema: { type: 'object', properties: { orderId: { type: 'string' } }, required: ['orderId'] },
67
+ },
68
+ ],
69
+ });
70
+ for (const call of result.message.toolCalls ?? []) {
71
+ console.log(call.name, call.arguments); // acme.orders.lookup { orderId: '1042' }
72
+ }
73
+ console.log(result.finishReason, result.costUsd);
74
+ ```
75
+
76
+ A local runner uses the same factory: `baseURL: BASE_URLS.OLLAMA_LOCAL`, `apiKey: 'unused'`, and zero cost rates in `metadata`.
77
+
78
+ ## Non-goals
79
+
80
+ - **Streaming.** Requests are sent with `stream: false`; `invoke()` resolves with the complete response.
81
+ - **Pricing discovery.** Cost rates are caller-supplied per model.
82
+ - **Cached-token accounting.** `usage` reports prompt and completion tokens only; all prompt tokens are billed at `promptUsdPer1kTokens`.
83
+
84
+ ## Related
85
+
86
+ - [`@kindgi/capabilities`](../../capabilities/) — `ModelProvider`, `ProviderMetadata`, and the provider registry.
87
+ - [`@kindgi/adapter-model-anthropic`](../model-anthropic/) — the Anthropic Messages API adapter, with a lazily resolved API key.
88
+ - [`@kindgi/adapter-model-in-process`](../model-in-process/) — local models inside the Node.js process, no HTTP endpoint.
@@ -0,0 +1,4 @@
1
+ export { BASE_URLS, EXTRA_BODY_PREFIX, EXTRA_BODY_RESERVED, OPENAI_COMPAT_ADAPTER_ID, createOpenAICompatModelProvider, openAICompatAdapterFactory, openAICompatBaseUrl, openAICompatExtraBody, } from './provider.js';
2
+ export type { OpenAICompatProviderOptions } from './provider.js';
3
+ export type { ModelProvider } from '@kindgi/capabilities';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,mBAAmB,EACnB,wBAAwB,EACxB,+BAA+B,EAC/B,0BAA0B,EAC1B,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,eAAe,CAAC;AACvB,YAAY,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AACjE,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ export { BASE_URLS, EXTRA_BODY_PREFIX, EXTRA_BODY_RESERVED, OPENAI_COMPAT_ADAPTER_ID, createOpenAICompatModelProvider, openAICompatAdapterFactory, openAICompatBaseUrl, openAICompatExtraBody, } from './provider.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAEjC,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,mBAAmB,EACnB,wBAAwB,EACxB,+BAA+B,EAC/B,0BAA0B,EAC1B,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,eAAe,CAAC"}
@@ -0,0 +1,104 @@
1
+ import OpenAI from 'openai';
2
+ import type { AdapterFactory, AdapterFactoryInput, Feature, ModelProvider, ProviderMetadata } from '@kindgi/capabilities';
3
+ /**
4
+ * Configuration for an OpenAI-compatible ModelProvider. `baseURL` is the
5
+ * key — same adapter, different endpoints (the well-known ones are
6
+ * exported as `BASE_URLS`):
7
+ *
8
+ * - OpenAI proper: `https://api.openai.com/v1`
9
+ * - Ollama: `http://localhost:11434/v1`
10
+ * - vLLM: `http://localhost:8000/v1`
11
+ * - llama-server: `http://localhost:8080/v1`
12
+ * - LM Studio: `http://localhost:1234/v1`
13
+ * - OpenRouter: `https://openrouter.ai/api/v1`
14
+ * - Groq: `https://api.groq.com/openai/v1`
15
+ * - Together: `https://api.together.xyz/v1`
16
+ * - Fireworks: `https://api.fireworks.ai/inference/v1`
17
+ * - DeepInfra: `https://api.deepinfra.com/v1/openai`
18
+ * - LiteLLM proxy: `http://localhost:4000/v1`
19
+ *
20
+ * `apiKey` is required by most hosted endpoints; some local runners
21
+ * (Ollama, vLLM, llama-server) accept a placeholder or none — the SDK
22
+ * still needs a non-empty string so pass anything like `'unused'`. It
23
+ * may be a resolver, called on every invoke, so a rotated key takes
24
+ * effect on the next call (the client is rebuilt when the key changes).
25
+ *
26
+ * `metadata.models[]` MUST list every model the caller expects to
27
+ * invoke through this connection; the adapter picks the right entry
28
+ * at invoke time based on `ModelCallInput.model`. Cost per 1K tokens
29
+ * is caller-supplied per model — the OpenAI wire format doesn't
30
+ * expose pricing, and each provider bills differently.
31
+ */
32
+ export interface OpenAICompatProviderOptions {
33
+ readonly baseURL: string;
34
+ readonly apiKey: string | (() => string | Promise<string>);
35
+ /** Metadata surfaced to the router — required. */
36
+ readonly metadata: ProviderMetadata;
37
+ /** Optional HTTP overrides passed through to the OpenAI SDK. */
38
+ readonly clientOptions?: Omit<ConstructorParameters<typeof OpenAI>[0], 'apiKey' | 'baseURL'>;
39
+ /**
40
+ * Fields merged into every Chat Completions request body: settings an
41
+ * endpoint takes that the OpenAI format has no field for. A Qwen
42
+ * thinking model served by vLLM, SGLang or llama-server answers with its
43
+ * thinking first unless asked not to:
44
+ * `{ chat_template_kwargs: { enable_thinking: false } }`. The fields the
45
+ * adapter sets itself (`EXTRA_BODY_RESERVED`) are refused.
46
+ */
47
+ readonly extraBody?: Readonly<Record<string, unknown>>;
48
+ }
49
+ /** Request fields the adapter sets itself; `extraBody` can't override them. */
50
+ export declare const EXTRA_BODY_RESERVED: readonly ["model", "messages", "tools", "response_format", "temperature", "max_tokens", "stream"];
51
+ /**
52
+ * Create an OpenAI-compatible `ModelProvider`. The OpenAI SDK is
53
+ * instantiated lazily at first invoke — construction cost is minimal
54
+ * but we want to keep import-side effects zero for shape tests.
55
+ */
56
+ export declare function createOpenAICompatModelProvider(options: OpenAICompatProviderOptions): ModelProvider;
57
+ /**
58
+ * Well-known base URLs — surfaced as constants so callers can import
59
+ * without typos. Adding a new alias here doesn't lock anyone in; the
60
+ * adapter accepts any `baseURL` string.
61
+ */
62
+ export declare const BASE_URLS: {
63
+ readonly OPENAI: "https://api.openai.com/v1";
64
+ readonly OLLAMA_LOCAL: "http://localhost:11434/v1";
65
+ readonly VLLM_LOCAL: "http://localhost:8000/v1";
66
+ readonly LLAMA_SERVER_LOCAL: "http://localhost:8080/v1";
67
+ readonly LM_STUDIO_LOCAL: "http://localhost:1234/v1";
68
+ readonly OPENROUTER: "https://openrouter.ai/api/v1";
69
+ readonly GROQ: "https://api.groq.com/openai/v1";
70
+ readonly TOGETHER: "https://api.together.xyz/v1";
71
+ readonly FIREWORKS: "https://api.fireworks.ai/inference/v1";
72
+ readonly DEEPINFRA: "https://api.deepinfra.com/v1/openai";
73
+ readonly LITELLM_LOCAL: "http://localhost:4000/v1";
74
+ };
75
+ export type Feature_ = Feature;
76
+ /** The id the runtime registers this adapter under. */
77
+ export declare const OPENAI_COMPAT_ADAPTER_ID = "@kindgi/adapter-model-openai-compat";
78
+ /**
79
+ * The runtime's factory. A provider registration names its endpoint in
80
+ * `adapter_config.baseURL` (an http(s) URL; `BASE_URLS` has the
81
+ * well-known ones) and, for an endpoint that needs a key, its secret in
82
+ * `secret_ref` (resolved on every call). Without one, the adapter sends
83
+ * a placeholder key, as local runners (Ollama, vLLM, llama-server)
84
+ * expect. Its `extraBody.*` keys (`EXTRA_BODY_PREFIX`) are extra request
85
+ * fields, merged into every request (`OpenAICompatProviderOptions.extraBody`).
86
+ */
87
+ export declare const openAICompatAdapterFactory: AdapterFactory;
88
+ /** The endpoint a registration names (see `openAICompatAdapterFactory`). */
89
+ export declare function openAICompatBaseUrl(input: AdapterFactoryInput): string;
90
+ /**
91
+ * The `adapter_config` key prefix for extra request fields. `adapter_config`
92
+ * is flat, so each field is its own key and dots nest:
93
+ * `"extraBody.chat_template_kwargs.enable_thinking": false` sends
94
+ * `{ "chat_template_kwargs": { "enable_thinking": false } }`.
95
+ */
96
+ export declare const EXTRA_BODY_PREFIX = "extraBody.";
97
+ /**
98
+ * A registration's extra request fields: its `adapter_config` keys under
99
+ * `EXTRA_BODY_PREFIX`, expanded into the body they add. `undefined` when it
100
+ * has none. Throws, naming the key, on an empty or unsafe field name, two
101
+ * keys that collide, or a field the adapter sets.
102
+ */
103
+ export declare function openAICompatExtraBody(input: AdapterFactoryInput): Readonly<Record<string, unknown>> | undefined;
104
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAGA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,KAAK,EACV,cAAc,EACd,mBAAmB,EACnB,OAAO,EAKP,aAAa,EAGb,gBAAgB,EACjB,MAAM,sBAAsB,CAAC;AAsB9B;;;;;;;;;;;;;;;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: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ import OpenAI from 'openai';
4
+ /**
5
+ * OpenAI (and every downstream compat endpoint — Ollama, vLLM, Groq,
6
+ * OpenRouter, Together, Fireworks, LiteLLM, ...) constrains
7
+ * `function.name` to `^[a-zA-Z0-9_-]{1,128}$` — dots are rejected.
8
+ * The framework's tool id convention is `<pack>.<tool>`, so this
9
+ * adapter transparently encodes on send and decodes on receive.
10
+ *
11
+ * See the sibling comment in
12
+ * `packages/adapters/model-anthropic/src/translate.ts` — same
13
+ * substitution (`.` → `__`), same reversibility caveat (authors
14
+ * should not put literal `__` in tool ids).
15
+ */
16
+ function encodeToolName(name) {
17
+ return name.replace(/\./g, '__');
18
+ }
19
+ function decodeToolName(name) {
20
+ return name.replace(/__/g, '.');
21
+ }
22
+ /** Request fields the adapter sets itself; `extraBody` can't override them. */
23
+ export const EXTRA_BODY_RESERVED = [
24
+ 'model',
25
+ 'messages',
26
+ 'tools',
27
+ 'response_format',
28
+ 'temperature',
29
+ 'max_tokens',
30
+ 'stream',
31
+ ];
32
+ /**
33
+ * Create an OpenAI-compatible `ModelProvider`. The OpenAI SDK is
34
+ * instantiated lazily at first invoke — construction cost is minimal
35
+ * but we want to keep import-side effects zero for shape tests.
36
+ */
37
+ export function createOpenAICompatModelProvider(options) {
38
+ const metadata = options.metadata;
39
+ const problem = extraBodyProblem(options.extraBody);
40
+ if (problem !== undefined) {
41
+ throw new Error(`${OPENAI_COMPAT_ADAPTER_ID}: provider "${metadata.id}": ${problem}`);
42
+ }
43
+ const extraBody = options.extraBody ?? {};
44
+ const modelsByName = new Map(metadata.models.map((m) => [m.name, m]));
45
+ // One client per key: reused while the resolver returns the same key
46
+ // (the SDK keeps its connection pool), rebuilt when it rotates.
47
+ let cached;
48
+ async function clientForCall() {
49
+ const key = typeof options.apiKey === 'function' ? await options.apiKey() : options.apiKey;
50
+ if (cached !== undefined && cached.key === key)
51
+ return cached.client;
52
+ const client = new OpenAI({
53
+ apiKey: key,
54
+ baseURL: options.baseURL,
55
+ ...(options.clientOptions ?? {}),
56
+ });
57
+ cached = { key, client };
58
+ return client;
59
+ }
60
+ return {
61
+ metadata,
62
+ async invoke(input) {
63
+ const modelInfo = modelsByName.get(input.model);
64
+ if (modelInfo === undefined) {
65
+ throw new Error(`@kindgi/adapter-model-openai-compat: provider "${metadata.id}" does not expose model "${input.model}". ` +
66
+ `Available: ${[...modelsByName.keys()].join(', ') || '<none>'}.`);
67
+ }
68
+ const startedAt = Date.now();
69
+ const openai = await clientForCall();
70
+ const messages = input.messages.map(toOpenAiMessage);
71
+ const tools = input.tools?.map(toOpenAiTool);
72
+ const responseFormat = input.structuredOutput
73
+ ? {
74
+ type: 'json_schema',
75
+ json_schema: {
76
+ name: input.structuredOutput.name,
77
+ schema: input.structuredOutput.schema,
78
+ strict: true,
79
+ },
80
+ }
81
+ : undefined;
82
+ const completion = await openai.chat.completions.create({
83
+ ...extraBody,
84
+ model: input.model,
85
+ messages,
86
+ ...(tools !== undefined && tools.length > 0 && { tools }),
87
+ ...(responseFormat !== undefined && { response_format: responseFormat }),
88
+ ...(input.temperature !== undefined && { temperature: input.temperature }),
89
+ ...(input.maxOutputTokens !== undefined && { max_tokens: input.maxOutputTokens }),
90
+ stream: false,
91
+ }, input.abortSignal !== undefined ? { signal: input.abortSignal } : undefined);
92
+ const durationMs = Date.now() - startedAt;
93
+ const choice = completion.choices[0];
94
+ const contentText = choice?.message.content ?? '';
95
+ const toolCalls = extractToolCalls(choice?.message.tool_calls);
96
+ const responseMessage = {
97
+ role: 'assistant',
98
+ content: contentText,
99
+ ...(toolCalls.length > 0 && { toolCalls }),
100
+ };
101
+ const promptTokens = completion.usage?.prompt_tokens ?? 0;
102
+ const completionTokens = completion.usage?.completion_tokens ?? 0;
103
+ return {
104
+ message: responseMessage,
105
+ finishReason: mapFinishReason(choice?.finish_reason),
106
+ usage: { promptTokens, completionTokens },
107
+ costUsd: computeCost(modelInfo, promptTokens, completionTokens),
108
+ durationMs,
109
+ provider: { id: metadata.id, model: input.model },
110
+ };
111
+ },
112
+ };
113
+ }
114
+ function toOpenAiMessage(m) {
115
+ if (m.role === 'tool') {
116
+ return {
117
+ role: 'tool',
118
+ content: m.content,
119
+ tool_call_id: m.toolCallId ?? '',
120
+ };
121
+ }
122
+ if (m.role === 'assistant' && m.toolCalls !== undefined && m.toolCalls.length > 0) {
123
+ return {
124
+ role: 'assistant',
125
+ content: m.content,
126
+ tool_calls: m.toolCalls.map((tc) => ({
127
+ id: tc.id,
128
+ type: 'function',
129
+ function: {
130
+ // Encode when replaying prior assistant turns — see the
131
+ // module-level comment on `encodeToolName`.
132
+ name: encodeToolName(tc.name),
133
+ arguments: JSON.stringify(tc.arguments),
134
+ },
135
+ })),
136
+ };
137
+ }
138
+ if (m.role === 'system')
139
+ return { role: 'system', content: m.content };
140
+ if (m.role === 'user')
141
+ return { role: 'user', content: m.content };
142
+ return { role: 'assistant', content: m.content };
143
+ }
144
+ function toOpenAiTool(tool) {
145
+ return {
146
+ type: 'function',
147
+ function: {
148
+ name: encodeToolName(tool.name),
149
+ description: tool.description,
150
+ parameters: tool.inputSchema,
151
+ },
152
+ };
153
+ }
154
+ function extractToolCalls(raw) {
155
+ if (raw === undefined || raw.length === 0)
156
+ return [];
157
+ const out = [];
158
+ for (const tc of raw) {
159
+ if (tc.type !== 'function')
160
+ continue;
161
+ let args;
162
+ try {
163
+ args = JSON.parse(tc.function.arguments);
164
+ }
165
+ catch {
166
+ args = {};
167
+ }
168
+ // Decode: the wire returns the encoded name; the framework
169
+ // expects the canonical dotted form.
170
+ out.push({ id: tc.id, name: decodeToolName(tc.function.name), arguments: args });
171
+ }
172
+ return out;
173
+ }
174
+ function mapFinishReason(reason) {
175
+ switch (reason) {
176
+ case 'stop':
177
+ return 'stop';
178
+ case 'length':
179
+ return 'length';
180
+ case 'tool_calls':
181
+ case 'function_call':
182
+ return 'tool-use';
183
+ case 'content_filter':
184
+ return 'content-filter';
185
+ default:
186
+ return 'stop';
187
+ }
188
+ }
189
+ function computeCost(modelInfo, promptTokens, completionTokens) {
190
+ const promptCost = (promptTokens / 1000) * modelInfo.cost.promptUsdPer1kTokens;
191
+ const completionCost = (completionTokens / 1000) * modelInfo.cost.completionUsdPer1kTokens;
192
+ return promptCost + completionCost;
193
+ }
194
+ /**
195
+ * Well-known base URLs — surfaced as constants so callers can import
196
+ * without typos. Adding a new alias here doesn't lock anyone in; the
197
+ * adapter accepts any `baseURL` string.
198
+ */
199
+ export const BASE_URLS = {
200
+ OPENAI: 'https://api.openai.com/v1',
201
+ OLLAMA_LOCAL: 'http://localhost:11434/v1',
202
+ VLLM_LOCAL: 'http://localhost:8000/v1',
203
+ LLAMA_SERVER_LOCAL: 'http://localhost:8080/v1',
204
+ LM_STUDIO_LOCAL: 'http://localhost:1234/v1',
205
+ OPENROUTER: 'https://openrouter.ai/api/v1',
206
+ GROQ: 'https://api.groq.com/openai/v1',
207
+ TOGETHER: 'https://api.together.xyz/v1',
208
+ FIREWORKS: 'https://api.fireworks.ai/inference/v1',
209
+ DEEPINFRA: 'https://api.deepinfra.com/v1/openai',
210
+ LITELLM_LOCAL: 'http://localhost:4000/v1',
211
+ };
212
+ /** The id the runtime registers this adapter under. */
213
+ export const OPENAI_COMPAT_ADAPTER_ID = '@kindgi/adapter-model-openai-compat';
214
+ /** The key sent when a registration has none: local runners ignore it. */
215
+ const NO_KEY = 'unused';
216
+ /**
217
+ * The runtime's factory. A provider registration names its endpoint in
218
+ * `adapter_config.baseURL` (an http(s) URL; `BASE_URLS` has the
219
+ * well-known ones) and, for an endpoint that needs a key, its secret in
220
+ * `secret_ref` (resolved on every call). Without one, the adapter sends
221
+ * a placeholder key, as local runners (Ollama, vLLM, llama-server)
222
+ * expect. Its `extraBody.*` keys (`EXTRA_BODY_PREFIX`) are extra request
223
+ * fields, merged into every request (`OpenAICompatProviderOptions.extraBody`).
224
+ */
225
+ export const openAICompatAdapterFactory = (input) => {
226
+ const extraBody = openAICompatExtraBody(input);
227
+ return createOpenAICompatModelProvider({
228
+ metadata: input.metadata,
229
+ baseURL: openAICompatBaseUrl(input),
230
+ apiKey: input.resolveApiKey ?? NO_KEY,
231
+ ...(extraBody !== undefined && { extraBody }),
232
+ // The registration chose the endpoint: the runtime's fetch decides
233
+ // which hosts it may reach (`AdapterFactoryInput.fetch`).
234
+ ...(input.fetch !== undefined && { clientOptions: { fetch: input.fetch } }),
235
+ });
236
+ };
237
+ /** The endpoint a registration names (see `openAICompatAdapterFactory`). */
238
+ export function openAICompatBaseUrl(input) {
239
+ const value = input.config?.baseURL;
240
+ if (typeof value !== 'string' || !/^https?:\/\/[^\s/]+/.test(value)) {
241
+ throw new Error(`${OPENAI_COMPAT_ADAPTER_ID}: provider "${input.metadata.id}" needs adapter_config.baseURL, an http(s) URL (e.g. ${BASE_URLS.OPENAI}).`);
242
+ }
243
+ return value;
244
+ }
245
+ /**
246
+ * The `adapter_config` key prefix for extra request fields. `adapter_config`
247
+ * is flat, so each field is its own key and dots nest:
248
+ * `"extraBody.chat_template_kwargs.enable_thinking": false` sends
249
+ * `{ "chat_template_kwargs": { "enable_thinking": false } }`.
250
+ */
251
+ export const EXTRA_BODY_PREFIX = 'extraBody.';
252
+ /** Names that would reach an object's prototype; never a field name here. */
253
+ const UNSAFE_FIELDS = new Set(['__proto__', 'constructor', 'prototype']);
254
+ /**
255
+ * A registration's extra request fields: its `adapter_config` keys under
256
+ * `EXTRA_BODY_PREFIX`, expanded into the body they add. `undefined` when it
257
+ * has none. Throws, naming the key, on an empty or unsafe field name, two
258
+ * keys that collide, or a field the adapter sets.
259
+ */
260
+ export function openAICompatExtraBody(input) {
261
+ const fail = (problem) => {
262
+ throw new Error(`${OPENAI_COMPAT_ADAPTER_ID}: provider "${input.metadata.id}": ${problem}`);
263
+ };
264
+ const config = input.config ?? {};
265
+ if (Object.hasOwn(config, 'extraBody')) {
266
+ fail(`adapter_config takes extra request fields one per key, "${EXTRA_BODY_PREFIX}<field>" (dots nest), e.g. "${EXTRA_BODY_PREFIX}chat_template_kwargs.enable_thinking": false`);
267
+ }
268
+ let body;
269
+ for (const [key, value] of Object.entries(config)) {
270
+ if (!key.startsWith(EXTRA_BODY_PREFIX))
271
+ continue;
272
+ body ??= {};
273
+ const problem = setField(body, key.slice(EXTRA_BODY_PREFIX.length).split('.'), value);
274
+ if (problem !== undefined)
275
+ fail(`adapter_config "${key}" ${problem}`);
276
+ }
277
+ const problem = extraBodyProblem(body);
278
+ if (problem !== undefined)
279
+ fail(`adapter_config ${problem}`);
280
+ return body;
281
+ }
282
+ /** Set `path` in `body` to `value`; what's wrong, if anything. */
283
+ function setField(body, path, value) {
284
+ if (path.some((field) => field === '' || UNSAFE_FIELDS.has(field))) {
285
+ return "isn't a field path";
286
+ }
287
+ let node = body;
288
+ for (const field of path.slice(0, -1)) {
289
+ const next = Object.hasOwn(node, field) ? node[field] : undefined;
290
+ if (next === undefined) {
291
+ const child = {};
292
+ node[field] = child;
293
+ node = child;
294
+ }
295
+ else if (typeof next === 'object' && next !== null) {
296
+ node = next;
297
+ }
298
+ else {
299
+ return 'nests under a field another key sets';
300
+ }
301
+ }
302
+ const leaf = path[path.length - 1];
303
+ if (Object.hasOwn(node, leaf))
304
+ return 'collides with another key';
305
+ node[leaf] = value;
306
+ return undefined;
307
+ }
308
+ function extraBodyProblem(value) {
309
+ if (value === undefined)
310
+ return undefined;
311
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
312
+ return 'extraBody must be an object of request fields, e.g. { chat_template_kwargs: { enable_thinking: false } }';
313
+ }
314
+ const reserved = EXTRA_BODY_RESERVED.filter((key) => Object.hasOwn(value, key));
315
+ return reserved.length > 0
316
+ ? `extraBody can't set ${reserved.join(', ')}: the adapter sets ${reserved.length === 1 ? 'it' : 'them'}`
317
+ : undefined;
318
+ }
319
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA,sC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,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC;IAChF,OAAO,QAAQ,CAAC,MAAM,GAAG,CAAC;QACxB,CAAC,CAAC,uBAAuB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,sBAAsB,QAAQ,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE;QACzG,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@kindgi/adapter-model-openai-compat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "OpenAI-compatible ModelProvider for @kindgi/capabilities. Points at any endpoint speaking the OpenAI Chat Completions wire format — OpenAI proper, Ollama (/v1), vLLM, llama-server, LM Studio, OpenRouter, Groq, Together, Fireworks, DeepInfra, LiteLLM proxy (base URLs exported as BASE_URLS), or any other compatible endpoint. One adapter, many backends. Cost per 1K tokens is supplied by the caller (from the provider's public pricing) since the API surface itself doesn't expose it.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/kindgi/kindgi-sdk.git",
9
+ "directory": "packages/adapters/model-openai-compat"
10
+ },
11
+ "homepage": "https://github.com/kindgi/kindgi-sdk/tree/main/packages/adapters/model-openai-compat#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/kindgi/kindgi-sdk/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "src",
27
+ "README.md"
28
+ ],
29
+ "dependencies": {
30
+ "@kindgi/capabilities": "0.1.0",
31
+ "openai": "^7.17.0"
32
+ },
33
+ "engines": {
34
+ "node": ">=22.0.0"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "provenance": true
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^22.10.5",
42
+ "typescript": "^5.7.3",
43
+ "vitest": "^2.1.8"
44
+ },
45
+ "scripts": {
46
+ "build": "tsc -p tsconfig.build.json",
47
+ "typecheck": "tsc --noEmit",
48
+ "test": "vitest run",
49
+ "clean": "rm -rf dist *.tsbuildinfo"
50
+ }
6
51
  }
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+
4
+ export {
5
+ BASE_URLS,
6
+ EXTRA_BODY_PREFIX,
7
+ EXTRA_BODY_RESERVED,
8
+ OPENAI_COMPAT_ADAPTER_ID,
9
+ createOpenAICompatModelProvider,
10
+ openAICompatAdapterFactory,
11
+ openAICompatBaseUrl,
12
+ openAICompatExtraBody,
13
+ } from './provider.js';
14
+ export type { OpenAICompatProviderOptions } from './provider.js';
15
+ export type { ModelProvider } from '@kindgi/capabilities';
@@ -0,0 +1,410 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+
4
+ import OpenAI from 'openai';
5
+
6
+ import type {
7
+ AdapterFactory,
8
+ AdapterFactoryInput,
9
+ Feature,
10
+ ModelCallInput,
11
+ ModelCallResult,
12
+ ModelInfo,
13
+ ModelMessage,
14
+ ModelProvider,
15
+ ModelToolCall,
16
+ ModelToolDefinition,
17
+ ProviderMetadata,
18
+ } from '@kindgi/capabilities';
19
+
20
+ /**
21
+ * OpenAI (and every downstream compat endpoint — Ollama, vLLM, Groq,
22
+ * OpenRouter, Together, Fireworks, LiteLLM, ...) constrains
23
+ * `function.name` to `^[a-zA-Z0-9_-]{1,128}$` — dots are rejected.
24
+ * The framework's tool id convention is `<pack>.<tool>`, so this
25
+ * adapter transparently encodes on send and decodes on receive.
26
+ *
27
+ * See the sibling comment in
28
+ * `packages/adapters/model-anthropic/src/translate.ts` — same
29
+ * substitution (`.` → `__`), same reversibility caveat (authors
30
+ * should not put literal `__` in tool ids).
31
+ */
32
+ function encodeToolName(name: string): string {
33
+ return name.replace(/\./g, '__');
34
+ }
35
+
36
+ function decodeToolName(name: string): string {
37
+ return name.replace(/__/g, '.');
38
+ }
39
+
40
+ /**
41
+ * Configuration for an OpenAI-compatible ModelProvider. `baseURL` is the
42
+ * key — same adapter, different endpoints (the well-known ones are
43
+ * exported as `BASE_URLS`):
44
+ *
45
+ * - OpenAI proper: `https://api.openai.com/v1`
46
+ * - Ollama: `http://localhost:11434/v1`
47
+ * - vLLM: `http://localhost:8000/v1`
48
+ * - llama-server: `http://localhost:8080/v1`
49
+ * - LM Studio: `http://localhost:1234/v1`
50
+ * - OpenRouter: `https://openrouter.ai/api/v1`
51
+ * - Groq: `https://api.groq.com/openai/v1`
52
+ * - Together: `https://api.together.xyz/v1`
53
+ * - Fireworks: `https://api.fireworks.ai/inference/v1`
54
+ * - DeepInfra: `https://api.deepinfra.com/v1/openai`
55
+ * - LiteLLM proxy: `http://localhost:4000/v1`
56
+ *
57
+ * `apiKey` is required by most hosted endpoints; some local runners
58
+ * (Ollama, vLLM, llama-server) accept a placeholder or none — the SDK
59
+ * still needs a non-empty string so pass anything like `'unused'`. It
60
+ * may be a resolver, called on every invoke, so a rotated key takes
61
+ * effect on the next call (the client is rebuilt when the key changes).
62
+ *
63
+ * `metadata.models[]` MUST list every model the caller expects to
64
+ * invoke through this connection; the adapter picks the right entry
65
+ * at invoke time based on `ModelCallInput.model`. Cost per 1K tokens
66
+ * is caller-supplied per model — the OpenAI wire format doesn't
67
+ * expose pricing, and each provider bills differently.
68
+ */
69
+ export interface OpenAICompatProviderOptions {
70
+ readonly baseURL: string;
71
+ readonly apiKey: string | (() => string | Promise<string>);
72
+ /** Metadata surfaced to the router — required. */
73
+ readonly metadata: ProviderMetadata;
74
+ /** Optional HTTP overrides passed through to the OpenAI SDK. */
75
+ readonly clientOptions?: Omit<ConstructorParameters<typeof OpenAI>[0], 'apiKey' | 'baseURL'>;
76
+ /**
77
+ * Fields merged into every Chat Completions request body: settings an
78
+ * endpoint takes that the OpenAI format has no field for. A Qwen
79
+ * thinking model served by vLLM, SGLang or llama-server answers with its
80
+ * thinking first unless asked not to:
81
+ * `{ chat_template_kwargs: { enable_thinking: false } }`. The fields the
82
+ * adapter sets itself (`EXTRA_BODY_RESERVED`) are refused.
83
+ */
84
+ readonly extraBody?: Readonly<Record<string, unknown>>;
85
+ }
86
+
87
+ /** Request fields the adapter sets itself; `extraBody` can't override them. */
88
+ export const EXTRA_BODY_RESERVED = [
89
+ 'model',
90
+ 'messages',
91
+ 'tools',
92
+ 'response_format',
93
+ 'temperature',
94
+ 'max_tokens',
95
+ 'stream',
96
+ ] as const;
97
+
98
+ /**
99
+ * Create an OpenAI-compatible `ModelProvider`. The OpenAI SDK is
100
+ * instantiated lazily at first invoke — construction cost is minimal
101
+ * but we want to keep import-side effects zero for shape tests.
102
+ */
103
+ export function createOpenAICompatModelProvider(
104
+ options: OpenAICompatProviderOptions,
105
+ ): ModelProvider {
106
+ const metadata = options.metadata;
107
+ const problem = extraBodyProblem(options.extraBody);
108
+ if (problem !== undefined) {
109
+ throw new Error(`${OPENAI_COMPAT_ADAPTER_ID}: provider "${metadata.id}": ${problem}`);
110
+ }
111
+ const extraBody = options.extraBody ?? {};
112
+ const modelsByName = new Map<string, ModelInfo>(metadata.models.map((m) => [m.name, m] as const));
113
+ // One client per key: reused while the resolver returns the same key
114
+ // (the SDK keeps its connection pool), rebuilt when it rotates.
115
+ let cached: { readonly key: string; readonly client: OpenAI } | undefined;
116
+ async function clientForCall(): Promise<OpenAI> {
117
+ const key = typeof options.apiKey === 'function' ? await options.apiKey() : options.apiKey;
118
+ if (cached !== undefined && cached.key === key) return cached.client;
119
+ const client = new OpenAI({
120
+ apiKey: key,
121
+ baseURL: options.baseURL,
122
+ ...(options.clientOptions ?? {}),
123
+ });
124
+ cached = { key, client };
125
+ return client;
126
+ }
127
+
128
+ return {
129
+ metadata,
130
+ async invoke(input: ModelCallInput): Promise<ModelCallResult> {
131
+ const modelInfo = modelsByName.get(input.model);
132
+ if (modelInfo === undefined) {
133
+ throw new Error(
134
+ `@kindgi/adapter-model-openai-compat: provider "${metadata.id}" does not expose model "${input.model}". ` +
135
+ `Available: ${[...modelsByName.keys()].join(', ') || '<none>'}.`,
136
+ );
137
+ }
138
+ const startedAt = Date.now();
139
+ const openai = await clientForCall();
140
+
141
+ const messages = input.messages.map(toOpenAiMessage);
142
+ const tools = input.tools?.map(toOpenAiTool);
143
+
144
+ const responseFormat = input.structuredOutput
145
+ ? {
146
+ type: 'json_schema' as const,
147
+ json_schema: {
148
+ name: input.structuredOutput.name,
149
+ schema: input.structuredOutput.schema,
150
+ strict: true,
151
+ },
152
+ }
153
+ : undefined;
154
+
155
+ const completion = await openai.chat.completions.create(
156
+ {
157
+ ...extraBody,
158
+ model: input.model,
159
+ messages,
160
+ ...(tools !== undefined && tools.length > 0 && { tools }),
161
+ ...(responseFormat !== undefined && { response_format: responseFormat }),
162
+ ...(input.temperature !== undefined && { temperature: input.temperature }),
163
+ ...(input.maxOutputTokens !== undefined && { max_tokens: input.maxOutputTokens }),
164
+ stream: false,
165
+ },
166
+ input.abortSignal !== undefined ? { signal: input.abortSignal } : undefined,
167
+ );
168
+
169
+ const durationMs = Date.now() - startedAt;
170
+ const choice = completion.choices[0];
171
+ const contentText = choice?.message.content ?? '';
172
+ const toolCalls = extractToolCalls(choice?.message.tool_calls);
173
+ const responseMessage: ModelMessage = {
174
+ role: 'assistant',
175
+ content: contentText,
176
+ ...(toolCalls.length > 0 && { toolCalls }),
177
+ };
178
+
179
+ const promptTokens = completion.usage?.prompt_tokens ?? 0;
180
+ const completionTokens = completion.usage?.completion_tokens ?? 0;
181
+
182
+ return {
183
+ message: responseMessage,
184
+ finishReason: mapFinishReason(choice?.finish_reason),
185
+ usage: { promptTokens, completionTokens },
186
+ costUsd: computeCost(modelInfo, promptTokens, completionTokens),
187
+ durationMs,
188
+ provider: { id: metadata.id, model: input.model },
189
+ };
190
+ },
191
+ };
192
+ }
193
+
194
+ function toOpenAiMessage(m: ModelMessage): OpenAI.Chat.Completions.ChatCompletionMessageParam {
195
+ if (m.role === 'tool') {
196
+ return {
197
+ role: 'tool',
198
+ content: m.content,
199
+ tool_call_id: m.toolCallId ?? '',
200
+ };
201
+ }
202
+ if (m.role === 'assistant' && m.toolCalls !== undefined && m.toolCalls.length > 0) {
203
+ return {
204
+ role: 'assistant',
205
+ content: m.content,
206
+ tool_calls: m.toolCalls.map((tc) => ({
207
+ id: tc.id,
208
+ type: 'function' as const,
209
+ function: {
210
+ // Encode when replaying prior assistant turns — see the
211
+ // module-level comment on `encodeToolName`.
212
+ name: encodeToolName(tc.name),
213
+ arguments: JSON.stringify(tc.arguments),
214
+ },
215
+ })),
216
+ };
217
+ }
218
+ if (m.role === 'system') return { role: 'system', content: m.content };
219
+ if (m.role === 'user') return { role: 'user', content: m.content };
220
+ return { role: 'assistant', content: m.content };
221
+ }
222
+
223
+ function toOpenAiTool(tool: ModelToolDefinition): OpenAI.Chat.Completions.ChatCompletionTool {
224
+ return {
225
+ type: 'function',
226
+ function: {
227
+ name: encodeToolName(tool.name),
228
+ description: tool.description,
229
+ parameters: tool.inputSchema as Record<string, unknown>,
230
+ },
231
+ };
232
+ }
233
+
234
+ function extractToolCalls(
235
+ raw: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] | undefined,
236
+ ): ModelToolCall[] {
237
+ if (raw === undefined || raw.length === 0) return [];
238
+ const out: ModelToolCall[] = [];
239
+ for (const tc of raw) {
240
+ if (tc.type !== 'function') continue;
241
+ let args: Record<string, unknown>;
242
+ try {
243
+ args = JSON.parse(tc.function.arguments) as Record<string, unknown>;
244
+ } catch {
245
+ args = {};
246
+ }
247
+ // Decode: the wire returns the encoded name; the framework
248
+ // expects the canonical dotted form.
249
+ out.push({ id: tc.id, name: decodeToolName(tc.function.name), arguments: args });
250
+ }
251
+ return out;
252
+ }
253
+
254
+ function mapFinishReason(reason: string | null | undefined): ModelCallResult['finishReason'] {
255
+ switch (reason) {
256
+ case 'stop':
257
+ return 'stop';
258
+ case 'length':
259
+ return 'length';
260
+ case 'tool_calls':
261
+ case 'function_call':
262
+ return 'tool-use';
263
+ case 'content_filter':
264
+ return 'content-filter';
265
+ default:
266
+ return 'stop';
267
+ }
268
+ }
269
+
270
+ function computeCost(modelInfo: ModelInfo, promptTokens: number, completionTokens: number): number {
271
+ const promptCost = (promptTokens / 1000) * modelInfo.cost.promptUsdPer1kTokens;
272
+ const completionCost = (completionTokens / 1000) * modelInfo.cost.completionUsdPer1kTokens;
273
+ return promptCost + completionCost;
274
+ }
275
+
276
+ /**
277
+ * Well-known base URLs — surfaced as constants so callers can import
278
+ * without typos. Adding a new alias here doesn't lock anyone in; the
279
+ * adapter accepts any `baseURL` string.
280
+ */
281
+ export const BASE_URLS = {
282
+ OPENAI: 'https://api.openai.com/v1',
283
+ OLLAMA_LOCAL: 'http://localhost:11434/v1',
284
+ VLLM_LOCAL: 'http://localhost:8000/v1',
285
+ LLAMA_SERVER_LOCAL: 'http://localhost:8080/v1',
286
+ LM_STUDIO_LOCAL: 'http://localhost:1234/v1',
287
+ OPENROUTER: 'https://openrouter.ai/api/v1',
288
+ GROQ: 'https://api.groq.com/openai/v1',
289
+ TOGETHER: 'https://api.together.xyz/v1',
290
+ FIREWORKS: 'https://api.fireworks.ai/inference/v1',
291
+ DEEPINFRA: 'https://api.deepinfra.com/v1/openai',
292
+ LITELLM_LOCAL: 'http://localhost:4000/v1',
293
+ } as const;
294
+
295
+ export type Feature_ = Feature; // local alias; not exported from the package entry (src/index.ts)
296
+
297
+ /** The id the runtime registers this adapter under. */
298
+ export const OPENAI_COMPAT_ADAPTER_ID = '@kindgi/adapter-model-openai-compat';
299
+
300
+ /** The key sent when a registration has none: local runners ignore it. */
301
+ const NO_KEY = 'unused';
302
+
303
+ /**
304
+ * The runtime's factory. A provider registration names its endpoint in
305
+ * `adapter_config.baseURL` (an http(s) URL; `BASE_URLS` has the
306
+ * well-known ones) and, for an endpoint that needs a key, its secret in
307
+ * `secret_ref` (resolved on every call). Without one, the adapter sends
308
+ * a placeholder key, as local runners (Ollama, vLLM, llama-server)
309
+ * expect. Its `extraBody.*` keys (`EXTRA_BODY_PREFIX`) are extra request
310
+ * fields, merged into every request (`OpenAICompatProviderOptions.extraBody`).
311
+ */
312
+ export const openAICompatAdapterFactory: AdapterFactory = (input) => {
313
+ const extraBody = openAICompatExtraBody(input);
314
+ return createOpenAICompatModelProvider({
315
+ metadata: input.metadata,
316
+ baseURL: openAICompatBaseUrl(input),
317
+ apiKey: input.resolveApiKey ?? NO_KEY,
318
+ ...(extraBody !== undefined && { extraBody }),
319
+ // The registration chose the endpoint: the runtime's fetch decides
320
+ // which hosts it may reach (`AdapterFactoryInput.fetch`).
321
+ ...(input.fetch !== undefined && { clientOptions: { fetch: input.fetch } }),
322
+ });
323
+ };
324
+
325
+ /** The endpoint a registration names (see `openAICompatAdapterFactory`). */
326
+ export function openAICompatBaseUrl(input: AdapterFactoryInput): string {
327
+ const value = input.config?.baseURL;
328
+ if (typeof value !== 'string' || !/^https?:\/\/[^\s/]+/.test(value)) {
329
+ throw new Error(
330
+ `${OPENAI_COMPAT_ADAPTER_ID}: provider "${input.metadata.id}" needs adapter_config.baseURL, an http(s) URL (e.g. ${BASE_URLS.OPENAI}).`,
331
+ );
332
+ }
333
+ return value;
334
+ }
335
+
336
+ /**
337
+ * The `adapter_config` key prefix for extra request fields. `adapter_config`
338
+ * is flat, so each field is its own key and dots nest:
339
+ * `"extraBody.chat_template_kwargs.enable_thinking": false` sends
340
+ * `{ "chat_template_kwargs": { "enable_thinking": false } }`.
341
+ */
342
+ export const EXTRA_BODY_PREFIX = 'extraBody.';
343
+
344
+ /** Names that would reach an object's prototype; never a field name here. */
345
+ const UNSAFE_FIELDS = new Set(['__proto__', 'constructor', 'prototype']);
346
+
347
+ /**
348
+ * A registration's extra request fields: its `adapter_config` keys under
349
+ * `EXTRA_BODY_PREFIX`, expanded into the body they add. `undefined` when it
350
+ * has none. Throws, naming the key, on an empty or unsafe field name, two
351
+ * keys that collide, or a field the adapter sets.
352
+ */
353
+ export function openAICompatExtraBody(
354
+ input: AdapterFactoryInput,
355
+ ): Readonly<Record<string, unknown>> | undefined {
356
+ const fail = (problem: string): never => {
357
+ throw new Error(`${OPENAI_COMPAT_ADAPTER_ID}: provider "${input.metadata.id}": ${problem}`);
358
+ };
359
+ const config = input.config ?? {};
360
+ if (Object.hasOwn(config, 'extraBody')) {
361
+ fail(
362
+ `adapter_config takes extra request fields one per key, "${EXTRA_BODY_PREFIX}<field>" (dots nest), e.g. "${EXTRA_BODY_PREFIX}chat_template_kwargs.enable_thinking": false`,
363
+ );
364
+ }
365
+ let body: Record<string, unknown> | undefined;
366
+ for (const [key, value] of Object.entries(config)) {
367
+ if (!key.startsWith(EXTRA_BODY_PREFIX)) continue;
368
+ body ??= {};
369
+ const problem = setField(body, key.slice(EXTRA_BODY_PREFIX.length).split('.'), value);
370
+ if (problem !== undefined) fail(`adapter_config "${key}" ${problem}`);
371
+ }
372
+ const problem = extraBodyProblem(body);
373
+ if (problem !== undefined) fail(`adapter_config ${problem}`);
374
+ return body;
375
+ }
376
+
377
+ /** Set `path` in `body` to `value`; what's wrong, if anything. */
378
+ function setField(body: Record<string, unknown>, path: readonly string[], value: unknown) {
379
+ if (path.some((field) => field === '' || UNSAFE_FIELDS.has(field))) {
380
+ return "isn't a field path";
381
+ }
382
+ let node = body;
383
+ for (const field of path.slice(0, -1)) {
384
+ const next = Object.hasOwn(node, field) ? node[field] : undefined;
385
+ if (next === undefined) {
386
+ const child: Record<string, unknown> = {};
387
+ node[field] = child;
388
+ node = child;
389
+ } else if (typeof next === 'object' && next !== null) {
390
+ node = next as Record<string, unknown>;
391
+ } else {
392
+ return 'nests under a field another key sets';
393
+ }
394
+ }
395
+ const leaf = path[path.length - 1] as string;
396
+ if (Object.hasOwn(node, leaf)) return 'collides with another key';
397
+ node[leaf] = value;
398
+ return undefined;
399
+ }
400
+
401
+ function extraBodyProblem(value: unknown): string | undefined {
402
+ if (value === undefined) return undefined;
403
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
404
+ return 'extraBody must be an object of request fields, e.g. { chat_template_kwargs: { enable_thinking: false } }';
405
+ }
406
+ const reserved = EXTRA_BODY_RESERVED.filter((key) => Object.hasOwn(value, key));
407
+ return reserved.length > 0
408
+ ? `extraBody can't set ${reserved.join(', ')}: the adapter sets ${reserved.length === 1 ? 'it' : 'them'}`
409
+ : undefined;
410
+ }