提示操纵是应用开发者用来影响 生成式 AI 模型的输出。例如,使用 LLM 时,你可以 会影响语气、格式、长度和其他特征 模型的回答。
Genkit 在设计时遵循的是提示是代码的前提条件。您负责撰写和 在源文件中维护提示,并使用同一版本跟踪对提示的更改 控制系统,你可以将它们与代码一起部署, 调用自己的生成式 AI 模型。
大多数开发者会发现随附的 Dotprompt 库 能够满足他们在 Genkit 中使用提示的需求。不过, 方法也支持直接使用提示。
定义提示
Genkit 的生成辅助函数接受字符串提示, 以这种方式调用模型,以用于简单直接的用例。
Go
request := ai.GenerateRequest{Messages: []*ai.Message{
{Content: []*ai.Part{ai.NewTextPart("You are a helpful AI assistant named Walt.")}},
}}
model.Generate(context.Background(), &request, nil)
在大多数情况下,您需要在提示中添加一些由用户提供的内容。 您可以定义一个函数来渲染它们,如下所示:
Go
func helloPrompt(name string) *ai.Part {
prompt := fmt.Sprintf("You are a helpful AI assistant named Walt. Say hello to %s.", name)
return ai.NewTextPart(prompt)
}
request := ai.GenerateRequest{Messages: []*ai.Message{
{Content: []*ai.Part{helloPrompt("Fred")}},
}}
response, err := model.Generate(context.Background(), &request, nil)
不过,在代码中定义提示的一个缺点是,测试需要执行 将它们作为数据流的一部分为了加快迭代速度,Genkit 提供了一个工具 定义提示并在开发者界面中运行提示。
Go
使用 DefinePrompt
函数向 Genkit 注册提示。
type HelloPromptInput struct {
UserName string
}
helloPrompt := ai.DefinePrompt(
"prompts",
"helloPrompt",
nil, // Additional model config
jsonschema.Reflect(&HelloPromptInput{}),
func(ctx context.Context, input any) (*ai.GenerateRequest, error) {
params, ok := input.(HelloPromptInput)
if !ok {
return nil, errors.New("input doesn't satisfy schema")
}
prompt := fmt.Sprintf(
"You are a helpful AI assistant named Walt. Say hello to %s.",
params.UserName)
return &ai.GenerateRequest{Messages: []*ai.Message{
{Content: []*ai.Part{ai.NewTextPart(prompt)}},
}}, nil
},
)
提示操作定义了一个返回 GenerateRequest
的函数,
可用于任何模型。您还可以选择定义输入架构
与流的输入架构类似。
提示还可以定义任何常见的模型配置选项,例如
温度或输出词元数量。
您可以使用提供的辅助函数将此提示渲染到模型请求。 提供提示所需的输入变量以及要调用的模型。
Go
request, err := helloPrompt.Render(context.Background(), HelloPromptInput{UserName: "Fred"})
if err != nil {
return err
}
response, err := model.Generate(context.Background(), request, nil)
在 Genkit 开发者界面中,您可以运行以这种方式定义的任何提示。 这样,你就可以对超出以下范围的单个提示进行实验: 可能用到的流
点提示
Genkit 包含 Dotprompt 库,该库新增了 添加提示的功能
- 正在从
.prompt
源文件加载提示 - 基于手柄的模板
- 支持多轮提示模板和多媒体内容
- 简洁的输入和输出架构定义
- 通过
generate()
流利使用