1
0
Fork 0

fix(ai-compose): one prose output contract for every field prompt

Rich text fields received the plugin's richText system prompt, which
demanded lexical JSON and a blog layout of [paragraph]/[heading] markers,
next to an instruction asking for plain prose. The model answered by
arguing about the conflict, and that argument was saved into the field.
Text fields had the mirror problem: a prose instruction sent over a
transport that forced JSON.

Every field now asks for plain prose and nothing else, and the handler
assembles the JSON the Compose client already parses:

- src/lib/ai/composeSystem.ts owns the shared rules, keeps only the
  plugin's [[[BLOCK_<n>]]] echo instruction for richText, and wraps prose
  into lexical JSON or a single field value.
- payload.config.ts routes every wrappable schema through
  generatePlainText; streamObject stays only as the fallback for shapes
  prose cannot fill, such as a hasMany array.
- Truncated output reaches the client again (finish_reason length was
  swallowed on the prose path).

Adds tests/int/ai-compose-system.int.spec.ts (10 cases) and picks up the
generated payload-types.ts drift for the model field description.
This commit is contained in:
Jason Fraley 2026-10-19 13:03:33 -04:00
parent d82e8057ba
commit 3d73aee193
4 changed files with 316 additions and 47 deletions

124
src/lib/ai/composeSystem.ts Normal file
View file

@ -0,0 +1,124 @@
/**
* The single output contract shared by every AI Compose generation.
*
* The plugin builds a richText system prompt that asks the model for lexical
* JSON and injects a blog layout of `[paragraph]` / `[heading]` markers, while
* the same field's instruction asks for plain prose with "no markdown, no
* lists, no headings". Both reach the model in one request, and it answers by
* arguing about the conflict (which the handler then saves as the first
* paragraph of the field).
*
* Every field now follows one rule instead: the model is asked for plain prose
* and nothing else, and the application assembles the JSON the Compose client
* parses. `AI_OUTPUT_RULES` is appended to every generation; the helpers below
* decide what prose is wrapped into for a given field schema.
*/
export const AI_OUTPUT_RULES = `OUTPUT RULES:
Respond with plain prose only. Do not output JSON, code fences, schema definitions, or layout markers.
Ordinary sentences and paragraphs are the entire expected output; the application converts them into the editor's format.
CRITICAL:
Never use em-dashes (\u2014) in your writing. Avoid obvious AI tells.`;
/**
* The plugin's block-placeholder paragraph. Preserved embed blocks are replaced
* with `[[[BLOCK_<n>]]]` tokens before generation and swapped back afterwards, so
* the model has to echo the tokens verbatim for the blocks to survive. It is the
* only instruction from the plugin's richText system worth keeping.
*/
const BLOCK_PLACEHOLDER_INSTRUCTION =
/- The text may contain one or more standalone placeholder tokens[\s\S]*?surrounding text\./;
export const extractBlockPlaceholderInstruction = (pluginSystem?: string): string => {
if (!pluginSystem) return "";
const match = pluginSystem.match(BLOCK_PLACEHOLDER_INSTRUCTION);
return match ? match[0].trim() : "";
};
export const buildComposeSystem = ({
pluginSystem,
fieldType,
}: {
pluginSystem?: string;
fieldType?: string;
}): string => {
const parts: string[] = [];
if (fieldType === "richText") {
const blockInstruction = extractBlockPlaceholderInstruction(pluginSystem);
if (blockInstruction) parts.push(blockInstruction);
}
parts.push(AI_OUTPUT_RULES);
return parts.join("\n\n");
};
type JsonSchemaLike = {
definitions?: unknown;
properties?: Record<string, { type?: string } | undefined>;
};
export type ProseShape = { kind: "lexical" } | { kind: "field"; key: string };
/**
* Whether a generation schema is one this module knows how to fill with prose:
* the lexical editor schema for richText (identified by its `definitions`), or
* a single string property for text/textarea. Anything else (e.g. a hasMany
* array) is left to the handler's structured fallback.
*/
export const resolveProseShape = (schema: unknown): ProseShape | null => {
if (!schema || typeof schema !== "object") return null;
const candidate = schema as JsonSchemaLike;
if (candidate.definitions) return { kind: "lexical" };
const keys = Object.keys(candidate.properties ?? {});
if (keys.length !== 1) return null;
const property = candidate.properties?.[keys[0]];
if (property?.type !== "string") return null;
return { kind: "field", key: keys[0] };
};
export const wrapProse = (shape: ProseShape, text: string): Record<string, unknown> =>
shape.kind === "lexical" ? plainTextToLexicalJson(text) : { [shape.key]: text };
export function plainTextToLexicalJson(text: string): Record<string, unknown> {
const paragraphs = text.split(/\n\n+/).filter((p) => p.trim());
const children = paragraphs.map((para) => ({
type: "paragraph",
children: [
{
type: "text",
text: para.trim(),
format: 0,
style: "",
mode: "normal",
detail: 0,
direction: "ltr",
indent: 0,
version: 1,
},
],
direction: "ltr",
format: "start",
indent: 0,
textFormat: 0,
textStyle: "",
version: 1,
}));
return {
root: {
type: "root",
children,
direction: "ltr",
format: "",
indent: 0,
version: 1,
},
};
}

View file

@ -6597,6 +6597,9 @@ export interface PluginAiInstruction {
system?: string | null;
layout?: string | null;
'ornith-9b-settings'?: {
/**
* Leave blank to use the UNSLOTH_MODEL environment variable.
*/
model?: string | null;
};
updatedAt: string;

View file

@ -109,6 +109,7 @@ import type { SeedPromptFunction } from "@ai-stack/payloadcms/types";
import { mcpPlugin } from "@payloadcms/plugin-mcp";
import { formBuilderPlugin } from "@payloadcms/plugin-form-builder";
import { surveyFormBuilderConfig } from "@/lib/surveys/formBuilderConfig";
import { buildComposeSystem, resolveProseShape, wrapProse } from "@/lib/ai/composeSystem";
import { createOpenAI } from "@ai-sdk/openai";
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
@ -210,7 +211,7 @@ const staticAiPrompt = (
: `Suggest a single fitting title for the ${noun} {{ title }}. Reply with the title only, no explanation.`;
default:
if (fieldType === "richText") {
return `Write long-form content for the "${fieldLabel}" section of the ${noun} {{ title }}. Structured prose with an introduction, clear sections, and a conclusion.`;
return `Write long-form content for the "${fieldLabel}" section of the ${noun} {{ title }}. Several paragraphs of plain prose with an opening, supporting detail, and a closing sentence.`;
}
return `Write suitable content for the "${fieldLabel}" of the ${noun} {{ title }}. Plain prose, concise and relevant.`;
}
@ -237,44 +238,6 @@ const aiFieldSeedPrompts: SeedPromptFunction = ({ path, fieldType, fieldLabel })
return false;
};
function plainTextToLexicalJson(text: string): Record<string, unknown> {
const paragraphs = text.split(/\n\n+/).filter((p) => p.trim());
const children = paragraphs.map((para) => ({
type: "paragraph",
children: [
{
type: "text",
text: para.trim(),
format: 0,
style: "",
mode: "normal",
detail: 0,
direction: "ltr",
indent: 0,
version: 1,
},
],
direction: "ltr",
format: "start",
indent: 0,
textFormat: 0,
textStyle: "",
version: 1,
}));
return {
root: {
type: "root",
children,
direction: "ltr",
format: "",
indent: 0,
version: 1,
},
};
}
// Gemma tends to answer schema-y prompts with fenced JSON blobs. The plain-text
// fallback is meant to produce prose that plainTextToLexicalJson wraps into
// paragraphs, so strip any markdown code fences before using the output.
@ -284,7 +247,19 @@ const stripCodeFences = (text: string): string =>
.replace(/\n?```\s*$/, "")
.trim();
async function generatePlainText(prompt: string, system: string, model: string): Promise<string> {
type PlainTextResult = { text: string; truncated: boolean };
// Every Compose field now runs through this one call: the model is asked for
// prose and the handler wraps the result into the JSON the client parses. The
// token cap and temperature mirror what the old structured path used, and
// `finish_reason === "length"` is reported so the truncation marker reaches the
// client (the prose path previously swallowed it).
async function generatePlainText(
prompt: string,
system: string,
model: string,
options: { maxTokens?: number; temperature?: number } = {},
): Promise<PlainTextResult> {
const baseUrl = process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1";
const response = await fetch(`${baseUrl}/chat/completions`, {
method: "POST",
@ -299,6 +274,8 @@ async function generatePlainText(prompt: string, system: string, model: string):
{ role: "user", content: prompt },
],
stream: false,
max_tokens: options.maxTokens ?? 5000,
temperature: options.temperature ?? 0.7,
...REASONING_DISABLED,
}),
});
@ -308,7 +285,11 @@ async function generatePlainText(prompt: string, system: string, model: string):
}
const result = await response.json();
return stripCodeFences(result.choices[0].message.content ?? "");
const choice = result.choices?.[0];
return {
text: stripCodeFences(choice?.message?.content ?? ""),
truncated: choice?.finish_reason === "length",
};
}
const filename = fileURLToPath(import.meta.url);
@ -800,23 +781,35 @@ export default buildConfig({
},
) => {
const model = options.model || DEFAULT_MODEL;
const shape = resolveProseShape(options.schema);
if (options.schema?.definitions) {
const text = await generatePlainText(
// One contract for every supported field: the model writes prose and
// the JSON the Compose client parses is assembled here. The plugin's
// richText system asks for lexical JSON and a blog layout, which is
// exactly what contradicted the prose instruction, so only its
// block-placeholder paragraph survives (see composeSystem.ts).
if (shape) {
const { text, truncated } = await generatePlainText(
prompt,
`${options.system}\n\nOUTPUT RULES:\nRespond with plain prose paragraphs only. Do not output JSON, code fences, or schema definitions. Plain sentences and paragraphs are the entire expected output.`,
buildComposeSystem({
pluginSystem: options.system,
fieldType: shape.kind === "lexical" ? "richText" : "text",
}),
model,
{ maxTokens: options.maxTokens, temperature: options.temperature },
);
const lexicalJson = plainTextToLexicalJson(text);
const json = wrapProse(shape, text);
const ts = new ReadableStream({
start(controller) {
controller.enqueue(JSON.stringify(lexicalJson));
controller.enqueue(JSON.stringify(json) + (truncated ? "\u0000" : ""));
controller.close();
},
});
return createTextStreamResponse({ textStream: ts });
}
// Shapes we do not convert (e.g. a hasMany array) keep the
// structured path rather than guessing at a wrapper.
const streamResult = streamObject({
maxOutputTokens: options.maxTokens || 5000,
model: unslothProvider(model),
@ -855,7 +848,8 @@ export default buildConfig({
return createTextStreamResponse({ textStream });
},
generateText: async (prompt: string, system: string) => {
return generatePlainText(prompt, system, DEFAULT_MODEL);
const { text } = await generatePlainText(prompt, system, DEFAULT_MODEL);
return text;
},
output: "text",
settings: {

View file

@ -0,0 +1,148 @@
import { describe, expect, it } from "vitest";
import {
AI_OUTPUT_RULES,
buildComposeSystem,
extractBlockPlaceholderInstruction,
plainTextToLexicalJson,
resolveProseShape,
wrapProse,
} from "@/lib/ai/composeSystem";
// The exact system `@ai-stack/payloadcms@3.2.30` builds for a richText field
// (dist/endpoints/index.js -> buildRichTextSystem). Captured verbatim so that a
// plugin upgrade which changes the wording fails this spec loudly instead of
// silently letting the JSON/layout instructions back into the model's prompt.
const PLUGIN_RICH_TEXT_SYSTEM = `INSTRUCTIONS:
You are a highly skilled and professional blog writer,
renowned for crafting engaging and well-organized articles.
RULES:
- Generate original and unique content based on the given topic.
- Ensure the output follows the provided rich text JSON schema exactly.
- Produce valid JSON with no undefined or null values.
- The text may contain one or more standalone placeholder tokens of the exact form
"[[[BLOCK_<number>]]]" (e.g. "[[[BLOCK_0]]]").
These represent embedded content you cannot see. Reproduce every such token EXACTLY as given,
completely unchanged (do not translate, reword, remove, or merge it with other text), as its
own paragraph, in the same relative position within the surrounding text.
---
LAYOUT INSTRUCTIONS:
[paragraph] - Write a concise introduction (2-3 sentences) that outlines the main topic.
[horizontalrule] - Insert a horizontal rule to separate the introduction from the main content.
[list] - Create a list with 3-5 items. Each list item should contain:
a. [heading] - A brief, descriptive heading (up to 5 words)
b. [paragraph] - A short explanation or elaboration (1-2 sentences)
---
ADDITIONAL GUIDELINES:
- Ensure coherence and logical flow between all sections.
`;
describe("buildComposeSystem", () => {
it("strips the plugin's JSON rules and layout markers from the model's system prompt", () => {
const system = buildComposeSystem({
pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
fieldType: "richText",
});
expect(system).not.toContain("rich text JSON schema");
expect(system).not.toContain("Produce valid JSON");
expect(system).not.toMatch(/LAYOUT INSTRUCTIONS/);
expect(system).not.toMatch(/\[paragraph\]|\[horizontalrule\]|\[list\]|\[heading\]|\[quote\]/);
});
it("keeps the block-placeholder paragraph and nothing else from the plugin system", () => {
const system = buildComposeSystem({
pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
fieldType: "richText",
});
expect(system).toContain("- The text may contain one or more standalone placeholder tokens");
expect(system).toContain("[[[BLOCK_<number>]]]");
expect(system).not.toContain("professional blog writer");
});
it("asks for prose plus the em-dash rule exactly once for every field type", () => {
for (const fieldType of ["richText", "text", "textarea"]) {
const system = buildComposeSystem({
pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
fieldType,
});
expect(system.match(/Never use em-dashes/g)).toHaveLength(1);
expect(system).toContain("Respond with plain prose only.");
expect(system).not.toContain("rich text JSON schema");
expect(system).not.toContain("Produce valid JSON");
}
});
it("sends short fields only the shared rules, with no plugin material", () => {
const system = buildComposeSystem({
pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
fieldType: "text",
});
expect(system).toBe(AI_OUTPUT_RULES);
});
it("sends the real em-dash character to the model", () => {
expect(AI_OUTPUT_RULES).toContain("em-dashes (\u2014)");
});
});
describe("extractBlockPlaceholderInstruction", () => {
it("returns the placeholder paragraph without the surrounding rules", () => {
const block = extractBlockPlaceholderInstruction(PLUGIN_RICH_TEXT_SYSTEM);
expect(block.startsWith("- The text may contain")).toBe(true);
expect(block.endsWith("surrounding text.")).toBe(true);
expect(block).not.toMatch(/JSON/);
});
it("returns an empty string when there is nothing to keep", () => {
expect(extractBlockPlaceholderInstruction(undefined)).toBe("");
expect(extractBlockPlaceholderInstruction("just some prose")).toBe("");
});
});
describe("resolveProseShape / wrapProse", () => {
const lexicalSchema = { definitions: { root: {} }, type: "object" };
const textSchema = {
type: "object",
properties: { name: { type: "string" } },
required: ["name"],
};
it("wraps prose into lexical JSON for a richText schema", () => {
const shape = resolveProseShape(lexicalSchema);
expect(shape).toEqual({ kind: "lexical" });
const json = wrapProse(shape!, "First paragraph.\n\nSecond paragraph.");
expect(json).toEqual(plainTextToLexicalJson("First paragraph.\n\nSecond paragraph."));
const root = (json as { root: { children: Array<{ children: Array<{ text: string }> }> } }).root;
expect(root.children).toHaveLength(2);
expect(root.children[0].children[0].text).toBe("First paragraph.");
});
it("wraps prose into the field's own key for a single string property", () => {
const shape = resolveProseShape(textSchema);
expect(shape).toEqual({ kind: "field", key: "name" });
expect(wrapProse(shape!, "Barracks")).toEqual({ name: "Barracks" });
});
it("declines shapes it cannot wrap", () => {
expect(
resolveProseShape({ type: "object", properties: { tags: { type: "array" } } }),
).toBeNull();
expect(
resolveProseShape({
type: "object",
properties: { a: { type: "string" }, b: { type: "string" } },
}),
).toBeNull();
expect(resolveProseShape(undefined)).toBeNull();
});
});