import { completeSimple } from "@earendil-works/pi-ai/compat"; /** * One completion from the session's current model, outside the conversation: * nothing is added to the session. Returns the reply's text; throws when the * call fails, and when no model or way to call it is at hand. */ export async function completeOnce(ctx: any, context: { systemPrompt?: string; messages: any[] }, options: { maxTokens: number; signal: AbortSignal }): Promise { const registry = ctx?.modelRegistry; const model = ctx?.model; if (!model) throw new Error("no model selected"); // The host's own one-shot completion resolves auth and headers itself; the // provider call below is the path for hosts whose registry predates it. let result: any; if (typeof registry?.complete === "function") { result = await registry.complete(model, context, options); } else if (typeof registry?.getApiKeyAndHeaders === "function" && typeof completeSimple === "function") { const auth = await registry.getApiKeyAndHeaders(model); if (!auth?.ok) throw new Error(`no credentials for ${model.provider}/${model.id}`); result = await completeSimple(model, context as any, { ...options, apiKey: auth.apiKey, headers: auth.headers }); } else { throw new Error("this pi cannot make a one-off model call"); } if (result?.stopReason === "error" || result?.stopReason === "aborted") throw new Error(result.errorMessage || `the call ended: ${result.stopReason}`); return responseText(result); } export function responseText(message: any): string { const parts = Array.isArray(message?.content) ? message.content : []; return parts .filter((part: any) => part?.type === "text" && typeof part.text === "string") .map((part: any) => part.text) .join("") .trim(); }