feat(ai): add admin-configurable model connections
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.
This commit is contained in:
parent
de27a53044
commit
7abca7185c
21 changed files with 48708 additions and 53 deletions
107
docs/ai-settings.md
Normal file
107
docs/ai-settings.md
Normal file
|
|
@ -0,0 +1,107 @@
|
||||||
|
# AI model connections
|
||||||
|
|
||||||
|
Every AI surface in the app talks to an OpenAI-compatible chat-completions
|
||||||
|
endpoint. By default that is the Unsloth Studio box on the LAN, configured by
|
||||||
|
environment variables. A stored connection lets a different provider or model be
|
||||||
|
chosen from the admin panel without editing `.env` or redeploying.
|
||||||
|
|
||||||
|
## The three surfaces
|
||||||
|
|
||||||
|
Each surface has its own selector, because they want different things from a
|
||||||
|
model:
|
||||||
|
|
||||||
|
| Surface | What it asks for | Bean counter note |
|
||||||
|
|---|---|---|
|
||||||
|
| AI Compose | prose, wrapped into the field's JSON shape | runs on every allowlisted field, so the cheapest capable model wins |
|
||||||
|
| Dialogue draft | a whole conversation as one strict JSON object | needs the strongest schema adherence |
|
||||||
|
| Dialogue rewrite | one rewritten line | prose only, a small model is fine |
|
||||||
|
|
||||||
|
**Settings → AI Settings** (`ai-settings`, a global) holds the three selectors.
|
||||||
|
Blank means the environment defaults, so an empty global changes nothing.
|
||||||
|
|
||||||
|
## Creating a connection
|
||||||
|
|
||||||
|
**Server → AI Connections** (`ai-connections`).
|
||||||
|
|
||||||
|
| Field | Notes |
|
||||||
|
|---|---|
|
||||||
|
| Label | shown in the selectors and recorded in draft provenance; say which provider and model |
|
||||||
|
| Base URL | includes the API prefix, e.g. `http://192.168.1.7:8888/v1` or `https://api.deepseek.com/v1`. `/chat/completions` is appended |
|
||||||
|
| Model id | exactly what the provider expects, e.g. `deepseek-v4.1-flash` |
|
||||||
|
| API key | write-only (see below). Blank leaves the stored key alone |
|
||||||
|
| Structured mode | `json_schema`, `json_object`, or `prompt` |
|
||||||
|
| Send reasoning off | sends `reasoning_effort: "none"`, off for strict providers |
|
||||||
|
|
||||||
|
### The key is write-only
|
||||||
|
|
||||||
|
The `apiKey` field's read access denies everyone, so it never appears in the admin
|
||||||
|
form, REST, GraphQL, or a populated relationship. The server reads it with
|
||||||
|
`overrideAccess: true` when it makes a request.
|
||||||
|
|
||||||
|
That design makes a blank submission ambiguous, so the rule is: **blank means
|
||||||
|
unchanged**. Replacing the key means typing a new one. Deleting it means ticking
|
||||||
|
**Clear API key** and saving. `hasApiKey` shows whether one is stored without
|
||||||
|
revealing it. The `clearApiKey` checkbox resets itself after each save so a later
|
||||||
|
edit cannot silently delete a key that was just set.
|
||||||
|
|
||||||
|
The key still lives in the database, so database backups contain it. If that is
|
||||||
|
unacceptable for a provider, keep using the `UNSLOTH_API_KEY` env var and leave the
|
||||||
|
connection's key blank: a blank connection key falls back to the env var.
|
||||||
|
|
||||||
|
## Structured output modes
|
||||||
|
|
||||||
|
`json_schema` is the default and the best option: the provider enforces the schema,
|
||||||
|
so a malformed draft is rejected before it reaches the app.
|
||||||
|
|
||||||
|
Some OpenAI-compatible providers reject a `json_schema` request. For those:
|
||||||
|
|
||||||
|
- `json_object` asks for JSON mode and puts the schema in the system prompt.
|
||||||
|
- `prompt` asks for nothing and relies on the prompt, then parses the reply.
|
||||||
|
|
||||||
|
Both weaker modes serialise the schema into the prompt and parse the reply, so a
|
||||||
|
model that does not follow instructions still fails, but through the app's existing
|
||||||
|
validate-and-retry loop rather than a provider 400.
|
||||||
|
|
||||||
|
## Test the connection before trusting it
|
||||||
|
|
||||||
|
The **Test connection** button on the edit view runs two probes against the saved
|
||||||
|
values:
|
||||||
|
|
||||||
|
1. a plain completion, which validates URL, key and model id;
|
||||||
|
2. a tiny structured object, which validates the configured mode.
|
||||||
|
|
||||||
|
Both must pass. The second one is the important one: a provider that rejects
|
||||||
|
`json_schema` looks perfectly healthy on a plain completion and fails every draft.
|
||||||
|
The result is stored on the record (`lastTestOk`, `lastTestedAt`,
|
||||||
|
`lastTestMessage`) and cleared whenever the base URL, model id or mode changes,
|
||||||
|
because a passing test only describes the configuration that was tested.
|
||||||
|
|
||||||
|
## What changes when a connection is active
|
||||||
|
|
||||||
|
- Requests go to `baseUrl` with `modelId` and the stored key instead of the
|
||||||
|
`UNSLOTH_*` values.
|
||||||
|
- `reasoning_effort: "none"` is sent only when the connection allows it.
|
||||||
|
- A draft's provenance records the connection label and model id, so a stored
|
||||||
|
conversation still says which provider produced it.
|
||||||
|
- Compose's model dropdown has a single fixed entry ("Active AI connection"). The
|
||||||
|
plugin's config is built once at boot and cannot list database rows, so the label
|
||||||
|
names the routing rule; the handler resolves the actual connection per request.
|
||||||
|
|
||||||
|
## Failure messages worth recognising
|
||||||
|
|
||||||
|
- `… API error: 401 … Invalid API key`: the key is wrong or expired. Note that the
|
||||||
|
Unsloth box rejects an unknown key with this, so a 401 against the LAN host usually
|
||||||
|
means `UNSLOTH_API_KEY` is stale, not that a connection is misconfigured.
|
||||||
|
- `… API error: 400 … response_format`: the provider rejects the structured mode.
|
||||||
|
Switch to `json_object` or `prompt`, or turn off the reasoning toggle if the
|
||||||
|
error names `reasoning_effort`.
|
||||||
|
- Drafts fail twice with `before blaming the model`: the prompt voice is suspect,
|
||||||
|
not the provider. The message names which voice was in use.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
- `tests/int/ai-connections.int.spec.ts`: key write-only contract, blank-means-keep,
|
||||||
|
clear, per-surface resolution, half-filled fallback, test-result invalidation.
|
||||||
|
- `tests/int/ai-generate-modes.int.spec.ts`: request shape against a local stub
|
||||||
|
server (URL, model, key header, reasoning toggle), all three structured modes, and
|
||||||
|
provider-error surfacing.
|
||||||
|
|
@ -145,9 +145,12 @@ Everything resolves through `src/lib/ai/generate.ts`:
|
||||||
structured work only, for the case where prose and graph generation want
|
structured work only, for the case where prose and graph generation want
|
||||||
different GGUFs.
|
different GGUFs.
|
||||||
|
|
||||||
An admin-configurable connection selector records providers in the database, so a
|
A connection can be selected per surface from **Settings → AI Settings**, which is
|
||||||
remote model can be chosen without an env change. When a connection is active its
|
what lets a remote provider (or a different model on the same box) be used without
|
||||||
label and model id are recorded in provenance instead of the env-derived model.
|
an env change. Drafting and line rewrite have separate selectors. When a connection
|
||||||
|
is active its label and model id are recorded in provenance instead of the
|
||||||
|
env-derived model. Managing connections, the write-only key, structured modes and
|
||||||
|
the test probe are documented in `docs/ai-settings.md`.
|
||||||
|
|
||||||
`reasoning_effort: "none"` is sent on every request. Ornith is a reasoning model
|
`reasoning_effort: "none"` is sent on every request. Ornith is a reasoning model
|
||||||
and with a small token budget its reasoning block consumes the whole allowance,
|
and with a small token budget its reasoning block consumes the whole allowance,
|
||||||
|
|
@ -169,6 +172,9 @@ dash normalisation.
|
||||||
global through real Payload: dash normalisation on save, revision moving only on a
|
global through real Payload: dash normalisation on save, revision moving only on a
|
||||||
real change, version history, and the `loadDialogueSettings` read path.
|
real change, version history, and the `loadDialogueSettings` read path.
|
||||||
|
|
||||||
|
The connection side is covered by `tests/int/ai-connections.int.spec.ts` and
|
||||||
|
`tests/int/ai-generate-modes.int.spec.ts` (see `docs/ai-settings.md`).
|
||||||
|
|
||||||
## Changing the prompts safely
|
## Changing the prompts safely
|
||||||
|
|
||||||
1. Edit `generationPrompt.ts`, bump `PROMPT_VERSION`.
|
1. Edit `generationPrompt.ts`, bump `PROMPT_VERSION`.
|
||||||
|
|
|
||||||
|
|
@ -424,6 +424,8 @@ export interface GeneratedDialogueDraft {
|
||||||
/** Which voice shaped the prompt, for the dialog's provenance line. */
|
/** Which voice shaped the prompt, for the dialog's provenance line. */
|
||||||
promptSource: "builtin" | "global" | "dialogue";
|
promptSource: "builtin" | "global" | "dialogue";
|
||||||
promptRevision: number | null;
|
promptRevision: number | null;
|
||||||
|
/** The admin connection that served the model, or null for the env defaults. */
|
||||||
|
connectionLabel: string | null;
|
||||||
/** True when the model hit its token cap, so the tail of the draft may be missing. */
|
/** True when the model hit its token cap, so the tail of the draft may be missing. */
|
||||||
truncated: boolean;
|
truncated: boolean;
|
||||||
}
|
}
|
||||||
|
|
@ -566,6 +568,7 @@ export async function generateNpcDialogueDraft(
|
||||||
promptVersion: outcome.promptVersion,
|
promptVersion: outcome.promptVersion,
|
||||||
promptSource: outcome.promptSource,
|
promptSource: outcome.promptSource,
|
||||||
promptRevision: outcome.promptRevision,
|
promptRevision: outcome.promptRevision,
|
||||||
|
connectionLabel: outcome.connectionLabel,
|
||||||
truncated: outcome.truncated,
|
truncated: outcome.truncated,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,7 @@ import { default as default_2d468cc5cf0b647ffca3201592c20825 } from '@/component
|
||||||
import { default as default_8e873aa39584420378774e6c9c4ac54b } from '@/components/admin/VehicleLibraryPicker'
|
import { default as default_8e873aa39584420378774e6c9c4ac54b } from '@/components/admin/VehicleLibraryPicker'
|
||||||
import { AudioPreviewField as AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2 } from '@/components/admin/voiceover/AudioPreviewField'
|
import { AudioPreviewField as AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2 } from '@/components/admin/voiceover/AudioPreviewField'
|
||||||
import { default as default_7fa52484aec46e988e9cfb5e86c0c759 } from '@/components/admin/narrative-flow/NarrativeFlowEditor'
|
import { default as default_7fa52484aec46e988e9cfb5e86c0c759 } from '@/components/admin/narrative-flow/NarrativeFlowEditor'
|
||||||
|
import { default as default_b6b06afff77de9004b742c9e09ce66ea } from '@/components/admin/ai/TestConnectionButton'
|
||||||
import { default as default_b7f86fb8e028bca592f57e6d387a0380 } from '@/components/admin/minigames/PeriodCloseControl'
|
import { default as default_b7f86fb8e028bca592f57e6d387a0380 } from '@/components/admin/minigames/PeriodCloseControl'
|
||||||
import { SelectField as SelectField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
|
import { SelectField as SelectField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
|
||||||
import { PromptEditorField as PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
|
import { PromptEditorField as PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
|
||||||
|
|
@ -99,6 +100,7 @@ export const importMap = {
|
||||||
"@/components/admin/VehicleLibraryPicker#default": default_8e873aa39584420378774e6c9c4ac54b,
|
"@/components/admin/VehicleLibraryPicker#default": default_8e873aa39584420378774e6c9c4ac54b,
|
||||||
"@/components/admin/voiceover/AudioPreviewField#AudioPreviewField": AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2,
|
"@/components/admin/voiceover/AudioPreviewField#AudioPreviewField": AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2,
|
||||||
"@/components/admin/narrative-flow/NarrativeFlowEditor#default": default_7fa52484aec46e988e9cfb5e86c0c759,
|
"@/components/admin/narrative-flow/NarrativeFlowEditor#default": default_7fa52484aec46e988e9cfb5e86c0c759,
|
||||||
|
"@/components/admin/ai/TestConnectionButton#default": default_b6b06afff77de9004b742c9e09ce66ea,
|
||||||
"@/components/admin/minigames/PeriodCloseControl#default": default_b7f86fb8e028bca592f57e6d387a0380,
|
"@/components/admin/minigames/PeriodCloseControl#default": default_b7f86fb8e028bca592f57e6d387a0380,
|
||||||
"@ai-stack/payloadcms/client#SelectField": SelectField_4490b89d4413c1ffaecdacfe72efaf73,
|
"@ai-stack/payloadcms/client#SelectField": SelectField_4490b89d4413c1ffaecdacfe72efaf73,
|
||||||
"@ai-stack/payloadcms/client#PromptEditorField": PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73,
|
"@ai-stack/payloadcms/client#PromptEditorField": PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73,
|
||||||
|
|
|
||||||
|
|
@ -167,6 +167,15 @@ export const NpcDialogues: CollectionConfig = {
|
||||||
readOnly: true,
|
readOnly: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "connectionLabel",
|
||||||
|
type: "text",
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"The admin connection that served the model. Empty means the Unsloth environment defaults.",
|
||||||
|
readOnly: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "promptRevision",
|
name: "promptRevision",
|
||||||
type: "number",
|
type: "number",
|
||||||
|
|
|
||||||
228
src/collections/server/AiConnections.ts
Normal file
228
src/collections/server/AiConnections.ts
Normal file
|
|
@ -0,0 +1,228 @@
|
||||||
|
import type { CollectionConfig } from "payload";
|
||||||
|
|
||||||
|
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||||
|
import { STRUCTURED_MODES } from "@/lib/ai/generate";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One OpenAI-compatible model endpoint.
|
||||||
|
*
|
||||||
|
* Records exist so a provider can be swapped from the admin panel instead of an
|
||||||
|
* env change and a restart. The API key is **write-only**: the field's read access
|
||||||
|
* denies everyone, so it never reaches the admin form value, the REST API, or
|
||||||
|
* GraphQL. Saving a blank key keeps the stored one, and `clearApiKey` is the only
|
||||||
|
* way to remove it, which avoids the classic "masked field round-trips empty and
|
||||||
|
* wipes the secret" bug.
|
||||||
|
*
|
||||||
|
* Gated to `system:admin-access` deliberately. Changing a connection repoints every
|
||||||
|
* AI surface, including Compose, which sends field content from collections the
|
||||||
|
* editor of a connection may not be allowed to read. This is not a dialogue-author
|
||||||
|
* permission.
|
||||||
|
*/
|
||||||
|
export const AiConnections: CollectionConfig = {
|
||||||
|
slug: "ai-connections",
|
||||||
|
labels: { singular: "AI Connection", plural: "AI Connections" },
|
||||||
|
admin: {
|
||||||
|
group: "Server",
|
||||||
|
useAsTitle: "label",
|
||||||
|
defaultColumns: ["label", "modelId", "structuredMode", "hasApiKey", "lastTestOk"],
|
||||||
|
description:
|
||||||
|
"A model endpoint the AI surfaces can use. Leave the key blank to keep the saved one; use Clear API key to remove it.",
|
||||||
|
},
|
||||||
|
access: {
|
||||||
|
read: requirePermission("system:admin-access"),
|
||||||
|
create: requirePermission("system:admin-access"),
|
||||||
|
update: requirePermission("system:admin-access"),
|
||||||
|
delete: requirePermission("system:admin-access"),
|
||||||
|
},
|
||||||
|
endpoints: [
|
||||||
|
{
|
||||||
|
// POST /api/ai-connections/:id/test. The admin Test button calls this.
|
||||||
|
path: "/:id/test",
|
||||||
|
method: "post",
|
||||||
|
handler: async (req) => {
|
||||||
|
const { hasPermission } = await import("@/utils/access-control/hasPermission");
|
||||||
|
if (!(await hasPermission(req.payload, req.user, "system:admin-access"))) {
|
||||||
|
return Response.json(
|
||||||
|
{ ok: false, message: "You do not have permission to test connections." },
|
||||||
|
{ status: 403 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = req.routeParams?.id;
|
||||||
|
const id = typeof raw === "string" ? Number(raw) : Number(raw);
|
||||||
|
if (!Number.isInteger(id) || id <= 0) {
|
||||||
|
return Response.json({ ok: false, message: "Unknown connection." }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { probeConnection } = await import("@/lib/ai/probe");
|
||||||
|
const result = await probeConnection(req.payload, id);
|
||||||
|
return Response.json(result, { status: result.ok ? 200 : 200 });
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
hooks: {
|
||||||
|
beforeChange: [
|
||||||
|
({ data, originalDoc }) => {
|
||||||
|
const submitted =
|
||||||
|
typeof data?.apiKey === "string" ? data.apiKey.trim() : "";
|
||||||
|
|
||||||
|
let apiKey: string | null;
|
||||||
|
if (data?.clearApiKey) {
|
||||||
|
apiKey = null;
|
||||||
|
} else if (submitted) {
|
||||||
|
// A new value replaces the stored one.
|
||||||
|
apiKey = submitted;
|
||||||
|
} else {
|
||||||
|
// Blank means "unchanged": field-level read access means the form can
|
||||||
|
// never show the current value, so a blank submission is not a delete.
|
||||||
|
apiKey = (originalDoc?.apiKey as string | null | undefined) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
apiKey,
|
||||||
|
hasApiKey: Boolean(apiKey),
|
||||||
|
// The checkbox is an action, not state: reset it so the next save does
|
||||||
|
// not silently clear the key that was just set.
|
||||||
|
clearApiKey: false,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
],
|
||||||
|
afterChange: [
|
||||||
|
({ doc, operation, previousDoc }) => {
|
||||||
|
// Renaming or repointing a connection must not leave a passing test result
|
||||||
|
// attached to a configuration nobody tested.
|
||||||
|
if (operation !== "update") return;
|
||||||
|
const changed = (field: "baseUrl" | "modelId" | "structuredMode") =>
|
||||||
|
(previousDoc?.[field] ?? null) !== (doc?.[field] ?? null);
|
||||||
|
if (changed("baseUrl") || changed("modelId") || changed("structuredMode")) {
|
||||||
|
return { ...doc, lastTestOk: false, lastTestMessage: "Configuration changed; run the test again." };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: "label",
|
||||||
|
type: "text",
|
||||||
|
required: true,
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"Shown in the surface selectors and recorded in draft provenance, so make it say which provider and model this is.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "baseUrl",
|
||||||
|
type: "text",
|
||||||
|
required: true,
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"OpenAI-compatible base URL including the API prefix, e.g. http://192.168.1.7:8888/v1 or https://api.deepseek.com/v1. The /chat/completions path is appended.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "modelId",
|
||||||
|
type: "text",
|
||||||
|
required: true,
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"The model id that provider expects, e.g. deepseek-v4.1-flash or unsloth/Tiel-Coder-35B-GGUF.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "apiKey",
|
||||||
|
type: "text",
|
||||||
|
access: {
|
||||||
|
// Never leaves the server. The resolver reads it with overrideAccess.
|
||||||
|
read: () => false,
|
||||||
|
},
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"Stored encrypted at rest by the database, server-only. Leave blank to keep the current key.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "hasApiKey",
|
||||||
|
type: "checkbox",
|
||||||
|
admin: {
|
||||||
|
readOnly: true,
|
||||||
|
description: "Whether a key is stored. The key itself is never shown.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "clearApiKey",
|
||||||
|
type: "checkbox",
|
||||||
|
admin: {
|
||||||
|
description: "Tick and save to delete the stored key. Cannot be undone.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "structuredMode",
|
||||||
|
type: "select",
|
||||||
|
required: true,
|
||||||
|
defaultValue: "json_schema",
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
label: "JSON schema (strict)",
|
||||||
|
value: "json_schema",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "JSON object mode",
|
||||||
|
value: "json_object",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Prompt only",
|
||||||
|
value: "prompt",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"How to ask this provider for structured output. Strict schema is best and works on Unsloth Studio and OpenAI-style APIs. Use JSON object mode, or prompt only, for providers that reject a json_schema request. The connection test tells you which one works.",
|
||||||
|
},
|
||||||
|
validate: (value: unknown) =>
|
||||||
|
typeof value === "string" && (STRUCTURED_MODES as readonly string[]).includes(value)
|
||||||
|
? true
|
||||||
|
: "Pick a structured output mode.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sendReasoningOff",
|
||||||
|
type: "checkbox",
|
||||||
|
defaultValue: true,
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"Send reasoning_effort: none so a reasoning model answers immediately. Turn off for a provider that rejects unknown request fields.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "testConnection",
|
||||||
|
type: "ui",
|
||||||
|
admin: {
|
||||||
|
components: {
|
||||||
|
Field: "@/components/admin/ai/TestConnectionButton",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "collapsible",
|
||||||
|
label: "Last test",
|
||||||
|
admin: { initCollapsed: true },
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: "lastTestOk",
|
||||||
|
type: "checkbox",
|
||||||
|
admin: { readOnly: true, description: "Result of the last connection test." },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "lastTestedAt",
|
||||||
|
type: "date",
|
||||||
|
admin: { readOnly: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "lastTestMessage",
|
||||||
|
type: "textarea",
|
||||||
|
admin: { readOnly: true, description: "What the probe said, including any provider error." },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
62
src/collections/server/AiSettings.ts
Normal file
62
src/collections/server/AiSettings.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
import type { GlobalConfig } from "payload";
|
||||||
|
|
||||||
|
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which model connection each AI surface uses.
|
||||||
|
*
|
||||||
|
* Blank means the env defaults (`UNSLOTH_URL`, `UNSLOTH_MODEL`,
|
||||||
|
* `UNSLOTH_API_KEY`), which is what ran before connections existed, so an empty
|
||||||
|
* global changes nothing. Surfaces are separate on purpose: dialogue drafting wants
|
||||||
|
* a model that follows a JSON schema, while a line rewrite only needs prose, and
|
||||||
|
* they can reasonably be different price points.
|
||||||
|
*
|
||||||
|
* Superuser-gated to match the connections it points at: choosing a connection for
|
||||||
|
* Compose repoints traffic that includes field content from every allowlisted
|
||||||
|
* collection, so this is not a dialogue-author permission.
|
||||||
|
*/
|
||||||
|
export const AiSettings: GlobalConfig = {
|
||||||
|
slug: "ai-settings",
|
||||||
|
label: "AI Settings",
|
||||||
|
admin: {
|
||||||
|
group: "Server",
|
||||||
|
description:
|
||||||
|
"Which model connection each AI surface uses. Leave a selector blank to use the Unsloth env defaults.",
|
||||||
|
},
|
||||||
|
access: {
|
||||||
|
read: requirePermission("system:admin-access"),
|
||||||
|
update: requirePermission("system:admin-access"),
|
||||||
|
},
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: "composeConnection",
|
||||||
|
type: "relationship",
|
||||||
|
relationTo: "ai-connections",
|
||||||
|
hasMany: false,
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"The AI Compose field assistant across every allowlisted collection. Blank uses the env defaults.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "dialogueDraftConnection",
|
||||||
|
type: "relationship",
|
||||||
|
relationTo: "ai-connections",
|
||||||
|
hasMany: false,
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"Whole-conversation NPC dialogue drafting. This one needs a model that reliably returns JSON in the configured structured mode. Blank uses the env defaults.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "dialogueLineConnection",
|
||||||
|
type: "relationship",
|
||||||
|
relationTo: "ai-connections",
|
||||||
|
hasMany: false,
|
||||||
|
admin: {
|
||||||
|
description:
|
||||||
|
"Per-line rewrites (Rewrite, Shorten, Sharpen). Prose only, so a cheaper model is usually fine. Blank uses the env defaults.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
81
src/components/admin/ai/TestConnectionButton.tsx
Normal file
81
src/components/admin/ai/TestConnectionButton.tsx
Normal file
|
|
@ -0,0 +1,81 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useState } from "react";
|
||||||
|
import { useDocumentInfo } from "@payloadcms/ui";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the connection probes from the edit view.
|
||||||
|
*
|
||||||
|
* The probes are the only honest answer to "will this provider accept our
|
||||||
|
* requests", because the two failure modes (a rejected key, and a provider that
|
||||||
|
* refuses the configured structured-output mode) both look like a broken model
|
||||||
|
* from the drafting surface. The endpoint tests a *saved* document, so an unsaved
|
||||||
|
* edit has to be saved first; that is called out rather than silently probing the
|
||||||
|
* old values.
|
||||||
|
*
|
||||||
|
* Styled in zinc because the admin bundle does not load the frontend theme's CSS
|
||||||
|
* variables (see the root AGENTS.md note on custom admin field components).
|
||||||
|
*/
|
||||||
|
export function TestConnectionButton() {
|
||||||
|
const { id } = useDocumentInfo();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null);
|
||||||
|
|
||||||
|
const run = useCallback(async () => {
|
||||||
|
if (typeof id !== "number" && typeof id !== "string") return;
|
||||||
|
setBusy(true);
|
||||||
|
setResult(null);
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/ai-connections/${id}/test`, {
|
||||||
|
method: "POST",
|
||||||
|
credentials: "include",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
});
|
||||||
|
const data = (await response.json()) as { ok?: boolean; message?: string };
|
||||||
|
setResult({
|
||||||
|
ok: Boolean(data.ok),
|
||||||
|
message: data.message ?? (response.ok ? "Test finished." : `Test failed (${response.status}).`),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
setResult({
|
||||||
|
ok: false,
|
||||||
|
message: error instanceof Error ? error.message : "The test request could not be sent.",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
const saved = typeof id === "number" || typeof id === "string";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-2 rounded-md border border-white/15 bg-zinc-900/60 p-3">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void run()}
|
||||||
|
disabled={busy || !saved}
|
||||||
|
className="rounded border border-fuchsia-500/40 bg-fuchsia-500/10 px-2.5 py-1 text-[11px] font-medium text-fuchsia-200 hover:bg-fuchsia-500/20 disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy ? "Testing..." : "Test connection"}
|
||||||
|
</button>
|
||||||
|
<span className="text-[11px] text-white/40">
|
||||||
|
{saved
|
||||||
|
? "Sends one plain prompt and one structured prompt. Save first; the test uses the stored values."
|
||||||
|
: "Save this connection before testing it."}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{result ? (
|
||||||
|
<p
|
||||||
|
className={`mt-2 whitespace-pre-wrap text-[11px] ${
|
||||||
|
result.ok ? "text-emerald-300" : "text-rose-300"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{result.ok ? "Passed. " : "Failed. "}
|
||||||
|
{result.message}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -215,6 +215,7 @@ function FlowEditor() {
|
||||||
promptVersion: string;
|
promptVersion: string;
|
||||||
promptSource: "builtin" | "global" | "dialogue";
|
promptSource: "builtin" | "global" | "dialogue";
|
||||||
promptRevision: number | null;
|
promptRevision: number | null;
|
||||||
|
connectionLabel: string | null;
|
||||||
attempts: number;
|
attempts: number;
|
||||||
truncated: boolean;
|
truncated: boolean;
|
||||||
}, brief: DialogueBrief) => {
|
}, brief: DialogueBrief) => {
|
||||||
|
|
@ -228,6 +229,7 @@ function FlowEditor() {
|
||||||
promptVersion: result.promptVersion,
|
promptVersion: result.promptVersion,
|
||||||
promptSource: result.promptSource,
|
promptSource: result.promptSource,
|
||||||
promptRevision: result.promptRevision,
|
promptRevision: result.promptRevision,
|
||||||
|
connectionLabel: result.connectionLabel,
|
||||||
attempts: result.attempts,
|
attempts: result.attempts,
|
||||||
generatedAt: new Date().toISOString(),
|
generatedAt: new Date().toISOString(),
|
||||||
brief,
|
brief,
|
||||||
|
|
@ -241,10 +243,11 @@ function FlowEditor() {
|
||||||
: result.promptSource === "dialogue"
|
: result.promptSource === "dialogue"
|
||||||
? " Voice: this dialogue's own override."
|
? " Voice: this dialogue's own override."
|
||||||
: " Voice: the global setting.";
|
: " Voice: the global setting.";
|
||||||
|
const modelNote = result.connectionLabel ? ` Connection: ${result.connectionLabel}.` : "";
|
||||||
setDraftNotice(
|
setDraftNotice(
|
||||||
result.truncated
|
result.truncated
|
||||||
? `AI draft.${voiceNote} The model hit its output limit, so the ending may be missing. Review every line before saving.`
|
? `AI draft.${voiceNote}${modelNote} The model hit its output limit, so the ending may be missing. Review every line before saving.`
|
||||||
: `AI draft.${voiceNote} Review every line, then save the document to publish it.`,
|
: `AI draft.${voiceNote}${modelNote} Review every line, then save the document to publish it.`,
|
||||||
);
|
);
|
||||||
// Fit the new graph once React Flow has measured the nodes it was handed.
|
// Fit the new graph once React Flow has measured the nodes it was handed.
|
||||||
window.setTimeout(() => {
|
window.setTimeout(() => {
|
||||||
|
|
|
||||||
129
src/lib/ai/connections.ts
Normal file
129
src/lib/ai/connections.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
||||||
|
/**
|
||||||
|
* Admin-configurable model connections.
|
||||||
|
*
|
||||||
|
* The env vars (`UNSLOTH_URL`, `UNSLOTH_MODEL`, `UNSLOTH_API_KEY`) remain the
|
||||||
|
* default: a surface with no connection selected behaves exactly as before. When
|
||||||
|
* one is selected, the request goes to that base URL with that model and key
|
||||||
|
* instead, which is what lets a provider be swapped from the admin panel without a
|
||||||
|
* redeploy.
|
||||||
|
*
|
||||||
|
* Every lookup is `overrideAccess: true` with `depth: 0`. Depth matters: the key
|
||||||
|
* field is write-only, and an access-bypassing read is the only way to get it back
|
||||||
|
* for a request. Fetching by id keeps that explicit instead of relying on
|
||||||
|
* relationship population to carry a restricted field.
|
||||||
|
*
|
||||||
|
* Server-only.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { Payload } from "payload";
|
||||||
|
|
||||||
|
import type { AiConnection, StructuredMode } from "./generate";
|
||||||
|
|
||||||
|
/** Must match the global's slug in `src/collections/server/AiSettings.ts`. */
|
||||||
|
export const AI_SETTINGS_SLUG = "ai-settings";
|
||||||
|
/** Must match the collection's slug in `src/collections/server/AiConnections.ts`. */
|
||||||
|
export const AI_CONNECTIONS_SLUG = "ai-connections";
|
||||||
|
|
||||||
|
/** The AI surfaces that can each point at their own model. */
|
||||||
|
export type AiPurpose = "compose" | "dialogue-draft" | "dialogue-line";
|
||||||
|
|
||||||
|
const PURPOSE_FIELD: Record<AiPurpose, string> = {
|
||||||
|
compose: "composeConnection",
|
||||||
|
"dialogue-draft": "dialogueDraftConnection",
|
||||||
|
"dialogue-line": "dialogueLineConnection",
|
||||||
|
};
|
||||||
|
|
||||||
|
type ConnectionDoc = {
|
||||||
|
label?: string | null;
|
||||||
|
baseUrl?: string | null;
|
||||||
|
modelId?: string | null;
|
||||||
|
apiKey?: string | null;
|
||||||
|
structuredMode?: StructuredMode | null;
|
||||||
|
sendReasoningOff?: boolean | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const asId = (value: unknown): number | null => {
|
||||||
|
if (typeof value === "number") return value;
|
||||||
|
if (value && typeof value === "object" && "id" in value) {
|
||||||
|
const id = (value as { id?: unknown }).id;
|
||||||
|
return typeof id === "number" ? id : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Boot a Payload instance for callers that have none.
|
||||||
|
*
|
||||||
|
* Only the Compose plugin handler needs this: the plugin hands its handler plain
|
||||||
|
* arguments, not a `req`. The config import is dynamic so this module does not
|
||||||
|
* create a load-time cycle with `payload.config.ts`, which imports the generator.
|
||||||
|
*/
|
||||||
|
async function bootPayload(): Promise<Payload> {
|
||||||
|
const [{ getPayload }, { default: config }] = await Promise.all([
|
||||||
|
import("payload"),
|
||||||
|
import("@payload-config"),
|
||||||
|
]);
|
||||||
|
return getPayload({ config });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The model connection for one surface, or null to use the env defaults.
|
||||||
|
*
|
||||||
|
* Never throws: a misconfigured connection must fail the generation with a clear
|
||||||
|
* message from the client call, not crash the page that tried to draft.
|
||||||
|
*/
|
||||||
|
export async function resolveConnection(
|
||||||
|
payload: Payload | null,
|
||||||
|
purpose: AiPurpose,
|
||||||
|
): Promise<AiConnection | null> {
|
||||||
|
try {
|
||||||
|
const instance = payload ?? (await bootPayload());
|
||||||
|
const settings = (await instance.findGlobal({
|
||||||
|
slug: AI_SETTINGS_SLUG,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})) as unknown as Record<string, unknown> | null;
|
||||||
|
|
||||||
|
const connectionId = asId(settings?.[PURPOSE_FIELD[purpose]]);
|
||||||
|
if (!connectionId) return null;
|
||||||
|
|
||||||
|
const doc = (await instance.findByID({
|
||||||
|
collection: AI_CONNECTIONS_SLUG,
|
||||||
|
id: connectionId,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})) as ConnectionDoc | null;
|
||||||
|
|
||||||
|
const baseUrl = doc?.baseUrl?.trim();
|
||||||
|
const modelId = doc?.modelId?.trim();
|
||||||
|
// A half-filled connection is a configuration mistake, not a routing choice:
|
||||||
|
// falling back to env keeps drafting working while it is being fixed.
|
||||||
|
if (!baseUrl || !modelId) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
label: doc?.label?.trim() || modelId,
|
||||||
|
baseUrl,
|
||||||
|
modelId,
|
||||||
|
apiKey: doc?.apiKey?.trim() || null,
|
||||||
|
structuredMode: doc?.structuredMode ?? "json_schema",
|
||||||
|
sendReasoningOff: doc?.sendReasoningOff !== false,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when any surface has a connection selected, for docs and admin hints. */
|
||||||
|
export async function hasAnyConnection(payload: Payload): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const settings = (await payload.findGlobal({
|
||||||
|
slug: AI_SETTINGS_SLUG,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})) as unknown as Record<string, unknown> | null;
|
||||||
|
|
||||||
|
return Object.values(PURPOSE_FIELD).some((field) => asId(settings?.[field]) !== null);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,16 +1,19 @@
|
||||||
/**
|
/**
|
||||||
* Shared access to the Unsloth Studio model that powers every AI surface in the
|
* Shared access to the language model that powers every AI surface in the app:
|
||||||
* app: the Compose field plugin in `payload.config.ts` and the NPC dialogue
|
* the Compose field plugin in `payload.config.ts`, the NPC dialogue drafting
|
||||||
* drafting actions in `src/lib/npc-dialogue/generation.ts`.
|
* actions, and the per-line rewrites.
|
||||||
*
|
*
|
||||||
* Everything here was lifted out of `payload.config.ts` unchanged. The only
|
* Two ways to reach a model:
|
||||||
* additions are `generateStructured` (a non-streaming companion to the object
|
|
||||||
* path Compose already used) and `resolveModel`, which keeps model selection in
|
|
||||||
* one place so a caller can point a structured task at a different GGUF without
|
|
||||||
* touching the prose default.
|
|
||||||
*
|
*
|
||||||
* Server-only: this reads UNSLOTH_* environment variables and talks to the
|
* - **Environment default.** `UNSLOTH_URL`, `UNSLOTH_MODEL` and `UNSLOTH_API_KEY`
|
||||||
* model host over the network.
|
* 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 { createOpenAI } from "@ai-sdk/openai";
|
||||||
|
|
@ -20,10 +23,13 @@ import { jsonSchema, streamObject } from "ai";
|
||||||
* The model-id select and its Postgres enum use a stable internal key. Changing
|
* 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:
|
* that key requires a migration, so the served model is configured separately:
|
||||||
* point UNSLOTH_MODEL at the GGUF loaded in Unsloth Studio.
|
* 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";
|
export const MODEL_ID = "unsloth/Ornith-1.0-9B-GGUF";
|
||||||
|
|
||||||
/** The served model for every AI surface unless a task overrides it. */
|
/** The served model for every AI surface unless a task or connection overrides it. */
|
||||||
export const DEFAULT_MODEL = process.env.UNSLOTH_MODEL || MODEL_ID;
|
export const DEFAULT_MODEL = process.env.UNSLOTH_MODEL || MODEL_ID;
|
||||||
|
|
||||||
// Dropdown label for the model. UNSLOTH_MODEL_NAME wins; otherwise derive a
|
// Dropdown label for the model. UNSLOTH_MODEL_NAME wins; otherwise derive a
|
||||||
|
|
@ -40,32 +46,94 @@ export const MODEL_LABEL =
|
||||||
// whole allowance, leaving `content` empty. Unsloth Studio (llama.cpp) accepts
|
// whole allowance, leaving `content` empty. Unsloth Studio (llama.cpp) accepts
|
||||||
// `reasoning_effort: "none"` to turn thinking off for the request, so the model
|
// `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.
|
// behaves like a plain instruct model and small budgets still produce output.
|
||||||
// Sent on every request; harmless on models that do not support it.
|
//
|
||||||
|
// Only sent when the active connection allows it: a strict provider rejects
|
||||||
|
// unrecognised body fields with a 400.
|
||||||
export const REASONING_DISABLED = { reasoning_effort: "none" } as const;
|
export const REASONING_DISABLED = { reasoning_effort: "none" } as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ornith-9B is served by the "Apex" Unsloth connection (a separate machine,
|
* 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
|
* 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
|
* API. Point UNSLOTH_URL at that instance; the default is the LAN address of the
|
||||||
* the Apex box.
|
* Apex box.
|
||||||
*/
|
*/
|
||||||
export const UNSLOTH_BASE_URL = process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1";
|
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({
|
export const unslothProvider = createOpenAI({
|
||||||
apiKey: process.env.UNSLOTH_API_KEY,
|
apiKey: process.env.UNSLOTH_API_KEY,
|
||||||
baseURL: UNSLOTH_BASE_URL,
|
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 model a structured (graph/schema) task should use. Falls through to the
|
* The provider for a connection, for callers that build their own stream (the
|
||||||
* shared default, so setting only UNSLOTH_MODEL changes every surface at once.
|
* Compose plugin's non-prose branch does).
|
||||||
* UNSLOTH_MODEL_STRUCTURED exists for the case where prose and structured work
|
*/
|
||||||
* want different GGUFs; leaving it unset changes nothing.
|
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 {
|
export function resolveModel(): string {
|
||||||
return process.env.UNSLOTH_MODEL_STRUCTURED || DEFAULT_MODEL;
|
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
|
// Gemma tends to answer schema-y prompts with fenced JSON blobs. The plain-text
|
||||||
// fallback is meant to produce prose that plainTextToLexicalJson wraps into
|
// fallback is meant to produce prose that plainTextToLexicalJson wraps into
|
||||||
// paragraphs, so strip any markdown code fences before using the output.
|
// paragraphs, so strip any markdown code fences before using the output.
|
||||||
|
|
@ -77,27 +145,42 @@ export const stripCodeFences = (text: string): string =>
|
||||||
|
|
||||||
export type PlainTextResult = { text: string; truncated: boolean };
|
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
|
* 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
|
* 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
|
* parses. The token cap and temperature mirror what the old structured path
|
||||||
* used, and `finish_reason === "length"` is reported so the truncation marker
|
* used, and `finish_reason === "length"` is reported so the truncation marker
|
||||||
* reaches the client.
|
* 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(
|
export async function generatePlainText(
|
||||||
prompt: string,
|
prompt: string,
|
||||||
system: string,
|
system: string,
|
||||||
model: string,
|
model: string,
|
||||||
options: { maxTokens?: number; temperature?: number } = {},
|
options: PlainTextOptions = {},
|
||||||
): Promise<PlainTextResult> {
|
): Promise<PlainTextResult> {
|
||||||
const response = await fetch(`${UNSLOTH_BASE_URL}/chat/completions`, {
|
const connection = options.connection ?? null;
|
||||||
|
const reasoning = connection ? connection.sendReasoningOff !== false : true;
|
||||||
|
|
||||||
|
const response = await fetch(completionsUrl(connection), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: "Bearer " + process.env.UNSLOTH_API_KEY,
|
Authorization: "Bearer " + (connection?.apiKey || process.env.UNSLOTH_API_KEY),
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
model,
|
model: connection?.modelId || model,
|
||||||
messages: [
|
messages: [
|
||||||
{ role: "system", content: system || "You are a helpful assistant." },
|
{ role: "system", content: system || "You are a helpful assistant." },
|
||||||
{ role: "user", content: prompt },
|
{ role: "user", content: prompt },
|
||||||
|
|
@ -105,12 +188,20 @@ export async function generatePlainText(
|
||||||
stream: false,
|
stream: false,
|
||||||
max_tokens: options.maxTokens ?? 5000,
|
max_tokens: options.maxTokens ?? 5000,
|
||||||
temperature: options.temperature ?? 0.7,
|
temperature: options.temperature ?? 0.7,
|
||||||
...REASONING_DISABLED,
|
...(reasoning ? REASONING_DISABLED : {}),
|
||||||
|
...(options.responseFormat ? { response_format: { type: options.responseFormat } } : {}),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`Unsloth API error: ${response.statusText}`);
|
// 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 result = await response.json();
|
||||||
|
|
@ -128,10 +219,12 @@ export interface StructuredGenerationOptions {
|
||||||
system?: string;
|
system?: string;
|
||||||
/** A JSON schema (from `zod`-free callers, so a plain JSON schema object). */
|
/** A JSON schema (from `zod`-free callers, so a plain JSON schema object). */
|
||||||
schema: Record<string, unknown>;
|
schema: Record<string, unknown>;
|
||||||
/** Overrides `resolveModel()`. */
|
/** Overrides `resolveModel()` (ignored when a connection supplies a model). */
|
||||||
model?: string;
|
model?: string;
|
||||||
maxTokens?: number;
|
maxTokens?: number;
|
||||||
temperature?: number;
|
temperature?: number;
|
||||||
|
/** Route through a stored connection, which also determines the mode. */
|
||||||
|
connection?: AiConnection | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface StructuredResult<T> {
|
export interface StructuredResult<T> {
|
||||||
|
|
@ -140,10 +233,55 @@ export interface StructuredResult<T> {
|
||||||
truncated: boolean;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Non-streaming object generation using the same provider configuration the
|
* Structured output for providers without strict schema support: the schema goes
|
||||||
* Compose fallback already proved against Unsloth Studio: strict JSON schema,
|
* into the prompt, and the reply is parsed. `json_object` asks the provider for
|
||||||
* structured outputs, and reasoning disabled.
|
* 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
|
* Throws when the model's output cannot be parsed into the schema. Callers that
|
||||||
* want a retry should catch and re-prompt; see
|
* want a retry should catch and re-prompt; see
|
||||||
|
|
@ -152,11 +290,20 @@ export interface StructuredResult<T> {
|
||||||
export async function generateStructured<T>(
|
export async function generateStructured<T>(
|
||||||
options: StructuredGenerationOptions,
|
options: StructuredGenerationOptions,
|
||||||
): Promise<StructuredResult<T>> {
|
): 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({
|
const result = streamObject({
|
||||||
maxOutputTokens: options.maxTokens ?? 5000,
|
maxOutputTokens: options.maxTokens ?? 5000,
|
||||||
model: unslothProvider(options.model || resolveModel()),
|
model: providerFor(connection)(connection?.modelId || options.model || resolveModel()),
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
console.error("Unsloth generateStructured: ", error);
|
console.error("AI generateStructured: ", error);
|
||||||
},
|
},
|
||||||
prompt: options.prompt,
|
prompt: options.prompt,
|
||||||
schema: jsonSchema(options.schema),
|
schema: jsonSchema(options.schema),
|
||||||
|
|
@ -166,7 +313,7 @@ export async function generateStructured<T>(
|
||||||
openai: {
|
openai: {
|
||||||
strictJsonSchema: true,
|
strictJsonSchema: true,
|
||||||
structuredOutputs: true,
|
structuredOutputs: true,
|
||||||
...REASONING_DISABLED,
|
...(reasoning ? REASONING_DISABLED : {}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
|
||||||
146
src/lib/ai/probe.ts
Normal file
146
src/lib/ai/probe.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
||||||
|
/**
|
||||||
|
* 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.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
@ -98,6 +98,10 @@ pass server-side, so a flag value can never smuggle in another token.
|
||||||
to a hyphen (it is a range). Shipped copy never carries an em-dash.
|
to a hyphen (it is a range). Shipped copy never carries an em-dash.
|
||||||
- The model is reachable only through `src/lib/ai/generate.ts`. Do not call
|
- The model is reachable only through `src/lib/ai/generate.ts`. Do not call
|
||||||
`fetch` against Unsloth anywhere else.
|
`fetch` against Unsloth anywhere else.
|
||||||
|
- Which model serves a draft comes from `resolveConnection(payload, purpose)`
|
||||||
|
(`src/lib/ai/connections.ts`), resolved once per request alongside the voice. A
|
||||||
|
null connection means the env defaults, which is the unchanged behaviour. See
|
||||||
|
`docs/ai-settings.md`.
|
||||||
- The voice is resolved once per draft, not per attempt, so a retry cannot change
|
- The voice is resolved once per draft, not per attempt, so a retry cannot change
|
||||||
register mid-generation. `rewriteDialogueLine` resolves it the same way, so a
|
register mid-generation. `rewriteDialogueLine` resolves it the same way, so a
|
||||||
house voice shapes drafts and rewrites alike.
|
house voice shapes drafts and rewrites alike.
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,15 @@
|
||||||
|
|
||||||
import type { Payload } from "payload";
|
import type { Payload } from "payload";
|
||||||
|
|
||||||
import { generatePlainText, generateStructured, resolveModel, stripCodeFences } from "@/lib/ai/generate";
|
import {
|
||||||
|
effectiveModel,
|
||||||
|
generatePlainText,
|
||||||
|
generateStructured,
|
||||||
|
resolveModel,
|
||||||
|
stripCodeFences,
|
||||||
|
} from "@/lib/ai/generate";
|
||||||
|
import type { AiConnection } from "@/lib/ai/generate";
|
||||||
|
import { resolveConnection } from "@/lib/ai/connections";
|
||||||
import { lexicalToPlaintext } from "@/lib/lexical/text";
|
import { lexicalToPlaintext } from "@/lib/lexical/text";
|
||||||
|
|
||||||
import { deriveEdges } from "./dialogue";
|
import { deriveEdges } from "./dialogue";
|
||||||
|
|
@ -159,6 +167,8 @@ export interface DraftRunnerInput {
|
||||||
prompt: string;
|
prompt: string;
|
||||||
system: string;
|
system: string;
|
||||||
schema: Record<string, unknown>;
|
schema: Record<string, unknown>;
|
||||||
|
/** The resolved connection, or null for the env defaults. */
|
||||||
|
connection?: AiConnection | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DraftRunnerResult {
|
export interface DraftRunnerResult {
|
||||||
|
|
@ -189,12 +199,14 @@ export interface DraftOutcome {
|
||||||
promptSource: VoiceSource;
|
promptSource: VoiceSource;
|
||||||
/** The settings revision used, or null for the built-in voice. */
|
/** The settings revision used, or null for the built-in voice. */
|
||||||
promptRevision: number | null;
|
promptRevision: number | null;
|
||||||
|
/** The admin connection used, or null for the env defaults. */
|
||||||
|
connectionLabel: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultRunner: DraftRunner = (input) =>
|
const defaultRunner: DraftRunner = (input) =>
|
||||||
generateStructured<{ nodes?: RawDraftNode[] }>({
|
generateStructured<{ nodes?: RawDraftNode[] }>({
|
||||||
...input,
|
...input,
|
||||||
model: resolveModel(),
|
model: effectiveModel(input.connection),
|
||||||
maxTokens: 4000,
|
maxTokens: 4000,
|
||||||
temperature: 0.8,
|
temperature: 0.8,
|
||||||
});
|
});
|
||||||
|
|
@ -212,7 +224,10 @@ export async function generateDialogueDraft(
|
||||||
const { npc, flags } = await buildGenerationContext(payload, input.npcId);
|
const { npc, flags } = await buildGenerationContext(payload, input.npcId);
|
||||||
const basePrompt = buildGenerationPrompt({ npc, brief: input.brief, flags });
|
const basePrompt = buildGenerationPrompt({ npc, brief: input.brief, flags });
|
||||||
const knownKeys = flags.map((flag) => flag.key);
|
const knownKeys = flags.map((flag) => flag.key);
|
||||||
const model = resolveModel();
|
// One connection per draft, resolved alongside the voice, so a retry cannot
|
||||||
|
// silently land on a different provider than the attempt it is correcting.
|
||||||
|
const connection = await resolveConnection(payload, "dialogue-draft");
|
||||||
|
const model = effectiveModel(connection);
|
||||||
|
|
||||||
// The voice is resolved once per draft, not per attempt, so both attempts use
|
// The voice is resolved once per draft, not per attempt, so both attempts use
|
||||||
// the same instruction and a retry cannot silently change register.
|
// the same instruction and a retry cannot silently change register.
|
||||||
|
|
@ -238,7 +253,7 @@ Fix every problem above and return the whole conversation again.`;
|
||||||
|
|
||||||
let parsed: DraftRunnerResult;
|
let parsed: DraftRunnerResult;
|
||||||
try {
|
try {
|
||||||
parsed = await run({ prompt, system, schema: dialogueFlowSchema });
|
parsed = await run({ prompt, system, schema: dialogueFlowSchema, connection });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
errors = [
|
errors = [
|
||||||
`The model's output could not be read as a conversation: ${
|
`The model's output could not be read as a conversation: ${
|
||||||
|
|
@ -264,6 +279,7 @@ Fix every problem above and return the whole conversation again.`;
|
||||||
promptVersion: PROMPT_VERSION,
|
promptVersion: PROMPT_VERSION,
|
||||||
promptSource: resolved.source,
|
promptSource: resolved.source,
|
||||||
promptRevision: resolved.revision,
|
promptRevision: resolved.revision,
|
||||||
|
connectionLabel: connection?.label ?? null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -288,6 +304,7 @@ Fix every problem above and return the whole conversation again.`;
|
||||||
promptVersion: PROMPT_VERSION,
|
promptVersion: PROMPT_VERSION,
|
||||||
promptSource: resolved.source,
|
promptSource: resolved.source,
|
||||||
promptRevision: resolved.revision,
|
promptRevision: resolved.revision,
|
||||||
|
connectionLabel: connection?.label ?? null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -303,10 +320,16 @@ export type LineRunner = (input: {
|
||||||
prompt: string;
|
prompt: string;
|
||||||
system: string;
|
system: string;
|
||||||
model: string;
|
model: string;
|
||||||
|
/** The resolved connection, or null for the env defaults. */
|
||||||
|
connection?: AiConnection | null;
|
||||||
}) => Promise<{ text: string }>;
|
}) => Promise<{ text: string }>;
|
||||||
|
|
||||||
const defaultLineRunner: LineRunner = ({ prompt, system, model }) =>
|
const defaultLineRunner: LineRunner = ({ prompt, system, model, connection }) =>
|
||||||
generatePlainText(prompt, system, model, { maxTokens: 400, temperature: 0.8 });
|
generatePlainText(prompt, system, model, {
|
||||||
|
maxTokens: 400,
|
||||||
|
temperature: 0.8,
|
||||||
|
connection,
|
||||||
|
});
|
||||||
|
|
||||||
export interface LineRewriteOutcome {
|
export interface LineRewriteOutcome {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
|
|
@ -352,7 +375,14 @@ export async function rewriteDialogueLine(
|
||||||
voice: resolved.voice,
|
voice: resolved.voice,
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await run({ prompt, system, model: resolveModel() });
|
// Rewrites are prose only, so they can point at a cheaper model than drafting.
|
||||||
|
const connection = await resolveConnection(payload, "dialogue-line");
|
||||||
|
const result = await run({
|
||||||
|
prompt,
|
||||||
|
system,
|
||||||
|
model: effectiveModel(connection),
|
||||||
|
connection,
|
||||||
|
});
|
||||||
const cleaned = cleanRewrittenLine(result.text ?? "");
|
const cleaned = cleanRewrittenLine(result.text ?? "");
|
||||||
|
|
||||||
if (!cleaned) {
|
if (!cleaned) {
|
||||||
|
|
|
||||||
47095
src/migrations/20261124_175950_add_ai_connections.json
Normal file
47095
src/migrations/20261124_175950_add_ai_connections.json
Normal file
File diff suppressed because it is too large
Load diff
66
src/migrations/20261124_175950_add_ai_connections.ts
Normal file
66
src/migrations/20261124_175950_add_ai_connections.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||||
|
|
||||||
|
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
CREATE TYPE "public"."enum_ai_connections_structured_mode" AS ENUM('json_schema', 'json_object', 'prompt');
|
||||||
|
CREATE TABLE "ai_connections" (
|
||||||
|
"id" serial PRIMARY KEY NOT NULL,
|
||||||
|
"label" varchar NOT NULL,
|
||||||
|
"base_url" varchar NOT NULL,
|
||||||
|
"model_id" varchar NOT NULL,
|
||||||
|
"api_key" varchar,
|
||||||
|
"has_api_key" boolean,
|
||||||
|
"clear_api_key" boolean,
|
||||||
|
"structured_mode" "enum_ai_connections_structured_mode" DEFAULT 'json_schema' NOT NULL,
|
||||||
|
"send_reasoning_off" boolean DEFAULT true,
|
||||||
|
"last_test_ok" boolean,
|
||||||
|
"last_tested_at" timestamp(3) with time zone,
|
||||||
|
"last_test_message" varchar,
|
||||||
|
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||||
|
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "ai_settings" (
|
||||||
|
"id" serial PRIMARY KEY NOT NULL,
|
||||||
|
"compose_connection_id" integer,
|
||||||
|
"dialogue_draft_connection_id" integer,
|
||||||
|
"dialogue_line_connection_id" integer,
|
||||||
|
"updated_at" timestamp(3) with time zone,
|
||||||
|
"created_at" timestamp(3) with time zone
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_connection_label" varchar;
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "ai_connections_find" boolean DEFAULT false;
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "ai_connections_create" boolean DEFAULT false;
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "ai_connections_update" boolean DEFAULT false;
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "ai_connections_delete" boolean DEFAULT false;
|
||||||
|
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "ai_connections_id" integer;
|
||||||
|
ALTER TABLE "ai_settings" ADD CONSTRAINT "ai_settings_compose_connection_id_ai_connections_id_fk" FOREIGN KEY ("compose_connection_id") REFERENCES "public"."ai_connections"("id") ON DELETE set null ON UPDATE no action;
|
||||||
|
ALTER TABLE "ai_settings" ADD CONSTRAINT "ai_settings_dialogue_draft_connection_id_ai_connections_id_fk" FOREIGN KEY ("dialogue_draft_connection_id") REFERENCES "public"."ai_connections"("id") ON DELETE set null ON UPDATE no action;
|
||||||
|
ALTER TABLE "ai_settings" ADD CONSTRAINT "ai_settings_dialogue_line_connection_id_ai_connections_id_fk" FOREIGN KEY ("dialogue_line_connection_id") REFERENCES "public"."ai_connections"("id") ON DELETE set null ON UPDATE no action;
|
||||||
|
CREATE INDEX "ai_connections_updated_at_idx" ON "ai_connections" USING btree ("updated_at");
|
||||||
|
CREATE INDEX "ai_connections_created_at_idx" ON "ai_connections" USING btree ("created_at");
|
||||||
|
CREATE INDEX "ai_settings_compose_connection_idx" ON "ai_settings" USING btree ("compose_connection_id");
|
||||||
|
CREATE INDEX "ai_settings_dialogue_draft_connection_idx" ON "ai_settings" USING btree ("dialogue_draft_connection_id");
|
||||||
|
CREATE INDEX "ai_settings_dialogue_line_connection_idx" ON "ai_settings" USING btree ("dialogue_line_connection_id");
|
||||||
|
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_ai_connections_fk" FOREIGN KEY ("ai_connections_id") REFERENCES "public"."ai_connections"("id") ON DELETE cascade ON UPDATE no action;
|
||||||
|
CREATE INDEX "payload_locked_documents_rels_ai_connections_id_idx" ON "payload_locked_documents_rels" USING btree ("ai_connections_id");`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
ALTER TABLE "ai_connections" DISABLE ROW LEVEL SECURITY;
|
||||||
|
ALTER TABLE "ai_settings" DISABLE ROW LEVEL SECURITY;
|
||||||
|
DROP TABLE "ai_connections" CASCADE;
|
||||||
|
DROP TABLE "ai_settings" CASCADE;
|
||||||
|
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_ai_connections_fk";
|
||||||
|
|
||||||
|
DROP INDEX "payload_locked_documents_rels_ai_connections_id_idx";
|
||||||
|
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_connection_label";
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "ai_connections_find";
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "ai_connections_create";
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "ai_connections_update";
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "ai_connections_delete";
|
||||||
|
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "ai_connections_id";
|
||||||
|
DROP TYPE "public"."enum_ai_connections_structured_mode";`)
|
||||||
|
}
|
||||||
|
|
@ -165,6 +165,7 @@ import * as migration_20261120_234950_add_locker_unlimited from './20261120_2349
|
||||||
import * as migration_20261121_015435_add_mission_attendance_unlocks from './20261121_015435_add_mission_attendance_unlocks';
|
import * as migration_20261121_015435_add_mission_attendance_unlocks from './20261121_015435_add_mission_attendance_unlocks';
|
||||||
import * as migration_20261123_073019_add_tech_tree_notes from './20261123_073019_add_tech_tree_notes';
|
import * as migration_20261123_073019_add_tech_tree_notes from './20261123_073019_add_tech_tree_notes';
|
||||||
import * as migration_20261124_174637_add_npc_dialogue_prompt_settings from './20261124_174637_add_npc_dialogue_prompt_settings';
|
import * as migration_20261124_174637_add_npc_dialogue_prompt_settings from './20261124_174637_add_npc_dialogue_prompt_settings';
|
||||||
|
import * as migration_20261124_175950_add_ai_connections from './20261124_175950_add_ai_connections';
|
||||||
|
|
||||||
export const migrations = [
|
export const migrations = [
|
||||||
{
|
{
|
||||||
|
|
@ -1000,6 +1001,11 @@ export const migrations = [
|
||||||
{
|
{
|
||||||
up: migration_20261124_174637_add_npc_dialogue_prompt_settings.up,
|
up: migration_20261124_174637_add_npc_dialogue_prompt_settings.up,
|
||||||
down: migration_20261124_174637_add_npc_dialogue_prompt_settings.down,
|
down: migration_20261124_174637_add_npc_dialogue_prompt_settings.down,
|
||||||
name: '20261124_174637_add_npc_dialogue_prompt_settings'
|
name: '20261124_174637_add_npc_dialogue_prompt_settings',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
up: migration_20261124_175950_add_ai_connections.up,
|
||||||
|
down: migration_20261124_175950_add_ai_connections.down,
|
||||||
|
name: '20261124_175950_add_ai_connections'
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -153,6 +153,7 @@ export interface Config {
|
||||||
'game-servers': GameServer;
|
'game-servers': GameServer;
|
||||||
'arma-sync-events': ArmaSyncEvent;
|
'arma-sync-events': ArmaSyncEvent;
|
||||||
'arma-commands': ArmaCommand;
|
'arma-commands': ArmaCommand;
|
||||||
|
'ai-connections': AiConnection;
|
||||||
'respawn-tickets': RespawnTicket;
|
'respawn-tickets': RespawnTicket;
|
||||||
'supply-boxes': SupplyBox;
|
'supply-boxes': SupplyBox;
|
||||||
'operation-events': OperationEvent;
|
'operation-events': OperationEvent;
|
||||||
|
|
@ -271,6 +272,7 @@ export interface Config {
|
||||||
'game-servers': GameServersSelect<false> | GameServersSelect<true>;
|
'game-servers': GameServersSelect<false> | GameServersSelect<true>;
|
||||||
'arma-sync-events': ArmaSyncEventsSelect<false> | ArmaSyncEventsSelect<true>;
|
'arma-sync-events': ArmaSyncEventsSelect<false> | ArmaSyncEventsSelect<true>;
|
||||||
'arma-commands': ArmaCommandsSelect<false> | ArmaCommandsSelect<true>;
|
'arma-commands': ArmaCommandsSelect<false> | ArmaCommandsSelect<true>;
|
||||||
|
'ai-connections': AiConnectionsSelect<false> | AiConnectionsSelect<true>;
|
||||||
'respawn-tickets': RespawnTicketsSelect<false> | RespawnTicketsSelect<true>;
|
'respawn-tickets': RespawnTicketsSelect<false> | RespawnTicketsSelect<true>;
|
||||||
'supply-boxes': SupplyBoxesSelect<false> | SupplyBoxesSelect<true>;
|
'supply-boxes': SupplyBoxesSelect<false> | SupplyBoxesSelect<true>;
|
||||||
'operation-events': OperationEventsSelect<false> | OperationEventsSelect<true>;
|
'operation-events': OperationEventsSelect<false> | OperationEventsSelect<true>;
|
||||||
|
|
@ -305,6 +307,7 @@ export interface Config {
|
||||||
'minigame-rules': MinigameRule;
|
'minigame-rules': MinigameRule;
|
||||||
'discord-presence': DiscordPresence;
|
'discord-presence': DiscordPresence;
|
||||||
'npc-dialogue-settings': NpcDialogueSetting;
|
'npc-dialogue-settings': NpcDialogueSetting;
|
||||||
|
'ai-settings': AiSetting;
|
||||||
};
|
};
|
||||||
globalsSelect: {
|
globalsSelect: {
|
||||||
'game-rules': GameRulesSelect<false> | GameRulesSelect<true>;
|
'game-rules': GameRulesSelect<false> | GameRulesSelect<true>;
|
||||||
|
|
@ -312,6 +315,7 @@ export interface Config {
|
||||||
'minigame-rules': MinigameRulesSelect<false> | MinigameRulesSelect<true>;
|
'minigame-rules': MinigameRulesSelect<false> | MinigameRulesSelect<true>;
|
||||||
'discord-presence': DiscordPresenceSelect<false> | DiscordPresenceSelect<true>;
|
'discord-presence': DiscordPresenceSelect<false> | DiscordPresenceSelect<true>;
|
||||||
'npc-dialogue-settings': NpcDialogueSettingsSelect<false> | NpcDialogueSettingsSelect<true>;
|
'npc-dialogue-settings': NpcDialogueSettingsSelect<false> | NpcDialogueSettingsSelect<true>;
|
||||||
|
'ai-settings': AiSettingsSelect<false> | AiSettingsSelect<true>;
|
||||||
};
|
};
|
||||||
locale: null;
|
locale: null;
|
||||||
widgets: {
|
widgets: {
|
||||||
|
|
@ -3070,6 +3074,10 @@ export interface NpcDialogue {
|
||||||
* Which voice shaped the prompt: the built-in default, the global setting, or this dialogue's override.
|
* Which voice shaped the prompt: the built-in default, the global setting, or this dialogue's override.
|
||||||
*/
|
*/
|
||||||
promptSource?: ('builtin' | 'global' | 'dialogue') | null;
|
promptSource?: ('builtin' | 'global' | 'dialogue') | null;
|
||||||
|
/**
|
||||||
|
* The admin connection that served the model. Empty means the Unsloth environment defaults.
|
||||||
|
*/
|
||||||
|
connectionLabel?: string | null;
|
||||||
/**
|
/**
|
||||||
* Revision of the prompt settings in force when this draft was made. Empty for the built-in voice, which has no settings revision.
|
* Revision of the prompt settings in force when this draft was made. Empty for the built-in voice, which has no settings revision.
|
||||||
*/
|
*/
|
||||||
|
|
@ -6676,6 +6684,58 @@ export interface ArmaCommand {
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* A model endpoint the AI surfaces can use. Leave the key blank to keep the saved one; use Clear API key to remove it.
|
||||||
|
*
|
||||||
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
|
* via the `definition` "ai-connections".
|
||||||
|
*/
|
||||||
|
export interface AiConnection {
|
||||||
|
id: number;
|
||||||
|
/**
|
||||||
|
* Shown in the surface selectors and recorded in draft provenance, so make it say which provider and model this is.
|
||||||
|
*/
|
||||||
|
label: string;
|
||||||
|
/**
|
||||||
|
* OpenAI-compatible base URL including the API prefix, e.g. http://192.168.1.7:8888/v1 or https://api.deepseek.com/v1. The /chat/completions path is appended.
|
||||||
|
*/
|
||||||
|
baseUrl: string;
|
||||||
|
/**
|
||||||
|
* The model id that provider expects, e.g. deepseek-v4.1-flash or unsloth/Tiel-Coder-35B-GGUF.
|
||||||
|
*/
|
||||||
|
modelId: string;
|
||||||
|
/**
|
||||||
|
* Stored encrypted at rest by the database, server-only. Leave blank to keep the current key.
|
||||||
|
*/
|
||||||
|
apiKey?: string | null;
|
||||||
|
/**
|
||||||
|
* Whether a key is stored. The key itself is never shown.
|
||||||
|
*/
|
||||||
|
hasApiKey?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Tick and save to delete the stored key. Cannot be undone.
|
||||||
|
*/
|
||||||
|
clearApiKey?: boolean | null;
|
||||||
|
/**
|
||||||
|
* How to ask this provider for structured output. Strict schema is best and works on Unsloth Studio and OpenAI-style APIs. Use JSON object mode, or prompt only, for providers that reject a json_schema request. The connection test tells you which one works.
|
||||||
|
*/
|
||||||
|
structuredMode: 'json_schema' | 'json_object' | 'prompt';
|
||||||
|
/**
|
||||||
|
* Send reasoning_effort: none so a reasoning model answers immediately. Turn off for a provider that rejects unknown request fields.
|
||||||
|
*/
|
||||||
|
sendReasoningOff?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Result of the last connection test.
|
||||||
|
*/
|
||||||
|
lastTestOk?: boolean | null;
|
||||||
|
lastTestedAt?: string | null;
|
||||||
|
/**
|
||||||
|
* What the probe said, including any provider error.
|
||||||
|
*/
|
||||||
|
lastTestMessage?: string | null;
|
||||||
|
updatedAt: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* This interface was referenced by `Config`'s JSON-Schema
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "respawn-tickets".
|
* via the `definition` "respawn-tickets".
|
||||||
|
|
@ -9116,6 +9176,24 @@ export interface PayloadMcpApiKey {
|
||||||
*/
|
*/
|
||||||
delete?: boolean | null;
|
delete?: boolean | null;
|
||||||
};
|
};
|
||||||
|
aiConnections?: {
|
||||||
|
/**
|
||||||
|
* Allow clients to find ai-connections.
|
||||||
|
*/
|
||||||
|
find?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Allow clients to create ai-connections.
|
||||||
|
*/
|
||||||
|
create?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Allow clients to update ai-connections.
|
||||||
|
*/
|
||||||
|
update?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Allow clients to delete ai-connections.
|
||||||
|
*/
|
||||||
|
delete?: boolean | null;
|
||||||
|
};
|
||||||
respawnTickets?: {
|
respawnTickets?: {
|
||||||
/**
|
/**
|
||||||
* Allow clients to find respawn-tickets.
|
* Allow clients to find respawn-tickets.
|
||||||
|
|
@ -9757,6 +9835,10 @@ export interface PayloadLockedDocument {
|
||||||
relationTo: 'arma-commands';
|
relationTo: 'arma-commands';
|
||||||
value: number | ArmaCommand;
|
value: number | ArmaCommand;
|
||||||
} | null)
|
} | null)
|
||||||
|
| ({
|
||||||
|
relationTo: 'ai-connections';
|
||||||
|
value: number | AiConnection;
|
||||||
|
} | null)
|
||||||
| ({
|
| ({
|
||||||
relationTo: 'respawn-tickets';
|
relationTo: 'respawn-tickets';
|
||||||
value: number | RespawnTicket;
|
value: number | RespawnTicket;
|
||||||
|
|
@ -10204,6 +10286,7 @@ export interface NpcDialoguesSelect<T extends boolean = true> {
|
||||||
model?: T;
|
model?: T;
|
||||||
promptVersion?: T;
|
promptVersion?: T;
|
||||||
promptSource?: T;
|
promptSource?: T;
|
||||||
|
connectionLabel?: T;
|
||||||
promptRevision?: T;
|
promptRevision?: T;
|
||||||
attempts?: T;
|
attempts?: T;
|
||||||
generatedAt?: T;
|
generatedAt?: T;
|
||||||
|
|
@ -12486,6 +12569,25 @@ export interface ArmaCommandsSelect<T extends boolean = true> {
|
||||||
updatedAt?: T;
|
updatedAt?: T;
|
||||||
createdAt?: T;
|
createdAt?: T;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
|
* via the `definition` "ai-connections_select".
|
||||||
|
*/
|
||||||
|
export interface AiConnectionsSelect<T extends boolean = true> {
|
||||||
|
label?: T;
|
||||||
|
baseUrl?: T;
|
||||||
|
modelId?: T;
|
||||||
|
apiKey?: T;
|
||||||
|
hasApiKey?: T;
|
||||||
|
clearApiKey?: T;
|
||||||
|
structuredMode?: T;
|
||||||
|
sendReasoningOff?: T;
|
||||||
|
lastTestOk?: T;
|
||||||
|
lastTestedAt?: T;
|
||||||
|
lastTestMessage?: T;
|
||||||
|
updatedAt?: T;
|
||||||
|
createdAt?: T;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* This interface was referenced by `Config`'s JSON-Schema
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "respawn-tickets_select".
|
* via the `definition` "respawn-tickets_select".
|
||||||
|
|
@ -13674,6 +13776,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
||||||
update?: T;
|
update?: T;
|
||||||
delete?: T;
|
delete?: T;
|
||||||
};
|
};
|
||||||
|
aiConnections?:
|
||||||
|
| T
|
||||||
|
| {
|
||||||
|
find?: T;
|
||||||
|
create?: T;
|
||||||
|
update?: T;
|
||||||
|
delete?: T;
|
||||||
|
};
|
||||||
respawnTickets?:
|
respawnTickets?:
|
||||||
| T
|
| T
|
||||||
| {
|
| {
|
||||||
|
|
@ -14173,6 +14283,29 @@ export interface NpcDialogueSetting {
|
||||||
updatedAt?: string | null;
|
updatedAt?: string | null;
|
||||||
createdAt?: string | null;
|
createdAt?: string | null;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Which model connection each AI surface uses. Leave a selector blank to use the Unsloth env defaults.
|
||||||
|
*
|
||||||
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
|
* via the `definition` "ai-settings".
|
||||||
|
*/
|
||||||
|
export interface AiSetting {
|
||||||
|
id: number;
|
||||||
|
/**
|
||||||
|
* The AI Compose field assistant across every allowlisted collection. Blank uses the env defaults.
|
||||||
|
*/
|
||||||
|
composeConnection?: (number | null) | AiConnection;
|
||||||
|
/**
|
||||||
|
* Whole-conversation NPC dialogue drafting. This one needs a model that reliably returns JSON in the configured structured mode. Blank uses the env defaults.
|
||||||
|
*/
|
||||||
|
dialogueDraftConnection?: (number | null) | AiConnection;
|
||||||
|
/**
|
||||||
|
* Per-line rewrites (Rewrite, Shorten, Sharpen). Prose only, so a cheaper model is usually fine. Blank uses the env defaults.
|
||||||
|
*/
|
||||||
|
dialogueLineConnection?: (number | null) | AiConnection;
|
||||||
|
updatedAt?: string | null;
|
||||||
|
createdAt?: string | null;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* This interface was referenced by `Config`'s JSON-Schema
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "game-rules_select".
|
* via the `definition` "game-rules_select".
|
||||||
|
|
@ -14312,6 +14445,18 @@ export interface NpcDialogueSettingsSelect<T extends boolean = true> {
|
||||||
createdAt?: T;
|
createdAt?: T;
|
||||||
globalType?: T;
|
globalType?: T;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
|
* via the `definition` "ai-settings_select".
|
||||||
|
*/
|
||||||
|
export interface AiSettingsSelect<T extends boolean = true> {
|
||||||
|
composeConnection?: T;
|
||||||
|
dialogueDraftConnection?: T;
|
||||||
|
dialogueLineConnection?: T;
|
||||||
|
updatedAt?: T;
|
||||||
|
createdAt?: T;
|
||||||
|
globalType?: T;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* This interface was referenced by `Config`'s JSON-Schema
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "collections_widget".
|
* via the `definition` "collections_widget".
|
||||||
|
|
|
||||||
|
|
@ -33,6 +33,8 @@ import { ModLists } from "@/collections/server/ModLists";
|
||||||
import { GameServers } from "@/collections/server/GameServers";
|
import { GameServers } from "@/collections/server/GameServers";
|
||||||
import { ArmaSyncEvents } from "@/collections/server/ArmaSyncEvents";
|
import { ArmaSyncEvents } from "@/collections/server/ArmaSyncEvents";
|
||||||
import { ArmaCommands } from "@/collections/server/ArmaCommands";
|
import { ArmaCommands } from "@/collections/server/ArmaCommands";
|
||||||
|
import { AiConnections } from "@/collections/server/AiConnections";
|
||||||
|
import { AiSettings } from "@/collections/server/AiSettings";
|
||||||
import { RespawnTickets } from "@/collections/server/RespawnTickets";
|
import { RespawnTickets } from "@/collections/server/RespawnTickets";
|
||||||
import { SupplyBoxes } from "@/collections/server/SupplyBoxes";
|
import { SupplyBoxes } from "@/collections/server/SupplyBoxes";
|
||||||
import { OperationEvents } from "@/collections/operations/OperationEvents";
|
import { OperationEvents } from "@/collections/operations/OperationEvents";
|
||||||
|
|
@ -123,13 +125,14 @@ import { surveyFormBuilderConfig } from "@/lib/surveys/formBuilderConfig";
|
||||||
import { buildComposeSystem, resolveProseShape, wrapProse } from "@/lib/ai/composeSystem";
|
import { buildComposeSystem, resolveProseShape, wrapProse } from "@/lib/ai/composeSystem";
|
||||||
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
|
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
|
||||||
import {
|
import {
|
||||||
|
connectionProvider,
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
generatePlainText,
|
generatePlainText,
|
||||||
MODEL_ID,
|
MODEL_ID,
|
||||||
MODEL_LABEL,
|
MODEL_LABEL,
|
||||||
REASONING_DISABLED,
|
reasoningOptionsFor,
|
||||||
unslothProvider,
|
|
||||||
} from "@/lib/ai/generate";
|
} from "@/lib/ai/generate";
|
||||||
|
import { resolveConnection } from "@/lib/ai/connections";
|
||||||
|
|
||||||
// AI Compose allowlist: the plugin's default init makes an LLM call per field
|
// AI Compose allowlist: the plugin's default init makes an LLM call per field
|
||||||
// to seed prompts. Returning false here skips a field (no instruction row, no
|
// to seed prompts. Returning false here skips a field (no instruction row, no
|
||||||
|
|
@ -346,6 +349,7 @@ const collections = [
|
||||||
GameServers,
|
GameServers,
|
||||||
ArmaSyncEvents,
|
ArmaSyncEvents,
|
||||||
ArmaCommands,
|
ArmaCommands,
|
||||||
|
AiConnections,
|
||||||
RespawnTickets,
|
RespawnTickets,
|
||||||
SupplyBoxes,
|
SupplyBoxes,
|
||||||
|
|
||||||
|
|
@ -514,7 +518,7 @@ export default buildConfig({
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
globals: [GameRules, Shims, MinigameRules, DiscordPresence, NpcDialogueSettings],
|
globals: [GameRules, Shims, MinigameRules, DiscordPresence, NpcDialogueSettings, AiSettings],
|
||||||
collections: scopedCollections,
|
collections: scopedCollections,
|
||||||
editor: ptfLexicalEditor(),
|
editor: ptfLexicalEditor(),
|
||||||
secret: process.env.PAYLOAD_SECRET || "",
|
secret: process.env.PAYLOAD_SECRET || "",
|
||||||
|
|
@ -729,7 +733,10 @@ export default buildConfig({
|
||||||
generationModels: [
|
generationModels: [
|
||||||
{
|
{
|
||||||
id: MODEL_ID,
|
id: MODEL_ID,
|
||||||
name: MODEL_LABEL,
|
// The dropdown cannot list database connections (plugin config is built
|
||||||
|
// once at boot), so it names the routing rule instead of a model. The
|
||||||
|
// handler resolves the admin-selected connection per request.
|
||||||
|
name: "Active AI connection",
|
||||||
fields: ["text", "textarea", "richText"],
|
fields: ["text", "textarea", "richText"],
|
||||||
handler: async (
|
handler: async (
|
||||||
prompt: string,
|
prompt: string,
|
||||||
|
|
@ -742,7 +749,10 @@ export default buildConfig({
|
||||||
temperature?: number;
|
temperature?: number;
|
||||||
},
|
},
|
||||||
) => {
|
) => {
|
||||||
const model = options.model || DEFAULT_MODEL;
|
// The admin-selected Compose connection. Null means the env defaults,
|
||||||
|
// which is the pre-connection behaviour.
|
||||||
|
const connection = await resolveConnection(null, "compose");
|
||||||
|
const model = connection?.modelId || options.model || DEFAULT_MODEL;
|
||||||
const shape = resolveProseShape(options.schema);
|
const shape = resolveProseShape(options.schema);
|
||||||
|
|
||||||
// One contract for every supported field: the model writes prose and
|
// One contract for every supported field: the model writes prose and
|
||||||
|
|
@ -756,7 +766,7 @@ export default buildConfig({
|
||||||
prompt,
|
prompt,
|
||||||
buildComposeSystem({ pluginSystem: options.system }),
|
buildComposeSystem({ pluginSystem: options.system }),
|
||||||
model,
|
model,
|
||||||
{ maxTokens: options.maxTokens, temperature: options.temperature },
|
{ maxTokens: options.maxTokens, temperature: options.temperature, connection },
|
||||||
);
|
);
|
||||||
const json = wrapProse(shape, text);
|
const json = wrapProse(shape, text);
|
||||||
const ts = new ReadableStream({
|
const ts = new ReadableStream({
|
||||||
|
|
@ -772,7 +782,7 @@ export default buildConfig({
|
||||||
// structured path rather than guessing at a wrapper.
|
// structured path rather than guessing at a wrapper.
|
||||||
const streamResult = streamObject({
|
const streamResult = streamObject({
|
||||||
maxOutputTokens: options.maxTokens || 5000,
|
maxOutputTokens: options.maxTokens || 5000,
|
||||||
model: unslothProvider(model),
|
model: connectionProvider(connection)(model),
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
console.error("Unsloth generateObject: ", error);
|
console.error("Unsloth generateObject: ", error);
|
||||||
},
|
},
|
||||||
|
|
@ -784,7 +794,7 @@ export default buildConfig({
|
||||||
openai: {
|
openai: {
|
||||||
strictJsonSchema: true,
|
strictJsonSchema: true,
|
||||||
structuredOutputs: true,
|
structuredOutputs: true,
|
||||||
...REASONING_DISABLED,
|
...reasoningOptionsFor(connection),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
@ -808,7 +818,13 @@ export default buildConfig({
|
||||||
return createTextStreamResponse({ textStream });
|
return createTextStreamResponse({ textStream });
|
||||||
},
|
},
|
||||||
generateText: async (prompt: string, system: string) => {
|
generateText: async (prompt: string, system: string) => {
|
||||||
const { text } = await generatePlainText(prompt, system, DEFAULT_MODEL);
|
const connection = await resolveConnection(null, "compose");
|
||||||
|
const { text } = await generatePlainText(
|
||||||
|
prompt,
|
||||||
|
system,
|
||||||
|
connection?.modelId || DEFAULT_MODEL,
|
||||||
|
{ connection },
|
||||||
|
);
|
||||||
return text;
|
return text;
|
||||||
},
|
},
|
||||||
output: "text",
|
output: "text",
|
||||||
|
|
|
||||||
213
tests/int/ai-connections.int.spec.ts
Normal file
213
tests/int/ai-connections.int.spec.ts
Normal file
|
|
@ -0,0 +1,213 @@
|
||||||
|
import type { Payload } from "payload";
|
||||||
|
import { beforeAll, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { getTestPayload } from "../helpers/get-test-payload";
|
||||||
|
import { resolveConnection } from "@/lib/ai/connections";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The connection record is where a swapped provider can break silently, so the two
|
||||||
|
* things that must not drift are pinned here: the write-only key contract, and the
|
||||||
|
* resolution the AI calls actually perform.
|
||||||
|
*
|
||||||
|
* The key rules exist because the field's read access denies everyone, so the admin
|
||||||
|
* form can never show the stored value. That makes a blank submission ambiguous
|
||||||
|
* ("unchanged" or "delete?"), which is why blank means unchanged and `clearApiKey`
|
||||||
|
* is the only delete.
|
||||||
|
*/
|
||||||
|
let payload: Payload;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getTestPayload();
|
||||||
|
});
|
||||||
|
|
||||||
|
const createConnection = (overrides: Record<string, unknown> = {}) =>
|
||||||
|
payload.create({
|
||||||
|
collection: "ai-connections",
|
||||||
|
data: {
|
||||||
|
label: "Unit box",
|
||||||
|
baseUrl: "http://192.168.1.7:8888/v1",
|
||||||
|
modelId: "unsloth/Ornith-1.0-9B-GGUF",
|
||||||
|
structuredMode: "json_schema",
|
||||||
|
sendReasoningOff: true,
|
||||||
|
...overrides,
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("ai-connections key handling", () => {
|
||||||
|
it("denies the key field to every reader that does not bypass access", async () => {
|
||||||
|
const created = await createConnection({ apiKey: "sk-test-secret" });
|
||||||
|
expect(created.hasApiKey).toBe(true);
|
||||||
|
|
||||||
|
// The local API defaults to overrideAccess: true, so a plain findByID proves
|
||||||
|
// nothing about the gate. Assert the field's own access rule instead: this is
|
||||||
|
// what strips the value from REST, GraphQL and the admin form.
|
||||||
|
const collection = payload.config.collections.find((c) => c.slug === "ai-connections");
|
||||||
|
const field = collection?.fields.find(
|
||||||
|
(candidate) => "name" in candidate && candidate.name === "apiKey",
|
||||||
|
) as { access?: { read?: (args: unknown) => unknown } } | undefined;
|
||||||
|
|
||||||
|
expect(typeof field?.access?.read).toBe("function");
|
||||||
|
expect(await field?.access?.read?.({ req: {} })).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides the collection from a caller without the superuser tier", async () => {
|
||||||
|
await createConnection({ apiKey: "sk-test-secret" });
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
payload.find({ collection: "ai-connections", overrideAccess: false, depth: 0 }),
|
||||||
|
).rejects.toThrow(/not allowed/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the stored key when the form submits it blank", async () => {
|
||||||
|
const created = await createConnection({ apiKey: "sk-first" });
|
||||||
|
|
||||||
|
const updated = await payload.update({
|
||||||
|
collection: "ai-connections",
|
||||||
|
id: created.id,
|
||||||
|
data: { label: "Renamed", apiKey: "" },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(updated.hasApiKey).toBe(true);
|
||||||
|
|
||||||
|
const stored = await payload.findByID({
|
||||||
|
collection: "ai-connections",
|
||||||
|
id: created.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
expect((stored as { apiKey?: string | null }).apiKey).toBe("sk-first");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replaces the key when a new value is submitted", async () => {
|
||||||
|
const created = await createConnection({ apiKey: "sk-first" });
|
||||||
|
|
||||||
|
await payload.update({
|
||||||
|
collection: "ai-connections",
|
||||||
|
id: created.id,
|
||||||
|
data: { apiKey: "sk-second" },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const stored = await payload.findByID({
|
||||||
|
collection: "ai-connections",
|
||||||
|
id: created.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
expect((stored as { apiKey?: string | null }).apiKey).toBe("sk-second");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears the key only when clearApiKey is set, and resets the flag", async () => {
|
||||||
|
const created = await createConnection({ apiKey: "sk-first" });
|
||||||
|
|
||||||
|
const cleared = await payload.update({
|
||||||
|
collection: "ai-connections",
|
||||||
|
id: created.id,
|
||||||
|
data: { clearApiKey: true },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(cleared.hasApiKey).toBe(false);
|
||||||
|
// The checkbox is an action: leaving it ticked would clear a key set later.
|
||||||
|
expect(cleared.clearApiKey).toBe(false);
|
||||||
|
|
||||||
|
const stored = await payload.findByID({
|
||||||
|
collection: "ai-connections",
|
||||||
|
id: created.id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
expect((stored as { apiKey?: string | null }).apiKey ?? null).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolveConnection", () => {
|
||||||
|
it("returns null when a surface has no connection selected", async () => {
|
||||||
|
await payload.updateGlobal({
|
||||||
|
slug: "ai-settings",
|
||||||
|
data: { composeConnection: null, dialogueDraftConnection: null, dialogueLineConnection: null },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(await resolveConnection(payload, "compose")).toBeNull();
|
||||||
|
expect(await resolveConnection(payload, "dialogue-draft")).toBeNull();
|
||||||
|
expect(await resolveConnection(payload, "dialogue-line")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves the connection selected for that surface only", async () => {
|
||||||
|
const draft = await createConnection({
|
||||||
|
label: "Draft box",
|
||||||
|
modelId: "draft-model",
|
||||||
|
apiKey: "sk-draft",
|
||||||
|
structuredMode: "json_object",
|
||||||
|
});
|
||||||
|
const line = await createConnection({
|
||||||
|
label: "Line box",
|
||||||
|
modelId: "line-model",
|
||||||
|
sendReasoningOff: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
await payload.updateGlobal({
|
||||||
|
slug: "ai-settings",
|
||||||
|
data: {
|
||||||
|
composeConnection: null,
|
||||||
|
dialogueDraftConnection: draft.id,
|
||||||
|
dialogueLineConnection: line.id,
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const draftResolved = await resolveConnection(payload, "dialogue-draft");
|
||||||
|
expect(draftResolved).toMatchObject({
|
||||||
|
label: "Draft box",
|
||||||
|
modelId: "draft-model",
|
||||||
|
apiKey: "sk-draft",
|
||||||
|
structuredMode: "json_object",
|
||||||
|
});
|
||||||
|
|
||||||
|
const lineResolved = await resolveConnection(payload, "dialogue-line");
|
||||||
|
expect(lineResolved).toMatchObject({
|
||||||
|
label: "Line box",
|
||||||
|
modelId: "line-model",
|
||||||
|
sendReasoningOff: false,
|
||||||
|
structuredMode: "json_schema",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Compose was left blank, so it must keep using the env defaults.
|
||||||
|
expect(await resolveConnection(payload, "compose")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the env defaults for a half-filled connection", async () => {
|
||||||
|
const connection = await createConnection({ modelId: " " });
|
||||||
|
|
||||||
|
await payload.updateGlobal({
|
||||||
|
slug: "ai-settings",
|
||||||
|
data: { dialogueDraftConnection: connection.id },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(await resolveConnection(payload, "dialogue-draft")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resets a passing test result when the configuration changes", async () => {
|
||||||
|
const connection = await createConnection();
|
||||||
|
await payload.update({
|
||||||
|
collection: "ai-connections",
|
||||||
|
id: connection.id,
|
||||||
|
data: { lastTestOk: true, lastTestMessage: "passed" },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const changed = await payload.update({
|
||||||
|
collection: "ai-connections",
|
||||||
|
id: connection.id,
|
||||||
|
data: { modelId: "some-other-model" },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(changed.lastTestOk).toBe(false);
|
||||||
|
expect(changed.lastTestMessage).toContain("run the test again");
|
||||||
|
});
|
||||||
|
});
|
||||||
157
tests/int/ai-generate-modes.int.spec.ts
Normal file
157
tests/int/ai-generate-modes.int.spec.ts
Normal file
|
|
@ -0,0 +1,157 @@
|
||||||
|
import { createServer } from "node:http";
|
||||||
|
import type { AddressInfo } from "node:net";
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { generatePlainText, generateStructured } from "@/lib/ai/generate";
|
||||||
|
import type { AiConnection } from "@/lib/ai/generate";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The provider-aware paths are the ones a connection change can break, and they are
|
||||||
|
* pure HTTP: a local server stands in for the model so the request body and the
|
||||||
|
* reply parsing are checked without a GPU, a key, or the real model host.
|
||||||
|
*
|
||||||
|
* What is pinned here: the connection's URL and model win, the key travels in the
|
||||||
|
* header, the reasoning toggle is honoured (a strict provider rejects unknown
|
||||||
|
* fields), the non-strict structured modes actually degrade, and a provider error
|
||||||
|
* surfaces its body instead of a bare status.
|
||||||
|
*/
|
||||||
|
type Captured = { url: string; auth: string | undefined; body: Record<string, unknown> };
|
||||||
|
|
||||||
|
let captured: Captured[] = [];
|
||||||
|
let reply = "";
|
||||||
|
let status = 200;
|
||||||
|
let server: ReturnType<typeof createServer>;
|
||||||
|
let baseUrl = "";
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
server = createServer((req, res) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
req.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||||
|
req.on("end", () => {
|
||||||
|
captured.push({
|
||||||
|
url: req.url ?? "",
|
||||||
|
auth: req.headers.authorization,
|
||||||
|
body: JSON.parse(Buffer.concat(chunks).toString() || "{}") as Record<string, unknown>,
|
||||||
|
});
|
||||||
|
res.writeHead(status, { "Content-Type": "application/json" });
|
||||||
|
res.end(
|
||||||
|
status === 200
|
||||||
|
? JSON.stringify({ choices: [{ message: { content: reply }, finish_reason: "stop" }] })
|
||||||
|
: JSON.stringify({ error: { message: reply } }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||||
|
const address = server.address() as AddressInfo;
|
||||||
|
baseUrl = `http://127.0.0.1:${address.port}/v1`;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||||
|
});
|
||||||
|
|
||||||
|
const connection = (overrides: Partial<AiConnection> = {}): AiConnection => ({
|
||||||
|
label: "Probe box",
|
||||||
|
baseUrl,
|
||||||
|
modelId: "probe-model",
|
||||||
|
apiKey: "sk-probe",
|
||||||
|
structuredMode: "json_schema",
|
||||||
|
sendReasoningOff: true,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const last = () => captured[captured.length - 1];
|
||||||
|
|
||||||
|
describe("generatePlainText with a connection", () => {
|
||||||
|
it("posts to the connection's endpoint with its model and key", async () => {
|
||||||
|
captured = [];
|
||||||
|
reply = "ready";
|
||||||
|
|
||||||
|
const result = await generatePlainText("ping", "probe", "env-model", {
|
||||||
|
connection: connection(),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.text).toBe("ready");
|
||||||
|
expect(last().url).toBe("/v1/chat/completions");
|
||||||
|
expect(last().auth).toBe("Bearer sk-probe");
|
||||||
|
expect(last().body.model).toBe("probe-model");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends reasoning off when the connection allows it, and omits it otherwise", async () => {
|
||||||
|
captured = [];
|
||||||
|
reply = "ok";
|
||||||
|
|
||||||
|
await generatePlainText("ping", "probe", "env-model", { connection: connection() });
|
||||||
|
expect(last().body.reasoning_effort).toBe("none");
|
||||||
|
|
||||||
|
await generatePlainText("ping", "probe", "env-model", {
|
||||||
|
connection: connection({ sendReasoningOff: false }),
|
||||||
|
});
|
||||||
|
expect(last().body).not.toHaveProperty("reasoning_effort");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports a provider error with its status and body", async () => {
|
||||||
|
captured = [];
|
||||||
|
status = 401;
|
||||||
|
reply = "Invalid API key";
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
generatePlainText("ping", "probe", "env-model", { connection: connection() }),
|
||||||
|
).rejects.toThrow(/Probe box API error: 401[\s\S]*Invalid API key/);
|
||||||
|
|
||||||
|
status = 200;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("generateStructured modes", () => {
|
||||||
|
const schema = {
|
||||||
|
type: "object",
|
||||||
|
properties: { status: { type: "string" } },
|
||||||
|
required: ["status"],
|
||||||
|
additionalProperties: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("parses a fenced reply in prompt mode and describes the schema", async () => {
|
||||||
|
captured = [];
|
||||||
|
reply = '```json\n{"status":"ready"}\n```';
|
||||||
|
|
||||||
|
const result = await generateStructured<{ status: string }>({
|
||||||
|
prompt: "probe",
|
||||||
|
schema,
|
||||||
|
connection: connection({ structuredMode: "prompt" }),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.object.status).toBe("ready");
|
||||||
|
// No provider-side JSON mode is claimed, so none is requested.
|
||||||
|
expect(last().body).not.toHaveProperty("response_format");
|
||||||
|
const messages = last().body.messages as { role: string; content: string }[];
|
||||||
|
expect(messages[0].content).toContain("additionalProperties");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("asks for json_object mode when the connection says so", async () => {
|
||||||
|
captured = [];
|
||||||
|
reply = '{"status":"ready"}';
|
||||||
|
|
||||||
|
const result = await generateStructured<{ status: string }>({
|
||||||
|
prompt: "probe",
|
||||||
|
schema,
|
||||||
|
connection: connection({ structuredMode: "json_object" }),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.object.status).toBe("ready");
|
||||||
|
expect(last().body.response_format).toEqual({ type: "json_object" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("surfaces unparsable output as an error, so the caller's retry can act on it", async () => {
|
||||||
|
captured = [];
|
||||||
|
reply = "I am not JSON at all.";
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
generateStructured({
|
||||||
|
prompt: "probe",
|
||||||
|
schema,
|
||||||
|
connection: connection({ structuredMode: "prompt" }),
|
||||||
|
}),
|
||||||
|
).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue