|
| 1 | +import OpenAI from 'openai' |
| 2 | +import { OpenAIBaseChatCompletionsTextAdapter } from '@tanstack/openai-base' |
| 3 | +import { getLiteLLMApiKeyFromEnv, withLiteLLMDefaults } from '../utils/client' |
| 4 | +import type { LiteLLMClientConfig } from '../utils' |
| 5 | + |
| 6 | +/** |
| 7 | + * Configuration for the LiteLLM text adapter. |
| 8 | + */ |
| 9 | +export interface LiteLLMTextConfig extends LiteLLMClientConfig {} |
| 10 | + |
| 11 | +/** |
| 12 | + * LiteLLM Text (Chat) Adapter |
| 13 | + * |
| 14 | + * Tree-shakeable adapter for LiteLLM AI gateway. LiteLLM exposes an |
| 15 | + * OpenAI-compatible Chat Completions endpoint, so we drive it with the |
| 16 | + * OpenAI SDK via a baseURL override (the same pattern as ai-groq and |
| 17 | + * ai-grok). |
| 18 | + * |
| 19 | + * LiteLLM supports 100+ providers (OpenAI, Anthropic, Google, Azure, |
| 20 | + * AWS Bedrock, Ollama, Groq, Mistral, and more) through a single proxy. |
| 21 | + * The model string determines the provider routing, e.g. |
| 22 | + * "anthropic/claude-sonnet-4-6" or "openai/gpt-4o". |
| 23 | + */ |
| 24 | +export class LiteLLMTextAdapter extends OpenAIBaseChatCompletionsTextAdapter< |
| 25 | + string, |
| 26 | + Record<string, any>, |
| 27 | + readonly [], |
| 28 | + Record<string, never>, |
| 29 | + readonly [] |
| 30 | +> { |
| 31 | + override readonly kind = 'text' as const |
| 32 | + override readonly name = 'litellm' as const |
| 33 | + |
| 34 | + constructor(config: LiteLLMTextConfig, model: string) { |
| 35 | + super(model, 'litellm', new OpenAI(withLiteLLMDefaults(config))) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Creates a LiteLLM text adapter with explicit API key. |
| 41 | + * |
| 42 | + * @example |
| 43 | + * ```typescript |
| 44 | + * const adapter = createLitellmText('anthropic/claude-sonnet-4-6', 'sk-...'); |
| 45 | + * ``` |
| 46 | + */ |
| 47 | +export function createLitellmText( |
| 48 | + model: string, |
| 49 | + apiKey: string, |
| 50 | + config?: Omit<LiteLLMTextConfig, 'apiKey'>, |
| 51 | +): LiteLLMTextAdapter { |
| 52 | + return new LiteLLMTextAdapter({ apiKey, ...config }, model) |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Creates a LiteLLM text adapter with API key from `LITELLM_API_KEY`. |
| 57 | + * |
| 58 | + * @example |
| 59 | + * ```typescript |
| 60 | + * const adapter = litellmText('anthropic/claude-sonnet-4-6'); |
| 61 | + * ``` |
| 62 | + */ |
| 63 | +export function litellmText( |
| 64 | + model: string, |
| 65 | + config?: Omit<LiteLLMTextConfig, 'apiKey'>, |
| 66 | +): LiteLLMTextAdapter { |
| 67 | + const apiKey = getLiteLLMApiKeyFromEnv() |
| 68 | + return createLitellmText(model, apiKey, config) |
| 69 | +} |
0 commit comments