1
0
Fork 0
polaris-task-force/src/lib/ai/generate.ts
Z8MB1E 5ccb25e643 fix(ai): bound the structured path too, and stop the dialog overpromising
The timeout from the previous commit only covered the plain-text fetch, so
the default drafting path was still unbounded: `streamObject` for
json_schema had no abort signal, which is what `generateDialogueDraft` and
the probe's structured half use. A provider that answers the plain probe
and then stalls could still hold the Generate modal and the Test button
open, while the docs claimed every request was bounded. Both
`streamObject` calls (the shared structured path and Compose's fallback)
now carry the same ceiling.

Dialog copy told the author the branch continues into the successor even
after they cleared the return box, which is when it does not. It now says
that step becomes unreachable until wired by hand. When the node cannot
take a return at all the checkbox used to vanish without explanation; the
reason is now stated where the toggle would be.

A choice node marked as the start could receive the return hop, drawing an
edge into the start node that `connectHop` and the drop handler both
refuse. It no longer returns, and its open end stays free like the other
cases.

Also: the two misplaced doc comments now sit above the declarations they
describe, and the whole-conversation caveat moved into the shared preview
component so the global settings tab carries it too.
2026-11-24 15:00:30 -05:00

351 lines
14 KiB
TypeScript

/**
* Shared access to the language model that powers every AI surface in the app:
* the Compose field plugin in `payload.config.ts`, the NPC dialogue drafting
* actions, and the per-line rewrites.
*
* Two ways to reach a model:
*
* - **Environment default.** `UNSLOTH_URL`, `UNSLOTH_MODEL` and `UNSLOTH_API_KEY`
* describe the local Unsloth Studio box. This is what runs when no connection is
* selected, and it is unchanged from before connections existed.
* - **A stored connection.** `src/lib/ai/connections.ts` resolves an admin-created
* record (base URL, model id, key, structured-output mode, reasoning toggle) for
* one surface, and every call below honours it.
*
* Server-only: this reads environment variables and talks to a model over the
* network.
*/
import { createOpenAI } from "@ai-sdk/openai";
import { jsonSchema, streamObject } from "ai";
/**
* The model-id select and its Postgres enum use a stable internal key. Changing
* that key requires a migration, so the served model is configured separately:
* point UNSLOTH_MODEL at the GGUF loaded in Unsloth Studio.
*
* With connections in play this is only the Compose dropdown's internal id and the
* value recorded when no connection is selected. The handler routes per request.
*/
export const MODEL_ID = "unsloth/Ornith-1.0-9B-GGUF";
/** The served model for every AI surface unless a task or connection overrides it. */
export const DEFAULT_MODEL = process.env.UNSLOTH_MODEL || MODEL_ID;
// Dropdown label for the model. UNSLOTH_MODEL_NAME wins; otherwise derive a
// readable name from UNSLOTH_MODEL, falling back to the bundled Ornith label.
const prettifyModel = (id: string) =>
(id.split("/").pop() || id).replace(/[-_]+/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
export const MODEL_LABEL =
process.env.UNSLOTH_MODEL_NAME ||
(process.env.UNSLOTH_MODEL ? prettifyModel(process.env.UNSLOTH_MODEL) : "Ornith 1.0 9B");
// Ornith is a reasoning model: it emits a long `reasoning_content` block before
// the actual answer, and with a small token budget the reasoning consumes the
// whole allowance, leaving `content` empty. Unsloth Studio (llama.cpp) accepts
// `reasoning_effort: "none"` to turn thinking off for the request, so the model
// behaves like a plain instruct model and small budgets still produce output.
//
// Only sent when the active connection allows it: a strict provider rejects
// unrecognised body fields with a 400.
/** Ceiling for one completion, including a slow local model. */
export const REQUEST_TIMEOUT_MS = 600_000;
const REASONING_DISABLED = { reasoning_effort: "none" } as const;
/**
* Ornith-9B is served by the "Apex" Unsloth connection (a separate machine,
* apex-lnx / 192.168.1.7), reached through Unsloth Studio's OpenAI-compatible
* API. Point UNSLOTH_URL at that instance; the default is the LAN address of the
* Apex box.
*/
export const UNSLOTH_BASE_URL = process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1";
/** How a provider is asked for structured output. */
export const STRUCTURED_MODES = ["json_schema", "json_object", "prompt"] as const;
export type StructuredMode = (typeof STRUCTURED_MODES)[number];
export const STRUCTURED_MODE_LABELS: Record<StructuredMode, string> = {
json_schema: "JSON schema (strict, enforced by the provider)",
json_object: "JSON object mode (schema described in the prompt)",
prompt: "Prompt only (parse the reply, no provider JSON mode)",
};
/** One resolved connection. `null` everywhere below means the env default. */
export interface AiConnection {
/** Human label, recorded in provenance instead of a URL. */
label: string;
/** Base URL including the API prefix, e.g. `https://api.deepseek.com/v1`. */
baseUrl: string;
modelId: string;
/** Falls back to `UNSLOTH_API_KEY` when empty. */
apiKey?: string | null;
structuredMode?: StructuredMode;
/** Send `reasoning_effort: "none"`. Off for providers that reject it. */
sendReasoningOff?: boolean;
}
export const unslothProvider = createOpenAI({
apiKey: process.env.UNSLOTH_API_KEY,
baseURL: UNSLOTH_BASE_URL,
});
/** An OpenAI-compatible provider for one connection, or the shared default. */
function providerFor(connection?: AiConnection | null) {
if (!connection) return unslothProvider;
return createOpenAI({
apiKey: connection.apiKey || process.env.UNSLOTH_API_KEY,
baseURL: connection.baseUrl,
});
}
/**
* The provider for a connection, for callers that build their own stream (the
* Compose plugin's non-prose branch does).
*/
export function connectionProvider(connection?: AiConnection | null) {
return providerFor(connection);
}
/** `reasoning_effort: none` when the connection allows it, else nothing. */
export function reasoningOptionsFor(connection?: AiConnection | null): Record<string, string> {
const allowed = connection ? connection.sendReasoningOff !== false : true;
return allowed ? { ...REASONING_DISABLED } : {};
}
/** The chat-completions URL for a connection or the env default. */
function completionsUrl(connection?: AiConnection | null): string {
const base = (connection?.baseUrl ?? UNSLOTH_BASE_URL).replace(/\/+$/, "");
return `${base}/chat/completions`;
}
/**
* The model a structured (graph/schema) task should use when no connection is
* selected. Falls through to the shared default, so setting only UNSLOTH_MODEL
* changes every surface at once. UNSLOTH_MODEL_STRUCTURED exists for the case where
* prose and structured work want different GGUFs; leaving it unset changes nothing.
*/
export function resolveModel(): string {
return process.env.UNSLOTH_MODEL_STRUCTURED || DEFAULT_MODEL;
}
/**
* The model id to record in provenance: the connection's, or the env-resolved one.
*/
export function effectiveModel(connection?: AiConnection | null): string {
return connection?.modelId || resolveModel();
}
// Gemma tends to answer schema-y prompts with fenced JSON blobs. The plain-text
// fallback is meant to produce prose that plainTextToLexicalJson wraps into
// paragraphs, so strip any markdown code fences before using the output.
export const stripCodeFences = (text: string): string =>
text
.replace(/^```[a-zA-Z]*\s*\n?/, "")
.replace(/\n?```\s*$/, "")
.trim();
export type PlainTextResult = { text: string; truncated: boolean };
export interface PlainTextOptions {
maxTokens?: number;
temperature?: number;
/** Route through a stored connection instead of the env defaults. */
connection?: AiConnection | null;
/** Ask the provider for `{"type":"json_object"}` output. */
responseFormat?: "json_object";
}
/**
* Plain-completion call. Every Compose field runs through this: the model is
* asked for prose and the handler wraps the result into the JSON the client
* parses. The token cap and temperature mirror what the old structured path
* used, and `finish_reason === "length"` is reported so the truncation marker
* reaches the client.
*
* `model` is the env-resolved id; a connection's `modelId` wins when one is set,
* so callers never have to decide which applies.
*/
export async function generatePlainText(
prompt: string,
system: string,
model: string,
options: PlainTextOptions = {},
): Promise<PlainTextResult> {
const connection = options.connection ?? null;
const reasoning = connection ? connection.sendReasoningOff !== false : true;
let response: Response;
try {
response = await fetch(completionsUrl(connection), {
method: "POST",
// Bounded because the base URL is now admin-configured: a host that accepts
// the connection and never answers would otherwise hang this call forever,
// and the caller has no other deadline. Ten minutes is generous for a 5k
// token completion on a slow local model, and still finite.
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
headers: {
Authorization: "Bearer " + (connection?.apiKey || process.env.UNSLOTH_API_KEY),
"Content-Type": "application/json",
},
body: JSON.stringify({
model: connection?.modelId || model,
messages: [
{ role: "system", content: system || "You are a helpful assistant." },
{ role: "user", content: prompt },
],
stream: false,
max_tokens: options.maxTokens ?? 5000,
temperature: options.temperature ?? 0.7,
...(reasoning ? REASONING_DISABLED : {}),
...(options.responseFormat ? { response_format: { type: options.responseFormat } } : {}),
}),
});
} catch (error) {
// A dead host or a mistyped URL fails here, before any status exists. The
// underlying cause ("connect ECONNREFUSED 10.0.0.5:8888") is the only part an
// admin can act on, and Node hides it inside `cause`.
const cause = (error as { cause?: unknown }).cause;
throw new Error(
`${connection?.label ?? "Unsloth"} request failed: ${
cause ? String(cause) : error instanceof Error ? error.message : String(error)
}`,
);
}
if (!response.ok) {
// The body carries the reason a provider rejected a request (bad key, unknown
// model, unsupported field) and the status alone would hide it.
const detail = await response.text().catch(() => "");
throw new Error(
`${connection?.label ?? "Unsloth"} API error: ${response.status} ${response.statusText}${
detail ? `: ${detail.slice(0, 300)}` : ""
}`,
);
}
const result = await response.json();
const choice = result.choices?.[0];
return {
text: stripCodeFences(choice?.message?.content ?? ""),
truncated: choice?.finish_reason === "length",
};
}
export interface StructuredGenerationOptions {
/** The user-turn instruction. */
prompt: string;
/** The task framing. Omit for the generic assistant prompt. */
system?: string;
/** A JSON schema (from `zod`-free callers, so a plain JSON schema object). */
schema: Record<string, unknown>;
/** Overrides `resolveModel()` (ignored when a connection supplies a model). */
model?: string;
maxTokens?: number;
temperature?: number;
/** Route through a stored connection, which also determines the mode. */
connection?: AiConnection | null;
}
export interface StructuredResult<T> {
object: T;
/** True when the generator hit the token cap, so `object` may be incomplete. */
truncated: boolean;
}
/** Pull the JSON object out of a reply that may still carry prose or fences. */
function extractJsonObject(text: string): string {
const stripped = stripCodeFences(text);
const start = stripped.indexOf("{");
const end = stripped.lastIndexOf("}");
return start >= 0 && end > start ? stripped.slice(start, end + 1) : stripped;
}
/**
* Structured output for providers without strict schema support: the schema goes
* into the prompt, and the reply is parsed. `json_object` asks the provider for
* JSON mode on top of that; `prompt` asks for nothing and relies on the prompt.
*
* A parse failure throws so the caller's existing retry (which feeds validator
* complaints back) handles it the same way as a schema rejection.
*/
async function generateStructuredViaText<T>(
options: StructuredGenerationOptions,
mode: Exclude<StructuredMode, "json_schema">,
): Promise<StructuredResult<T>> {
const system = [
options.system || "You are a helpful assistant.",
"Return only one JSON object. No commentary, no code fences.",
`The object must match this JSON schema:\n${JSON.stringify(options.schema)}`,
].join("\n\n");
const { text, truncated } = await generatePlainText(
options.prompt,
system,
options.model || resolveModel(),
{
maxTokens: options.maxTokens,
temperature: options.temperature,
connection: options.connection,
responseFormat: mode === "json_object" ? "json_object" : undefined,
},
);
return { object: JSON.parse(extractJsonObject(text)) as T, truncated };
}
/**
* Non-streaming object generation.
*
* Default mode is the path Compose already proved against Unsloth Studio: strict
* JSON schema, structured outputs, reasoning disabled. A connection can select a
* weaker mode for providers that do not implement `json_schema`; guessing wrong
* there would look like a broken model, which is why the mode is explicit on the
* connection record and probed by its Test button.
*
* Throws when the model's output cannot be parsed into the schema. Callers that
* want a retry should catch and re-prompt; see
* `generateDialogueDraft` in `src/lib/npc-dialogue/generation.ts`.
*/
export async function generateStructured<T>(
options: StructuredGenerationOptions,
): Promise<StructuredResult<T>> {
const connection = options.connection ?? null;
const mode = connection?.structuredMode ?? "json_schema";
if (mode !== "json_schema") {
return generateStructuredViaText<T>(options, mode);
}
const reasoning = connection ? connection.sendReasoningOff !== false : true;
const result = streamObject({
maxOutputTokens: options.maxTokens ?? 5000,
// Same ceiling as the plain path. Without it a provider that answers the
// plain probe and then stalls leaves Generate busy forever, because the
// modal waits on `result.object` for as long as the stream dribbles.
abortSignal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
model: providerFor(connection)(connection?.modelId || options.model || resolveModel()),
onError: (error) => {
console.error("AI generateStructured: ", error);
},
prompt: options.prompt,
schema: jsonSchema(options.schema),
system: options.system || "You are a helpful assistant.",
temperature: options.temperature ?? 0.7,
providerOptions: {
openai: {
strictJsonSchema: true,
structuredOutputs: true,
...(reasoning ? REASONING_DISABLED : {}),
},
},
});
// Awaiting `object` drives the stream to completion and resolves once the
// final JSON parses; it rejects when the output never satisfied the schema.
const object = (await result.object) as T;
const finishReason = await result.finishReason;
return { object, truncated: finishReason === "length" };
}