prompts.chat 程序化 Prompt 工具包 API 全解析:变量归一、相似度去重、本地质量校验与多模态 Prompt 构建器
packages/prompts.chat/API.md 是 prompts.chat 仓库中 npm 包 prompts.chat(v0.1.1,MIT 协议)的完整 API 参考文档,覆盖 variables、similarity、quality、parser 四个核心工具模块以及 builder/chat/image/video/audio 五套流畅链式(fluent)构建器。本文以该文档为骨架逐模块展开,并结合 packages/prompts.chat/src 下的源码实现与测试用例,把每个函数的签名、默认值、底层算法和边界行为讲透,读完即可在自己的项目中直接编写类型安全、可复用、可校验的 AI Prompt 模板。
一、包总览:定位、入口与模块地图
从 package.json 可以确认包的基本事实:
- 包名
prompts.chat,版本0.1.1,要求 Node.js>=18,MIT 许可; - 双格式分发:
main指向 CJS(./dist/index.js),module指向 ESM(./dist/index.mjs),并附带完整类型声明; - 除主入口外提供 5 个 子路径导出(subpath exports),可按需引入、减小打包体积:
.、./variables、./similarity、./quality、./builder、./parser; - 同时附带 CLI:
bin中注册了prompts.chat与prompts-chat两个可执行入口(./bin/cli.js),可用npx prompts.chat在终端交互式浏览、检索、运行 Prompt,或用npx prompts.chat new <目录>脚手架化部署一套完整站点(说明详见 packages/prompts.chat/README.md)。
主入口 src/index.ts 的组织方式决定了 API 的使用形态:
// 命名空间导出(API.md 中四个工具模块)
export * as variables from './variables';
export * as similarity from './similarity';
export * as quality from './quality';
export * as parser from './parser';
// 构建器:同时以“具名导出”和“命名空间”两种方式提供
export { builder, fromPrompt, templates, video, audio, image, chat, chatPresets, ... } from './builder';
因此两种写法等价:import { variables } from 'prompts.chat' 后用 variables.normalize(...),或 import { normalizeVariables } from 'prompts.chat'。API.md 的目录结构也完全按这 9 个模块划分:
| 模块 | 源码位置 | 职责 |
|---|---|---|
variables |
src/variables/index.ts | 多格式变量检测、归一化、提取与编译 |
similarity |
src/similarity/index.ts | 内容相似度计算与去重 |
quality |
src/quality/index.ts | 本地(无需 API)Prompt 质量校验 |
parser |
src/parser/index.ts | YAML/JSON/Markdown/纯文本多格式解析 |
builder |
src/builder/ | 文本 DSL、chat、image、video、audio 五套构建器 |
值得注意的是,API.md 头部标注“Auto-generated from TypeScript source files”,且 package.json 的 scripts 中有 docs:generate(执行 scripts/generate-docs.ts)——说明这份 API 文档是由源码自动生成的,与实现保持一致,本文引用的每个签名都能回溯到对应源文件。
二、variables 模块:七种变量格式的检测与归一化
API.md 中 variables/index 小节定义了 VariablePattern 类型(7 种模式)与 DetectedVariable 接口,以及 6 个函数和 2 个别名常量。
2.1 类型与数据结构
VariablePattern 定义了全部可识别的变量包裹风格:
type VariablePattern =
| "double_bracket" // [[name]]
| "double_curly" // {{name}}
| "single_bracket" // [NAME]
| "single_curly" // {NAME}
| "angle_bracket" // <NAME>
| "percent" // %NAME%
| "dollar_curly"; // ${name}(本包支持的标准格式)
DetectedVariable 则携带完整的位置信息,便于 UI 高亮与定点替换:
interface DetectedVariable {
original: string; // 原文,如 "[Your Name]"
name: string; // 变量名,如 "Your Name"
defaultValue?: string; // 可选默认值,仅 [[name: default]] / {{name: default}} 支持
pattern: VariablePattern;
startIndex: number; // 在原文中的起始下标
endIndex: number; // 结束下标
}
2.2 函数一览(API.md 签名原样保留)
| 函数 | 签名 | 作用 |
|---|---|---|
detectVariables() |
(text: string): DetectedVariable[] |
检测非标准格式的变量模式 |
convertToSupportedFormat() |
(variable: DetectedVariable): string |
把单个检测结果转成 ${var} |
convertAllVariables() |
(text: string): string |
全文转换;别名 normalize |
getPatternDescription() |
(pattern: VariablePattern): string |
返回人可读模式描述,如 "{{...}}" |
extractVariables() |
(text: string): Array<{ name: string; defaultValue?: string }> |
从 ${var} / ${var:default} 中提取变量 |
compile() |
(template: string, values: Record<string, string>, options?: { useDefaults?: boolean }): string |
用值填充模板 |
典型工作流(可直接运行):
import { variables } from 'prompts.chat';
const detected = variables.detect("Hello {{name}}, welcome to [COMPANY]");
// → [{ name: "name", pattern: "double_curly" }, { name: "COMPANY", pattern: "single_bracket" }]
const normalized = variables.normalize("Hello {{name}}, you are [ROLE]");
// → "Hello ${name}, you are ${role}"
const vars = variables.extractVariables("Hello ${name:World}");
// → [{ name: "name", defaultValue: "World" }]
const result = variables.compile("Hello ${name:World}", { name: "Developer" });
// → "Hello Developer"
2.3 源码纵深:检测器如何避免误报
阅读 src/variables/index.ts 的实现,可以看到检测逻辑比签名复杂得多,这些细节直接影响生产可用性和:
- 模式按特异性排序匹配:
PATTERNS数组(L33-L78)把[[...]]、{{...}}等“更强包裹”排在[...]、<...>之前,并用seenRanges区间去重,保证[NAME]不会把已识别为[[NAME]]的片段再报一次。 - 标准格式先占位:
detectVariables()(L116-L192)会先把所有${...}的位置记入seenRanges,因此已支持格式的变量不会被当作问题上报——这与文档“Returns detected variables that are NOT in our supported format”的描述一致。 - 内置误报黑名单:
FALSE_POSITIVES(L81-L97)收录了常见 HTML 标签(div、span…)、编程语言关键字(if、for、function…)和 JSON 结构词(type、id、data…),防止解析 HTML/代码时满屏误报。 - JSON 字符串上下文加严:
isInsideJsonString()会扫描下标之前的引号判断是否处于 JSON 字符串内;若是,{NAME}/[NAME]模式要求变量名首字母大写或含空格才予以识别,降低把 JSON 对象误判为变量模板的概率。 - 尖括号单独加严:
angle_bracket要求名字首字母大写或含空格(<a>、<div>这类单字小写标签被排除);同时任何名称长度小于 2 的匹配一律忽略。 - 名称归一化规则:
convertToSupportedFormat()(L197-L209)把变量名转小写、空格换下划线、剔除非字母数字下划线字符——所以[Your Name]→${your_name},这也是 README 示例中[ROLE]→${role}的原因。 - 全文替换从后往前:
convertAllVariables()先按startIndex降序排列再逐一切片替换,避免前面的替换移动了后面片段的偏移量。 compile()的默认值语义(L277-L297):options.useDefaults默认为true——变量在values中不存在但模板写了默认值时取默认值;既无值也无默认值时原样保留${name}占位符而不是替换为空串。若想强制暴露缺失变量,可传{ useDefaults: false }后自行检查残留。
对应测试见 src/tests/variables.test.ts。
三、similarity 模块:加权 Jaccard + n-gram 的重复检测
API.md 的 similarity/index 小节列出 6 个函数,默认去重阈值统一为 0.85(85% 相似):
| 函数 | 签名 | 作用 |
|---|---|---|
normalizeContent() |
(content: string): string |
归一化后再比较 |
calculateSimilarity() |
(content1: string, content2: string): number |
综合相似度分数 0~1 |
isSimilarContent() |
(content1, content2, threshold?: number): boolean |
是否达到阈值(默认 0.85) |
getContentFingerprint() |
(content: string): string |
用于数据库快速索引的内容指纹 |
findDuplicates() |
<T extends {content: string}>(prompts: T[], threshold?: number): T[][] |
找出重复组 |
deduplicate() |
<T extends {content: string}>(prompts: T[], threshold?: number): T[] |
去重,保留首次出现 |
(calculate、isDuplicate 是前两者的别名,见 src/similarity/index.ts 中的常量导出。)
import { similarity } from 'prompts.chat';
const score = similarity.calculate(prompt1, prompt2); // → 0~1
const isDupe = similarity.isDuplicate(prompt1, prompt2, 0.85); // 默认阈值即 0.85
const groups = similarity.findDuplicates(prompts, 0.85); // → [[p1, p3], [p2, p5]]
const unique = similarity.deduplicate(prompts, 0.85); // 保留每个相似组的首个
3.1 归一化管线(normalizeContent,L12-L26)
比较前对内容做五步清洗,顺序即源码顺序:
- 移除
${variable}/${variable:default}占位符(避免同一提示词仅变量名不同就被判为不同); - 移除
[placeholder]与<placeholder>占位符; - 转小写;
- 去标点(只保留
\w与空白); - 空白折叠为单空格并 trim。
3.2 分数合成:60% 词级 Jaccard + 40% 字符级 3-gram
calculateSimilarity()(L75-L91)在归一化文本上做短路判断后,按加权平均合成:
- 归一化后完全相等 → 直接返回 1;任一为空 → 返回 0;
- 否则
score = jaccard * 0.6 + ngram * 0.4。
其中 Jaccard 以词集合(按空格切分去重)计算交并比,度量“词表重合度”;n-gram 以带空格填充的 3 字符滑窗计算交并比,度量“序列/拼写相似度”。两者互补:只换措辞但用词接近的提示词靠 Jaccard 识别,仅词序微调、字符几乎相同的靠 n-gram 识别。
3.3 指纹与批量去重的取舍
getContentFingerprint()(L119-L123)并非加密哈希,而是取归一化内容的前 500 个字符——这是一个刻意的工程取舍:数据库索引/等值比较开销极低,可作全量相似度计算前的“快筛”,文档注释也明确其为“quick lookups before full similarity check”。findDuplicates() 则是对数组做两两比较的单链分组(以每个未分组元素为锚点向后吸纳相似项,O(n²)),适合中等规模列表的治理场景而非海量数据的实时路径。验证用例见 src/tests/similarity.test.ts。从源码结构看,主站 Next.js 应用侧另有一份同名工具 src/lib/similarity.ts,服务端提交流程与 npm 包共享同一套相似度思路。
四、quality 模块:零 API 依赖的本地质量校验
API.md 的 quality/index 小节提供 4 个函数:check()、validate()、isValid()、getSuggestions(),全部纯本地执行、无需调用任何模型 API。核心返回结构:
interface QualityIssue {
type: 'error' | 'warning' | 'suggestion';
code: string; // 如 'EMPTY'、'GIBBERISH'
message: string;
position?: { start: number; end: number };
}
interface QualityResult {
valid: boolean; // 存在 error 级问题即为 false
score: number; // 0~1 综合分
issues: QualityIssue[];
stats: { /* 见下 */ };
}
import { quality } from 'prompts.chat';
const result = quality.check("Act as a developer...");
console.log(result.score); // 0~1
console.log(result.issues); // QualityIssue[]
quality.validate(prompt); // 不合法时 throw Error
const ok = quality.isValid(prompt); // boolean
const tips = quality.getSuggestions(prompt); // 改进建议字符串数组
4.1 判定阈值(源码 src/quality/index.ts L38-L41)
| 常量 | 值 | 触发的问题级别 |
|---|---|---|
MIN_CHAR_COUNT |
20 字符 | 低于此值 → error TOO_SHORT;为 0 → error EMPTY |
MIN_WORD_COUNT |
5 词 | 低于此值 → warning FEW_WORDS |
OPTIMAL_MIN_WORDS |
20 词 | 短于此按线性比例扣分 |
OPTIMAL_MAX_WORDS |
2000 词 | 超过扣 0.05 |
4.2 分数算法逐项拆解
calculateScore()(L109-L144)从 1.0 出发,逐项加减后夹到 [0, 1]:
- 每个 error 扣 0.2,每个 warning 扣 0.05;
- 结构加分:检测到角色定义(
hasRole)+0.05、任务指令(hasTask)+0.05、约束(hasConstraints)+0.03、示例(hasExamples)+0.05; - 过短惩罚:
score -= 0.1 * (1 - wordCount / 20)(少于 20 词时); - 变量加分:包含任意格式变量(
${}、{{}}、[[ ]]、[VAR])+0.05,因为变量意味着可复用性。
结构检测基于关键词正则(L67-L83):act as / you are / imagine you / role: 等判定角色;your task / you must / please / help me 等判定任务;do not / never / always / avoid 及 rule / constraint 判定约束;example / e.g. / ```代码块``` 判定示例。乱码检测 isGibberish()覆盖连续 5 个重复字符、键盘序(qwerty/asdfgh…)以及元音/辅音比低于 0.1 三种情形。此外还有UNBALANCED_BRACKETS(三类括号配对检查,warning)与 LONG_LINES(超 500 字符长行,suggestion)。validate()在有 error 时以分号拼接错误消息抛出Invalid prompt: ...;getSuggestions()` 则汇总 warning/suggestion 并按 stats 补充“加角色定义 / 加约束 / 加示例 / 加变量”等具体建议(L278-L307)。测试覆盖见 src/tests/quality.test.ts。
五、parser 模块:四种 Prompt 文件格式的统一解析
API.md 的 parser/index 小节声明支持 .prompt.yml / .prompt.yaml(YAML)、.prompt.json(JSON)、.prompt.md(Markdown + frontmatter)、.txt(纯文本)。函数签名:
| 函数 | 签名 | 作用 |
|---|---|---|
parse() |
(content: string, format?: 'yaml' | 'json' | 'markdown' | 'text'): ParsedPrompt |
多格式解析(format 可省略,按内容推断) |
toYaml() |
(prompt: ParsedPrompt): string |
序列化回 YAML |
toJson() |
(prompt: ParsedPrompt, pretty?: boolean): string |
序列化回 JSON(pretty 默认 true) |
getSystemPrompt() |
(prompt: ParsedPrompt): string |
取 system 消息内容 |
interpolate() |
(prompt: ParsedPrompt, values: Record<string, string>): ParsedPrompt |
变量插值,返回新对象 |
统一中间模型 ParsedPrompt(src/parser/index.ts L28-L46):
interface ParsedPrompt {
name?: string;
description?: string;
model?: string;
modelParameters?: { // 模型参数,全部可选
temperature?: number;
maxTokens?: number;
topP?: number;
frequencyPenalty?: number;
presencePenalty?: number;
};
messages: PromptMessage[]; // { role: 'system'|'user'|'assistant'; content: string }[]
variables?: Record<string, { description?: string; default?: string; required?: boolean }>;
metadata?: Record<string, unknown>;
}
文档中的示例(原样可运行):
import { parser } from 'prompts.chat';
const prompt = parser.parse(`
name: Code Review
messages:
- role: system
content: You are a code reviewer.
`);
一个重要的实现边界:源码注释明确写道 YAML 解析是“a simple YAML parser for common prompt file structures”,实现见 parseSimpleYaml()(L53 起),它按行处理键值、- 数组项与 | 多行块;对于完整 YAML 支持,消费方项目应自行引入专业 YAML 库——在把该模块用于复杂文档时,这是必须知晓的适用前提。interpolate() 基于前文的 ${var} / ${var:default} 约定工作,与 variables 模块的 compile() 语义一致,两者可组合:先 parse() 得到结构化提示词,再对每条 message 做变量填充。
六、builder 核心模块:文本 Prompt 的流畅 DSL
API.md 的 builder/index 小节定义了 PromptBuilder 类、builder() 工厂函数、fromPrompt() 与 templates 常量。它把“角色—上下文—任务—约束—输出—示例—变量”这一经典提示词结构映射为链式方法,且每个主方法都配了语义别名:
| 方法 | 别名 | 说明 |
|---|---|---|
.role(role) |
.persona() |
设定 AI 角色/人格 |
.context(context) |
.background() |
背景信息 |
.task(task) |
.instruction() |
主任务指令 |
.constraints(list) |
.rules() |
批量约束;另有单条 .constraint(text) |
.output(format) |
.format() |
期望输出格式 |
.example(in, out) / .examples(list) |
— | 示例对(few-shot) |
.variable(name, options?) |
— | 声明变量,options 含 description / required / defaultValue |
.section(title, content) |
— | 追加自定义小节 |
.raw(content) |
— | 直接设置原始内容,绕过结构化拼装 |
.build() |
— | 产出 BuiltPrompt |
.toString() |
— | 构建后仅返回 content 字符串 |
import { builder, fromPrompt, templates } from 'prompts.chat';
const prompt = builder()
.role("Senior TypeScript Developer")
.context("You are helping review code")
.task("Analyze the following code for bugs")
.constraints(["Be concise", "Focus on critical issues"])
.output("JSON with { bugs: [], suggestions: [] }")
.variable("code", { required: true })
.build();
// BuiltPrompt = { content: string; variables: PromptVariable[]; metadata: unknown }
console.log(prompt.content, prompt.variables);
const existing = fromPrompt("You are a helpful assistant...").build();
PromptVariable 与 BuiltPrompt 的结构(API.md 表格):
interface PromptVariable {
name: string;
description?: string;
required?: boolean;
defaultValue?: string;
}
interface BuiltPrompt {
content: string;
variables: PromptVariable[];
metadata: unknown;
}
fromPrompt(content) 适合把既有长文本提示词“接管”进构建器继续增补;templates 常量则提供开箱模板——packages/prompts.chat/README.md 给出了 templates.codeReview({ language, focus })、templates.translation(from, to)、templates.summarize({ maxLength, style })、templates.qa(context) 四个工厂函数。构建器输出的结构化 variables 数组可无缝对接第 2 节的 extractVariables() / compile(),形成“声明变量 → 填充变量”的闭环。行为测试见 src/tests/builder.test.ts。
七、builder/chat:模型无关的对话式 Prompt 构建器
builder/chat 小节对应 src/builder/chat.ts 中的 ChatPromptBuilder,定位为“model-agnostic”——面向 GPT、Claude、Gemini、Llama 等任意聊天模型做提示词工程,不绑定任何模型特性。
7.1 核心类型
| 类型 | 取值 |
|---|---|
MessageRole |
'system' | 'user' | 'assistant' |
ResponseFormatType |
'text' | 'json' | 'markdown' | 'code' | 'table' |
PersonaTone(20 种语气) |
professional / casual / formal / friendly / academic / technical / creative / empathetic / authoritative / playful / concise / detailed / socratic / coaching / analytical / encouraging / neutral / humorous / serious |
PersonaExpertise(20 种专业域) |
general / coding / writing / analysis / research / teaching / counseling / creative / legal / medical / financial / scientific / engineering / design / marketing / business / philosophy / history / languages / mathematics |
ReasoningStyle(10 种推理方式) |
step-by-step / chain-of-thought / tree-of-thought / direct / analytical / comparative / deductive / inductive / first-principles / analogical / devil-advocate |
OutputLength |
brief / moderate / detailed / comprehensive / exhaustive |
OutputStyle |
prose / bullet-points / numbered-list / table / code / mixed / qa / dialogue |
结构化配置对象 ChatPersona(name/role/tone/expertise/personality/background/language/verbosity)、ChatContext(background/domain/audience/purpose/constraints/assumptions/knowledge)、ChatTask(instruction/steps/deliverables/criteria/antiPatterns/priority,priority 取 accuracy | speed | creativity | thoroughness)、ChatOutput(format/length/style/language/includeExplanation/includeExamples/includeSources/includeConfidence)、ChatReasoning(style/showWork/verifyAnswer/considerAlternatives/explainAssumptions)、ChatMemory(summary/facts/preferences/history)一一对应,方法名与字段名保持一致,可传“完整对象”也可用细粒度方法逐字段覆盖(细粒度方法在源码中后置覆盖同名字段)。
7.2 方法分组速查(API.md 全量方法表节选)
- 消息:
system / user(content, name?) / assistant / message(role, content, name?) / messages(ChatMessage[]) / conversation(turns[]) - 人格:
persona / role / tone / expertise / personality / background / speakAs / responseLanguage - 上下文:
context / domain / audience / purpose / constraints / constraint / assumptions / knowledge - 任务:
task / instruction / steps / deliverables / criteria / avoid / priority - 示例:
example(input, output, explanation?) / examples / fewShot - 输出格式:
output / outputFormat / json(schema?) / jsonSchema(name, schema, description?) / markdown / code(language?) / table - 输出长度/风格:
length / brief / moderate / detailed / comprehensive / exhaustive / style / withExamples / withExplanation / withSources / withConfidence - 推理:
reasoning / reasoningStyle / stepByStep / chainOfThought / treeOfThought / firstPrinciples / devilsAdvocate / showWork / verifyAnswer / considerAlternatives / explainAssumptions(各xxx()快捷方法同时置位showWork等布尔位,如devilsAdvocate()附带considerAlternatives) - 记忆:
memory / remember / preferences / history / summarizeHistory - 自定义与产出:
addSystemPart / raw / build(),以及导出方法toString / toSystemPrompt / toMessages / toJSON / toYAML / toMarkdown
构建结果 BuiltChatPrompt 含 messages(含 system 的完整消息数组)、systemPrompt(拼装好的系统提示词)、userPrompt(最新用户消息)、metadata(persona/context/task/output/reasoning/examples 的结构化元数据)。一个覆盖主要链路的完整示例:
import { chat } from 'prompts.chat';
const prompt = chat()
.persona({
name: "Alex",
role: "senior software architect",
tone: ["professional", "analytical"],
expertise: ["coding", "engineering"],
verbosity: "detailed"
})
.context({
background: "Reviewing a pull request for an e-commerce platform",
domain: "software engineering",
audience: "mid-level developers",
constraints: ["Follow team coding standards"]
})
.task({
instruction: "Review the submitted code and provide actionable feedback",
steps: ["Analyze code structure", "Check for potential bugs", "Suggest improvements"],
deliverables: ["Summary of issues", "Code examples"],
antiPatterns: ["Vague criticism"],
priority: "accuracy"
})
.example("const [data, setData] = useState()",
"Add a type parameter: useState<DataType>()",
"TypeScript generics improve type safety")
.jsonSchema("CodeReview", {
type: "object",
properties: { issues: { type: "array" }, suggestions: { type: "array" } }
})
.stepByStep()
.user("Please review this component...")
.build();
const yaml = prompt.toYAML(); // 也可直接 toJSON() / toMarkdown() / toMessages()
7.3 预设:chatPresets
chatPresets 常量提供 10 个开箱即用的预配置构建器,各自已设定人格、语气、输出风格与推理方式(详见 packages/prompts.chat/README.md 的 Presets 一节):
import { chatPresets } from 'prompts.chat';
const coder = chatPresets.coder("TypeScript"); // 专家型代码评审
const writer = chatPresets.writer("creative"); // creative | professional | academic
const tutor = chatPresets.tutor("mathematics"); // 耐心导师 + 学科专长
const analyst = chatPresets.analyst(); // 数据分析师(chain-of-thought)
const socratic = chatPresets.socratic(); // 苏格拉底式追问
const critic = chatPresets.critic(); // 建设性批评者
const brainstormer = chatPresets.brainstormer(); // 创意发散
const jsonBot = chatPresets.jsonResponder("Response", { /* JSON Schema */ });
const summarizer = chatPresets.summarizer("brief"); // 带长度控制的摘要器
const translator = chatPresets.translator("Japanese"); // 目标语言翻译器
// 预设返回的仍是 builder,可继续链式追加
const prompt = coder.task("Review this function")
.user("function add(a, b) { return a + b }")
.build();
八、媒体构建器:image()、video() 与 audio()
builder/media、builder/video、builder/audio 三个小节对应 src/builder/media.ts、src/builder/video.ts、src/builder/audio.ts,统一自称“Media Prompt Builders - The D3.js of Prompt Building”——即把专业影视/音乐制作中的每个属性都暴露为类型安全的链式方法。三者的导出格式一致:OutputFormat = 'text' | 'json' | 'yaml' | 'markdown',构建结果均为 { prompt: string; structure: unknown }(媒体类),并支持 toString / toJSON / toYAML / toMarkdown(image 另有 format(fmt) 统一入口)。
8.1 image():约 60 个方法的摄影级建模
ImagePromptBuilder 的方法按专业维度分组(API.md 方法表全量保留):
- 主体:
subject(main | ImageSubject)(ImageSubject 含 main/details/expression/pose/action/clothing/accessories/age/ethnicity/gender/count)、subjectDetails / expression / pose / action / clothing / accessories / subjectCount - 摄影机:
camera(ImageCamera)整包设置,或细粒度angle / shot / lens / focus / aperture / bokeh / filmStock / filmFormat / cameraBrand / cameraModel / sensor / lensModel / lensBrand / focalLength / filter / iso / shutterSpeed / whiteBalance / colorProfile - 布光:
lighting(ImageLighting)或lightingType / timeOfDay / weather / lightDirection / lightIntensity - 构图:
composition / ruleOfThirds / goldenRatio / symmetry / foreground / midground / background - 环境:
environment / location / props / atmosphere / season - 风格与色彩:
style / medium / artist / influence、color / palette / primaryColors / accentColors / colorGrade - 技术规格:
technical / aspectRatio(9 种比例)/ resolution / quality(draft→masterpiece 五档)/ mood / negative / custom
配套类型把行业术语固化为字面量联合,例如 CameraBrand(sony/canon/nikon/fujifilm/leica/hasselblad…含 Arri/RED/Blackmagic 电影机)、LensType(wide-angle…tilt-shift 及各焦段 14mm~800mm)、FilmStock(Kodak Portra/Tri-X、Fuji Pro 400H、Ilford HP5、CineStill 等 60 余种)、LightingType(natural/studio/rim/rembrandt/butterfly/chiaroscuro…24 种)、ArtStyle(photorealistic/cinematic/cyberpunk/anime/3d-render 等 35 种)。一个可直接运行的示例:
import { image } from 'prompts.chat';
const prompt = image()
.subject({
main: "a cyberpunk samurai warrior",
expression: "determined and fierce",
pose: "dynamic battle stance",
clothing: "neon-lit armor with glowing circuits",
accessories: ["holographic visor"],
gender: "female"
})
.environment({
setting: "rain-soaked Tokyo alley",
location: "Shibuya district",
atmosphere: "electric and mysterious",
season: "winter"
})
.camera({ angle: "low-angle", shot: "wide", lens: "35mm" })
.lighting({ type: ["rim", "practical"], time: "night", intensity: "dramatic" })
.style({ medium: ["cinematic", "cyberpunk"], quality: ["highly detailed"] })
.color({ palette: "neon", temperature: "cool", contrast: "high" })
.aspectRatio("16:9")
.resolution("8K")
.build();
console.log(prompt.prompt);
8.2 video():面向生成模型的分镜化建模
VideoPromptBuilder 在图像维度基础上增加时间轴概念(API.md 接口表):VideoScene(description/setting/timeOfDay/weather/atmosphere)、VideoSubject、VideoCamera(在静态摄影机属性外新增 anamorphic / anamorphicRatio(1.33x~2x)/ movement(25 种运镜:pan/dolly/crane/whip-pan/vertigo-effect…)/ movementSpeed / movementDirection / rig / gimbal / platform / shutterAngle / frameRate(24/25/30/48/60/120/240)/ slowMotion / filmGrain / halation)、VideoAction(beat/duration/timing)、VideoMotion(subject/type/direction/speed/beats)、VideoStyle、VideoColor、VideoAudio(diegetic/ambient/dialogue/music/soundEffects/mix)、VideoTechnical(duration/resolution:480p~4K/fps/aspectRatio/shutterAngle),以及 VideoShot(timestamp/name/camera/action/purpose)用于多镜头列表。
方法表覆盖 scene / setting / subject / appearance / clothing / camera / shot / angle / movement / lens / platform / cameraSpeed / movementDirection / rig / gimbal / anamorphic / aperture / frameRate / slowMotion / shutterAngle / filmStock / filmGrain / halation / lighting / action / actions / motion / motionBeats / style / format / era / look / reference / color / palette / colorGrade / audio / dialogue / ambient / diegetic / soundEffects / music / technical / duration / resolution / fps / aspectRatio / addShot / shotList / mood / pacing(7 档)/ transition / transitions(cut/fade/dissolve/morph/match-cut…11 种)/ custom。示例:
import { video } from 'prompts.chat';
const prompt = video()
.scene({
description: "A samurai walks through a bamboo forest",
timeOfDay: "golden-hour",
weather: "foggy"
})
.camera({ movement: "tracking", angle: "low", frameRate: 24, anamorphic: "1.8x" })
.lighting({ time: "golden-hour", type: "natural" })
.action("walks slowly forward", { duration: 3, timing: "start" })
.audio({ ambient: "wind through bamboo", diegetic: ["footsteps on gravel"] })
.duration(5)
.resolution("1080p")
.fps(24)
.pacing("slow")
.build();
8.3 audio():音乐生成提示词
AudioPromptBuilder 面向音乐/音频生成平台,核心类型与 image/video 共享 MusicGenre(pop/rock/jazz/electronic/lo-fi/synthwave/orchestral…30 种)、Instrument(30 余种)、VocalStyle(male/female/duet/choir/a-cappella/rap/falsetto/whisper/growl…12 种)、Mood(20 种情绪)、Tempo(音乐术语 largo…presto 与数字 BPM 联合类型)。README 的 Quick Start 展示了最小用法:
import { audio } from 'prompts.chat';
const musicPrompt = audio()
.genre("electronic")
.mood("energetic")
.bpm(128)
.instruments(["synthesizer", "drums", "bass"])
.build();
console.log(musicPrompt.prompt);
三套媒体构建器共同的特点是:所有取值均为字面量联合类型,IDE 可直接给出自动补全,拼写错误在编译期即暴露;构建产物保留 structure 原始对象,既能取纯文本喂给生成平台,也能以 JSON/YAML/Markdown 形式入库管理——这与 prompts.chat 主站“收集、管理、分发 Prompt”的产品定位完全同构。
九、验证与延伸阅读:测试、文档生成与 Web 端同源实现
这套 API 的可信度由三层工程设施支撑,均可在当前仓库内直接查证:
- 单元/集成测试:src/tests 下
variables.test.ts、similarity.test.ts、quality.test.ts、parser.test.ts、builder.test.ts、platforms.test.ts逐一覆盖各模块,package.json的test: vitest run一键执行; - 文档自动生成:API.md 由 scripts/generate-docs.ts 从 TypeScript 源码生成(
npm run docs:generate),签名与实现同步演进; - 同源服务端实现:主站 Next.js 应用内保留了同名的 src/lib/similarity.ts 与 src/lib/variable-detection.ts(配套测试见 src/tests/lib/),从源码结构看,npm 包与 Web 端共享同一套变量/相似度算法思路,提示词提交流程中的格式归一与重复拦截正是这些模块的服务端化身。
适用前提与限制:本文所有结论基于当前仓库快照(包版本 0.1.1,Node >= 18)。需要特别注意的两点限制——parser.parse() 的 YAML 解析是面向常见提示词结构的简化实现,复杂 YAML 建议自行引入专业库;similarity.findDuplicates/deduplicate 为 O(n²) 两两比较,适合中小规模数据治理。除上述模块外,仓库中的 CLI 交互浏览器(npx prompts.chat)与 npx prompts.chat new 部署脚手架属于同一包的周边能力,细节见 packages/prompts.chat/README.md,而主站的完整自托管文档见仓库根目录的 SELF-HOSTING.md。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0622
Hy4-previewHy4 preview 是由腾讯混元团队研发的新一代混合专家(MoE)旗舰模型。模型总参数量 770B,每个 token 激活 49B,主干共包含78层,第一层采用标准 FFN,其余 77 层均为 MoE 结构,每层包含 256 个路由专家与 1 个共享专家,每个 token 激活 top-8 路由专家及共享专家。主干之外原生内置 1 层 MTP(总参数量 10B,激活 0.7B)以支持投机解码。Python00
GLM-5.3GLM-5.3 与 GLM-5.2 使用相同的基座模型——所有提升均来自后训练。与 GLM-5.2 相比,它在复杂编程和长程任务上的表现显著提升。Jinja00
GLM-5.3-FlashGLM-5.3-Flash (320B-A18B),是GLM-5系列的首个原生多模态模型。320B总参数,能力超过GLM-5.2Jinja00
Spark-X2.5-4BSpark-X2.5-4B 旨在让强大的 AI 更实用、更高效、更易获得。在广泛日常任务中表现强劲,涵盖对话、写作、翻译、推理、编码、工具调用以及智能体工作流,并在同等规模的开源模型中取得领先成绩。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00
Spark-X2.5-1.7BSpark-X2.5-1.7B 旨在让强大的 AI 更加实用、高效且易于获取。这些模型在广泛的日常任务中表现出色,涵盖对话、写作、翻译、推理、编程、工具调用和智能体工作流,并在同等规模的开源模型中取得领先结果。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00