Every AI surface talked to the Unsloth box through env vars, so swapping provider or model meant editing .env and restarting. A connection is now a stored record: base URL, model id, key, structured-output mode, and a reasoning toggle. Three surfaces with their own selector (Compose, dialogue draft, line rewrite), because they want different things from a model: a draft needs strict schema adherence while a line rewrite only needs prose. Blank means the env defaults, so an empty global behaves exactly as before. The API key is write-only: field read access denies everyone, so it never reaches the admin form, REST, GraphQL, or a populated relationship. Blank submission means "unchanged" and `clearApiKey` is the only delete, which avoids the masked-field-round-trips-empty bug. Backups still contain it; a blank connection key falls back to UNSLOTH_API_KEY for that reason. Structured output is no longer assumed to be json_schema. Some OpenAI-compatible providers reject it, so a connection selects json_schema, json_object or prompt, and the weaker modes serialise the schema into the prompt and parse the reply. The Test button runs a plain probe and a structured probe, because a provider that refuses json_schema passes the first and fails every draft. Compose keeps a single fixed dropdown entry: plugin config is built at boot and cannot list database rows, so the handler resolves the selected connection per request instead. Draft provenance records the connection label, so a stored conversation still names the provider that produced it.
146 lines
4.6 KiB
TypeScript
146 lines
4.6 KiB
TypeScript
/**
|
|
* 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<ProbeResult> {
|
|
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<ProbeResult> => {
|
|
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<string, unknown>,
|
|
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.`,
|
|
});
|
|
}
|