47 lines
1.9 KiB
JavaScript
47 lines
1.9 KiB
JavaScript
// server/provider.mjs -- the endpoint client. One OpenAI-compatible
|
|
// endpoint per deployment (server.json "endpoint"); the model name
|
|
// comes from the run (run.json override) or the config default.
|
|
/** @typedef {import('./shapes.mjs').ViewMessage} ViewMessage */
|
|
/** @typedef {import('./shapes.mjs').ToolCall} ToolCall */
|
|
/** @typedef {import('./shapes.mjs').ChatResponse} ChatResponse */
|
|
|
|
/**
|
|
* @param {{ baseUrl?: string, apiKey?: string, apiKeyEnv?: string }} endpoint
|
|
*/
|
|
export function makeProvider(endpoint) {
|
|
const base = String(endpoint.baseUrl ?? '').replace(/\/+$/, '');
|
|
if (!base) throw new Error('server.json: endpoint.baseUrl is required');
|
|
const key = endpoint.apiKey ?? process.env[endpoint.apiKeyEnv ?? 'RP_API_KEY'] ?? '';
|
|
const headers = { 'content-type': 'application/json', authorization: `Bearer ${key}` };
|
|
|
|
return {
|
|
/**
|
|
* @param {?string} model @param {ViewMessage[]} messages
|
|
* @param {?import('./shapes.mjs').ToolDef[]} [tools] @param {Record<string, unknown>} [params]
|
|
* @returns {Promise<ChatResponse>}
|
|
*/
|
|
async chat(model, messages, tools, params = {}) {
|
|
const res = await fetch(`${base}/chat/completions`, {
|
|
method: 'POST',
|
|
headers,
|
|
body: JSON.stringify({ model, messages, ...(tools ? { tools, tool_choice: 'auto' } : {}), ...params }),
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
|
|
}
|
|
const data = /** @type {ChatResponse} */ (await res.json());
|
|
return data;
|
|
},
|
|
|
|
/** @returns {Promise<string[]>} */
|
|
async models() {
|
|
const res = await fetch(`${base}/models`, { headers });
|
|
if (!res.ok) {
|
|
throw new Error(`API ${res.status}: ${(await res.text()).slice(0, 300)}`);
|
|
}
|
|
const data = /** @type {{ data: { id: string }[] }} */ (await res.json());
|
|
return (data.data ?? []).map((m) => m.id).sort();
|
|
},
|
|
};
|
|
}
|