@aeye/anthropic 0.0.0-stage → 0.11.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/README.md +109 -3
- package/aeye-anthropic.md +109 -0
- package/dist/anthropic.d.ts +349 -0
- package/dist/anthropic.d.ts.map +1 -0
- package/dist/anthropic.js +726 -0
- package/dist/anthropic.js.map +1 -0
- package/dist/convert.d.ts +263 -0
- package/dist/convert.d.ts.map +1 -0
- package/dist/convert.js +808 -0
- package/dist/convert.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/models.d.ts +136 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +80 -0
- package/dist/models.js.map +1 -0
- package/dist/retry.d.ts +104 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +181 -0
- package/dist/retry.js.map +1 -0
- package/dist/types.d.ts +45 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +72 -0
- package/dist/types.js.map +1 -0
- package/package.json +74 -4
|
@@ -0,0 +1,726 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic Provider
|
|
3
|
+
*
|
|
4
|
+
* Claude through the Anthropic Messages API: chat and streaming, tool use,
|
|
5
|
+
* structured output, image and document input, thinking, prompt caching,
|
|
6
|
+
* server tools (web search, web fetch, code execution, MCP), message
|
|
7
|
+
* batches, token counting, the Files API and the Models API.
|
|
8
|
+
*/
|
|
9
|
+
import { isModelInfo, supportedRequest } from '@aeye/ai';
|
|
10
|
+
import { deliverSchema, getModel, getResponseFromChunks, prepareRequest, schemaRejection, toFile, withAllowedTools, withSystemText, } from '@aeye/core';
|
|
11
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
12
|
+
import { ANTHROPIC_PROVIDER, cacheableBlocks, claudeCost, JSON_INSTRUCTION, limitCacheBreakpoints, MAX_CACHE_BREAKPOINTS, messageChunks, StreamAccumulator, toMessages, toOutputFormat, toThinking, toTools, toWireServiceTier, } from './convert';
|
|
13
|
+
import { claudeParameters, DEFAULT_API_VERSION, ANTHROPIC_SCHEMA_DEFAULTS, findModel, traitsOf, } from './models';
|
|
14
|
+
import { abortError, errorStatus, isSpendLimit, retryAfterMs, withRetry } from './retry';
|
|
15
|
+
import { ContextWindowError, ProviderAuthError, ProviderError, ProviderQuotaError, RateLimitError } from './types';
|
|
16
|
+
/**
|
|
17
|
+
* Models used when neither the request, the context, nor the config names one.
|
|
18
|
+
*/
|
|
19
|
+
const DEFAULT_MODELS = {
|
|
20
|
+
imageAnalyze: 'claude-sonnet-5-5',
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Default `max_tokens` without and with streaming. Non-streaming stays under
|
|
24
|
+
* the SDK's ten-minute ceiling; a larger non-streaming request is streamed
|
|
25
|
+
* underneath.
|
|
26
|
+
*/
|
|
27
|
+
const DEFAULT_MAX_TOKENS = { get: 16_000, stream: 64_000 };
|
|
28
|
+
/**
|
|
29
|
+
* The most `max_tokens` the SDK sends without streaming (ten minutes at its
|
|
30
|
+
* estimate of 128,000 tokens an hour).
|
|
31
|
+
*/
|
|
32
|
+
const NON_STREAMING_LIMIT = 21_333;
|
|
33
|
+
/**
|
|
34
|
+
* The beta header fast mode needs on its research-preview models.
|
|
35
|
+
*/
|
|
36
|
+
const FAST_MODE_BETA = 'fast-mode-2026-02-01';
|
|
37
|
+
/**
|
|
38
|
+
* Keys of `Request.extra` that configure the call rather than go in the body.
|
|
39
|
+
*/
|
|
40
|
+
const CALL_KEYS = new Set(['retry', 'retryEvents', 'betas', 'headers']);
|
|
41
|
+
/**
|
|
42
|
+
* Words the API uses when a prompt doesn't fit the context window.
|
|
43
|
+
*/
|
|
44
|
+
const CONTEXT_WINDOW = /prompt is too long|context window|context length|exceeds? the (?:model'?s? )?(?:maximum )?context/i;
|
|
45
|
+
/**
|
|
46
|
+
* The model the request names, or the selected one in its context.
|
|
47
|
+
*/
|
|
48
|
+
function pickModelInfo(metadata, ctx, modelId) {
|
|
49
|
+
return [metadata?.model, ctx?.metadata?.model].find((candidate) => !!candidate && isModelInfo(candidate) && candidate.id === modelId);
|
|
50
|
+
}
|
|
51
|
+
// ============================================================================
|
|
52
|
+
// Provider
|
|
53
|
+
// ============================================================================
|
|
54
|
+
/**
|
|
55
|
+
* Anthropic provider for the @aeye framework: Claude through the Messages
|
|
56
|
+
* API.
|
|
57
|
+
*
|
|
58
|
+
* - Chat and streaming, with tool use (parallel calls, tool choice, strict
|
|
59
|
+
* tools), structured output, and image, PDF and text document input
|
|
60
|
+
* - Thinking: adaptive with effort, or a token budget on older models,
|
|
61
|
+
* returned as signed reasoning that is replayed on later turns
|
|
62
|
+
* - Prompt caching (`cacheBreakpoint`, or automatic), with cache reads and
|
|
63
|
+
* writes in usage and cost
|
|
64
|
+
* - Server tools: web search, web fetch, code execution, MCP servers
|
|
65
|
+
* - Message batches, token counting, the Files API, and the Models API
|
|
66
|
+
*
|
|
67
|
+
* Claude has no embeddings, image generation, speech or transcription, so
|
|
68
|
+
* the provider offers none of them.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* import { AnthropicProvider } from '@aeye/anthropic';
|
|
73
|
+
*
|
|
74
|
+
* const anthropic = new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY! });
|
|
75
|
+
* const response = await anthropic.createExecutor()(
|
|
76
|
+
* { messages: [{ role: 'user', content: 'Hello!' }] },
|
|
77
|
+
* {},
|
|
78
|
+
* { model: 'claude-haiku-5-5' },
|
|
79
|
+
* );
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
export class AnthropicProvider {
|
|
83
|
+
name = ANTHROPIC_PROVIDER;
|
|
84
|
+
config;
|
|
85
|
+
defaultMetadata;
|
|
86
|
+
defaults = DEFAULT_MODELS;
|
|
87
|
+
constructor(config = {}) {
|
|
88
|
+
this.config = config;
|
|
89
|
+
}
|
|
90
|
+
// ============================================================================
|
|
91
|
+
// Client
|
|
92
|
+
// ============================================================================
|
|
93
|
+
/**
|
|
94
|
+
* The SDK client for a config. Its own retries are off: `withRetry` does
|
|
95
|
+
* them, so retry events fire.
|
|
96
|
+
*/
|
|
97
|
+
createClient(config) {
|
|
98
|
+
const credential = config.apiKey ? { apiKey: config.apiKey } : config.authToken ? { authToken: config.authToken } : {};
|
|
99
|
+
return new Anthropic({
|
|
100
|
+
...credential,
|
|
101
|
+
baseURL: config.baseURL,
|
|
102
|
+
maxRetries: 0,
|
|
103
|
+
timeout: config.timeout,
|
|
104
|
+
fetch: config.fetch,
|
|
105
|
+
defaultHeaders: {
|
|
106
|
+
...(config.apiVersion && config.apiVersion !== DEFAULT_API_VERSION ? { 'anthropic-version': config.apiVersion } : {}),
|
|
107
|
+
...(config.workspaceId ? { 'anthropic-workspace-id': config.workspaceId } : {}),
|
|
108
|
+
...config.defaultHeaders,
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Resolve what one API call needs: the effective config and its client,
|
|
114
|
+
* the model (request, then context, then metadata, then defaults), what
|
|
115
|
+
* the model takes, and retries.
|
|
116
|
+
*/
|
|
117
|
+
prepare(operation, request, ctx, metadata, config, signal, defaultModel) {
|
|
118
|
+
const effectiveConfig = { ...this.config, ...config };
|
|
119
|
+
const model = getModel(request.model || ctx.metadata?.model || metadata?.model ||
|
|
120
|
+
effectiveConfig.defaultModels?.[defaultModel] || this.defaults[defaultModel]);
|
|
121
|
+
if (!model) {
|
|
122
|
+
throw new ProviderError(this.name, `Model is required for ${this.name} requests`);
|
|
123
|
+
}
|
|
124
|
+
const apiVersion = effectiveConfig.apiVersion ?? DEFAULT_API_VERSION;
|
|
125
|
+
const modelInfo = (isModelInfo(model) ? model : undefined) ?? pickModelInfo(metadata, ctx, model.id) ?? findModel(effectiveConfig.models, model.id);
|
|
126
|
+
const retryConfig = { ...effectiveConfig.retry, ...request.extra?.retry };
|
|
127
|
+
const retryEvents = request.extra?.retryEvents || effectiveConfig.retryEvents || {};
|
|
128
|
+
const retryContext = { operation, model: model.id, provider: this.name, startTime: Date.now() };
|
|
129
|
+
const effectiveSignal = signal || ctx.signal;
|
|
130
|
+
return {
|
|
131
|
+
config: effectiveConfig,
|
|
132
|
+
client: this.createClient(effectiveConfig),
|
|
133
|
+
ctx,
|
|
134
|
+
metadata,
|
|
135
|
+
model,
|
|
136
|
+
modelInfo,
|
|
137
|
+
traits: traitsOf(modelInfo),
|
|
138
|
+
apiVersion,
|
|
139
|
+
signal: effectiveSignal,
|
|
140
|
+
retry: (call) => withRetry(call, retryContext, retryConfig, retryEvents, effectiveSignal),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The model a call's schemas are planned for: its `ModelInfo`, or its id
|
|
145
|
+
* alone (then planned with {@link ANTHROPIC_SCHEMA_DEFAULTS} and no strict
|
|
146
|
+
* capabilities, so nothing is sent strict that isn't known to be taken).
|
|
147
|
+
*/
|
|
148
|
+
schemaModel(run) {
|
|
149
|
+
return run.modelInfo ?? { id: run.model.id, provider: this.name };
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The schema families this provider sends on the wire.
|
|
153
|
+
*/
|
|
154
|
+
supportedStrictFamilies = new Set(['anthropic']);
|
|
155
|
+
/**
|
|
156
|
+
* How a request's schemas are planned: the families the provider speaks,
|
|
157
|
+
* and the rules of a model whose `ModelInfo` has no `schema`.
|
|
158
|
+
*/
|
|
159
|
+
planOptions() {
|
|
160
|
+
return { speaks: this.supportedStrictFamilies, defaults: ANTHROPIC_SCHEMA_DEFAULTS };
|
|
161
|
+
}
|
|
162
|
+
// ============================================================================
|
|
163
|
+
// Models
|
|
164
|
+
// ============================================================================
|
|
165
|
+
/**
|
|
166
|
+
* A Models API entry as `ModelInfo`, from what the API reports alone:
|
|
167
|
+
* limits, effort levels, thinking modes (`always` when thinking can't be
|
|
168
|
+
* turned off, `budget` without adaptive thinking, `adaptive` otherwise,
|
|
169
|
+
* which only thinks when asked), input types and strict-schema support.
|
|
170
|
+
* Everything the API doesn't report (prices, sampling, forced tool choice,
|
|
171
|
+
* mid-conversation system messages, prefill, fast mode, measured schema
|
|
172
|
+
* limits) is left to the model's data: the AI registry merges
|
|
173
|
+
* `@aeye/models` over these entries, and `config.models` entries are used
|
|
174
|
+
* as they are.
|
|
175
|
+
*/
|
|
176
|
+
convertModel(model, apiVersion) {
|
|
177
|
+
const known = findModel(this.config.models, model.id);
|
|
178
|
+
const caps = model.capabilities;
|
|
179
|
+
const capabilities = new Set(known?.capabilities ?? ['chat', 'streaming', 'tools', 'json']);
|
|
180
|
+
const toggle = (capability, supported) => {
|
|
181
|
+
if (supported === true)
|
|
182
|
+
capabilities.add(capability);
|
|
183
|
+
if (supported === false)
|
|
184
|
+
capabilities.delete(capability);
|
|
185
|
+
};
|
|
186
|
+
if (caps) {
|
|
187
|
+
toggle('vision', caps.image_input?.supported);
|
|
188
|
+
toggle('files', caps.pdf_input?.supported);
|
|
189
|
+
toggle('reasoning', caps.thinking?.supported);
|
|
190
|
+
toggle('structured', caps.structured_outputs?.supported);
|
|
191
|
+
toggle('toolsStrict', caps.structured_outputs?.supported);
|
|
192
|
+
}
|
|
193
|
+
const levels = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
194
|
+
const efforts = caps?.effort?.supported
|
|
195
|
+
? levels.filter(level => caps.effort[level]?.supported)
|
|
196
|
+
: caps?.effort ? undefined : known?.reasoningEfforts;
|
|
197
|
+
const types = caps?.thinking?.types;
|
|
198
|
+
const listed = types ? {
|
|
199
|
+
thinking: types.adaptive?.supported && !types.disabled?.supported && !types.between_tools?.supported ? 'always'
|
|
200
|
+
: !types.adaptive?.supported && types.enabled?.supported ? 'budget'
|
|
201
|
+
: 'adaptive',
|
|
202
|
+
thinkingOff: types.between_tools?.supported ? 'between_tools' : types.disabled?.supported ? 'disabled' : undefined,
|
|
203
|
+
} : {};
|
|
204
|
+
const options = { ...listed, ...known?.providerOptions?.anthropic };
|
|
205
|
+
const traits = traitsOf({ providerOptions: { anthropic: options } });
|
|
206
|
+
return {
|
|
207
|
+
// Without data: no prices, and the tier from the API's lifecycle (not from the id)
|
|
208
|
+
...(known ?? { pricing: {}, tier: model.lifecycle && model.lifecycle !== 'active' ? 'legacy' : 'flagship', tokenizer: 'Claude' }),
|
|
209
|
+
id: model.id,
|
|
210
|
+
provider: this.name,
|
|
211
|
+
name: model.display_name || known?.name || model.id,
|
|
212
|
+
capabilities,
|
|
213
|
+
contextWindow: model.max_input_tokens ?? known?.contextWindow ?? 0,
|
|
214
|
+
maxOutputTokens: model.max_tokens ?? known?.maxOutputTokens,
|
|
215
|
+
supportedParameters: claudeParameters(traits, apiVersion),
|
|
216
|
+
reasoningEfforts: efforts,
|
|
217
|
+
retiresAt: model.retires_at?.slice(0, 10) ?? known?.retiresAt,
|
|
218
|
+
schema: known?.schema ?? (caps?.structured_outputs?.supported ? ANTHROPIC_SCHEMA_DEFAULTS : undefined),
|
|
219
|
+
providerOptions: { ...known?.providerOptions, anthropic: options },
|
|
220
|
+
metadata: {
|
|
221
|
+
...known?.metadata,
|
|
222
|
+
created: model.created_at,
|
|
223
|
+
lifecycle: model.lifecycle,
|
|
224
|
+
line: model.line,
|
|
225
|
+
batch: caps?.batch?.supported,
|
|
226
|
+
citations: caps?.citations?.supported,
|
|
227
|
+
webSearch: caps?.server_tools?.web_search?.supported,
|
|
228
|
+
codeExecution: caps?.server_tools?.code_execution?.supported,
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* List the models the account can use (the Models API), from what the API
|
|
234
|
+
* reports (see `convertModel`) and `config.models`.
|
|
235
|
+
*/
|
|
236
|
+
async listModels(config) {
|
|
237
|
+
const effective = { ...this.config, ...config };
|
|
238
|
+
const client = this.createClient(effective);
|
|
239
|
+
const apiVersion = effective.apiVersion ?? DEFAULT_API_VERSION;
|
|
240
|
+
try {
|
|
241
|
+
const models = [];
|
|
242
|
+
for await (const model of client.models.list({ limit: 1000 })) {
|
|
243
|
+
models.push(this.convertModel(model, apiVersion));
|
|
244
|
+
}
|
|
245
|
+
return models;
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
throw new ProviderError(this.name, 'Failed to list models', error instanceof Error ? error : undefined);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Whether the API answers with these credentials.
|
|
253
|
+
*/
|
|
254
|
+
async checkHealth(config) {
|
|
255
|
+
try {
|
|
256
|
+
await this.createClient({ ...this.config, ...config }).models.list({ limit: 1 });
|
|
257
|
+
return true;
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// ============================================================================
|
|
264
|
+
// Requests
|
|
265
|
+
// ============================================================================
|
|
266
|
+
/**
|
|
267
|
+
* A request without the optional settings the model's data says it
|
|
268
|
+
* doesn't take (`supportedRequest` over its `supportedParameters`, with
|
|
269
|
+
* `temperature` and `top_p` on API version 2023-06-01 for a model whose
|
|
270
|
+
* `sampling` option says so). A model with no `supportedParameters` keeps
|
|
271
|
+
* them; the options decide the rest.
|
|
272
|
+
*/
|
|
273
|
+
supported(request, run) {
|
|
274
|
+
const listed = run.modelInfo?.supportedParameters;
|
|
275
|
+
if (!listed?.size)
|
|
276
|
+
return request;
|
|
277
|
+
const sampling = run.traits.sampling && run.apiVersion === '2023-06-01' ? ['temperature', 'topP'] : [];
|
|
278
|
+
return supportedRequest(request, { supportedParameters: new Set([...listed, ...sampling]) }).request;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The Messages parameters for a request (prepared by `prepareRequest`):
|
|
282
|
+
*
|
|
283
|
+
* - only the allowed tools, and forced tool use as the model takes it;
|
|
284
|
+
* - structured output when the plan rendered the schema strict, otherwise
|
|
285
|
+
* the schema in the prompt; JSON without a schema as an instruction;
|
|
286
|
+
* - thinking and effort for the model (`toThinking`), sampling only where
|
|
287
|
+
* the model and API version take it, and never `temperature` (or a
|
|
288
|
+
* `top_p` under 0.95) with thinking on;
|
|
289
|
+
* - cache breakpoints, at most four, automatic caching, service tier and
|
|
290
|
+
* fast mode, `metadata.user_id` from `userKey`;
|
|
291
|
+
* - `request.extra` on top (but `retry`, `retryEvents`, `betas` and
|
|
292
|
+
* `headers`, which configure the call).
|
|
293
|
+
*
|
|
294
|
+
* @param streaming - Whether the response streams, which sets the default `max_tokens`.
|
|
295
|
+
*/
|
|
296
|
+
async buildParams(planned, run, streaming) {
|
|
297
|
+
const { traits, modelInfo, config } = run;
|
|
298
|
+
// Only what the model's data says it takes goes on the wire
|
|
299
|
+
const request = this.supported(planned, run);
|
|
300
|
+
const cache = config.cache?.ttl ? { type: 'ephemeral', ttl: config.cache.ttl } : { type: 'ephemeral' };
|
|
301
|
+
const allowed = withAllowedTools(request);
|
|
302
|
+
const tools = toTools(allowed, traits, this.name);
|
|
303
|
+
const format = toOutputFormat(allowed);
|
|
304
|
+
let sent = typeof allowed.responseFormat === 'object' && !format ? deliverSchema(allowed, 'prompt') : allowed;
|
|
305
|
+
if (sent.responseFormat === 'json') {
|
|
306
|
+
sent = { ...sent, messages: withSystemText(sent.messages, JSON_INSTRUCTION) };
|
|
307
|
+
}
|
|
308
|
+
const { system, messages } = await toMessages(sent.messages, traits, cache);
|
|
309
|
+
// A model that takes no prefill rejects a conversation that ends with the assistant
|
|
310
|
+
if (!traits.prefill && messages[messages.length - 1]?.role === 'assistant') {
|
|
311
|
+
messages.push({ role: 'user', content: [{ type: 'text', text: 'Continue.' }] });
|
|
312
|
+
}
|
|
313
|
+
const limit = modelInfo?.maxOutputTokens || undefined;
|
|
314
|
+
const fallback = config.maxTokens ?? (streaming ? DEFAULT_MAX_TOKENS.stream : DEFAULT_MAX_TOKENS.get);
|
|
315
|
+
// A max_tokens over the model's limit is a 400, so it's capped
|
|
316
|
+
const maxTokens = Math.min(request.maxTokens ?? fallback, limit ?? Number.MAX_SAFE_INTEGER);
|
|
317
|
+
const thinking = toThinking(traits, request.reason, modelInfo?.reasoningEfforts, maxTokens, tools.forced, limit);
|
|
318
|
+
const thinkingOn = thinking.thinking?.type === 'adaptive' || thinking.thinking?.type === 'enabled' || (!thinking.thinking && traits.thinking !== 'adaptive' && traits.thinking !== 'budget');
|
|
319
|
+
// Sampling: only on 2023-06-01, only on models whose data says so, one of
|
|
320
|
+
// temperature and top_p, and with thinking on only a top_p of 0.95 to 1
|
|
321
|
+
const sampling = traits.sampling && run.apiVersion === '2023-06-01';
|
|
322
|
+
const temperature = sampling && !thinkingOn ? request.temperature : undefined;
|
|
323
|
+
const topP = sampling && temperature === undefined && request.topP !== undefined
|
|
324
|
+
? thinkingOn ? Math.min(1, Math.max(0.95, request.topP)) : request.topP
|
|
325
|
+
: undefined;
|
|
326
|
+
const extra = Object.fromEntries(Object.entries(request.extra ?? {}).filter(([key]) => !CALL_KEYS.has(key)));
|
|
327
|
+
const fast = request.serviceTier === 'fast' && !!traits.fastMode;
|
|
328
|
+
const fastBeta = fast && traits.fastMode === 'beta';
|
|
329
|
+
const stop = request.stop === undefined ? undefined : Array.isArray(request.stop) ? request.stop : [request.stop];
|
|
330
|
+
const params = {
|
|
331
|
+
model: run.model.id,
|
|
332
|
+
max_tokens: thinking.maxTokens,
|
|
333
|
+
messages,
|
|
334
|
+
...(system.length ? { system } : {}),
|
|
335
|
+
...(tools.tools ? { tools: tools.tools } : {}),
|
|
336
|
+
...(tools.toolChoice ? { tool_choice: tools.toolChoice } : {}),
|
|
337
|
+
...(tools.mcpServers ? { mcp_servers: tools.mcpServers } : {}),
|
|
338
|
+
...(thinking.thinking ? { thinking: thinking.thinking } : {}),
|
|
339
|
+
...(format || thinking.effort ? { output_config: { ...(format ? { format } : {}), ...(thinking.effort ? { effort: thinking.effort } : {}) } } : {}),
|
|
340
|
+
...(stop?.length ? { stop_sequences: stop } : {}),
|
|
341
|
+
...(temperature !== undefined ? { temperature } : {}),
|
|
342
|
+
...(topP !== undefined ? { top_p: topP } : {}),
|
|
343
|
+
...(request.userKey ? { metadata: { user_id: request.userKey } } : {}),
|
|
344
|
+
...(toWireServiceTier(request.serviceTier) ? { service_tier: toWireServiceTier(request.serviceTier) } : {}),
|
|
345
|
+
...(fast ? { speed: 'fast' } : {}),
|
|
346
|
+
...(config.inferenceGeo && traits.inferenceGeo ? { inference_geo: config.inferenceGeo } : {}),
|
|
347
|
+
...(config.cache?.automatic ? { cache_control: cache } : {}),
|
|
348
|
+
...extra,
|
|
349
|
+
};
|
|
350
|
+
limitCacheBreakpoints(cacheableBlocks(params.tools, system, messages), config.cache?.automatic ? MAX_CACHE_BREAKPOINTS - 1 : MAX_CACHE_BREAKPOINTS);
|
|
351
|
+
const betas = [...new Set([...config.betas ?? [], ...tools.betas, ...(fastBeta ? [FAST_MODE_BETA] : []), ...(request.extra?.betas ?? [])])];
|
|
352
|
+
const headers = { ...(betas.length ? { 'anthropic-beta': betas.join(',') } : {}), ...request.extra?.headers };
|
|
353
|
+
return { params, sent, betas, headers };
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* An API error as the provider reports it: a context-window overflow, a
|
|
357
|
+
* rejected schema, bad credentials, a reached spend limit, or a rate limit
|
|
358
|
+
* that outlasted the retries. Other errors pass through unchanged.
|
|
359
|
+
*/
|
|
360
|
+
mapError(error, request) {
|
|
361
|
+
if (!(error instanceof Error) || error.name === 'AbortError' || error instanceof Anthropic.APIUserAbortError) {
|
|
362
|
+
return error;
|
|
363
|
+
}
|
|
364
|
+
const status = errorStatus(error);
|
|
365
|
+
const message = error.apiMessage ?? error.message;
|
|
366
|
+
if ((status === 400 || status === 413) && CONTEXT_WINDOW.test(message)) {
|
|
367
|
+
const [, , limit] = /(\d+)\s*tokens?\s*>\s*(\d+)/.exec(message) ?? [];
|
|
368
|
+
return new ContextWindowError(this.name, message, limit ? Number(limit) : undefined, error);
|
|
369
|
+
}
|
|
370
|
+
if (status === 400 && request) {
|
|
371
|
+
const rejected = schemaRejection(request, error, message);
|
|
372
|
+
if (rejected)
|
|
373
|
+
return rejected;
|
|
374
|
+
}
|
|
375
|
+
if (status === 401 || status === 403) {
|
|
376
|
+
return new ProviderAuthError(this.name, error);
|
|
377
|
+
}
|
|
378
|
+
if (isSpendLimit(error)) {
|
|
379
|
+
return new ProviderQuotaError(this.name, error);
|
|
380
|
+
}
|
|
381
|
+
if (status === 429 || status === 529) {
|
|
382
|
+
const after = retryAfterMs(error);
|
|
383
|
+
return new RateLimitError(this.name, status === 529 ? 'API overloaded' : 'Rate limit exceeded', after === undefined ? undefined : after / 1000, error);
|
|
384
|
+
}
|
|
385
|
+
return error;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Send one call with retries, around the operation's before and error hooks.
|
|
389
|
+
*/
|
|
390
|
+
async send(op, run, request, params, call) {
|
|
391
|
+
const hooks = run.config.hooks?.[op];
|
|
392
|
+
await hooks?.beforeRequest?.(request, params, run.ctx, run.metadata);
|
|
393
|
+
try {
|
|
394
|
+
return await run.retry(call);
|
|
395
|
+
}
|
|
396
|
+
catch (e) {
|
|
397
|
+
const mapped = this.mapError(e, op === 'chat' ? request : undefined);
|
|
398
|
+
if (mapped instanceof Error) {
|
|
399
|
+
await hooks?.onError?.(request, params, mapped, run.ctx, run.metadata);
|
|
400
|
+
}
|
|
401
|
+
throw mapped;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Report a response to the operation's after hook and return it.
|
|
406
|
+
*/
|
|
407
|
+
async finish(op, run, request, params, response) {
|
|
408
|
+
const hooks = run.config.hooks?.[op];
|
|
409
|
+
await hooks?.afterRequest?.(request, params, response, run.ctx, run.metadata);
|
|
410
|
+
return response;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Chunks of a complete message, its usage priced.
|
|
414
|
+
*/
|
|
415
|
+
priced(chunks, usage, run, batch = false) {
|
|
416
|
+
const cost = claudeCost(usage, run.modelInfo, batch);
|
|
417
|
+
if (cost !== undefined) {
|
|
418
|
+
const end = chunks[chunks.length - 1];
|
|
419
|
+
end.usage = { ...end.usage, cost };
|
|
420
|
+
}
|
|
421
|
+
return chunks;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Run a chat request without streaming. A turn the API pauses (long
|
|
425
|
+
* server tool use) is continued with what it produced so far, up to
|
|
426
|
+
* `maxContinuations` times. A request too long for a plain call streams
|
|
427
|
+
* underneath. A prompt that overflows the context window ends as `length`,
|
|
428
|
+
* so the prompt loop can trim and retry.
|
|
429
|
+
*/
|
|
430
|
+
async complete(request, run) {
|
|
431
|
+
const built = await this.buildParams(request, run, false);
|
|
432
|
+
if (built.params.max_tokens > NON_STREAMING_LIMIT) {
|
|
433
|
+
return this.drain(this.streamBuilt(request, built, run), run);
|
|
434
|
+
}
|
|
435
|
+
const { params, headers } = built;
|
|
436
|
+
const chunks = [];
|
|
437
|
+
let body = params;
|
|
438
|
+
try {
|
|
439
|
+
for (let continuation = 0;; continuation++) {
|
|
440
|
+
const message = await this.send('chat', run, request, body, (signal) => run.client.messages.create({ ...body, stream: false }, { signal, headers }));
|
|
441
|
+
const offset = chunks.reduce((n, chunk) => n + (chunk.content?.length ?? 0), 0);
|
|
442
|
+
chunks.push(...this.priced(messageChunks(message, offset, continuation * 1000), message.usage, run));
|
|
443
|
+
if (message.stop_reason !== 'pause_turn' || continuation >= (run.config.maxContinuations ?? 5)) {
|
|
444
|
+
break;
|
|
445
|
+
}
|
|
446
|
+
body = { ...body, messages: [...body.messages, { role: 'assistant', content: message.content }] };
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
catch (e) {
|
|
450
|
+
if (!(e instanceof ContextWindowError))
|
|
451
|
+
throw e;
|
|
452
|
+
return this.finish('chat', run, request, params, { content: '', toolCalls: [], finishReason: 'length', model: run.model, usage: { text: { input: e.contextWindow } } });
|
|
453
|
+
}
|
|
454
|
+
return this.finish('chat', run, request, params, getResponseFromChunks(chunks, run.model));
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* A stream's response.
|
|
458
|
+
*/
|
|
459
|
+
async drain(stream, run) {
|
|
460
|
+
for (;;) {
|
|
461
|
+
const next = await stream.next();
|
|
462
|
+
if (next.done)
|
|
463
|
+
return next.value;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Stream a built request, continuing paused turns, reporting the
|
|
468
|
+
* assembled response to the after hook (even when the stream fails part
|
|
469
|
+
* way) and returning it.
|
|
470
|
+
*/
|
|
471
|
+
async *streamBuilt(request, built, run) {
|
|
472
|
+
const { params, headers } = built;
|
|
473
|
+
const received = [];
|
|
474
|
+
let body = params;
|
|
475
|
+
let response;
|
|
476
|
+
let accumulator = new StreamAccumulator();
|
|
477
|
+
try {
|
|
478
|
+
for (let continuation = 0;; continuation++) {
|
|
479
|
+
let stream;
|
|
480
|
+
try {
|
|
481
|
+
stream = await this.send('chat', run, request, body, (signal) => run.client.messages.create({ ...body, stream: true }, { signal, headers }));
|
|
482
|
+
}
|
|
483
|
+
catch (e) {
|
|
484
|
+
if (e instanceof ContextWindowError && continuation === 0) {
|
|
485
|
+
response = { content: '', toolCalls: [], finishReason: 'length', model: run.model, usage: { text: { input: e.contextWindow } } };
|
|
486
|
+
await this.finish('chat', run, request, params, response);
|
|
487
|
+
return response;
|
|
488
|
+
}
|
|
489
|
+
throw e;
|
|
490
|
+
}
|
|
491
|
+
try {
|
|
492
|
+
for await (const event of stream) {
|
|
493
|
+
if (run.signal?.aborted) {
|
|
494
|
+
throw abortError(run.signal);
|
|
495
|
+
}
|
|
496
|
+
const chunk = accumulator.event(event);
|
|
497
|
+
if (!chunk)
|
|
498
|
+
continue;
|
|
499
|
+
if (event.type === 'message_stop') {
|
|
500
|
+
const cost = claudeCost(accumulator.counts, run.modelInfo);
|
|
501
|
+
if (cost !== undefined && chunk.usage)
|
|
502
|
+
chunk.usage.cost = cost;
|
|
503
|
+
// A paused turn isn't finished
|
|
504
|
+
if (accumulator.message?.stop_reason === 'pause_turn')
|
|
505
|
+
delete chunk.finishReason;
|
|
506
|
+
}
|
|
507
|
+
received.push(chunk);
|
|
508
|
+
yield chunk;
|
|
509
|
+
}
|
|
510
|
+
// The SDK ends an aborted stream quietly, as if it had finished
|
|
511
|
+
if (run.signal?.aborted) {
|
|
512
|
+
throw abortError(run.signal);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
catch (e) {
|
|
516
|
+
throw this.mapError(e, request);
|
|
517
|
+
}
|
|
518
|
+
const message = accumulator.message;
|
|
519
|
+
if (message?.stop_reason !== 'pause_turn' || continuation >= (run.config.maxContinuations ?? 5)) {
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
522
|
+
body = { ...body, messages: [...body.messages, { role: 'assistant', content: message.content }] };
|
|
523
|
+
accumulator = new StreamAccumulator(accumulator.length, (continuation + 1) * 1000);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
finally {
|
|
527
|
+
if (!response) {
|
|
528
|
+
response = getResponseFromChunks(received, run.model);
|
|
529
|
+
await this.finish('chat', run, request, params, response);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return response;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Plan a request's schemas for the model and resolve the call.
|
|
536
|
+
*/
|
|
537
|
+
async start(operation, request, ctx, metadata, config, signal) {
|
|
538
|
+
const run = this.prepare(operation, request, ctx, metadata, config, signal, 'chat');
|
|
539
|
+
const sent = await prepareRequest(request, this.schemaModel(run), this.planOptions());
|
|
540
|
+
return [sent, run];
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Create an executor for chat requests.
|
|
544
|
+
*/
|
|
545
|
+
createExecutor(config) {
|
|
546
|
+
return async (request, ctx, metadata, signal) => {
|
|
547
|
+
const [sent, run] = await this.start('chat', request, ctx, metadata, config, signal);
|
|
548
|
+
return this.complete(sent, run);
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Create a streamer for chat requests.
|
|
553
|
+
*/
|
|
554
|
+
createStreamer(config) {
|
|
555
|
+
const provider = this;
|
|
556
|
+
return async function* (request, ctx, metadata, signal) {
|
|
557
|
+
const [sent, run] = await provider.start('streaming chat', request, ctx, metadata, config, signal);
|
|
558
|
+
const built = await provider.buildParams(sent, run, true);
|
|
559
|
+
return yield* provider.streamBuilt(sent, built, run);
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
// ============================================================================
|
|
563
|
+
// Token counting
|
|
564
|
+
// ============================================================================
|
|
565
|
+
/**
|
|
566
|
+
* Count the input tokens a chat request would take on a model, as the API
|
|
567
|
+
* counts them (system prompt, tools, images and documents included),
|
|
568
|
+
* without running it. Free, and rate limited apart from requests.
|
|
569
|
+
*
|
|
570
|
+
* @param request - The chat request.
|
|
571
|
+
* @param ctx - Context; its `metadata.model` names the model when the request doesn't.
|
|
572
|
+
* @param config - Per-call config override.
|
|
573
|
+
* @returns The input tokens.
|
|
574
|
+
*/
|
|
575
|
+
async countTokens(request, ctx = {}, config) {
|
|
576
|
+
const [sent, run] = await this.start('count tokens', request, ctx, undefined, config, undefined);
|
|
577
|
+
const { params, headers } = await this.buildParams(sent, run, false);
|
|
578
|
+
const { model, messages, system, tools, tool_choice, thinking, output_config, speed } = params;
|
|
579
|
+
const counted = {
|
|
580
|
+
model, messages,
|
|
581
|
+
...(system ? { system } : {}),
|
|
582
|
+
...(tools ? { tools: tools } : {}),
|
|
583
|
+
...(tool_choice ? { tool_choice } : {}),
|
|
584
|
+
...(thinking ? { thinking } : {}),
|
|
585
|
+
...(output_config ? { output_config } : {}),
|
|
586
|
+
...(speed ? { speed } : {}),
|
|
587
|
+
};
|
|
588
|
+
const result = await this.send('countTokens', run, request, counted, (signal) => run.client.messages.countTokens(counted, { signal, headers }));
|
|
589
|
+
return this.finish('countTokens', run, request, counted, result.input_tokens);
|
|
590
|
+
}
|
|
591
|
+
// ============================================================================
|
|
592
|
+
// Files
|
|
593
|
+
// ============================================================================
|
|
594
|
+
/**
|
|
595
|
+
* Upload a file to the Files API. Its id (`file_...`) can then stand in
|
|
596
|
+
* for the file as image or file content in any later request, without
|
|
597
|
+
* sending the bytes again.
|
|
598
|
+
*
|
|
599
|
+
* @param file - The file's content.
|
|
600
|
+
* @param options - Its name and type, when the content doesn't carry them.
|
|
601
|
+
*/
|
|
602
|
+
async uploadFile(file, options = {}) {
|
|
603
|
+
const run = this.prepare('upload file', { model: 'files' }, {}, undefined, options.config, undefined, 'chat');
|
|
604
|
+
const upload = await toFile(file, options.mimeType, options.name);
|
|
605
|
+
return run.retry((signal) => run.client.files.upload({ file: upload }, { signal }));
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* The files uploaded to the Files API.
|
|
609
|
+
*/
|
|
610
|
+
async listFiles(config) {
|
|
611
|
+
const client = this.createClient({ ...this.config, ...config });
|
|
612
|
+
const files = [];
|
|
613
|
+
for await (const file of client.files.list({ limit: 1000 })) {
|
|
614
|
+
files.push(file);
|
|
615
|
+
}
|
|
616
|
+
return files;
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Delete an uploaded file.
|
|
620
|
+
*/
|
|
621
|
+
async deleteFile(id, config) {
|
|
622
|
+
const run = this.prepare('delete file', { model: 'files' }, {}, undefined, config, undefined, 'chat');
|
|
623
|
+
await run.retry((signal) => run.client.files.delete(id, {}, { signal }));
|
|
624
|
+
}
|
|
625
|
+
// ============================================================================
|
|
626
|
+
// Batches
|
|
627
|
+
// ============================================================================
|
|
628
|
+
/**
|
|
629
|
+
* Run chat requests as one Message Batch, at half price, on one model.
|
|
630
|
+
* Each request becomes the call a direct request would make.
|
|
631
|
+
*
|
|
632
|
+
* @param requests - Chat requests, whose results come back in this order.
|
|
633
|
+
*/
|
|
634
|
+
submitBatch = async (requests, ctx, config) => {
|
|
635
|
+
const [first] = requests;
|
|
636
|
+
if (!first) {
|
|
637
|
+
throw new ProviderError(this.name, 'A batch needs at least one request');
|
|
638
|
+
}
|
|
639
|
+
const run = this.prepare('submit batch', first, ctx, undefined, config, undefined, 'chat');
|
|
640
|
+
const entries = await Promise.all(requests.map(async (request, index) => {
|
|
641
|
+
const sent = await prepareRequest({ ...request, model: run.model }, this.schemaModel(run), this.planOptions());
|
|
642
|
+
const { params } = await this.buildParams(sent, run, false);
|
|
643
|
+
return { custom_id: String(index), params };
|
|
644
|
+
}));
|
|
645
|
+
const body = { requests: entries };
|
|
646
|
+
const created = await this.send('batch', run, requests, body, (signal) => run.client.messages.batches.create(body, { signal }));
|
|
647
|
+
return this.finish('batch', run, requests, body, this.batchJob(created, run));
|
|
648
|
+
};
|
|
649
|
+
/**
|
|
650
|
+
* A batch as it stands now, with its results once it has ended.
|
|
651
|
+
*/
|
|
652
|
+
getBatch = async (job, ctx, config) => {
|
|
653
|
+
const run = this.prepare('get batch', { model: job.model }, ctx, undefined, config, undefined, 'chat');
|
|
654
|
+
const batch = await run.retry((signal) => run.client.messages.batches.retrieve(job.id, {}, { signal }));
|
|
655
|
+
const current = this.batchJob(batch, run);
|
|
656
|
+
if (batch.processing_status !== 'ended') {
|
|
657
|
+
return current;
|
|
658
|
+
}
|
|
659
|
+
const total = current.counts?.total ?? 0;
|
|
660
|
+
const results = Array.from({ length: total }, () => ({ error: 'No result' }));
|
|
661
|
+
const decoder = await run.retry((signal) => run.client.messages.batches.results(job.id, {}, { signal }));
|
|
662
|
+
for await (const line of decoder) {
|
|
663
|
+
const index = Number(line.custom_id);
|
|
664
|
+
const result = line.result;
|
|
665
|
+
results[index] = result.type === 'succeeded'
|
|
666
|
+
? { response: getResponseFromChunks(this.priced(messageChunks(result.message), result.message.usage, run, true), run.model) }
|
|
667
|
+
: { error: result.type === 'errored' ? result.error.error?.message ?? 'Request failed' : `Request ${result.type}` };
|
|
668
|
+
}
|
|
669
|
+
return { ...current, results };
|
|
670
|
+
};
|
|
671
|
+
/**
|
|
672
|
+
* A batch as @aeye reports it.
|
|
673
|
+
*/
|
|
674
|
+
batchJob(batch, run) {
|
|
675
|
+
const counts = batch.request_counts;
|
|
676
|
+
const failed = counts.errored + counts.canceled + counts.expired;
|
|
677
|
+
const status = batch.processing_status === 'ended' ? (counts.succeeded === 0 && failed > 0 ? (counts.expired === failed ? 'expired' : counts.canceled === failed ? 'cancelled' : 'failed') : 'completed')
|
|
678
|
+
: batch.processing_status === 'canceling' ? 'cancelling'
|
|
679
|
+
: 'in_progress';
|
|
680
|
+
return {
|
|
681
|
+
id: batch.id,
|
|
682
|
+
provider: this.name,
|
|
683
|
+
model: run.model.id,
|
|
684
|
+
status,
|
|
685
|
+
counts: { total: counts.processing + counts.succeeded + failed, completed: counts.succeeded, failed },
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
// ============================================================================
|
|
689
|
+
// Image analysis
|
|
690
|
+
// ============================================================================
|
|
691
|
+
/**
|
|
692
|
+
* An image analysis request as a chat request, and the metadata naming
|
|
693
|
+
* the configured analysis model as the fallback.
|
|
694
|
+
*/
|
|
695
|
+
analysisChat(request, config) {
|
|
696
|
+
const chat = {
|
|
697
|
+
model: request.model,
|
|
698
|
+
messages: [{
|
|
699
|
+
role: 'user',
|
|
700
|
+
content: [
|
|
701
|
+
...request.images.map((image) => ({ type: 'image', content: image })),
|
|
702
|
+
{ type: 'text', content: request.prompt },
|
|
703
|
+
],
|
|
704
|
+
}],
|
|
705
|
+
temperature: request.temperature,
|
|
706
|
+
maxTokens: request.maxTokens,
|
|
707
|
+
};
|
|
708
|
+
const model = config?.defaultModels?.imageAnalyze ?? this.config.defaultModels?.imageAnalyze ?? this.defaults.imageAnalyze;
|
|
709
|
+
return [chat, { model }];
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Analyze images with a vision model, as a chat request.
|
|
713
|
+
*/
|
|
714
|
+
analyzeImage = (request, ctx, config) => {
|
|
715
|
+
const [chat, metadata] = this.analysisChat(request, config);
|
|
716
|
+
return this.createExecutor(config)(chat, ctx, metadata);
|
|
717
|
+
};
|
|
718
|
+
/**
|
|
719
|
+
* Analyze images with a vision model, streaming the answer.
|
|
720
|
+
*/
|
|
721
|
+
analyzeImageStream = (request, ctx, config) => {
|
|
722
|
+
const [chat, metadata] = this.analysisChat(request, config);
|
|
723
|
+
return this.createStreamer(config)(chat, ctx, metadata);
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
//# sourceMappingURL=anthropic.js.map
|