@demicodes/provider-anthropic-api 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 reasonable and customary use in describing the
141
+ origin of the Work and 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 [yyyy] [name of copyright owner]
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 ADDED
@@ -0,0 +1,11 @@
1
+ # @demicodes/provider-anthropic-api
2
+
3
+ A Demi provider for the Anthropic Messages API. Exposes
4
+ `createAnthropicApiProvider()`.
5
+
6
+ ```ts
7
+ import { createAnthropicApiProvider } from '@demicodes/provider-anthropic-api'
8
+ ```
9
+
10
+ Implements the [`@demicodes/provider`](../provider/README.md) contract. Part of
11
+ [Demi](../../README.md). Apache-2.0.
@@ -0,0 +1,51 @@
1
+ import { Provider, ProviderModel, ProviderModelList } from "@demicodes/provider";
2
+
3
+ //#region src/models.d.ts
4
+ interface AnthropicApiModelOptions {
5
+ id: string;
6
+ displayName?: string;
7
+ description?: string;
8
+ contextWindow: number;
9
+ outputLimit?: number | null;
10
+ supportsTools?: boolean | null;
11
+ supportsAttachments?: boolean | null;
12
+ supportsReasoning?: boolean | null;
13
+ supportedThinkingEfforts?: string[] | null;
14
+ defaultThinkingEffort?: string | null;
15
+ canDisableThinking?: boolean | null;
16
+ serviceTiers?: ProviderModel['serviceTiers'];
17
+ defaultServiceTierId?: string | null;
18
+ }
19
+ declare function anthropicApiDefaultModels(providerId?: string): ProviderModelList;
20
+ //#endregion
21
+ //#region src/provider.d.ts
22
+ type AnthropicApiSecretResolver = () => string | Promise<string> | null | undefined;
23
+ type AnthropicApiHeadersResolver = () => Record<string, string> | Promise<Record<string, string>>;
24
+ type AnthropicApiFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
25
+ interface AnthropicApiRequestOptions {
26
+ /** Overrides the derived max_tokens (default: the model's outputLimit, else 32000). */
27
+ maxTokens?: number;
28
+ /**
29
+ * Budget tokens used when an effort/adaptive thinking config is mapped onto
30
+ * the Messages API's budget knob. Merged over the built-in ladder
31
+ * (low 4k / medium 16k / high 32k / xhigh 64k / max 96k).
32
+ */
33
+ effortBudgetTokens?: Record<string, number>;
34
+ extraBody?: Record<string, unknown>;
35
+ }
36
+ interface AnthropicApiProviderOptions {
37
+ id?: string;
38
+ displayName?: string;
39
+ envPrefix?: string;
40
+ baseUrl?: string;
41
+ apiKey?: AnthropicApiSecretResolver;
42
+ headers?: AnthropicApiHeadersResolver;
43
+ anthropicVersion?: string;
44
+ models?: AnthropicApiModelOptions[];
45
+ defaultModelId?: string;
46
+ request?: AnthropicApiRequestOptions;
47
+ fetch?: AnthropicApiFetch;
48
+ }
49
+ declare function createAnthropicApiProvider(options?: AnthropicApiProviderOptions): Provider;
50
+ //#endregion
51
+ export { type AnthropicApiHeadersResolver, type AnthropicApiModelOptions, type AnthropicApiProviderOptions, type AnthropicApiRequestOptions, type AnthropicApiSecretResolver, anthropicApiDefaultModels, createAnthropicApiProvider };
package/dist/index.mjs ADDED
@@ -0,0 +1,537 @@
1
+ import { isAbortError, isRecord, normalizeBaseUrl, numberOrNull, numberOrZero, parseJsonObject, parseJsonOrString, stringOrNull } from "@demicodes/utils";
2
+ import { Buffer } from "node:buffer";
3
+ import process from "node:process";
4
+ import { zeroUsage } from "@demicodes/core";
5
+ import { authStatusFromKey, defineProvider, httpRequestFailedEvent, normalizeErrorCode, providerErrorFromUnknown, withProviderId } from "@demicodes/provider";
6
+ //#region src/models.ts
7
+ const SOURCE_FETCHED_AT = "1970-01-01T00:00:00.000Z";
8
+ function anthropicApiDefaultModels(providerId = "anthropic") {
9
+ return modelListFromAnthropicApiModels([
10
+ {
11
+ id: "claude-opus-4-8",
12
+ displayName: "Claude Opus 4.8",
13
+ contextWindow: 1e6,
14
+ outputLimit: 128e3,
15
+ supportsTools: true,
16
+ supportsAttachments: true,
17
+ supportsReasoning: true,
18
+ supportedThinkingEfforts: [
19
+ "low",
20
+ "medium",
21
+ "high",
22
+ "xhigh",
23
+ "max"
24
+ ],
25
+ canDisableThinking: false
26
+ },
27
+ {
28
+ id: "claude-opus-4-7",
29
+ displayName: "Claude Opus 4.7",
30
+ contextWindow: 1e6,
31
+ outputLimit: 128e3,
32
+ supportsTools: true,
33
+ supportsAttachments: true,
34
+ supportsReasoning: true,
35
+ supportedThinkingEfforts: [
36
+ "low",
37
+ "medium",
38
+ "high",
39
+ "xhigh",
40
+ "max"
41
+ ],
42
+ canDisableThinking: false
43
+ },
44
+ {
45
+ id: "claude-opus-4-6",
46
+ displayName: "Claude Opus 4.6",
47
+ contextWindow: 1e6,
48
+ outputLimit: 128e3,
49
+ supportsTools: true,
50
+ supportsAttachments: true,
51
+ supportsReasoning: true,
52
+ supportedThinkingEfforts: [
53
+ "low",
54
+ "medium",
55
+ "high",
56
+ "max"
57
+ ],
58
+ canDisableThinking: false
59
+ },
60
+ {
61
+ id: "claude-sonnet-4-6",
62
+ displayName: "Claude Sonnet 4.6",
63
+ contextWindow: 1e6,
64
+ outputLimit: 64e3,
65
+ supportsTools: true,
66
+ supportsAttachments: true,
67
+ supportsReasoning: true,
68
+ supportedThinkingEfforts: [
69
+ "low",
70
+ "medium",
71
+ "high",
72
+ "max"
73
+ ],
74
+ canDisableThinking: false
75
+ },
76
+ {
77
+ id: "claude-fable-5",
78
+ displayName: "Claude Fable 5",
79
+ contextWindow: 1e6,
80
+ outputLimit: 128e3,
81
+ supportsTools: true,
82
+ supportsAttachments: true,
83
+ supportsReasoning: true,
84
+ supportedThinkingEfforts: [
85
+ "low",
86
+ "medium",
87
+ "high",
88
+ "xhigh",
89
+ "max"
90
+ ],
91
+ canDisableThinking: false
92
+ }
93
+ ], {
94
+ providerId,
95
+ defaultModelId: "claude-opus-4-8",
96
+ sourceFetchedAt: SOURCE_FETCHED_AT
97
+ });
98
+ }
99
+ function modelListFromAnthropicApiModels(models, options) {
100
+ const sourceFetchedAt = options.sourceFetchedAt ?? (/* @__PURE__ */ new Date()).toISOString();
101
+ const stale = options.stale === true;
102
+ const mapped = models.map((model) => ({
103
+ providerId: options.providerId,
104
+ id: model.id,
105
+ displayName: model.displayName ?? model.id,
106
+ description: model.description,
107
+ contextWindow: positiveInteger(model.contextWindow, `models[${model.id}].contextWindow`),
108
+ outputLimit: model.outputLimit ?? null,
109
+ supportsTools: model.supportsTools ?? null,
110
+ supportsAttachments: model.supportsAttachments ?? null,
111
+ supportsReasoning: model.supportsReasoning ?? null,
112
+ supportedThinkingEfforts: model.supportedThinkingEfforts ? [...model.supportedThinkingEfforts] : null,
113
+ defaultThinkingEffort: model.defaultThinkingEffort ?? null,
114
+ canDisableThinking: model.canDisableThinking ?? null,
115
+ serviceTiers: model.serviceTiers ? model.serviceTiers.map((tier) => ({ ...tier })) : model.serviceTiers,
116
+ defaultServiceTierId: model.defaultServiceTierId ?? null,
117
+ sourceFetchedAt,
118
+ stale
119
+ }));
120
+ return {
121
+ providerId: options.providerId,
122
+ models: mapped,
123
+ defaultModelId: options.defaultModelId && mapped.some((model) => model.id === options.defaultModelId) ? options.defaultModelId : mapped[0]?.id ?? null,
124
+ warnings: [],
125
+ sourceFetchedAt,
126
+ stale
127
+ };
128
+ }
129
+ function positiveInteger(value, field) {
130
+ if (!Number.isInteger(value) || value <= 0) throw new Error(`${field} must be a positive integer`);
131
+ return value;
132
+ }
133
+ //#endregion
134
+ //#region src/provider.ts
135
+ const DEFAULT_ANTHROPIC_API_BASE_URL = "https://api.anthropic.com/v1";
136
+ const DEFAULT_ANTHROPIC_VERSION = "2023-06-01";
137
+ const DEFAULT_MAX_TOKENS = 32e3;
138
+ const MIN_THINKING_BUDGET_TOKENS = 1024;
139
+ const DEFAULT_EFFORT_BUDGET_TOKENS = {
140
+ low: 4096,
141
+ medium: 16384,
142
+ high: 32768,
143
+ xhigh: 65536,
144
+ max: 98304
145
+ };
146
+ var AnthropicApiProvider = class {
147
+ options;
148
+ constructor(options) {
149
+ this.options = options;
150
+ }
151
+ async *run(request) {
152
+ if (request.cancel.aborted) {
153
+ yield { type: "abort" };
154
+ return;
155
+ }
156
+ let apiKey;
157
+ let headers;
158
+ try {
159
+ apiKey = await this.options.apiKey();
160
+ headers = await this.buildHeaders(apiKey);
161
+ if (!apiKey && !headers.has("x-api-key")) {
162
+ yield {
163
+ type: "error",
164
+ message: "Anthropic API key is missing",
165
+ code: "auth_missing"
166
+ };
167
+ return;
168
+ }
169
+ } catch (error) {
170
+ yield providerErrorFromUnknown(error, apiKey);
171
+ return;
172
+ }
173
+ try {
174
+ const response = await this.options.fetch(anthropicMessagesUrl(this.options.baseUrl), {
175
+ method: "POST",
176
+ headers,
177
+ body: JSON.stringify(buildAnthropicMessagesBody(request, this.options.request)),
178
+ signal: request.cancel
179
+ });
180
+ if (!response.ok) {
181
+ yield await httpRequestFailedEvent(response, apiKey, "Anthropic");
182
+ return;
183
+ }
184
+ yield* mapAnthropicMessageStream(readServerSentEvents(response.body, request.cancel), request.cancel);
185
+ } catch (error) {
186
+ if (request.cancel.aborted || isAbortError(error)) {
187
+ yield { type: "abort" };
188
+ return;
189
+ }
190
+ yield providerErrorFromUnknown(error, apiKey);
191
+ }
192
+ }
193
+ async buildHeaders(apiKey) {
194
+ const headers = new Headers(await this.options.headers?.());
195
+ headers.set("accept", "text/event-stream");
196
+ headers.set("content-type", "application/json");
197
+ headers.set("anthropic-version", this.options.anthropicVersion);
198
+ if (apiKey) headers.set("x-api-key", apiKey);
199
+ return headers;
200
+ }
201
+ };
202
+ function createAnthropicApiProvider(options = {}) {
203
+ const id = options.id ?? "anthropic";
204
+ const displayName = options.displayName ?? "Anthropic API";
205
+ const envPrefix = options.envPrefix ?? "ANTHROPIC";
206
+ const baseUrl = normalizeBaseUrl(options.baseUrl ?? process.env[`${envPrefix}_BASE_URL`] ?? DEFAULT_ANTHROPIC_API_BASE_URL);
207
+ const apiKey = options.apiKey ?? (() => process.env[`${envPrefix}_API_KEY`]);
208
+ const fetchImpl = options.fetch ?? fetch;
209
+ const modelList = () => options.models ? modelListFromAnthropicApiModels(options.models, {
210
+ providerId: id,
211
+ defaultModelId: options.defaultModelId ?? null
212
+ }) : withProviderId(anthropicApiDefaultModels(id), id);
213
+ const runtimeOptions = {
214
+ baseUrl,
215
+ apiKey,
216
+ headers: options.headers,
217
+ anthropicVersion: options.anthropicVersion ?? DEFAULT_ANTHROPIC_VERSION,
218
+ request: options.request,
219
+ fetch: fetchImpl
220
+ };
221
+ return defineProvider({
222
+ id,
223
+ displayName,
224
+ auth: { status: () => authStatusFromKey(apiKey, options.headers, "x-api-key", "Anthropic") },
225
+ state: () => ({
226
+ status: "ready",
227
+ message: "Uses the Anthropic Messages API"
228
+ }),
229
+ listModels: modelList,
230
+ createRuntime: (selection) => {
231
+ const outputLimit = modelList().models.find((model) => model.id === selection.model.model.id)?.outputLimit ?? null;
232
+ const request = {
233
+ ...options.request,
234
+ maxTokens: options.request?.maxTokens ?? outputLimit ?? void 0
235
+ };
236
+ return new AnthropicApiProvider({
237
+ ...runtimeOptions,
238
+ request
239
+ });
240
+ }
241
+ });
242
+ }
243
+ function buildAnthropicMessagesBody(request, options) {
244
+ const maxTokens = options?.maxTokens ?? DEFAULT_MAX_TOKENS;
245
+ const body = {
246
+ model: request.modelId,
247
+ messages: inferenceItemsToAnthropicMessages(request.items),
248
+ max_tokens: maxTokens,
249
+ stream: true
250
+ };
251
+ if (request.systemPrompt.trim()) body.system = request.systemPrompt;
252
+ if (request.tools.length > 0) body.tools = request.tools.map(toolToAnthropicTool);
253
+ const budgetTokens = thinkingBudgetTokens(request.thinking, maxTokens, options?.effortBudgetTokens);
254
+ if (budgetTokens !== null) body.thinking = {
255
+ type: "enabled",
256
+ budget_tokens: budgetTokens
257
+ };
258
+ if (request.serviceTierId) body.service_tier = request.serviceTierId;
259
+ if (options?.extraBody) Object.assign(body, options.extraBody);
260
+ return body;
261
+ }
262
+ /**
263
+ * Maps any thinking config onto the Messages API budget knob: budget configs
264
+ * pass through, effort/adaptive configs resolve through the effort ladder
265
+ * (caller-overridable). Budgets clamp below max_tokens and to the API minimum;
266
+ * nothing is silently dropped.
267
+ */
268
+ function thinkingBudgetTokens(thinking, maxTokens, effortBudgets) {
269
+ if (!thinking || thinking.type === "disabled") return null;
270
+ const requested = thinking.type === "budget" ? thinking.budgetTokens : effortBudgets?.[thinking.effort] ?? DEFAULT_EFFORT_BUDGET_TOKENS[thinking.effort] ?? DEFAULT_EFFORT_BUDGET_TOKENS.medium;
271
+ const cap = Math.max(MIN_THINKING_BUDGET_TOKENS, maxTokens - MIN_THINKING_BUDGET_TOKENS);
272
+ return Math.max(MIN_THINKING_BUDGET_TOKENS, Math.min(requested, cap));
273
+ }
274
+ async function* mapAnthropicMessageStream(events, signal) {
275
+ const toolBlocks = /* @__PURE__ */ new Map();
276
+ let usage = zeroUsage();
277
+ for await (const event of events) {
278
+ if (signal?.aborted) {
279
+ yield { type: "abort" };
280
+ return;
281
+ }
282
+ for (const data of event.data) {
283
+ const value = parseJsonObject(data);
284
+ if (!value) continue;
285
+ const type = stringOrNull(value.type) ?? event.event;
286
+ if (type === "error") {
287
+ const error = isRecord(value.error) ? value.error : value;
288
+ const message = stringOrNull(error.message) ?? "Anthropic API stream error";
289
+ yield {
290
+ type: "error",
291
+ message,
292
+ code: normalizeErrorCode(stringOrNull(error.type), message)
293
+ };
294
+ return;
295
+ }
296
+ if (type === "message_start") {
297
+ const message = isRecord(value.message) ? value.message : null;
298
+ const messageUsage = message && isRecord(message.usage) ? message.usage : null;
299
+ if (messageUsage) usage = mergeAnthropicUsage(usage, messageUsage);
300
+ continue;
301
+ }
302
+ if (type === "content_block_start") {
303
+ const index = numberOrNull(value.index) ?? 0;
304
+ const block = isRecord(value.content_block) ? value.content_block : null;
305
+ if (block?.type === "tool_use") toolBlocks.set(index, {
306
+ id: stringOrNull(block.id) ?? `tool_use_${index}`,
307
+ name: stringOrNull(block.name) ?? "",
308
+ initialInput: block.input,
309
+ inputJson: ""
310
+ });
311
+ else if (block?.type === "thinking") yield { type: "thinking_start" };
312
+ else if (block?.type === "text") {
313
+ const text = stringOrNull(block.text);
314
+ if (text) yield {
315
+ type: "text_delta",
316
+ text
317
+ };
318
+ }
319
+ continue;
320
+ }
321
+ if (type === "content_block_delta") {
322
+ const index = numberOrNull(value.index) ?? 0;
323
+ const delta = isRecord(value.delta) ? value.delta : null;
324
+ if (!delta) continue;
325
+ if (delta.type === "text_delta") {
326
+ const text = stringOrNull(delta.text);
327
+ if (text) yield {
328
+ type: "text_delta",
329
+ text
330
+ };
331
+ } else if (delta.type === "thinking_delta") {
332
+ const text = stringOrNull(delta.thinking);
333
+ if (text) yield {
334
+ type: "thinking_delta",
335
+ text
336
+ };
337
+ } else if (delta.type === "signature_delta") {
338
+ const signature = stringOrNull(delta.signature);
339
+ if (signature) yield {
340
+ type: "thinking_signature",
341
+ signature
342
+ };
343
+ } else if (delta.type === "input_json_delta") {
344
+ const block = toolBlocks.get(index);
345
+ if (block) block.inputJson += stringOrNull(delta.partial_json) ?? "";
346
+ }
347
+ continue;
348
+ }
349
+ if (type === "content_block_stop") {
350
+ const index = numberOrNull(value.index) ?? 0;
351
+ const block = toolBlocks.get(index);
352
+ if (block && block.name) yield {
353
+ type: "tool_call_requested",
354
+ toolUseId: block.id,
355
+ toolName: block.name,
356
+ input: block.inputJson ? parseJsonOrString(block.inputJson) : block.initialInput ?? {}
357
+ };
358
+ toolBlocks.delete(index);
359
+ continue;
360
+ }
361
+ if (type === "message_delta") {
362
+ const deltaUsage = isRecord(value.usage) ? value.usage : null;
363
+ if (deltaUsage) usage = mergeAnthropicUsage(usage, deltaUsage);
364
+ continue;
365
+ }
366
+ if (type === "message_stop") {
367
+ yield {
368
+ type: "response",
369
+ usage
370
+ };
371
+ return;
372
+ }
373
+ }
374
+ }
375
+ yield {
376
+ type: "response",
377
+ usage
378
+ };
379
+ }
380
+ function inferenceItemsToAnthropicMessages(items) {
381
+ const messages = [];
382
+ const append = (role, content) => {
383
+ const last = messages[messages.length - 1];
384
+ if (last?.role === role) {
385
+ last.content.push(...content);
386
+ return;
387
+ }
388
+ messages.push({
389
+ role,
390
+ content
391
+ });
392
+ };
393
+ for (const item of items) switch (item.type) {
394
+ case "user_message":
395
+ case "user_steer":
396
+ append("user", userContentToAnthropic(item.content));
397
+ break;
398
+ case "assistant_text":
399
+ append("assistant", [{
400
+ type: "text",
401
+ text: item.text
402
+ }]);
403
+ break;
404
+ case "tool_use":
405
+ append("assistant", [{
406
+ type: "tool_use",
407
+ id: item.toolUseId,
408
+ name: item.toolName,
409
+ input: item.input ?? {}
410
+ }]);
411
+ break;
412
+ case "tool_result":
413
+ append("user", [{
414
+ type: "tool_result",
415
+ tool_use_id: item.toolUseId,
416
+ content: toolResultContentToAnthropic(item.output),
417
+ ...item.isError ? { is_error: true } : {}
418
+ }]);
419
+ break;
420
+ case "assistant_thinking":
421
+ case "assistant_redacted_thinking": break;
422
+ }
423
+ return messages;
424
+ }
425
+ function userContentToAnthropic(content) {
426
+ return content.flatMap((block) => {
427
+ if (block.type === "text") return [{
428
+ type: "text",
429
+ text: block.text
430
+ }];
431
+ if (block.type === "reference") return [{
432
+ type: "text",
433
+ text: block.reference
434
+ }];
435
+ if (block.type === "document") return [{
436
+ type: "text",
437
+ text: `[document:${block.source.fileName} ${block.source.mediaType}]`
438
+ }];
439
+ if (block.source.type === "url") return [{
440
+ type: "text",
441
+ text: `[image:${block.source.url}]`
442
+ }];
443
+ return [{
444
+ type: "image",
445
+ source: {
446
+ type: "base64",
447
+ media_type: block.source.mediaType,
448
+ data: Buffer.from(block.source.data).toString("base64")
449
+ }
450
+ }];
451
+ });
452
+ }
453
+ function toolResultContentToAnthropic(output) {
454
+ return output.map((block) => {
455
+ if (block.type === "text") return {
456
+ type: "text",
457
+ text: block.text
458
+ };
459
+ return {
460
+ type: "image",
461
+ source: {
462
+ type: "base64",
463
+ media_type: block.source.mediaType,
464
+ data: block.source.data
465
+ }
466
+ };
467
+ });
468
+ }
469
+ function toolToAnthropicTool(tool) {
470
+ return {
471
+ name: tool.name,
472
+ description: tool.description,
473
+ input_schema: tool.inputSchema
474
+ };
475
+ }
476
+ async function* readServerSentEvents(body, signal) {
477
+ if (!body) return;
478
+ const reader = body.getReader();
479
+ const decoder = new TextDecoder();
480
+ let buffer = "";
481
+ let eventName = null;
482
+ let data = [];
483
+ const flush = function* () {
484
+ if (data.length === 0) return;
485
+ yield {
486
+ event: eventName,
487
+ data
488
+ };
489
+ eventName = null;
490
+ data = [];
491
+ };
492
+ try {
493
+ while (true) {
494
+ if (signal?.aborted) return;
495
+ const { value, done } = await reader.read();
496
+ if (done) break;
497
+ buffer += decoder.decode(value, { stream: true });
498
+ let newline = buffer.indexOf("\n");
499
+ while (newline !== -1) {
500
+ const raw = buffer.slice(0, newline);
501
+ buffer = buffer.slice(newline + 1);
502
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
503
+ if (line === "") yield* flush();
504
+ else if (line.startsWith("event:")) eventName = line.slice(6).trim();
505
+ else if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
506
+ newline = buffer.indexOf("\n");
507
+ }
508
+ }
509
+ buffer += decoder.decode();
510
+ if (buffer) {
511
+ const line = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
512
+ if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
513
+ else if (line.startsWith("event:")) eventName = line.slice(6).trim();
514
+ }
515
+ yield* flush();
516
+ } finally {
517
+ reader.releaseLock();
518
+ }
519
+ }
520
+ function anthropicMessagesUrl(baseUrl) {
521
+ const normalized = normalizeBaseUrl(baseUrl);
522
+ return normalized.endsWith("/messages") ? normalized : `${normalized}/messages`;
523
+ }
524
+ function mergeAnthropicUsage(current, usage) {
525
+ const inputTokens = numberOrZero(usage.input_tokens);
526
+ const outputTokens = numberOrZero(usage.output_tokens);
527
+ const cacheReadTokens = numberOrZero(usage.cache_read_input_tokens);
528
+ const cacheWriteTokens = numberOrZero(usage.cache_creation_input_tokens);
529
+ return {
530
+ inputTokens: inputTokens || current.inputTokens,
531
+ outputTokens: outputTokens || current.outputTokens,
532
+ cacheReadTokens: cacheReadTokens || current.cacheReadTokens,
533
+ cacheWriteTokens: cacheWriteTokens || current.cacheWriteTokens
534
+ };
535
+ }
536
+ //#endregion
537
+ export { anthropicApiDefaultModels, createAnthropicApiProvider };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@demicodes/provider-anthropic-api",
3
+ "description": "Anthropic API provider adapter for Demi.",
4
+ "version": "0.1.0",
5
+ "private": false,
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "development": "./src/index.ts",
10
+ "types": "./dist/index.d.mts",
11
+ "import": "./dist/index.mjs"
12
+ }
13
+ },
14
+ "dependencies": {
15
+ "@demicodes/core": "workspace:*",
16
+ "@demicodes/provider": "workspace:*",
17
+ "@demicodes/utils": "workspace:*"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "main": "./dist/index.mjs",
21
+ "module": "./dist/index.mjs",
22
+ "types": "./dist/index.d.mts",
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsdown"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/wspl/demi.git",
35
+ "directory": "packages/provider-anthropic-api"
36
+ },
37
+ "homepage": "https://github.com/wspl/demi/tree/main/packages/provider-anthropic-api#readme",
38
+ "bugs": "https://github.com/wspl/demi/issues"
39
+ }