feat: 实现 PromptBuilder 段落构建器

This commit is contained in:
2026-06-11 16:30:42 +08:00
parent b709a01df3
commit 803533a7e0
2 changed files with 140 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
import type { PromptSection, SectionKind } from "./prompt-sections";
export class PromptBuilder {
private sections: PromptSection[] = [];
head(text: string): this {
const existing = this.sections.findIndex((s) => s.kind === "head");
if (existing !== -1) {
this.sections[existing] = { kind: "head", content: text };
} else {
this.sections.push({ kind: "head", content: text });
}
return this;
}
context(text: string): this {
this.sections.push({ kind: "context", content: text });
return this;
}
prompt(text: string): this {
const existing = this.sections.findIndex((s) => s.kind === "prompt");
if (existing !== -1) {
this.sections[existing] = { kind: "prompt", content: text };
} else {
this.sections.push({ kind: "prompt", content: text });
}
return this;
}
guide(text: string): this {
this.sections.push({ kind: "guide", content: text });
return this;
}
warn(text: string): this {
this.sections.push({ kind: "warn", content: text });
return this;
}
build(): string {
const order: SectionKind[] = ["head", "context", "prompt", "guide", "warn"];
const groups: string[][] = order.map(() => []);
for (const section of this.sections) {
if (section.content.trim() === "") continue;
const idx = order.indexOf(section.kind);
if (idx !== -1) {
groups[idx].push(section.content);
}
}
const rendered: string[] = [];
for (const group of groups) {
if (group.length > 0) {
rendered.push(group.join("\n\n"));
}
}
return rendered.join("\n\n");
}
}