// An assistant behind an HTTP endpoint: POST the request, get the protocol // back. The endpoint is where a real model lives (with ASSISTANT_INSTRUCTIONS // as its system prompt); this side does not care which. Nothing streams: the // pane is told when the request went and when the answer came. import type { Assistant, AssistantReply, AssistantRequest } from './types.ts'; import { ASSISTANT_INSTRUCTIONS, parseReply } from '../suggestions/protocol.ts'; import { countOf } from './stream.ts'; export type HttpAssistantOptions = { url: string; name?: string; prompts?: string[]; headers?: Record; fetch?: typeof fetch; }; export class HttpAssistant implements Assistant { readonly name: string; readonly prompts: string[] | undefined; #o: HttpAssistantOptions; constructor(o: HttpAssistantOptions) { this.#o = o; this.name = o.name ?? 'assistant'; this.prompts = o.prompts; } async suggest(req: AssistantRequest): Promise { const f = this.#o.fetch ?? fetch; const { onEvent, signal, ...rest } = req; const body = JSON.stringify({ instructions: ASSISTANT_INSTRUCTIONS, ...rest }); let host = this.#o.url; try { host = new URL(this.#o.url).host; } catch { // shown as given } onEvent?.({ kind: 'status', text: `Asking ${host}: ${countOf(body.length, 'character')}` }); const res = await f(this.#o.url, { method: 'POST', headers: { 'content-type': 'application/json', ...(this.#o.headers ?? {}) }, body, ...(signal ? { signal } : {}), }); if (!res.ok) throw new Error(`assistant: ${res.status} ${(await res.text()).slice(0, 200)}`); const text = await res.text(); onEvent?.({ kind: 'text', delta: text }); const { reply, errors } = parseReply(text); if (errors.length) reply.message += `\n\n(${errors.length} malformed suggestion${errors.length === 1 ? '' : 's'} ignored: ${errors.join('; ')})`; return reply; } }