import axios from 'axios';
const API_BASE = 'https://apick.app/rest/llm/chat';
export class Chatbot {
constructor({
apiKey,
model = 'meta-llama/Meta-Llama-3.1-8B-Instruct',
mode = 'chatbot', // 8종 프리셋 중 하나
windowPairs = 10,
maxTokens = 512,
speed = 'fast',
} = {}) {
this.cfg = { apiKey, model, mode, windowPairs, maxTokens, speed };
this.history = [];
this.totalCost = 0;
}
async _post(body, retryLeft = 1) {
try {
const { data: result } = await axios.post(API_BASE, body, {
headers: { 'CL_AUTH_KEY': this.cfg.apiKey },
timeout: 60000,
});
return result;
} catch (e) {
const status = e.response?.status;
if (status === 400) throw new Error('요청 오류 (입력 확인 필요)');
if (status === 402) throw new Error('포인트 부족 — 충전 필요');
if (retryLeft > 0 && (!status || status >= 500)) {
await new Promise(r => setTimeout(r, 500 + Math.random() * 500));
return this._post(body, retryLeft - 1);
}
throw e;
}
}
async ask(userText) {
this.history.push({ role: 'user', content: userText });
const result = await this._post({
model: this.cfg.model,
mode: this.cfg.mode,
messages: this.history,
compact: { strategy: 'sliding_window', window_pairs: this.cfg.windowPairs },
max_tokens: this.cfg.maxTokens,
speed: this.cfg.speed,
});
this.history = result.data.compacted_messages;
this.totalCost += result.api.cost || 0;
return result.data.message.content;
}
reset() { this.history = []; }
getCost() { return this.totalCost; }
}
// 사용 예시
const bot = new Chatbot({ apiKey: process.env.API_KEY, mode: 'chatbot' });
console.log(await bot.ask('내 이름은 지훈이야.'));
console.log(await bot.ask('내 이름 기억해?'));
console.log('누적 비용:', bot.getCost(), '포인트');