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

client.ts

77 lines2.3 KB

1import { getApiKeyFromEnv } from '@tanstack/ai-utils'
2import { normalizeNeonContent } from './normalize-content'
3import type { ClientOptions } from 'openai'
4​
5/**
6 * The gateway routes on the branch host. Chat Completions serves every chat
7 * model, Responses serves the OpenAI models, and Anthropic serves Claude. The
8 * Anthropic SDK appends `/v1/messages` itself.
9 */
10export const NEON_ROUTES = {
11 chat: '/v1', // also serves embeddings
12 responses: '/openai/v1',
13 anthropic: '/anthropic',
14} as const
15​
16export interface NeonClientConfig extends Omit<
17 ClientOptions,
18 'apiKey' | 'baseURL'
19> {
20 /** The Neon credential (`nt_live_...`), sent as `Authorization: Bearer`. */
21 apiKey: string
22 /**
23 * The bare branch gateway host, with no path, for example
24 * `https://<branch>-api.ai.<cell>.<region>.aws.neon.tech`. The adapter
25 * appends each route's path. Defaults to `NEON_AI_GATEWAY_BASE_URL`.
26 */
27 baseURL?: string
29​
30/**
31 * Gets the Neon credential from `NEON_AI_GATEWAY_TOKEN`.
32 * @throws Error if it is not set
33 */
34export function getNeonTokenFromEnv(): string {
35 try {
36 return getApiKeyFromEnv('NEON_AI_GATEWAY_TOKEN')
37 } catch (cause) {
38 throw new Error(
39 'NEON_AI_GATEWAY_TOKEN is required. Set it in the environment (`neon env pull` writes it) or pass the token to a create* factory.',
40 { cause },
41 )
42 }
44​
45/**
46 * The branch gateway host: `baseURL`, else `NEON_AI_GATEWAY_BASE_URL`, with
47 * any trailing slash removed.
48 * @throws Error if neither is set
49 */
50export function resolveNeonHost(baseURL?: string): string {
51 let host = baseURL
52 if (!host) {
53 try {
54 host = getApiKeyFromEnv('NEON_AI_GATEWAY_BASE_URL')
55 } catch (cause) {
56 throw new Error(
57 'NEON_AI_GATEWAY_BASE_URL is required. Set it in the environment (`neon env pull` writes it) or pass baseURL.',
58 { cause },
59 )
60 }
61 }
62 return host.replace(/\/+$/, '')
64​
65/** OpenAI client options for one route of the gateway. */
66export function withNeonDefaults(
67 config: NeonClientConfig,
68 route: 'chat' | 'responses',
69): ClientOptions {
70 const { baseURL, fetch, ...rest } = config
71 return {
72 ...rest,
73 baseURL: resolveNeonHost(baseURL) + NEON_ROUTES[route],
74 // Only Chat Completions returns the array `content` that needs fixing.
75 fetch: route === 'chat' ? normalizeNeonContent(fetch) : fetch,
76 }