Files
tiny-worlds/server/provider.mjs
T

60 lines
2.6 KiB
JavaScript
Raw Normal View History

// 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();
},
2026-11-16 21:32:02 +00:00
/** The listing with the API metadata the scrape carries into the
* preliminary registry (token ceilings when the provider states
* them).
* @returns {Promise<{ id: string, input: ?number, output: ?number }[]>} */
async modelsMeta() {
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, max_input_tokens?: ?number, max_output_tokens?: ?number }[] }} */ (await res.json());
return (data.data ?? []).map((m) => ({ id: m.id, input: m.max_input_tokens ?? null, output: m.max_output_tokens ?? null }));
},
};
}