Інтеграція LLM API в Backend
Інтеграція API мовних моделей (OpenAI, Anthropic, Google) у backend вебсайту. Охоплює аутентифікацію, обмеження швидкості, обробку помилок, оптимізацію вартості.
Паттерн інтеграції API
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
timeout: 30000,
maxRetries: 2,
});
async function callLLM(messages, options = {}) {
const {
model = 'gpt-4o-mini',
temperature = 0.7,
max_tokens = 500,
} = options;
try {
const response = await openai.chat.completions.create({
model,
messages,
temperature,
max_tokens,
});
return {
success: true,
content: response.choices[0].message.content,
usage: response.usage,
};
} catch (error) {
if (error.status === 429) {
// Rate limited - retry after delay
await sleep(60000);
return callLLM(messages, options);
}
throw error;
}
}
Оптимізація вартості
// Кешуй дорогі виклики
const redis = require('redis').createClient();
async function cachedLLMCall(prompt, ttl = 86400) {
const cacheKey = `llm:${crypto.createHash('sha256').update(prompt).digest('hex')}`;
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
const result = await callLLM([{ role: 'user', content: prompt }]);
await redis.setex(cacheKey, ttl, JSON.stringify(result));
return result;
}
// Групуй запити
async function batchLLMCalls(prompts) {
const results = await Promise.all(
prompts.map(p => callLLM([{ role: 'user', content: p }]))
);
return results;
}
Обмеження швидкості
import Bottleneck from 'bottleneck';
const limiter = new Bottleneck({
minTime: 100, // мін 100ms між запитами
maxConcurrent: 5, // макс 5 паралельних
});
export async function limitedLLMCall(prompt, options) {
return limiter.schedule(() => callLLM([{ role: 'user', content: prompt }], options));
}
Обробка помилок
class LLMError extends Error {
constructor(message, originalError) {
super(message);
this.originalError = originalError;
this.isRetryable = [408, 429, 500, 502, 503].includes(originalError?.status);
}
}
async function robustLLMCall(prompt, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await callLLM([{ role: 'user', content: prompt }]);
} catch (error) {
const llmError = new LLMError(`Виклик LLM не вдався: ${error.message}`, error);
if (!llmError.isRetryable || attempt === maxRetries - 1) {
throw llmError;
}
const delay = Math.pow(2, attempt) * 1000; // exponential backoff
await sleep(delay);
}
}
}
Терміни
- Базова інтеграція API — 1–2 дні
- Обмеження швидкості + кешування — 1 день
- Обробка помилок + retry — 1 день
- Моніторинг вартості — 1 день
- Тестування навантаження & оптимізація — 2–3 дні







