内联提示
prompt
或 runPrompt
函数允许构建内部LLM调用。它返回提示的输出。
prompt
是 runPrompt
的一种语法糖,它接受一个模板字符串字面量作为提示文本。
const { text } = await prompt`Write a short poem.`
你可以向runPrompt
传递一个函数,该函数接收单个参数_
,即提示构建器。
它定义了相同的辅助函数如$
、def
,但应用于内部提示。
const { text } = await runPrompt((_) => { // use def, $ and other helpers _.def("FILE", file) _.$`Summarize the FILE. Be concise.`})
你也可以简化函数,直接传递提示文本
const { text } = await runPrompt( `Select all the image files in ${env.files.map((f) => f.filename)}`)
不要在内部提示中混用全局助手
一个常见的错误是在内部提示中使用全局的def
、$
和其他辅助函数。
这些辅助函数在内部提示中不可用,您应该改用_.$
、_.def
和其他辅助函数。
- 不好
const { text } = await runPrompt((_) => { def("FILE", env.files) // oops, _. is missing and def added content in the main prompt $`Summarize files.` // oops, _ is missing and $ added content in the main prompt})
- 良好
const { text } = await runPrompt((_) => { _.def("FILE", env.files) // yes, def added content in the inner prompt _.$`Summarize the FILE.`})
选项
prompt
和 runPrompt
都支持与 script
函数类似的各种选项。
const { text } = await prompt`Write a short poem.`.options({ temperature: 1.5 })const { text } = await runPrompt((_) => { ...}, { temperature: 1.5 })
工具
您可以在tools中使用内部提示。
defTool( "poet", "Writes 4 line poem about a given theme", { theme: { type: "string", description: "Theme of the poem", } }, (({theme})) => prompt`Write a ${4} line ${"poem"} about ${theme}`)
并发
prompt
和 runPrompt
是异步函数,可以在循环中使用来同时运行多个提示。
await Promise.all(env.files, (file) => prompt`Summarize the ${file}`)
在内部,GenAIScript默认对每个模型应用8个并发限制。您可以使用modelConcurrency
选项更改此限制。
script({ ..., modelConcurrency: { "openai:gpt-4o": 20 }})
如果需要更精细地控制并发队列,可以尝试使用p-all、p-limit或类似的库。
仅限内联脚本
如果您的脚本最终调用了内联提示而从未生成主提示,您可以将其配置为使用none
LLM提供程序。
这将阻止GenAIScript尝试解析连接信息,并且如果您尝试在主执行中生成提示,还会抛出错误。
script({ model: "none",})
示例:使用Phi-3生成文件摘要汇总
下面的代码片段使用Phi-3 通过Ollama在将文件添加到主提示之前单独对它们进行摘要总结。
script({ model: "small", files: "src/rag/*", tests: { files: ["src/rag/*"], keywords: ["markdown", "lorem", "microsoft"], },})
if (!env.files.length) throw new Error("No files found")// summarize each files individuallyfor (const file of env.files) { const { text } = await runPrompt( (_) => { _.def("FILE", file) _.$`Extract keywords for the contents of FILE.` }, { model: "small", cache: "summary_summary" } ) def("FILE", { ...file, content: text })}// use summary$`Extract keywords for the contents of FILE.`