@kindgi/adapter-model-anthropic 0.0.0-bootstrap.0 → 0.1.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/LICENSE +201 -0
- package/README.md +83 -2
- package/dist/cost.d.ts +57 -0
- package/dist/cost.d.ts.map +1 -0
- package/dist/cost.js +72 -0
- package/dist/cost.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/provider.d.ts +69 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +94 -0
- package/dist/provider.js.map +1 -0
- package/dist/translate.d.ts +64 -0
- package/dist/translate.d.ts.map +1 -0
- package/dist/translate.js +175 -0
- package/dist/translate.js.map +1 -0
- package/package.json +48 -4
- package/src/cost.ts +92 -0
- package/src/index.ts +19 -0
- package/src/provider.ts +188 -0
- package/src/translate.ts +201 -0
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,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@kindgi/adapter-model-anthropic`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Anthropic `ModelProvider` for [`@kindgi/capabilities`](../../capabilities/). Wraps the official `@anthropic-ai/sdk` client behind the framework's provider-neutral interface and calls the Anthropic Messages API. One provider exposes every model listed in its `metadata.models[]`; `ModelCallInput.model` picks the model per call.
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
Translate between the framework's `ModelCallInput` / `ModelCallResult` and a non-streaming `messages.create` call:
|
|
8
|
+
|
|
9
|
+
- `system` messages are lifted into the top-level `system` parameter (several are joined with a blank line). `tool` messages become `tool_result` blocks folded into user turns, and assistant `toolCalls` become `tool_use` blocks.
|
|
10
|
+
- Tool names are encoded `.` → `__` on send and decoded on receive, because the Messages API rejects dots in tool names (`acme.orders.lookup` ↔ `acme__orders__lookup`). Tool ids must not contain a literal `__`.
|
|
11
|
+
- `max_tokens` is always sent, since Anthropic requires it: `input.maxOutputTokens`, else the model's `ModelInfo.maxOutputTokens`, else `4096`. `temperature` is sent when set, and `abortSignal` is passed to the request.
|
|
12
|
+
- `stop_reason` maps `end_turn` / `stop_sequence` / `pause_turn` → `stop`, `max_tokens` → `length`, `tool_use` → `tool-use`, `refusal` → `content-filter`, anything else → `stop`.
|
|
13
|
+
- Cost accounting that includes prompt caching. Anthropic reports four counters (`input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`), and `costUsd` bills each at its own rate:
|
|
14
|
+
`(input × rate + cacheCreation × rate × creationMultiplier + cacheRead × rate × readMultiplier + output × outputRate) / 1000`.
|
|
15
|
+
The multiplier defaults match the 5-minute cache tier (creation `1.25`, read `0.1`); set `promptCacheCreationMultiplier: 2` in a model's `cost` for the 1-hour tier. `usage.promptTokens` includes cache writes and reads; `usage.cachedTokens` reports the cache reads when there are any.
|
|
16
|
+
|
|
17
|
+
## Exports
|
|
18
|
+
|
|
19
|
+
- **`createAnthropicProvider(options)`** — returns a `ModelProvider` whose `metadata` is `options.metadata`. `invoke()` throws when `input.model` is not one of `metadata.models[].name`.
|
|
20
|
+
- **`AnthropicProviderOptions`**:
|
|
21
|
+
- `apiKey: string | (() => string | Promise<string>)` — a static key, or a resolver called on every `invoke()`. The SDK client is cached and rebuilt only when the resolved key changes, so a rotated secret takes effect on the next call. A per-tenant registry can register one provider per tenant whose resolver reads that tenant's secret.
|
|
22
|
+
- `metadata` — `ProviderMetadata` whose `models[]` are `AnthropicModelInfo`. Caller-supplied, because the API does not report pricing, context windows or features.
|
|
23
|
+
- `baseURL?` — override the API host (proxy, gateway, region routing).
|
|
24
|
+
- `clientOptions?` — other `@anthropic-ai/sdk` client options (`timeout`, `maxRetries`, `defaultHeaders`, `fetch`, …); `apiKey` and `baseURL` are excluded.
|
|
25
|
+
- `client?` — an injected SDK client, used as-is; `apiKey`, `baseURL` and `clientOptions` are then ignored. Useful in tests.
|
|
26
|
+
- **`AnthropicModelInfo`** — `ModelInfo` whose `cost` also accepts `promptCacheCreationMultiplier?` and `promptCacheReadMultiplier?`.
|
|
27
|
+
- **Cost helpers** — `computeCostUsd(usage, rates)`, `toFrameworkUsage(usage)`, `CostRates`, `DEFAULT_CACHE_CREATION_MULTIPLIER_5MIN` (`1.25`), `DEFAULT_CACHE_READ_MULTIPLIER` (`0.1`).
|
|
28
|
+
- **Translation helpers** — `toAnthropicMessages(messages)`, `toAnthropicTools(tools)`, `fromAnthropicResponse(response)`, `mapStopReason(reason)`.
|
|
29
|
+
- **`ModelProvider`** — type re-export from `@kindgi/capabilities`.
|
|
30
|
+
|
|
31
|
+
## Example
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { createProviderRegistry } from '@kindgi/capabilities';
|
|
35
|
+
import { createAnthropicProvider } from '@kindgi/adapter-model-anthropic';
|
|
36
|
+
|
|
37
|
+
const anthropic = createAnthropicProvider({
|
|
38
|
+
// Resolved on every call; `readTenantSecret` stands for your secret store lookup.
|
|
39
|
+
apiKey: () => readTenantSecret(tenantId, 'anthropic-api-key'),
|
|
40
|
+
metadata: {
|
|
41
|
+
id: 'anthropic',
|
|
42
|
+
region: 'us-east-1',
|
|
43
|
+
models: [
|
|
44
|
+
{
|
|
45
|
+
name: 'claude-opus-4-7',
|
|
46
|
+
contextWindow: 200_000,
|
|
47
|
+
features: ['tool-use'],
|
|
48
|
+
maxOutputTokens: 8_192,
|
|
49
|
+
// Rates from the provider's published pricing; cache multipliers default to the 5-minute tier.
|
|
50
|
+
cost: { promptUsdPer1kTokens: 0.005, completionUsdPer1kTokens: 0.025 },
|
|
51
|
+
},
|
|
52
|
+
],
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const { registry } = createProviderRegistry();
|
|
57
|
+
registry.register(tenantId, anthropic);
|
|
58
|
+
|
|
59
|
+
const result = await anthropic.invoke({
|
|
60
|
+
model: 'claude-opus-4-7',
|
|
61
|
+
messages: [
|
|
62
|
+
{ role: 'system', content: 'You are the acme support assistant.' },
|
|
63
|
+
{ role: 'user', content: 'Summarise order 1042 in one sentence.' },
|
|
64
|
+
],
|
|
65
|
+
maxOutputTokens: 256,
|
|
66
|
+
});
|
|
67
|
+
console.log(result.message.content, result.usage, result.costUsd);
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
A single-key deployment passes `apiKey: process.env.ANTHROPIC_API_KEY` (checked for `undefined` first) instead of a resolver.
|
|
71
|
+
|
|
72
|
+
## Non-goals
|
|
73
|
+
|
|
74
|
+
- **Streaming.** `invoke()` resolves with the complete response; streaming would need a different `ModelProvider` interface.
|
|
75
|
+
- **Extended thinking.** `ModelMessage` has no thinking field; `thinking` blocks in responses are dropped.
|
|
76
|
+
- **Image inputs.** `ModelMessage` content is text only.
|
|
77
|
+
- **Structured output.** `structuredOutput` on `ModelCallInput` is ignored.
|
|
78
|
+
- **Retry logic in the adapter.** Retries and timeouts are the SDK client's (`clientOptions.maxRetries`, `clientOptions.timeout`).
|
|
79
|
+
|
|
80
|
+
## Related
|
|
81
|
+
|
|
82
|
+
- [`@kindgi/capabilities`](../../capabilities/) — `ModelProvider`, `ProviderMetadata`, and the provider registry.
|
|
83
|
+
- [`@kindgi/adapter-model-openai-compat`](../model-openai-compat/) — the same interface for OpenAI-compatible endpoints.
|
|
84
|
+
- [`@kindgi/adapter-model-in-process`](../model-in-process/) — local models inside the Node.js process.
|
package/dist/cost.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type Anthropic from '@anthropic-ai/sdk';
|
|
2
|
+
/**
|
|
3
|
+
* Cost multipliers for prompt-cache tokens. Anthropic prices cache
|
|
4
|
+
* activity as a multiple of the base input rate:
|
|
5
|
+
*
|
|
6
|
+
* - Cache creation (writing tokens to a new cache entry): 1.25x base
|
|
7
|
+
* for the 5-minute TTL tier, 2x for the 1-hour tier.
|
|
8
|
+
* - Cache read (reading tokens from an existing cache entry): 0.1x
|
|
9
|
+
* base.
|
|
10
|
+
*
|
|
11
|
+
* Defaults below match the 5-minute tier — the framework's
|
|
12
|
+
* `ModelCallInput` doesn't distinguish TTLs, so callers using the
|
|
13
|
+
* 1-hour cache tier should override
|
|
14
|
+
* `promptCacheCreationMultiplier` at provider construction time.
|
|
15
|
+
*/
|
|
16
|
+
export declare const DEFAULT_CACHE_CREATION_MULTIPLIER_5MIN = 1.25;
|
|
17
|
+
export declare const DEFAULT_CACHE_READ_MULTIPLIER = 0.1;
|
|
18
|
+
export interface CostRates {
|
|
19
|
+
readonly promptUsdPer1kTokens: number;
|
|
20
|
+
readonly completionUsdPer1kTokens: number;
|
|
21
|
+
readonly promptCacheCreationMultiplier?: number;
|
|
22
|
+
readonly promptCacheReadMultiplier?: number;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Compute the USD cost of a single Anthropic invocation from the
|
|
26
|
+
* response's `usage` object.
|
|
27
|
+
*
|
|
28
|
+
* Anthropic reports four token counters:
|
|
29
|
+
* - `input_tokens` — regular (uncached) input tokens
|
|
30
|
+
* - `output_tokens` — completion tokens
|
|
31
|
+
* - `cache_creation_input_tokens` — tokens WRITTEN to cache this
|
|
32
|
+
* request (billed at `input * creationMultiplier`)
|
|
33
|
+
* - `cache_read_input_tokens` — tokens READ from cache this request
|
|
34
|
+
* (billed at `input * readMultiplier`)
|
|
35
|
+
*
|
|
36
|
+
* `input_tokens` already excludes cache-read + cache-creation counts,
|
|
37
|
+
* so we can sum the three input categories with their respective
|
|
38
|
+
* rates without double-counting.
|
|
39
|
+
*/
|
|
40
|
+
export declare function computeCostUsd(usage: Anthropic.Usage, rates: CostRates): number;
|
|
41
|
+
/**
|
|
42
|
+
* Roll up Anthropic's four-way token split into the framework's
|
|
43
|
+
* `UsageCounters` shape.
|
|
44
|
+
*
|
|
45
|
+
* - `promptTokens` = total tokens billed as input = regular +
|
|
46
|
+
* cache-creation + cache-read.
|
|
47
|
+
* - `completionTokens` = output tokens.
|
|
48
|
+
* - `cachedTokens` = cache-read tokens (surfaced for observability;
|
|
49
|
+
* the framework's cost meter uses `costUsd` directly, not this
|
|
50
|
+
* field, so we don't need to bake cache math into `promptTokens`).
|
|
51
|
+
*/
|
|
52
|
+
export declare function toFrameworkUsage(usage: Anthropic.Usage): {
|
|
53
|
+
readonly promptTokens: number;
|
|
54
|
+
readonly completionTokens: number;
|
|
55
|
+
readonly cachedTokens?: number;
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=cost.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../src/cost.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,SAAS,MAAM,mBAAmB,CAAC;AAE/C;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,sCAAsC,OAAO,CAAC;AAC3D,eAAO,MAAM,6BAA6B,MAAM,CAAC;AAEjD,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;IACtC,QAAQ,CAAC,wBAAwB,EAAE,MAAM,CAAC;IAC1C,QAAQ,CAAC,6BAA6B,CAAC,EAAE,MAAM,CAAC;IAChD,QAAQ,CAAC,yBAAyB,CAAC,EAAE,MAAM,CAAC;CAC7C;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,GAAG,MAAM,CAoB/E;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,SAAS,CAAC,KAAK,GAAG;IACxD,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAChC,CASA"}
|
package/dist/cost.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Copyright (C) 2026 Kindgi Inc.
|
|
3
|
+
/**
|
|
4
|
+
* Cost multipliers for prompt-cache tokens. Anthropic prices cache
|
|
5
|
+
* activity as a multiple of the base input rate:
|
|
6
|
+
*
|
|
7
|
+
* - Cache creation (writing tokens to a new cache entry): 1.25x base
|
|
8
|
+
* for the 5-minute TTL tier, 2x for the 1-hour tier.
|
|
9
|
+
* - Cache read (reading tokens from an existing cache entry): 0.1x
|
|
10
|
+
* base.
|
|
11
|
+
*
|
|
12
|
+
* Defaults below match the 5-minute tier — the framework's
|
|
13
|
+
* `ModelCallInput` doesn't distinguish TTLs, so callers using the
|
|
14
|
+
* 1-hour cache tier should override
|
|
15
|
+
* `promptCacheCreationMultiplier` at provider construction time.
|
|
16
|
+
*/
|
|
17
|
+
export const DEFAULT_CACHE_CREATION_MULTIPLIER_5MIN = 1.25;
|
|
18
|
+
export const DEFAULT_CACHE_READ_MULTIPLIER = 0.1;
|
|
19
|
+
/**
|
|
20
|
+
* Compute the USD cost of a single Anthropic invocation from the
|
|
21
|
+
* response's `usage` object.
|
|
22
|
+
*
|
|
23
|
+
* Anthropic reports four token counters:
|
|
24
|
+
* - `input_tokens` — regular (uncached) input tokens
|
|
25
|
+
* - `output_tokens` — completion tokens
|
|
26
|
+
* - `cache_creation_input_tokens` — tokens WRITTEN to cache this
|
|
27
|
+
* request (billed at `input * creationMultiplier`)
|
|
28
|
+
* - `cache_read_input_tokens` — tokens READ from cache this request
|
|
29
|
+
* (billed at `input * readMultiplier`)
|
|
30
|
+
*
|
|
31
|
+
* `input_tokens` already excludes cache-read + cache-creation counts,
|
|
32
|
+
* so we can sum the three input categories with their respective
|
|
33
|
+
* rates without double-counting.
|
|
34
|
+
*/
|
|
35
|
+
export function computeCostUsd(usage, rates) {
|
|
36
|
+
const inputRate = rates.promptUsdPer1kTokens;
|
|
37
|
+
const outputRate = rates.completionUsdPer1kTokens;
|
|
38
|
+
const creationMultiplier = rates.promptCacheCreationMultiplier ?? DEFAULT_CACHE_CREATION_MULTIPLIER_5MIN;
|
|
39
|
+
const readMultiplier = rates.promptCacheReadMultiplier ?? DEFAULT_CACHE_READ_MULTIPLIER;
|
|
40
|
+
const inputTokens = usage.input_tokens;
|
|
41
|
+
const outputTokens = usage.output_tokens;
|
|
42
|
+
const cacheCreation = usage.cache_creation_input_tokens ?? 0;
|
|
43
|
+
const cacheRead = usage.cache_read_input_tokens ?? 0;
|
|
44
|
+
const inputCost = (inputTokens * inputRate +
|
|
45
|
+
cacheCreation * inputRate * creationMultiplier +
|
|
46
|
+
cacheRead * inputRate * readMultiplier) /
|
|
47
|
+
1000;
|
|
48
|
+
const outputCost = (outputTokens * outputRate) / 1000;
|
|
49
|
+
return inputCost + outputCost;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Roll up Anthropic's four-way token split into the framework's
|
|
53
|
+
* `UsageCounters` shape.
|
|
54
|
+
*
|
|
55
|
+
* - `promptTokens` = total tokens billed as input = regular +
|
|
56
|
+
* cache-creation + cache-read.
|
|
57
|
+
* - `completionTokens` = output tokens.
|
|
58
|
+
* - `cachedTokens` = cache-read tokens (surfaced for observability;
|
|
59
|
+
* the framework's cost meter uses `costUsd` directly, not this
|
|
60
|
+
* field, so we don't need to bake cache math into `promptTokens`).
|
|
61
|
+
*/
|
|
62
|
+
export function toFrameworkUsage(usage) {
|
|
63
|
+
const cacheCreation = usage.cache_creation_input_tokens ?? 0;
|
|
64
|
+
const cacheRead = usage.cache_read_input_tokens ?? 0;
|
|
65
|
+
const promptTokens = usage.input_tokens + cacheCreation + cacheRead;
|
|
66
|
+
const base = {
|
|
67
|
+
promptTokens,
|
|
68
|
+
completionTokens: usage.output_tokens,
|
|
69
|
+
};
|
|
70
|
+
return cacheRead > 0 ? { ...base, cachedTokens: cacheRead } : base;
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=cost.js.map
|
package/dist/cost.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cost.js","sourceRoot":"","sources":["../src/cost.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAIjC;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,sCAAsC,GAAG,IAAI,CAAC;AAC3D,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,CAAC;AASjD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,cAAc,CAAC,KAAsB,EAAE,KAAgB;IACrE,MAAM,SAAS,GAAG,KAAK,CAAC,oBAAoB,CAAC;IAC7C,MAAM,UAAU,GAAG,KAAK,CAAC,wBAAwB,CAAC;IAClD,MAAM,kBAAkB,GACtB,KAAK,CAAC,6BAA6B,IAAI,sCAAsC,CAAC;IAChF,MAAM,cAAc,GAAG,KAAK,CAAC,yBAAyB,IAAI,6BAA6B,CAAC;IAExF,MAAM,WAAW,GAAG,KAAK,CAAC,YAAY,CAAC;IACvC,MAAM,YAAY,GAAG,KAAK,CAAC,aAAa,CAAC;IACzC,MAAM,aAAa,GAAG,KAAK,CAAC,2BAA2B,IAAI,CAAC,CAAC;IAC7D,MAAM,SAAS,GAAG,KAAK,CAAC,uBAAuB,IAAI,CAAC,CAAC;IAErD,MAAM,SAAS,GACb,CAAC,WAAW,GAAG,SAAS;QACtB,aAAa,GAAG,SAAS,GAAG,kBAAkB;QAC9C,SAAS,GAAG,SAAS,GAAG,cAAc,CAAC;QACzC,IAAI,CAAC;IACP,MAAM,UAAU,GAAG,CAAC,YAAY,GAAG,UAAU,CAAC,GAAG,IAAI,CAAC;IAEtD,OAAO,SAAS,GAAG,UAAU,CAAC;AAChC,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAsB;IAKrD,MAAM,aAAa,GAAG,KAAK,CAAC,2BAA2B,IAAI,CAAC,CAAC;IAC7D,MAAM,SAAS,GAAG,KAAK,CAAC,uBAAuB,IAAI,CAAC,CAAC;IACrD,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY,GAAG,aAAa,GAAG,SAAS,CAAC;IACpE,MAAM,IAAI,GAAG;QACX,YAAY;QACZ,gBAAgB,EAAE,KAAK,CAAC,aAAa;KACtC,CAAC;IACF,OAAO,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { createAnthropicProvider } from './provider.js';
|
|
2
|
+
export type { AnthropicModelInfo, AnthropicProviderOptions } from './provider.js';
|
|
3
|
+
export { DEFAULT_CACHE_CREATION_MULTIPLIER_5MIN, DEFAULT_CACHE_READ_MULTIPLIER, computeCostUsd, toFrameworkUsage, } from './cost.js';
|
|
4
|
+
export type { CostRates } from './cost.js';
|
|
5
|
+
export { fromAnthropicResponse, mapStopReason, toAnthropicMessages, toAnthropicTools, } from './translate.js';
|
|
6
|
+
export type { ModelProvider } from '@kindgi/capabilities';
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AACxD,YAAY,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAClF,OAAO,EACL,sCAAsC,EACtC,6BAA6B,EAC7B,cAAc,EACd,gBAAgB,GACjB,MAAM,WAAW,CAAC;AACnB,YAAY,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EACL,qBAAqB,EACrB,aAAa,EACb,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Copyright (C) 2026 Kindgi Inc.
|
|
3
|
+
export { createAnthropicProvider } from './provider.js';
|
|
4
|
+
export { DEFAULT_CACHE_CREATION_MULTIPLIER_5MIN, DEFAULT_CACHE_READ_MULTIPLIER, computeCostUsd, toFrameworkUsage, } from './cost.js';
|
|
5
|
+
export { fromAnthropicResponse, mapStopReason, toAnthropicMessages, toAnthropicTools, } from './translate.js';
|
|
6
|
+
//# 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,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAExD,OAAO,EACL,sCAAsC,EACtC,6BAA6B,EAC7B,cAAc,EACd,gBAAgB,GACjB,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,qBAAqB,EACrB,aAAa,EACb,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,gBAAgB,CAAC"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
2
|
+
import type { ModelInfo, ModelProvider, ProviderMetadata } from '@kindgi/capabilities';
|
|
3
|
+
/**
|
|
4
|
+
* Anthropic-specific `ModelInfo` extension. Widens the framework's
|
|
5
|
+
* `ModelInfo.cost` with the two Anthropic prompt-cache multipliers
|
|
6
|
+
* (`promptCacheCreationMultiplier`, `promptCacheReadMultiplier`) that
|
|
7
|
+
* `computeCostUsd` uses to bill cache activity per invocation.
|
|
8
|
+
*
|
|
9
|
+
* When either multiplier is omitted the framework falls back to
|
|
10
|
+
* Anthropic's 5-minute-tier defaults (1.25 / 0.1) inside `cost.ts`.
|
|
11
|
+
*/
|
|
12
|
+
export interface AnthropicModelInfo extends ModelInfo {
|
|
13
|
+
readonly cost: ModelInfo['cost'] & {
|
|
14
|
+
readonly promptCacheCreationMultiplier?: number;
|
|
15
|
+
readonly promptCacheReadMultiplier?: number;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Configuration for the Anthropic `ModelProvider`.
|
|
20
|
+
*
|
|
21
|
+
* `apiKey` accepts either a static string or a lazy resolver
|
|
22
|
+
* `() => Promise<string>`. The resolver form is what makes per-tenant
|
|
23
|
+
* BYO keys work: each tenant's `ModelProvider` instance is registered
|
|
24
|
+
* with a resolver that closes over that tenant's `SecretStore` scope
|
|
25
|
+
* plus the secret name. The adapter calls the resolver on every
|
|
26
|
+
* invocation, so rotating the underlying secret is transparent — the
|
|
27
|
+
* next call gets the new key.
|
|
28
|
+
*
|
|
29
|
+
* `metadata` follows the same pattern as the OpenAI-compat model
|
|
30
|
+
* adapter: caller-supplied, since Anthropic's API surface doesn't
|
|
31
|
+
* advertise pricing / context-window / features and pricing changes
|
|
32
|
+
* shouldn't force an adapter release. `models[]` is authoritative for
|
|
33
|
+
* routing; the adapter picks the right model at invoke time based on
|
|
34
|
+
* `ModelCallInput.model` (which must match one of `models[i].name`).
|
|
35
|
+
*/
|
|
36
|
+
export interface AnthropicProviderOptions {
|
|
37
|
+
readonly apiKey: string | (() => string | Promise<string>);
|
|
38
|
+
/**
|
|
39
|
+
* Metadata surfaced to the router. `models[]` MUST list every model
|
|
40
|
+
* the caller expects to invoke through this connection; the adapter
|
|
41
|
+
* uses `input.model` to pick the right entry per call. Per-model
|
|
42
|
+
* `cost` accepts Anthropic prompt-cache multipliers via
|
|
43
|
+
* `AnthropicModelInfo`.
|
|
44
|
+
*/
|
|
45
|
+
readonly metadata: Omit<ProviderMetadata, 'models'> & {
|
|
46
|
+
readonly models: readonly AnthropicModelInfo[];
|
|
47
|
+
};
|
|
48
|
+
/** Override the base URL (proxy, gateway, region routing). */
|
|
49
|
+
readonly baseURL?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Additional SDK client options (timeouts, custom fetch, headers,
|
|
52
|
+
* etc.). `apiKey` and `baseURL` from the top level always win.
|
|
53
|
+
*/
|
|
54
|
+
readonly clientOptions?: Omit<ConstructorParameters<typeof Anthropic>[0], 'apiKey' | 'baseURL'>;
|
|
55
|
+
/**
|
|
56
|
+
* Dependency-injected SDK client. When present, `apiKey` /
|
|
57
|
+
* `baseURL` / `clientOptions` are ignored on construction (tests
|
|
58
|
+
* pass a mock; production wires a shared client if needed).
|
|
59
|
+
*/
|
|
60
|
+
readonly client?: Anthropic;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Create an Anthropic `ModelProvider`. Non-streaming: the framework's
|
|
64
|
+
* `ModelProvider.invoke` returns a `Promise<ModelCallResult>` and
|
|
65
|
+
* doesn't expose a streaming seam yet — a streaming adapter is a
|
|
66
|
+
* separate primitive.
|
|
67
|
+
*/
|
|
68
|
+
export declare function createAnthropicProvider(options: AnthropicProviderOptions): ModelProvider;
|
|
69
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAGA,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAE1C,OAAO,KAAK,EAGV,SAAS,EACT,aAAa,EACb,gBAAgB,EACjB,MAAM,sBAAsB,CAAC;AAU9B;;;;;;;;GAQG;AACH,MAAM,WAAW,kBAAmB,SAAQ,SAAS;IACnD,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,GAAG;QACjC,QAAQ,CAAC,6BAA6B,CAAC,EAAE,MAAM,CAAC;QAChD,QAAQ,CAAC,yBAAyB,CAAC,EAAE,MAAM,CAAC;KAC7C,CAAC;CACH;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IAC3D;;;;;;OAMG;IACH,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,gBAAgB,EAAE,QAAQ,CAAC,GAAG;QACpD,QAAQ,CAAC,MAAM,EAAE,SAAS,kBAAkB,EAAE,CAAC;KAChD,CAAC;IACF,8DAA8D;IAC9D,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,IAAI,CAAC,qBAAqB,CAAC,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAC,CAAC;IAChG;;;;OAIG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,CAAC;CAC7B;AASD;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,wBAAwB,GAAG,aAAa,CA4FxF"}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// Copyright (C) 2026 Kindgi Inc.
|
|
3
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
4
|
+
import { computeCostUsd, toFrameworkUsage } from './cost.js';
|
|
5
|
+
import { fromAnthropicResponse, mapStopReason, toAnthropicMessages, toAnthropicTools, } from './translate.js';
|
|
6
|
+
/**
|
|
7
|
+
* Adapter-level fallback when neither `ModelCallInput.maxOutputTokens`
|
|
8
|
+
* nor the picked `ModelInfo.maxOutputTokens` is set. Anthropic requires
|
|
9
|
+
* `max_tokens` on every request.
|
|
10
|
+
*/
|
|
11
|
+
const DEFAULT_MAX_TOKENS = 4096;
|
|
12
|
+
/**
|
|
13
|
+
* Create an Anthropic `ModelProvider`. Non-streaming: the framework's
|
|
14
|
+
* `ModelProvider.invoke` returns a `Promise<ModelCallResult>` and
|
|
15
|
+
* doesn't expose a streaming seam yet — a streaming adapter is a
|
|
16
|
+
* separate primitive.
|
|
17
|
+
*/
|
|
18
|
+
export function createAnthropicProvider(options) {
|
|
19
|
+
const metadata = options.metadata;
|
|
20
|
+
// Build a name → model lookup so invoke can resolve in O(1). Callers
|
|
21
|
+
// routinely hit the same model for a whole conversation; the map is
|
|
22
|
+
// built once at construction.
|
|
23
|
+
const modelsByName = new Map(metadata.models.map((m) => [m.name, m]));
|
|
24
|
+
// Cache the SDK client keyed by the currently-resolved API key. When
|
|
25
|
+
// the resolver returns the same value it did last time, reuse the
|
|
26
|
+
// client instance (SDK internally maintains a fetch agent and TCP
|
|
27
|
+
// keepalive — throwing it away on every invoke would tank latency).
|
|
28
|
+
// When the resolver returns a new value (key rotation), rebuild.
|
|
29
|
+
let cached;
|
|
30
|
+
if (options.client !== undefined) {
|
|
31
|
+
// Dep-injected client — pin to sentinel key so resolveClient below
|
|
32
|
+
// always returns the same instance regardless of what the resolver
|
|
33
|
+
// says. Callers using dep injection are opting out of key rotation.
|
|
34
|
+
cached = { key: '<injected>', client: options.client };
|
|
35
|
+
}
|
|
36
|
+
async function resolveApiKey() {
|
|
37
|
+
if (typeof options.apiKey === 'function')
|
|
38
|
+
return options.apiKey();
|
|
39
|
+
return options.apiKey;
|
|
40
|
+
}
|
|
41
|
+
async function resolveClient() {
|
|
42
|
+
if (options.client !== undefined)
|
|
43
|
+
return options.client;
|
|
44
|
+
const key = await resolveApiKey();
|
|
45
|
+
if (cached !== undefined && cached.key === key)
|
|
46
|
+
return cached.client;
|
|
47
|
+
const client = new Anthropic({
|
|
48
|
+
apiKey: key,
|
|
49
|
+
...(options.baseURL !== undefined && { baseURL: options.baseURL }),
|
|
50
|
+
...(options.clientOptions ?? {}),
|
|
51
|
+
});
|
|
52
|
+
cached = { key, client };
|
|
53
|
+
return client;
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
metadata,
|
|
57
|
+
async invoke(input) {
|
|
58
|
+
const modelInfo = modelsByName.get(input.model);
|
|
59
|
+
if (modelInfo === undefined) {
|
|
60
|
+
throw new Error(`@kindgi/adapter-model-anthropic: provider "${metadata.id}" does not expose model "${input.model}". ` +
|
|
61
|
+
`Available: ${[...modelsByName.keys()].join(', ') || '<none>'}.`);
|
|
62
|
+
}
|
|
63
|
+
const startedAt = Date.now();
|
|
64
|
+
const client = await resolveClient();
|
|
65
|
+
const { system, messages } = toAnthropicMessages(input.messages);
|
|
66
|
+
const tools = input.tools !== undefined && input.tools.length > 0
|
|
67
|
+
? toAnthropicTools(input.tools)
|
|
68
|
+
: undefined;
|
|
69
|
+
const requestOptions = input.abortSignal !== undefined ? { signal: input.abortSignal } : {};
|
|
70
|
+
const maxTokens = input.maxOutputTokens ?? modelInfo.maxOutputTokens ?? DEFAULT_MAX_TOKENS;
|
|
71
|
+
const response = await client.messages.create({
|
|
72
|
+
model: input.model,
|
|
73
|
+
max_tokens: maxTokens,
|
|
74
|
+
...(system !== undefined && { system }),
|
|
75
|
+
messages: [...messages],
|
|
76
|
+
...(tools !== undefined && { tools: [...tools] }),
|
|
77
|
+
...(input.temperature !== undefined && { temperature: input.temperature }),
|
|
78
|
+
}, requestOptions);
|
|
79
|
+
const durationMs = Date.now() - startedAt;
|
|
80
|
+
const message = fromAnthropicResponse(response);
|
|
81
|
+
const usage = toFrameworkUsage(response.usage);
|
|
82
|
+
const costUsd = computeCostUsd(response.usage, modelInfo.cost);
|
|
83
|
+
return {
|
|
84
|
+
message,
|
|
85
|
+
finishReason: mapStopReason(response.stop_reason),
|
|
86
|
+
usage,
|
|
87
|
+
costUsd,
|
|
88
|
+
durationMs,
|
|
89
|
+
provider: { id: metadata.id, model: input.model },
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"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"}
|