Skip to main content

自定义 Go 提供者

Go (golang) 提供者允许你使用 Go 脚本作为评估提示的 API 提供者。当你有在 Go 中实现的定制逻辑或模型,并希望将其集成到你的测试套件中时,这非常有用。

info

当前 golang 提供者为实验性功能

配置

要配置 Go 提供者,你需要指定 Go 脚本的路径以及任何你希望传递给脚本的额外选项。以下是一个 YAML 格式的示例配置:

providers:
- id: 'file://path/to/your/script.go'
label: 'Go 提供者' # 此提供者的可选显示标签
config:
additionalOption: 123

Go 脚本

你的 Go 脚本应实现一个 CallApi 函数,该函数接受提示、选项和上下文作为参数。它应返回一个包含至少一个 output 字段的 map[string]interface{}

以下是一个可以与 Go 提供者一起使用的 Go 脚本示例:

package main

import (
"context"
"fmt"
"os"

"github.com/sashabaranov/go-openai"
)

var client *openai.Client

func init() {
client = openai.NewClient(os.Getenv("OPENAI_API_KEY"))
}

func CallApi(prompt string, options map[string]interface{}, ctx map[string]interface{}) (map[string]interface{}, error) {
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT4,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: "你是一家名为 Acme 的初创公司的营销人员。",
},
{
Role: openai.ChatMessageRoleUser,
Content: prompt,
},
},
},
)

if err != nil {
return nil, fmt.Errorf("ChatCompletion 错误: %v", err)
}

return map[string]interface{}{
"output": resp.Choices[0].Message.Content,
}, nil
}

使用提供者

要在你的 promptfoo 配置中使用 Go 提供者:

providers:
- id: 'file://path/to/your/script.go'
config:
# 任何额外的配置选项

或在 CLI 中:

promptfoo eval -p prompt1.txt prompt2.txt -o results.csv -v vars.csv -r 'file://path/to/your/script.go'