// Talks to Claude through the official Anthropic SDK, straight from the browser. // // The SDK class is injected (see main.js), which keeps this module free of // browser globals so the Node unit tests can drive it with a fake fetch. import { MODELS, DEPTHS, DEFAULT_DEPTH, FALLBACK_BETA } from './config.js'; import { costOfMessage, estimateAbortedCost } from './cost.js'; import { summaryRequest } from './persona.js'; /** An error the interface knows how to explain. `kind` says what went wrong. */ export class EngineError extends Error { constructor(kind, message, extra = {}) { super(message); this.name = 'EngineError'; this.kind = kind; Object.assign(this, extra); } } const textOf = (message) => message.content.filter((b) => b.type === 'text').map((b) => b.text).join(''); /** * @param {object} deps * @param deps.Anthropic the SDK's client class * @param [deps.fetch] custom fetch (tests) * @param [deps.baseURL] custom API URL (tests) */ export function createEngine({ Anthropic, fetch: fetchImpl, baseURL } = {}) { let client = null; let clientKey = null; // Set when the API rejected the fallback option once, so we stop sending it. let fallbacksOff = false; function getClient(apiKey) { if (!apiKey) throw new EngineError('no_key', 'No API key has been set.'); if (!client || clientKey !== apiKey) { client = new Anthropic({ apiKey, // The key belongs to the person using this browser and never leaves it // except to go to Anthropic. That is the case this switch exists for. dangerouslyAllowBrowser: true, maxRetries: 2, ...(fetchImpl ? { fetch: fetchImpl } : {}), ...(baseURL ? { baseURL } : {}), }); clientKey = apiKey; } return client; } function mapError(err) { const A = Anthropic; const extra = { cause: err, status: err?.status, requestId: err?.requestID ?? null, apiMessage: err?.apiMessage ?? null }; if (err instanceof EngineError) return err; if (err instanceof A.APIUserAbortError) return new EngineError('aborted', 'Stopped.', extra); if (err instanceof A.AuthenticationError) { return new EngineError('auth', 'Anthropic did not accept the API key.', extra); } if (err instanceof A.PermissionDeniedError) { return new EngineError('permission', err.apiMessage || 'This API key is not allowed to do that.', extra); } if (err instanceof A.NotFoundError) { return new EngineError('model_unavailable', 'That model is not available for this API key.', extra); } if (err instanceof A.RateLimitError) { if (err.errorCode === 'enforced_spend_limit_reached') { return new EngineError('spend_limit', 'The monthly spend limit for this API account has been reached.', extra); } const retryAfter = Number(err.headers?.get?.('retry-after')); return new EngineError('rate_limit', 'Too many requests right now.', { ...extra, retryAfter: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : null, }); } if (err instanceof A.BadRequestError) { return new EngineError('bad_request', err.apiMessage || 'The API rejected the request.', extra); } if (err instanceof A.APIConnectionTimeoutError) return new EngineError('timeout', 'The request timed out.', extra); if (err instanceof A.APIConnectionError) return new EngineError('network', 'Could not reach Anthropic.', extra); if (err instanceof A.APIError) { if (err.status === 402) return new EngineError('billing', err.apiMessage || 'There is a billing problem with this API account.', extra); if (err.status === 413) return new EngineError('too_large', 'That message is too large to send.', extra); if (err.status === 529) return new EngineError('overloaded', 'Anthropic is overloaded right now.', extra); if (err.status >= 500) return new EngineError('server', 'Anthropic had a server problem.', extra); return new EngineError('api', err.apiMessage || `The API returned an error (${err.status}).`, extra); } return new EngineError('unknown', err?.message || 'Something went wrong.', extra); } /** * One streamed request. * @returns {Promise<{text, stopReason, refusal, cost, servedBy, requestId}>} */ async function run({ apiKey, model, depth = DEFAULT_DEPTH, system, messages, maxTokens, onText, onThinking, signal }) { const anthropic = getClient(apiKey); const cfg = DEPTHS[depth] || DEPTHS[DEFAULT_DEPTH]; const params = { model, max_tokens: maxTokens ?? cfg.maxTokens, system, messages, // Caches the conversation so far; each turn then re-reads it at a fraction of the price. cache_control: { type: 'ephemeral' }, thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: cfg.effort }, }; const attempt = async (withFallbacks) => { let streamed = ''; let startUsage = null; // If a safety classifier declines a request on the main model, the API can // retry it on another model inside the same call. Opt in where supported. const stream = withFallbacks ? anthropic.beta.messages.stream({ ...params, betas: [FALLBACK_BETA], fallbacks: 'default' }, { signal }) : anthropic.messages.stream(params, { signal }); stream.on('text', (delta) => { streamed += delta; onText?.(delta, streamed); }); stream.on('thinking', (delta, snapshot) => onThinking?.(delta, snapshot)); stream.on('streamEvent', (event) => { if (event.type === 'message_start') startUsage = event.message?.usage ?? null; }); try { const message = await stream.finalMessage(); return { message, requestId: stream.request_id ?? null }; } catch (err) { err.partialText = streamed; err.startUsage = startUsage; throw err; } }; const useFallbacks = Boolean(MODELS[model]?.fallbacks) && !fallbacksOff; let done; try { done = await attempt(useFallbacks); } catch (err) { if (useFallbacks && err instanceof Anthropic.BadRequestError && !err.partialText) { // Most likely this account cannot use the fallback option. Try once without it. try { done = await attempt(false); fallbacksOff = true; } catch (err2) { throw decorate(mapError(err2), err2, model); } } else { throw decorate(mapError(err), err, model); } } const { message, requestId } = done; return { text: textOf(message), stopReason: message.stop_reason, refusal: message.stop_reason === 'refusal' ? { category: message.stop_details?.category ?? null, explanation: message.stop_details?.explanation ?? null } : null, cost: costOfMessage(message, model), servedBy: message.model, requestId, }; } // Attaches whatever had already streamed (and its rough cost) to an error. function decorate(mapped, original, model) { mapped.partialText = original?.partialText || ''; if (original?.startUsage) { mapped.cost = estimateAbortedCost(original.startUsage, model, mapped.partialText.length); } return mapped; } return { /** A chat turn. See run(). */ chat: run, /** * Asks the model to summarise the messages that are about to leave the context. * It reuses the chat request's exact prefix (same system prompt, same settings), * so the conversation is read from the cache instead of being paid for again. */ async summarize({ apiKey, model, depth, system, messages, previousSummary, signal }) { return run({ apiKey, model, depth, system, messages: [...messages, { role: 'user', content: summaryRequest(previousSummary) }], signal, }); }, /** Checks an API key without spending tokens. Returns true, false, or null if it could not tell. */ async checkKey(apiKey) { try { await getClient(apiKey).models.list({ limit: 1 }); return true; } catch (err) { if (err instanceof Anthropic.AuthenticationError) return false; return null; } }, }; }