| 1 | // Chat backend — talks to LiteLLM/relay via OpenAI-compatible /v1/chat/completions. |
| 2 | // Per-user override: if the calling user has settings.anthropicApiKey or |
| 3 | // settings.relayKey configured, those are used instead of the system defaults. |
| 4 | const OpenAI = require('openai'); |
| 5 | const settings = require('../routes/settings'); |
| 6 | const users = require('./users'); |
| 7 | |
| 8 | function resolveCreds(userSub) { |
| 9 | const sys = settings.read(); |
| 10 | const userSettings = userSub ? users.getUserSettings(userSub) : {}; |
| 11 | const baseURL = (userSettings.relayUrl || sys.relayUrl || 'http://localhost:3201').replace(/\/$/, '') + '/v1'; |
| 12 | // Priority for the API key: |
| 13 | // 1. user's anthropicApiKey (real Anthropic key — bypass relay) |
| 14 | // 2. user's relayKey (their token for the shared relay) |
| 15 | // 3. system relayKey |
| 16 | let apiKey = userSettings.anthropicApiKey || userSettings.relayKey || sys.relayKey || process.env.LITELLM_MASTER_KEY; |
| 17 | let actualBaseURL = baseURL; |
| 18 | if (userSettings.anthropicApiKey) { |
| 19 | actualBaseURL = (userSettings.anthropicBaseUrl || 'https://api.anthropic.com').replace(/\/$/, '') + '/v1'; |
| 20 | } |
| 21 | const model = userSettings.model || sys.model || 'claude-opus-4-7'; |
| 22 | if (!apiKey) throw new Error('No API key configured. Set one in Settings → Mi cuenta.'); |
| 23 | return { apiKey, baseURL: actualBaseURL, model }; |
| 24 | } |
| 25 | |
| 26 | async function chat({ system, messages, tools, userSub, toolChoice }) { |
| 27 | const { apiKey, baseURL, model } = resolveCreds(userSub); |
| 28 | const client = new OpenAI({ apiKey, baseURL }); |
| 29 | const fullMessages = system |
| 30 | ? [{ role: 'system', content: system }, ...messages] |
| 31 | : messages; |
| 32 | const useTools = tools && tools.length && toolChoice !== 'none'; |
| 33 | return client.chat.completions.create({ |
| 34 | model, |
| 35 | max_tokens: 2048, |
| 36 | messages: fullMessages, |
| 37 | tools: useTools ? tools : undefined, |
| 38 | tool_choice: useTools ? (toolChoice || 'auto') : undefined, |
| 39 | }); |
| 40 | } |
| 41 | |
| 42 | module.exports = { chat }; |