|
| 1 | +import { LLMProvider, LLMConfig, LLMInput, LLMOutput } from '@bitcode/llm-generics'; |
| 2 | + |
| 3 | +/** |
| 4 | + * xAI / Grok provider — OpenAI-compatible client against https://api.x.ai/v1. |
| 5 | + * |
| 6 | + * Auth: XAI_API_KEY (preferred) or GROK_API_KEY. |
| 7 | + * Default model: grok-4.5 (overridable via BITCODE_LLM_MODEL). |
| 8 | + * |
| 9 | + * Uses chat.completions (OpenAI-compatible surface on xAI). The Responses API |
| 10 | + * is also available on the same base URL; chat is sufficient for Bitcode's |
| 11 | + * message-shaped LLMInput. |
| 12 | + */ |
| 13 | + |
| 14 | +const XAI_BASE_URL = 'https://api.x.ai/v1'; |
| 15 | +const DEFAULT_XAI_MODEL = 'grok-4.5'; |
| 16 | + |
| 17 | +function resolveXaiApiKey(env: NodeJS.ProcessEnv = process.env): string | undefined { |
| 18 | + const key = env.XAI_API_KEY || env.GROK_API_KEY; |
| 19 | + return typeof key === 'string' && key.trim() ? key.trim() : undefined; |
| 20 | +} |
| 21 | + |
| 22 | +export const xaiProvider: LLMProvider = { |
| 23 | + name: 'xai', |
| 24 | + |
| 25 | + createLLM(config: LLMConfig) { |
| 26 | + return async (input: LLMInput): Promise<LLMOutput> => { |
| 27 | + const finalConfig = { ...config, ...input.config }; |
| 28 | + const model = finalConfig.model || DEFAULT_XAI_MODEL; |
| 29 | + |
| 30 | + try { |
| 31 | + // eslint-disable-next-line @typescript-eslint/no-var-requires |
| 32 | + const OpenAI = require('openai'); |
| 33 | + const apiKey = resolveXaiApiKey(); |
| 34 | + if (!apiKey) { |
| 35 | + throw new Error('XAI_API_KEY is not set'); |
| 36 | + } |
| 37 | + const client = new OpenAI({ |
| 38 | + apiKey, |
| 39 | + baseURL: XAI_BASE_URL, |
| 40 | + }); |
| 41 | + const sys = (input.messages || []) |
| 42 | + .filter((m) => m.role === 'system') |
| 43 | + .map((m) => ({ role: 'system' as const, content: m.content })); |
| 44 | + const nonSys = (input.messages || []) |
| 45 | + .filter((m) => m.role !== 'system') |
| 46 | + .map((m) => ({ |
| 47 | + role: (m.role === 'assistant' ? 'assistant' : 'user') as 'assistant' | 'user', |
| 48 | + content: m.content, |
| 49 | + })); |
| 50 | + const messages = [...sys, ...nonSys]; |
| 51 | + const resp = await client.chat.completions.create({ |
| 52 | + model, |
| 53 | + messages: messages as any, |
| 54 | + temperature: finalConfig.temperature, |
| 55 | + max_tokens: finalConfig.maxTokens, |
| 56 | + top_p: finalConfig.topP, |
| 57 | + frequency_penalty: finalConfig.frequencyPenalty, |
| 58 | + presence_penalty: finalConfig.presencePenalty, |
| 59 | + stop: finalConfig.stopSequences, |
| 60 | + response_format: |
| 61 | + finalConfig.responseFormat === 'json' |
| 62 | + ? { type: 'json_object' } |
| 63 | + : undefined, |
| 64 | + seed: finalConfig.seed, |
| 65 | + }); |
| 66 | + const choice = resp.choices?.[0]; |
| 67 | + const finish = choice?.finish_reason; |
| 68 | + const stopReason = |
| 69 | + finish === 'length' |
| 70 | + ? 'length' |
| 71 | + : finish === 'stop' |
| 72 | + ? 'stop' |
| 73 | + : finish || 'unknown'; |
| 74 | + return { |
| 75 | + content: choice?.message?.content || '', |
| 76 | + usage: { |
| 77 | + inputTokens: resp.usage?.prompt_tokens || 0, |
| 78 | + outputTokens: resp.usage?.completion_tokens || 0, |
| 79 | + totalTokens: resp.usage?.total_tokens || 0, |
| 80 | + }, |
| 81 | + metadata: { |
| 82 | + model: resp.model || model, |
| 83 | + provider: 'xai', |
| 84 | + finishReason: finish, |
| 85 | + stopReason, |
| 86 | + }, |
| 87 | + }; |
| 88 | + } catch (err) { |
| 89 | + const allowMock = |
| 90 | + process?.env?.BITCODE_LLM_ALLOW_MOCK === '1' || |
| 91 | + process?.env?.NODE_ENV === 'test'; |
| 92 | + if (!allowMock) { |
| 93 | + const hint = |
| 94 | + 'Provide XAI_API_KEY and ensure the OpenAI SDK can reach https://api.x.ai/v1, or set BITCODE_LLM_ALLOW_MOCK=1 to permit mock.'; |
| 95 | + const e = err instanceof Error ? err : new Error(String(err)); |
| 96 | + (e as any).provider = 'xai'; |
| 97 | + (e as any).model = model; |
| 98 | + throw new Error(`${e.message || 'xAI provider unavailable'}. ${hint}`); |
| 99 | + } |
| 100 | + const last = input.messages?.[input.messages.length - 1]?.content ?? ''; |
| 101 | + return { |
| 102 | + content: `xAI Grok (mock) response to: ${last}`, |
| 103 | + usage: { inputTokens: 100, outputTokens: 50, totalTokens: 150 }, |
| 104 | + metadata: { model, provider: 'xai', mocked: true }, |
| 105 | + }; |
| 106 | + } |
| 107 | + }; |
| 108 | + }, |
| 109 | +}; |
0 commit comments