/** * The connection Test button's server half. * * A connection is three values that have to agree: URL, model id, and a structured * output mode the provider actually supports. Without a probe, a wrong guess only * shows up as every draft failing, which looks like a broken model and sends the * author hunting in the wrong place. So the test proves both halves: * * 1. a plain completion, which validates URL, key and model id; * 2. a tiny structured object, which validates the configured mode. * * The second probe is the one that matters, because `json_schema` is rejected * outright by some OpenAI-compatible providers while `json_object` works. * * Server-only. */ import type { Payload } from "payload"; import { generatePlainText, generateStructured } from "./generate"; import { AI_CONNECTIONS_SLUG } from "./connections"; const PROBE_SCHEMA = { type: "object", properties: { status: { type: "string" }, }, required: ["status"], additionalProperties: false, } as const; export interface ProbeResult { ok: boolean; message: string; } type ConnectionDoc = { label?: string | null; baseUrl?: string | null; modelId?: string | null; apiKey?: string | null; structuredMode?: "json_schema" | "json_object" | "prompt" | null; sendReasoningOff?: boolean | null; }; const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error); /** * Probe one saved connection and record the outcome on it. * * Saves first, tests second, by design: an unsaved draft of a connection cannot be * probed without writing it, and the admin panel's Save is the moment the values * become real. The result is written back so the list view shows which connections * are known-good. */ export async function probeConnection(payload: Payload, id: number): Promise { const doc = (await payload.findByID({ collection: AI_CONNECTIONS_SLUG, id, depth: 0, overrideAccess: true, })) as ConnectionDoc | null; const baseUrl = doc?.baseUrl?.trim(); const modelId = doc?.modelId?.trim(); const finish = async (result: ProbeResult): Promise => { await payload.update({ collection: AI_CONNECTIONS_SLUG, id, data: { lastTestOk: result.ok, lastTestedAt: new Date().toISOString(), lastTestMessage: result.message, }, overrideAccess: true, }); return result; }; if (!baseUrl || !modelId) { return finish({ ok: false, message: "Base URL and model id are both required." }); } const connection = { label: doc?.label?.trim() || modelId, baseUrl, modelId, apiKey: doc?.apiKey?.trim() || null, structuredMode: doc?.structuredMode ?? "json_schema", sendReasoningOff: doc?.sendReasoningOff !== false, }; // 1. Plain completion: proves URL, key, and that the model id exists. try { const plain = await generatePlainText( "Reply with the single word: ready.", "You are a connectivity probe. Answer with one word and nothing else.", modelId, { connection, maxTokens: 32, temperature: 0 }, ); if (!plain.text.trim()) { return finish({ ok: false, message: "The endpoint answered with empty content. A reasoning model with a small token budget does this; keep Send reasoning off enabled, or raise the budget.", }); } } catch (error) { return finish({ ok: false, message: `Plain completion failed: ${errorMessage(error)}` }); } // 2. Structured probe: proves the configured mode. This is where a provider // that rejects json_schema shows its hand. try { const structured = await generateStructured<{ status?: string }>({ prompt: 'Return a JSON object with status set to "ready".', system: "You are a structured output probe. Return only the JSON object.", schema: PROBE_SCHEMA as unknown as Record, connection, maxTokens: 128, temperature: 0, }); if (!structured.object || typeof structured.object.status !== "string") { return finish({ ok: false, message: `Plain completion works, but the structured reply did not match the schema (mode: ${connection.structuredMode}). Try JSON object mode, or prompt only.`, }); } } catch (error) { return finish({ ok: false, message: `Plain completion works, but structured output failed in "${connection.structuredMode}" mode: ${errorMessage(error)}. ` + "Switch the mode on this connection and test again.", }); } return finish({ ok: true, message: `Both probes passed (${connection.structuredMode} mode). This connection can draft dialogue.`, }); }