Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

client.ts

117 lines3.5 KB

1import Anthropic_SDK from '@anthropic-ai/sdk'
2import { generateId as _generateId } from '@tanstack/ai-utils'
3import type { ClientOptions } from '@anthropic-ai/sdk'
4​
5/**
6 * How the adapter sends the credential.
7 * - `'api-key'`: the `x-api-key` header.
8 * - `'bearer'`: `Authorization: Bearer`, and no `x-api-key`.
9 * - `'oauth'`: the same as `'bearer'`, plus the Claude Code identity that a
10 * Claude OAuth token needs.
11 */
12export type AnthropicAuth = 'api-key' | 'bearer' | 'oauth'
13​
14export interface AnthropicClientConfig extends Omit<
15 ClientOptions,
16 'apiKey' | 'authToken'
17> {
18 apiKey: string
19 /**
20 * How to send `apiKey`. The default is `'oauth'` when the credential
21 * contains `sk-ant-oat`, else `'api-key'`.
22 */
23 auth?: AnthropicAuth
25​
26/** The explicit `auth`, else the kind that the credential shows. */
27export function resolveAnthropicAuth(
28 config: Pick<AnthropicClientConfig, 'apiKey' | 'auth'>,
29): AnthropicAuth {
30 return (
31 config.auth ?? (config.apiKey.includes('sk-ant-oat') ? 'oauth' : 'api-key')
32 )
34​
35type AnyAnthropicMessagesCreate = (
36 params: never,
37 ...args: Array<never>
38) => unknown
39​
40/**
41 * The minimal Anthropic client surface used by the text adapter.
42 *
43 * The callable is intentionally type-erased because alternative Anthropic
44 * clients can depend on a different 0.x release of the Anthropic SDK. Their
45 * request and response declarations may drift even when the runtime Messages
46 * protocol remains compatible.
47 */
48export interface AnthropicMessagesClient {
49 readonly beta: {
50 readonly messages: {
51 readonly create: AnyAnthropicMessagesCreate
52 }
53 }
55​
56/**
57 * Creates an Anthropic SDK client instance. It reads no credential from the
58 * environment.
59 */
60export function createAnthropicClient(
61 config: AnthropicClientConfig,
62): Anthropic_SDK {
63 const { auth: _auth, apiKey, ...options } = config
64 const token = resolveAnthropicAuth(config) !== 'api-key'
65 // Explicit nulls stop the SDK from reading `ANTHROPIC_API_KEY` and
66 // `ANTHROPIC_AUTH_TOKEN` on its own.
67 return new Anthropic_SDK({
68 ...options,
69 apiKey: token ? null : apiKey,
70 authToken: token ? apiKey : null,
71 ...(token && {
72 defaultHeaders: { ...options.defaultHeaders, 'x-api-key': null },
73 }),
74 })
76​
77/**
78 * Reads the credential from the environment (`window.env` or
79 * `process.env`), in this order:
80 * 1. `ANTHROPIC_AUTH_TOKEN`: `'bearer'`, or `'oauth'` for an `sk-ant-oat` token.
81 * 2. `ANTHROPIC_OAUTH_TOKEN`: `'oauth'`.
82 * 3. `ANTHROPIC_API_KEY`: `'api-key'`.
83 * @throws Error if none of them is set
84 */
85export function getAnthropicCredentialFromEnv(): {
86 credential: string
87 auth: AnthropicAuth
88} {
89 const { window: browser } = globalThis as {
90 window?: { env?: Record<string, string | undefined> }
91 }
92 const env =
93 browser?.env ?? (typeof process === 'undefined' ? undefined : process.env)
94 const authToken = env?.ANTHROPIC_AUTH_TOKEN
95 if (authToken) {
96 return {
97 credential: authToken,
98 auth: authToken.includes('sk-ant-oat') ? 'oauth' : 'bearer',
99 }
100 }
101 if (env?.ANTHROPIC_OAUTH_TOKEN) {
102 return { credential: env.ANTHROPIC_OAUTH_TOKEN, auth: 'oauth' }
103 }
104 if (env?.ANTHROPIC_API_KEY) {
105 return { credential: env.ANTHROPIC_API_KEY, auth: 'api-key' }
106 }
107 throw new Error(
108 'ANTHROPIC_AUTH_TOKEN, ANTHROPIC_OAUTH_TOKEN, and ANTHROPIC_API_KEY are not set. Please set one of these environment variables or pass the credential directly.',
109 )
111​
112/**
113 * Generates a unique ID with a prefix
114 */
115export function generateId(prefix: string): string {
116 return _generateId(prefix)