File size: 8,289 Bytes
d160eca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// 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;
      }
    },
  };
}