1
0
Fork 0

Compare commits

..

No commits in common. "53387c957fcd6a6d8db9bb4abf492764caceb078" and "2713a786e4c929a635dd9ed5351a590fa99a9100" have entirely different histories.

5 changed files with 59 additions and 160 deletions

View file

@ -1,13 +1,5 @@
# Changelog # Changelog
# v0.12.11
### Fixes
- Various bug fixes and improvements.
---
# v0.12.10 # v0.12.10
### Improvements ### Improvements

View file

@ -1,6 +1,6 @@
{ {
"name": "polaris-task-force", "name": "polaris-task-force",
"version": "0.12.11", "version": "0.12.10",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.", "description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",

View file

@ -1,18 +1,17 @@
/** /**
* The single output contract shared by every AI Compose generation. * The single output contract shared by every AI Compose generation.
* *
* The plugin sends a `system` prompt that carries the real task: the field's own * The plugin builds a richText system prompt that asks the model for lexical
* system prompt for Compose, or the named action's instruction (Expand, * JSON and injects a blog layout of `[paragraph]` / `[heading]` markers, while
* Simplify, Rephrase, Proofread, Summarize, Tone, Translate) for an action. * the same field's instruction asks for plain prose with "no markdown, no
* For richText Compose it wraps that task in `buildRichTextSystem`, which adds * lists, no headings". Both reach the model in one request, and it answers by
* rules demanding lexical JSON and a blog layout of `[paragraph]` / `[heading]` * arguing about the conflict (which the handler then saves as the first
* markers, contradicting the prose instruction and making the model argue about * paragraph of the field).
* the conflict instead of writing.
* *
* So the caller's system prompt is kept and only the contradicting part is * Every field now follows one rule instead: the model is asked for plain prose
* removed: every field follows one rule (plain prose out; the application * and nothing else, and the application assembles the JSON the Compose client
* assembles the JSON the Compose client parses), while the action instructions * parses. `AI_OUTPUT_RULES` is appended to every generation; the helpers below
* reach the model unchanged. `AI_OUTPUT_RULES` is appended to every generation. * decide what prose is wrapped into for a given field schema.
*/ */
export const AI_OUTPUT_RULES = `OUTPUT RULES: export const AI_OUTPUT_RULES = `OUTPUT RULES:
@ -26,7 +25,7 @@ Never use em-dashes (\u2014) in your writing. Avoid obvious AI tells.`;
* The plugin's block-placeholder paragraph. Preserved embed blocks are replaced * The plugin's block-placeholder paragraph. Preserved embed blocks are replaced
* with `[[[BLOCK_<n>]]]` tokens before generation and swapped back afterwards, so * 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 * the model has to echo the tokens verbatim for the blocks to survive. It is the
* only part of the plugin's richText RULES block worth keeping. * only instruction from the plugin's richText system worth keeping.
*/ */
const BLOCK_PLACEHOLDER_INSTRUCTION = const BLOCK_PLACEHOLDER_INSTRUCTION =
/- The text may contain one or more standalone placeholder tokens[\s\S]*?surrounding text\./; /- The text may contain one or more standalone placeholder tokens[\s\S]*?surrounding text\./;
@ -37,53 +36,22 @@ export const extractBlockPlaceholderInstruction = (pluginSystem?: string): strin
return match ? match[0].trim() : ""; return match ? match[0].trim() : "";
}; };
/** export const buildComposeSystem = ({
* `buildRichTextSystem` appends its RULES / LAYOUT INSTRUCTIONS / ADDITIONAL pluginSystem,
* GUIDELINES block after the caller's own prompt, so cutting at this marker fieldType,
* leaves the field's system prompt (or an action instruction) intact. }: {
*/ pluginSystem?: string;
const PLUGIN_RULES_MARKER = "\n\nRULES:"; fieldType?: string;
}): string => {
const parts: string[] = [];
/** if (fieldType === "richText") {
* Backstop for the same text if that marker wording ever changes: the lines that
* demand JSON or a layout are dropped wherever they appear. Each pattern matches
* a whole line, so an action instruction that merely mentions JSON-ish words in
* passing is never touched.
*/
const CONTRADICTORY_LINE_PATTERNS = [
/^-\s*Ensure the output follows the provided rich text JSON schema exactly\.?$/,
/^-\s*Produce valid JSON with no undefined or null values\.?$/,
/^LAYOUT INSTRUCTIONS:?$/,
/^ADDITIONAL GUIDELINES:?$/,
/^\[[a-z][a-z]*\]\s*(-|:)/,
];
const stripContradictoryLines = (text: string): string =>
text
.split("\n")
.filter((line) => !CONTRADICTORY_LINE_PATTERNS.some((pattern) => pattern.test(line.trim())))
.join("\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
const stripPluginOutputDemands = (pluginSystem: string): string => {
const markerIndex = pluginSystem.indexOf(PLUGIN_RULES_MARKER);
if (markerIndex === -1) return stripContradictoryLines(pluginSystem);
const base = pluginSystem.slice(0, markerIndex);
const blockInstruction = extractBlockPlaceholderInstruction(pluginSystem); const blockInstruction = extractBlockPlaceholderInstruction(pluginSystem);
return stripContradictoryLines([base, blockInstruction].filter(Boolean).join("\n\n")); if (blockInstruction) parts.push(blockInstruction);
}; }
/** parts.push(AI_OUTPUT_RULES);
* The system prompt for one generation: whatever task the plugin sent (the return parts.join("\n\n");
* field's system prompt, or a named action's instruction such as Expand or
* Simplify) plus the shared output rules, minus the plugin's JSON/layout demands.
*/
export const buildComposeSystem = ({ pluginSystem }: { pluginSystem?: string } = {}): string => {
const base = stripPluginOutputDemands(pluginSystem ?? "");
return base ? `${base}\n\n${AI_OUTPUT_RULES}` : AI_OUTPUT_RULES;
}; };
type JsonSchemaLike = { type JsonSchemaLike = {

View file

@ -784,15 +784,17 @@ export default buildConfig({
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
// the JSON the Compose client parses is assembled here. The system // the JSON the Compose client parses is assembled here. The plugin's
// prompt keeps the task the plugin sent (the field's own prompt, or a // richText system asks for lexical JSON and a blog layout, which is
// named action's instruction such as Expand or Simplify) and drops // exactly what contradicted the prose instruction, so only its
// only the JSON/layout demands that contradicted it, so the action // block-placeholder paragraph survives (see composeSystem.ts).
// instructions still reach the model (see composeSystem.ts).
if (shape) { if (shape) {
const { text, truncated } = await generatePlainText( const { text, truncated } = await generatePlainText(
prompt, prompt,
buildComposeSystem({ pluginSystem: options.system }), buildComposeSystem({
pluginSystem: options.system,
fieldType: shape.kind === "lexical" ? "richText" : "text",
}),
model, model,
{ maxTokens: options.maxTokens, temperature: options.temperature }, { maxTokens: options.maxTokens, temperature: options.temperature },
); );

View file

@ -39,113 +39,51 @@ ADDITIONAL GUIDELINES:
- Ensure coherence and logical flow between all sections. - Ensure coherence and logical flow between all sections.
`; `;
// Verbatim from the plugin's `defaultPrompts` (dist/ai/prompts.js). These named
// actions carry their whole instruction in the system prompt, so anything that
// drops it (as this module once did) turns them into a generic prose request.
const EXPAND_SYSTEM = `You are a creative writer and subject matter expert. Expand the given text by adding depth, detail, and relevant information while maintaining the original tone and style.
-------------
INSTRUCTIONS:
- Understand the main ideas and tone of the text.
- Add more details, examples, explanations, or context.
- Maintain the original tone, style, and intent.
- Ensure the expanded version flows naturally and coherently.
- Do not contradict or alter the original meaning.
-------------`;
const SIMPLIFY_SYSTEM = `You are a skilled communicator specializing in clear and concise writing. Simplify the given text to make it easier to understand while retaining its core message.
-------------
INSTRUCTIONS:
- Simplify the language, using more common words and shorter sentences.
- Remove unnecessary details or jargon while keeping essential information.
- Maintain the original meaning and key points.
-------------`;
const REPHRASE_SYSTEM = `You are a skilled language expert. Rephrase the given text while maintaining its original meaning, tone, and emotional content.
-------------
INSTRUCTIONS:
- Rephrase the text according to the guidelines of the ORIGINAL SYSTEM PROMPT, if provided.
- Retain the original meaning, tone, and emotional content.
-------------
Previous prompt:
Summarise the field in two sentences.`;
describe("buildComposeSystem", () => { describe("buildComposeSystem", () => {
it("keeps the field's own system prompt and drops the plugin's JSON/layout rules", () => { it("strips the plugin's JSON rules and layout markers from the model's system prompt", () => {
const system = buildComposeSystem({ pluginSystem: PLUGIN_RICH_TEXT_SYSTEM }); const system = buildComposeSystem({
pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
fieldType: "richText",
});
expect(system).toContain("professional blog writer");
expect(system).not.toContain("rich text JSON schema"); expect(system).not.toContain("rich text JSON schema");
expect(system).not.toContain("Produce valid JSON"); expect(system).not.toContain("Produce valid JSON");
expect(system).not.toMatch(/LAYOUT INSTRUCTIONS/); expect(system).not.toMatch(/LAYOUT INSTRUCTIONS/);
expect(system).not.toMatch(/\[paragraph\]|\[horizontalrule\]|\[list\]|\[heading\]|\[quote\]/); expect(system).not.toMatch(/\[paragraph\]|\[horizontalrule\]|\[list\]|\[heading\]|\[quote\]/);
expect(system).not.toContain("ADDITIONAL GUIDELINES");
}); });
it("keeps the block-placeholder paragraph so embedded blocks survive", () => { it("keeps the block-placeholder paragraph and nothing else from the plugin system", () => {
const system = buildComposeSystem({ pluginSystem: PLUGIN_RICH_TEXT_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("- The text may contain one or more standalone placeholder tokens");
expect(system).toContain("[[[BLOCK_<number>]]]"); expect(system).toContain("[[[BLOCK_<number>]]]");
expect(system).toContain("the same relative position within the surrounding text."); expect(system).not.toContain("professional blog writer");
}); });
it("passes every named action's instruction through unchanged", () => { it("asks for prose plus the em-dash rule exactly once for every field type", () => {
const cases = [ for (const fieldType of ["richText", "text", "textarea"]) {
[EXPAND_SYSTEM, "Expand the given text by adding depth, detail"], const system = buildComposeSystem({
[SIMPLIFY_SYSTEM, "Simplify the given text to make it easier to understand"], pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
[REPHRASE_SYSTEM, "Rephrase the given text while maintaining its original meaning"], fieldType,
] as const;
for (const [actionSystem, instruction] of cases) {
const system = buildComposeSystem({ pluginSystem: actionSystem });
expect(system).toContain(instruction);
expect(system).toContain("INSTRUCTIONS:");
// The output contract is still enforced on top of the action.
expect(system).toContain("Respond with plain prose only.");
expect(system.endsWith(AI_OUTPUT_RULES)).toBe(true);
}
// The Rephrase action also appends the field's previous prompt.
expect(buildComposeSystem({ pluginSystem: REPHRASE_SYSTEM })).toContain(
"Summarise the field in two sentences.",
);
}); });
it("adds the em-dash rule exactly once for every action and field shape", () => {
const systems = [
buildComposeSystem({ pluginSystem: PLUGIN_RICH_TEXT_SYSTEM }),
buildComposeSystem({ pluginSystem: EXPAND_SYSTEM }),
buildComposeSystem({ pluginSystem: SIMPLIFY_SYSTEM }),
buildComposeSystem({}),
buildComposeSystem({ pluginSystem: undefined }),
];
for (const system of systems) {
expect(system.match(/Never use em-dashes/g)).toHaveLength(1); expect(system.match(/Never use em-dashes/g)).toHaveLength(1);
expect(system).toContain("Respond with plain prose only."); 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 only the shared rules when the plugin provides no system prompt", () => { it("sends short fields only the shared rules, with no plugin material", () => {
expect(buildComposeSystem({})).toBe(AI_OUTPUT_RULES); const system = buildComposeSystem({
expect(buildComposeSystem()).toBe(AI_OUTPUT_RULES); pluginSystem: PLUGIN_RICH_TEXT_SYSTEM,
expect(buildComposeSystem({ pluginSystem: "" })).toBe(AI_OUTPUT_RULES); fieldType: "text",
}); });
it("still drops JSON and layout demands if the plugin's marker wording changes", () => { expect(system).toBe(AI_OUTPUT_RULES);
const reworded = PLUGIN_RICH_TEXT_SYSTEM.replace("\n\nRULES:", "\n\nGUIDELINES:");
const system = buildComposeSystem({ pluginSystem: reworded });
expect(system).not.toContain("rich text JSON schema");
expect(system).not.toContain("Produce valid JSON");
expect(system).not.toMatch(/LAYOUT INSTRUCTIONS/);
expect(system).not.toContain("[paragraph] - Write a concise introduction");
expect(system).toContain("professional blog writer");
}); });
it("sends the real em-dash character to the model", () => { it("sends the real em-dash character to the model", () => {
@ -165,7 +103,6 @@ describe("extractBlockPlaceholderInstruction", () => {
it("returns an empty string when there is nothing to keep", () => { it("returns an empty string when there is nothing to keep", () => {
expect(extractBlockPlaceholderInstruction(undefined)).toBe(""); expect(extractBlockPlaceholderInstruction(undefined)).toBe("");
expect(extractBlockPlaceholderInstruction("just some prose")).toBe(""); expect(extractBlockPlaceholderInstruction("just some prose")).toBe("");
expect(extractBlockPlaceholderInstruction(EXPAND_SYSTEM)).toBe("");
}); });
}); });