File size: 1,953 Bytes
3edcc9b
4381a41
c3e18bc
 
68d7f83
c3e18bc
 
3ee7765
 
 
c3e18bc
 
 
 
 
 
 
 
 
 
 
4381a41
3edcc9b
4381a41
 
 
 
 
 
a281e3b
3edcc9b
 
 
 
 
 
56dbcd5
3edcc9b
 
 
56dbcd5
 
 
 
 
 
 
 
 
4381a41
c3e18bc
 
 
4381a41
 
 
 
 
 
 
 
 
 
3edcc9b
4381a41
 
 
 
 
 
 
 
 
 
3edcc9b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const API_URL = process.env.INFERENCE_API_URL;
const API_KEY = process.env.INFERENCE_API_KEY;
const FETCH_TIMEOUT = 30000;

let currentModel = process.env.INFERENCE_MODEL || 'llama-3.1-8b-instant';

const AVAILABLE_MODELS = [
  'lightning',
  'gpt-4o-mini',
  'claude-sonnet-4-20250514',
  'llama-3.3-70b-versatile',
  'llama-3.1-8b-instant',
  'gemma2-9b-it',
];

function getModel() { return currentModel; }
function setModel(name) {
  if (name && typeof name === 'string') {
    currentModel = name.trim();
  }
}

if (!API_URL) {
  console.warn('[inferenceClient] INFERENCE_API_URL is not set - chat requests will fail.');
}
if (!API_KEY) {
  console.warn('[inferenceClient] INFERENCE_API_KEY is not set - chat requests will fail.');
}

async function chat(messages) {
  const body = {
    model: currentModel,
    messages,
  };

  let res;
  try {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT);
    res = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${API_KEY}`,
      },
      body: JSON.stringify(body),
      signal: controller.signal,
    });
    clearTimeout(timeout);
  } catch (e) {
    if (e.name === 'AbortError') {
      throw new Error(`Inference request timed out after ${FETCH_TIMEOUT / 1000}s`);
    }
    throw new Error(`Could not reach the Inference Port API: ${e.message}`);
  }

  if (!res.ok) {
    let detail = '';
    try {
      detail = await res.text();
    } catch {
      /* ignore */
    }
    throw new Error(`Inference Port API returned ${res.status}: ${detail.slice(0, 500)}`);
  }

  const data = await res.json();
  const choice = data.choices && data.choices[0];
  if (!choice) {
    throw new Error('Inference Port API returned no choices.');
  }
  return choice.message;
}

module.exports = { chat, getModel, setModel, AVAILABLE_MODELS, API_URL };