@meridian-flow/runtime 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 +202 -0
- package/README.md +67 -2
- package/dist/gateway/adapters/anthropic/adapter.d.ts +9 -0
- package/dist/gateway/adapters/anthropic/adapter.js +52 -0
- package/dist/gateway/adapters/anthropic/request-map.d.ts +46 -0
- package/dist/gateway/adapters/anthropic/request-map.js +285 -0
- package/dist/gateway/adapters/anthropic/stream-collect.d.ts +67 -0
- package/dist/gateway/adapters/anthropic/stream-collect.js +295 -0
- package/dist/gateway/adapters/anthropic/tool-schema.d.ts +8 -0
- package/dist/gateway/adapters/anthropic/tool-schema.js +68 -0
- package/dist/gateway/adapters/credentials.d.ts +25 -0
- package/dist/gateway/adapters/credentials.js +118 -0
- package/dist/gateway/adapters/gemini/adapter.d.ts +10 -0
- package/dist/gateway/adapters/gemini/adapter.js +90 -0
- package/dist/gateway/adapters/gemini/request-map.d.ts +29 -0
- package/dist/gateway/adapters/gemini/request-map.js +178 -0
- package/dist/gateway/adapters/gemini/stream-collect.d.ts +29 -0
- package/dist/gateway/adapters/gemini/stream-collect.js +116 -0
- package/dist/gateway/adapters/mock/response.d.ts +11 -0
- package/dist/gateway/adapters/mock/response.js +160 -0
- package/dist/gateway/adapters/mock/samples.d.ts +8 -0
- package/dist/gateway/adapters/mock/samples.js +133 -0
- package/dist/gateway/adapters/mock/script-queue.d.ts +10 -0
- package/dist/gateway/adapters/mock/script-queue.js +60 -0
- package/dist/gateway/adapters/mock/server.d.ts +16 -0
- package/dist/gateway/adapters/mock/server.js +342 -0
- package/dist/gateway/adapters/mock/write-directive.d.ts +15 -0
- package/dist/gateway/adapters/mock/write-directive.js +21 -0
- package/dist/gateway/adapters/openai/adapter.d.ts +3 -0
- package/dist/gateway/adapters/openai/adapter.js +35 -0
- package/dist/gateway/adapters/openai/request-map.d.ts +31 -0
- package/dist/gateway/adapters/openai/request-map.js +228 -0
- package/dist/gateway/adapters/openai/stream-collect.d.ts +63 -0
- package/dist/gateway/adapters/openai/stream-collect.js +490 -0
- package/dist/gateway/adapters/openai-compatible/adapter.d.ts +3 -0
- package/dist/gateway/adapters/openai-compatible/adapter.js +35 -0
- package/dist/gateway/adapters/openai-compatible/request-map.d.ts +31 -0
- package/dist/gateway/adapters/openai-compatible/request-map.js +180 -0
- package/dist/gateway/adapters/openai-compatible/stream-collect.d.ts +84 -0
- package/dist/gateway/adapters/openai-compatible/stream-collect.js +215 -0
- package/dist/gateway/adapters/provider-http-error.d.ts +65 -0
- package/dist/gateway/adapters/provider-http-error.js +188 -0
- package/dist/gateway/adapters/provider-stream.d.ts +23 -0
- package/dist/gateway/adapters/provider-stream.js +58 -0
- package/dist/gateway/attempt-stream.d.ts +27 -0
- package/dist/gateway/attempt-stream.js +329 -0
- package/dist/gateway/create-gateway.d.ts +25 -0
- package/dist/gateway/create-gateway.js +88 -0
- package/dist/gateway/deadline.d.ts +56 -0
- package/dist/gateway/deadline.js +120 -0
- package/dist/gateway/domain/index.d.ts +10 -0
- package/dist/gateway/domain/index.js +10 -0
- package/dist/gateway/domain/media.d.ts +62 -0
- package/dist/gateway/domain/media.js +126 -0
- package/dist/gateway/domain/metering.d.ts +7 -0
- package/dist/gateway/domain/metering.js +6 -0
- package/dist/gateway/domain/resolve-call.d.ts +24 -0
- package/dist/gateway/domain/resolve-call.js +39 -0
- package/dist/gateway/domain/types.d.ts +457 -0
- package/dist/gateway/domain/types.js +10 -0
- package/dist/gateway/helpers/messages.d.ts +17 -0
- package/dist/gateway/helpers/messages.js +29 -0
- package/dist/gateway/helpers/parse-tool-arguments.d.ts +9 -0
- package/dist/gateway/helpers/parse-tool-arguments.js +38 -0
- package/dist/gateway/helpers/tool-call-pairing.d.ts +13 -0
- package/dist/gateway/helpers/tool-call-pairing.js +25 -0
- package/dist/gateway/index.d.ts +12 -0
- package/dist/gateway/index.js +11 -0
- package/dist/gateway/mock-script.d.ts +129 -0
- package/dist/gateway/mock-script.js +129 -0
- package/dist/gateway/mock.d.ts +11 -0
- package/dist/gateway/mock.js +22 -0
- package/dist/gateway/ports/gateway.d.ts +18 -0
- package/dist/gateway/ports/gateway.js +1 -0
- package/dist/gateway/ports/provider-adapter.d.ts +21 -0
- package/dist/gateway/ports/provider-adapter.js +1 -0
- package/dist/gateway/routing.d.ts +28 -0
- package/dist/gateway/routing.js +48 -0
- package/dist/gateway/shapes/index.d.ts +7 -0
- package/dist/gateway/shapes/index.js +1 -0
- package/dist/gateway/shapes/json.d.ts +4 -0
- package/dist/gateway/shapes/json.js +1 -0
- package/dist/gateway/shapes/provider-error.d.ts +10 -0
- package/dist/gateway/shapes/provider-error.js +1 -0
- package/dist/gateway/shapes/usage.d.ts +41 -0
- package/dist/gateway/shapes/usage.js +29 -0
- package/dist/gateway/stream-events.d.ts +21 -0
- package/dist/gateway/stream-events.js +26 -0
- package/package.json +62 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,68 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @meridian-flow/runtime
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
What an AI product needs to run language models, as one npm package. Meridian Flow built it and is
|
|
4
|
+
its first user. Today it holds the model gateway; each part is its own subpath entry.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
npm install @meridian-flow/runtime
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Node 20 or newer, ESM only.
|
|
11
|
+
|
|
12
|
+
## Entries
|
|
13
|
+
|
|
14
|
+
| Entry | What it is |
|
|
15
|
+
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
16
|
+
| `@meridian-flow/runtime/gateway` | One streaming `Gateway` over Anthropic, OpenAI, Gemini and OpenAI-compatible providers: retries, deadlines, usage normalization and a credential per call. |
|
|
17
|
+
| `@meridian-flow/runtime/gateway/shapes` | The gateway's usage, provider-error and JSON types. No Node built-ins and no SDKs, so a browser bundle can import them. |
|
|
18
|
+
| `@meridian-flow/runtime/gateway/mock` | A mock provider server for tests and local development (needs `node:http`). |
|
|
19
|
+
| `@meridian-flow/runtime/gateway/mock-script` | The zod schemas of the mock's scripts. |
|
|
20
|
+
|
|
21
|
+
The package reads no environment variable: keys, URLs and policy come in through config or the call.
|
|
22
|
+
|
|
23
|
+
## Example
|
|
24
|
+
|
|
25
|
+
A gateway with one provider and a credential chosen per call:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { createGateway, user } from "@meridian-flow/runtime/gateway";
|
|
29
|
+
|
|
30
|
+
const gateway = createGateway({
|
|
31
|
+
providers: [
|
|
32
|
+
{
|
|
33
|
+
id: "anthropic",
|
|
34
|
+
adapter: "anthropic",
|
|
35
|
+
models: [
|
|
36
|
+
{
|
|
37
|
+
id: "claude-sonnet-4-5",
|
|
38
|
+
provider: "anthropic",
|
|
39
|
+
displayName: "Claude Sonnet 4.5",
|
|
40
|
+
contextWindow: 200_000,
|
|
41
|
+
maxOutputTokens: 64_000,
|
|
42
|
+
tokenizer: "anthropic",
|
|
43
|
+
inputModalities: ["text", "image"],
|
|
44
|
+
reasoning: { efforts: ["low", "medium", "high"], canDisable: true },
|
|
45
|
+
promptCache: { kind: "explicit", shortTtlSeconds: 300, longTtlSeconds: 3600 },
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const apiKey = "key-for-this-tenant"; // read it wherever your product keeps keys
|
|
53
|
+
|
|
54
|
+
for await (const event of gateway.stream({
|
|
55
|
+
model: "claude-sonnet-4-5",
|
|
56
|
+
messages: [user("Say hello.")],
|
|
57
|
+
promptCacheRetention: "none",
|
|
58
|
+
auth: { anthropic: { apiKey } },
|
|
59
|
+
})) {
|
|
60
|
+
if (event.type === "text.delta") process.stdout.write(event.text);
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`auth` is keyed by provider id and replaces that provider's own credential for this call only.
|
|
65
|
+
Instead of `{ apiKey }`, a credential can be `{ accessToken }`, a function that returns a token
|
|
66
|
+
and its expiry.
|
|
67
|
+
|
|
68
|
+
Licensed under [Apache-2.0](LICENSE).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ProviderConfig } from "../../domain/index.js";
|
|
2
|
+
import type { ProviderAdapter } from "../../ports/provider-adapter.js";
|
|
3
|
+
import { type ProviderErrorPatterns } from "../provider-http-error.js";
|
|
4
|
+
/**
|
|
5
|
+
* Anthropic also reports a filtered request as "blocked". The word must be "blocked",
|
|
6
|
+
* not "block": "invalid content block" is a malformed request, not a filter.
|
|
7
|
+
*/
|
|
8
|
+
export declare const ANTHROPIC_ERROR_PATTERNS: Partial<ProviderErrorPatterns>;
|
|
9
|
+
export declare function createAnthropicAdapter(config: ProviderConfig): ProviderAdapter;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic provider adapter: implements the provider-adapter port by streaming
|
|
3
|
+
* the Anthropic Messages SDK and translating to/from canonical gateway types.
|
|
4
|
+
* Owns the Anthropic-specific wiring; the only place the @anthropic-ai SDK is
|
|
5
|
+
* driven for streaming. The shared stream envelope is `../provider-stream.ts`.
|
|
6
|
+
*/
|
|
7
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
8
|
+
import { bearerClientOptions, clientForRequest } from "../credentials.js";
|
|
9
|
+
import { ANTHROPIC_ENV_OPTOUT, providerClientOptions, providerFetch, } from "../provider-http-error.js";
|
|
10
|
+
import { streamProvider } from "../provider-stream.js";
|
|
11
|
+
import { toAnthropicMessageParams } from "./request-map.js";
|
|
12
|
+
import { buildGenerateResult, createStreamAccumulator, eventsFromAnthropicStreamEvent, } from "./stream-collect.js";
|
|
13
|
+
/**
|
|
14
|
+
* Anthropic also reports a filtered request as "blocked". The word must be "blocked",
|
|
15
|
+
* not "block": "invalid content block" is a malformed request, not a filter.
|
|
16
|
+
*/
|
|
17
|
+
export const ANTHROPIC_ERROR_PATTERNS = {
|
|
18
|
+
contentFiltered: /content[\s\S]*(?:filter|blocked)|(?:filter|blocked)[\s\S]*content/,
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* A token goes through the shared `bearerFetch` (with Anthropic's OAuth beta header) instead of
|
|
22
|
+
* the SDK's `credentials`, because the SDK's one 401 refresh needs `maxRetries` above 0, which
|
|
23
|
+
* would also retry 5xx and 429 inside a call. `authToken: null` stops the SDK's environment
|
|
24
|
+
* lookup; with a key set, it never reads a profile or federation config from disk.
|
|
25
|
+
*/
|
|
26
|
+
function authOptions(credential) {
|
|
27
|
+
return { authToken: null, ...bearerClientOptions(credential, providerFetch, "anthropic") };
|
|
28
|
+
}
|
|
29
|
+
export function createAnthropicAdapter(config) {
|
|
30
|
+
const own = new Anthropic({
|
|
31
|
+
...providerClientOptions(config, "https://api.anthropic.com"),
|
|
32
|
+
...ANTHROPIC_ENV_OPTOUT,
|
|
33
|
+
...authOptions(config.auth),
|
|
34
|
+
});
|
|
35
|
+
const clientFor = clientForRequest(config, own, (credential) => own.withOptions(authOptions(credential)));
|
|
36
|
+
const providerId = config.id;
|
|
37
|
+
return {
|
|
38
|
+
stream(request, model, call) {
|
|
39
|
+
const acc = createStreamAccumulator(model.id, providerId, call.longCacheWrites);
|
|
40
|
+
return streamProvider({
|
|
41
|
+
start: { type: "start", model: model.id, provider: providerId },
|
|
42
|
+
signal: request.signal,
|
|
43
|
+
errorPatterns: ANTHROPIC_ERROR_PATTERNS,
|
|
44
|
+
open: () => clientFor(request).messages.create(toAnthropicMessageParams(request, model, call), {
|
|
45
|
+
signal: request.signal,
|
|
46
|
+
}),
|
|
47
|
+
events: (event) => eventsFromAnthropicStreamEvent(event, acc),
|
|
48
|
+
result: () => buildGenerateResult(acc),
|
|
49
|
+
});
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic request mapper: converts canonical GenerateRequests into Anthropic
|
|
3
|
+
* Messages request bodies (messages, system, tools, thinking config). Owns the
|
|
4
|
+
* canonical→Anthropic translation.
|
|
5
|
+
*
|
|
6
|
+
* Key decisions:
|
|
7
|
+
* - System messages are extracted into the top-level `system` param because
|
|
8
|
+
* Anthropic treats system prompts separately from the message array.
|
|
9
|
+
* - Tool-result messages (role="tool") become user messages with tool_result
|
|
10
|
+
* content blocks — Anthropic requires tool results in a user-turn message.
|
|
11
|
+
* - Reasoning replay: thinking/redacted_thinking blocks (with signature or
|
|
12
|
+
* data) are only sent back to the same provider/model pair. Redacted thinking
|
|
13
|
+
* carries opaque provider data for continuity.
|
|
14
|
+
* - Consecutive same-role messages are merged to satisfy Anthropic's
|
|
15
|
+
* alternating user/assistant requirement. Thinking blocks within assistant
|
|
16
|
+
* content are ordered first (Anthropic requires thinking before tool_use/text).
|
|
17
|
+
* - Last-step repair: models that think by default (`reasoning.thinksByDefault`) and
|
|
18
|
+
* are not switched off prepend empty `{ type: "thinking", thinking: "" }` when an
|
|
19
|
+
* assistant message has tool_use and no thinking block. Missing tool_result
|
|
20
|
+
* is repaired earlier in context-builder `completeToolResultGroups`.
|
|
21
|
+
* - Reasoning: a resolved effort goes out as `output_config.effort`; `off` (only
|
|
22
|
+
* resolved for models with a toggle, such as DeepSeek) goes out as
|
|
23
|
+
* `thinking: {type: "disabled"}`; `default` sends nothing. Opus 5.5, Sonnet 5.5
|
|
24
|
+
* and Fable 5.1 think adaptively, and `thinking: disabled` or `budget_tokens`
|
|
25
|
+
* is a 400 on them, which is why they never resolve to `off`.
|
|
26
|
+
* - Prompt caching: when the call resolves to an explicit `cache_control`
|
|
27
|
+
* (`markCachePrefix`), the mapper marks the last system block and the last
|
|
28
|
+
* block of the two most recent wire `user` messages — three breakpoints, under
|
|
29
|
+
* Anthropic's limit of 4. Tools are never marked: Anthropic renders tools before
|
|
30
|
+
* system before messages, so the system breakpoint covers them. The newest user
|
|
31
|
+
* mark writes this request's cache entry; the older one is the read point, where
|
|
32
|
+
* the previous request wrote its own tail, so the prefix is served from cache
|
|
33
|
+
* (Anthropic's "moving breakpoint" guidance). Anthropic folds tool results into
|
|
34
|
+
* user turns, so a long assistant/tool loop still leaves the previous tail as
|
|
35
|
+
* the second-latest user message; its ~20-block lookback tolerates a steer
|
|
36
|
+
* landing beside a tool result. Marks go on wire user messages, whose last block
|
|
37
|
+
* always accepts `cache_control`. Marks move as the tail
|
|
38
|
+
* advances; providers hash content, not the marker, so that never invalidates
|
|
39
|
+
* a cached prefix. A 1h write costs 2x input tokens (5m: 1.25x) — see the
|
|
40
|
+
* registry's `cacheWriteUsdPerMillionTokens` pinned rates.
|
|
41
|
+
*/
|
|
42
|
+
import type Anthropic from "@anthropic-ai/sdk";
|
|
43
|
+
import type { GenerateRequest, ModelInfo, ResolvedCall } from "../../domain/index.js";
|
|
44
|
+
/** Reject, at gateway creation, a model whose explicit cache lifetimes this API cannot be sent. */
|
|
45
|
+
export declare function assertCacheTtlsOnWire(model: Pick<ModelInfo, "id" | "promptCache">): void;
|
|
46
|
+
export declare function toAnthropicMessageParams(request: GenerateRequest, model: Pick<ModelInfo, "id" | "provider" | "wire" | "maxOutputTokens" | "reasoning" | "promptCache" | "projectToolSchema">, call: ResolvedCall): Anthropic.Messages.MessageCreateParamsStreaming;
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { wireMediaSource } from "../../domain/media.js";
|
|
2
|
+
import { anthropicToolSchema } from "./tool-schema.js";
|
|
3
|
+
/** The `cache_control` each supported lifetime, in seconds, is sent as. */
|
|
4
|
+
const CACHE_CONTROL_BY_TTL = new Map([
|
|
5
|
+
[5 * 60, { type: "ephemeral", ttl: "5m" }],
|
|
6
|
+
[60 * 60, { type: "ephemeral", ttl: "1h" }],
|
|
7
|
+
]);
|
|
8
|
+
/** Reject, at gateway creation, a model whose explicit cache lifetimes this API cannot be sent. */
|
|
9
|
+
export function assertCacheTtlsOnWire(model) {
|
|
10
|
+
const { kind, shortTtlSeconds, longTtlSeconds } = model.promptCache;
|
|
11
|
+
if (kind !== "explicit")
|
|
12
|
+
return;
|
|
13
|
+
for (const ttl of [shortTtlSeconds, longTtlSeconds]) {
|
|
14
|
+
if (ttl === null || !CACHE_CONTROL_BY_TTL.has(ttl)) {
|
|
15
|
+
throw new Error(`Explicit prompt cache TTL for ${model.id} must be 5 minutes or 1 hour`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function matchesReasoningOrigin(part, targetProviderId, targetModelId) {
|
|
20
|
+
const origin = part.providerOptions?.meridian;
|
|
21
|
+
return origin?.provider === targetProviderId && origin?.model === targetModelId;
|
|
22
|
+
}
|
|
23
|
+
function mapMediaToAnthropicBlock(part, target) {
|
|
24
|
+
const media = wireMediaSource(target, part);
|
|
25
|
+
const source = "url" in media
|
|
26
|
+
? { type: "url", url: media.url }
|
|
27
|
+
: { type: "base64", data: media.data, media_type: media.mediaType };
|
|
28
|
+
return { type: media.kind === "image" ? "image" : "document", source };
|
|
29
|
+
}
|
|
30
|
+
function mapContentPartToAnthropicBlock(part, target) {
|
|
31
|
+
switch (part.type) {
|
|
32
|
+
case "text":
|
|
33
|
+
if (part.text.length === 0)
|
|
34
|
+
return null;
|
|
35
|
+
return {
|
|
36
|
+
type: "text",
|
|
37
|
+
text: part.text,
|
|
38
|
+
};
|
|
39
|
+
case "media":
|
|
40
|
+
return mapMediaToAnthropicBlock(part, target);
|
|
41
|
+
case "tool_use":
|
|
42
|
+
return {
|
|
43
|
+
type: "tool_use",
|
|
44
|
+
id: part.toolCallId,
|
|
45
|
+
name: part.toolName,
|
|
46
|
+
input: part.input,
|
|
47
|
+
};
|
|
48
|
+
case "tool_result":
|
|
49
|
+
return mapToolResult(part, target);
|
|
50
|
+
case "reasoning": {
|
|
51
|
+
if (!matchesReasoningOrigin(part, target.provider, target.id))
|
|
52
|
+
return null;
|
|
53
|
+
const anthropic = part.providerOptions?.anthropic;
|
|
54
|
+
if (anthropic?.redacted === true && typeof anthropic.data === "string") {
|
|
55
|
+
return {
|
|
56
|
+
type: "redacted_thinking",
|
|
57
|
+
data: anthropic.data,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
if (typeof anthropic?.signature === "string" && anthropic.signature.length > 0) {
|
|
61
|
+
return {
|
|
62
|
+
type: "thinking",
|
|
63
|
+
thinking: part.text,
|
|
64
|
+
signature: anthropic.signature,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* A tool result with text only keeps the string shorthand. Media goes inside the result, except
|
|
73
|
+
* an `is_error` result: Anthropic rejects media there, so it carries text only and its media
|
|
74
|
+
* are returned separately to follow the tool results in the same user message.
|
|
75
|
+
*/
|
|
76
|
+
function mapToolResult(part, target) {
|
|
77
|
+
const text = part.content
|
|
78
|
+
.filter((p) => p.type === "text")
|
|
79
|
+
.map((p) => p.text)
|
|
80
|
+
.join("");
|
|
81
|
+
const media = part.content.filter((p) => p.type === "media");
|
|
82
|
+
const inside = media.length > 0 && !part.isError;
|
|
83
|
+
const content = inside
|
|
84
|
+
? part.content
|
|
85
|
+
.map((p) => p.type === "text"
|
|
86
|
+
? p.text.length > 0
|
|
87
|
+
? { type: "text", text: p.text }
|
|
88
|
+
: null
|
|
89
|
+
: mapMediaToAnthropicBlock(p, target))
|
|
90
|
+
.filter((block) => block !== null)
|
|
91
|
+
: text;
|
|
92
|
+
return {
|
|
93
|
+
type: "tool_result",
|
|
94
|
+
tool_use_id: part.toolCallId,
|
|
95
|
+
...(content.length > 0 ? { content } : {}),
|
|
96
|
+
is_error: part.isError ?? false,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function textFromParts(parts) {
|
|
100
|
+
return parts
|
|
101
|
+
.filter((p) => p.type === "text")
|
|
102
|
+
.map((p) => p.text)
|
|
103
|
+
.join("");
|
|
104
|
+
}
|
|
105
|
+
// ── Message mapping ───────────────────────────────────────────────
|
|
106
|
+
//
|
|
107
|
+
// Canonical Message → Anthropic MessageParam.
|
|
108
|
+
// System messages are extracted separately. Tool messages become user messages
|
|
109
|
+
// with tool_result blocks. Simple text-only messages use the string shorthand.
|
|
110
|
+
// Consecutive same-role messages are merged to satisfy Anthropic's
|
|
111
|
+
// alternating-role constraint.
|
|
112
|
+
//
|
|
113
|
+
/**
|
|
114
|
+
* Order thinking blocks before other content in assistant messages.
|
|
115
|
+
* Anthropic requires thinking/redacted_thinking blocks to precede
|
|
116
|
+
* text and tool_use blocks in the content array.
|
|
117
|
+
*/
|
|
118
|
+
function orderedAnthropicBlocks(blocks) {
|
|
119
|
+
const isThinking = (block) => block.type === "thinking" || block.type === "redacted_thinking";
|
|
120
|
+
return [...blocks.filter(isThinking), ...blocks.filter((block) => !isThinking(block))];
|
|
121
|
+
}
|
|
122
|
+
function mapMessage(message, target) {
|
|
123
|
+
// system messages are extracted separately
|
|
124
|
+
if (message.role === "system")
|
|
125
|
+
return null;
|
|
126
|
+
const role = message.role === "tool" ? "user" : message.role;
|
|
127
|
+
// Tool result messages → user message with tool_result blocks
|
|
128
|
+
if (message.role === "tool") {
|
|
129
|
+
const results = message.content.filter((p) => p.type === "tool_result");
|
|
130
|
+
const blocks = [
|
|
131
|
+
...results.map((p) => mapToolResult(p, target)),
|
|
132
|
+
// An error result's media follow the tool results as ordinary user content.
|
|
133
|
+
...results
|
|
134
|
+
.filter((p) => p.isError)
|
|
135
|
+
.flatMap((p) => p.content.filter((c) => c.type === "media"))
|
|
136
|
+
.map((p) => mapMediaToAnthropicBlock(p, target)),
|
|
137
|
+
];
|
|
138
|
+
return blocks.length > 0 ? { role: "user", content: blocks } : null;
|
|
139
|
+
}
|
|
140
|
+
// Simple text-only messages can use string shorthand
|
|
141
|
+
const hasOnlyText = message.content.every((p) => p.type === "text");
|
|
142
|
+
if (hasOnlyText && message.content.length > 0) {
|
|
143
|
+
const text = textFromParts(message.content);
|
|
144
|
+
if (text.length === 0)
|
|
145
|
+
return null;
|
|
146
|
+
return { role, content: text };
|
|
147
|
+
}
|
|
148
|
+
const blocks = message.content
|
|
149
|
+
.map((part) => mapContentPartToAnthropicBlock(part, target))
|
|
150
|
+
.filter((p) => p !== null);
|
|
151
|
+
return blocks.length > 0 ? { role, content: orderedAnthropicBlocks(blocks) } : null;
|
|
152
|
+
}
|
|
153
|
+
function messageContentBlocks(content) {
|
|
154
|
+
return typeof content === "string" ? [{ type: "text", text: content }] : [...content];
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Merge consecutive messages with the same role into a single message.
|
|
158
|
+
* Anthropic requires strict alternation between user and assistant roles;
|
|
159
|
+
* consecutive messages of the same role must be collapsed. Thinking blocks
|
|
160
|
+
* in the merged assistant content are re-ordered to the front.
|
|
161
|
+
*/
|
|
162
|
+
const EMPTY_THINKING = { type: "thinking", thinking: "" };
|
|
163
|
+
function blockIsThinking(block) {
|
|
164
|
+
return block.type === "thinking" || block.type === "redacted_thinking";
|
|
165
|
+
}
|
|
166
|
+
/** DeepSeek thinking mode (and Anthropic thinking) require thinking before tool_use. */
|
|
167
|
+
function ensureThinkingBeforeToolUse(messages) {
|
|
168
|
+
return messages.map((message) => {
|
|
169
|
+
if (message.role !== "assistant")
|
|
170
|
+
return message;
|
|
171
|
+
const blocks = messageContentBlocks(message.content);
|
|
172
|
+
const hasToolUse = blocks.some((block) => block.type === "tool_use");
|
|
173
|
+
if (!hasToolUse || blocks.some(blockIsThinking))
|
|
174
|
+
return message;
|
|
175
|
+
return {
|
|
176
|
+
...message,
|
|
177
|
+
content: orderedAnthropicBlocks([EMPTY_THINKING, ...blocks]),
|
|
178
|
+
};
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
function mergeConsecutiveSameRole(messages) {
|
|
182
|
+
const merged = [];
|
|
183
|
+
for (const message of messages) {
|
|
184
|
+
const previous = merged.at(-1);
|
|
185
|
+
if (!previous || previous.role !== message.role) {
|
|
186
|
+
merged.push(message);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const content = [
|
|
190
|
+
...messageContentBlocks(previous.content),
|
|
191
|
+
...messageContentBlocks(message.content),
|
|
192
|
+
];
|
|
193
|
+
merged[merged.length - 1] = {
|
|
194
|
+
...previous,
|
|
195
|
+
content: previous.role === "assistant" ? orderedAnthropicBlocks(content) : content,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
return merged;
|
|
199
|
+
}
|
|
200
|
+
// ── System prompt extraction ──────────────────────────────────────
|
|
201
|
+
//
|
|
202
|
+
// System messages are joined into the top-level `system` string; cache marking
|
|
203
|
+
// turns it into a single marked text block (see `markCachePrefix`).
|
|
204
|
+
//
|
|
205
|
+
function extractSystem(messages) {
|
|
206
|
+
const system = textFromParts(messages.filter((m) => m.role === "system").flatMap((m) => m.content));
|
|
207
|
+
return system.length > 0 ? system : undefined;
|
|
208
|
+
}
|
|
209
|
+
// ── Cache marking ─────────────────────────────────────────────────
|
|
210
|
+
/** Put `cacheControl` on the last block. Wire user messages are never empty and hold no thinking or empty-text block (both are dropped when mapped), so the last block can always carry it. */
|
|
211
|
+
function markLastBlock(content, cacheControl) {
|
|
212
|
+
const blocks = messageContentBlocks(content);
|
|
213
|
+
const last = blocks.length - 1;
|
|
214
|
+
blocks[last] = { ...blocks[last], cache_control: cacheControl };
|
|
215
|
+
return blocks;
|
|
216
|
+
}
|
|
217
|
+
/** Mark the system prompt and the two most recent wire user messages. */
|
|
218
|
+
function markCachePrefix(system, messages, cacheControl) {
|
|
219
|
+
const marked = [...messages];
|
|
220
|
+
let remaining = 2;
|
|
221
|
+
for (let index = marked.length - 1; index >= 0 && remaining > 0; index--) {
|
|
222
|
+
if (marked[index].role !== "user")
|
|
223
|
+
continue;
|
|
224
|
+
remaining--;
|
|
225
|
+
marked[index] = {
|
|
226
|
+
...marked[index],
|
|
227
|
+
content: markLastBlock(marked[index].content, cacheControl),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
return {
|
|
231
|
+
system: system && [{ type: "text", text: system, cache_control: cacheControl }],
|
|
232
|
+
messages: marked,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
// ── Tool mapping ──────────────────────────────────────────────────
|
|
236
|
+
//
|
|
237
|
+
// Canonical Tool[] → Anthropic ToolUnion[]. Function tools map to Anthropic
|
|
238
|
+
// tools with input_schema. Tools are never cache-marked directly: Anthropic
|
|
239
|
+
// renders tools before system before messages, so the system message's own
|
|
240
|
+
// breakpoint already covers them (see the file header).
|
|
241
|
+
//
|
|
242
|
+
function mapTools(tools, projectSchema) {
|
|
243
|
+
if (!tools?.length)
|
|
244
|
+
return undefined;
|
|
245
|
+
return tools.map((tool) => ({
|
|
246
|
+
name: tool.name,
|
|
247
|
+
description: tool.description,
|
|
248
|
+
input_schema: (projectSchema
|
|
249
|
+
? anthropicToolSchema(tool.inputSchema)
|
|
250
|
+
: tool.inputSchema),
|
|
251
|
+
}));
|
|
252
|
+
}
|
|
253
|
+
// ── Public: build Anthropic params ────────────────────────────────
|
|
254
|
+
//
|
|
255
|
+
// Assembles the full MessageCreateParamsStreaming from a canonical
|
|
256
|
+
// GenerateRequest. Always sets stream:true.
|
|
257
|
+
//
|
|
258
|
+
export function toAnthropicMessageParams(request, model, call) {
|
|
259
|
+
// Only an explicit-cache model gets cache_control: DeepSeek, on this adapter, caches on its own.
|
|
260
|
+
const cacheControl = model.promptCache.kind === "explicit" && call.cacheTtlSeconds !== null
|
|
261
|
+
? CACHE_CONTROL_BY_TTL.get(call.cacheTtlSeconds)
|
|
262
|
+
: undefined;
|
|
263
|
+
const tools = mapTools(request.tools, model.projectToolSchema === true);
|
|
264
|
+
const messages = mergeConsecutiveSameRole(request.messages
|
|
265
|
+
.map((message) => mapMessage(message, model))
|
|
266
|
+
.filter((m) => m !== null));
|
|
267
|
+
const { reasoning } = call;
|
|
268
|
+
const repaired = model.reasoning.thinksByDefault && reasoning !== "off"
|
|
269
|
+
? ensureThinkingBeforeToolUse(messages)
|
|
270
|
+
: messages;
|
|
271
|
+
const plainSystem = extractSystem(request.messages);
|
|
272
|
+
const { system, messages: wireMessages } = cacheControl
|
|
273
|
+
? markCachePrefix(plainSystem, repaired, cacheControl)
|
|
274
|
+
: { system: plainSystem, messages: repaired };
|
|
275
|
+
return {
|
|
276
|
+
model: model.id,
|
|
277
|
+
max_tokens: model.maxOutputTokens,
|
|
278
|
+
messages: wireMessages,
|
|
279
|
+
stream: true,
|
|
280
|
+
...(system !== undefined ? { system } : {}),
|
|
281
|
+
...(tools ? { tools } : {}),
|
|
282
|
+
...(typeof reasoning === "object" ? { output_config: { effort: reasoning.effort } } : {}),
|
|
283
|
+
...(reasoning === "off" ? { thinking: { type: "disabled" } } : {}),
|
|
284
|
+
};
|
|
285
|
+
}
|