Documentation
¶
Overview ¶
Package structured 提供 LLM 结构化输出能力
本包实现了类型安全的 LLM 结构化输出,支持:
- 自动 Schema 生成:从 Go 类型自动生成 JSON Schema
- 格式指令注入:自动在 Prompt 中添加格式说明
- 自动解析验证:JSON 解析 + 自定义验证
- 失败重试修复:解析失败时自动重试并附带错误信息
本包用 Go 泛型提供了 编译时类型安全的结构化输出体验。核心思路是:
- 从 Go 类型自动推导 JSON Schema
- 将 Schema 作为格式指令注入到系统提示词中
- 调用 LLM 获取 JSON 响应
- 解析并验证响应,失败时自动重试
使用示例:
type User struct {
Name string `json:"name" desc:"用户名"`
Age int `json:"age" desc:"年龄"`
Email string `json:"email" desc:"邮箱"`
}
user, err := structured.Generate[User](ctx, provider, "从以下文本中提取用户信息:张三,25岁,zhangsan@example.com")
带自定义选项:
user, err := structured.Generate[User](ctx, provider, prompt,
structured.WithModel("gpt-4o"),
structured.WithMaxRetries(5),
structured.WithTemperature(0.1),
)
使用自定义消息:
messages := []llm.Message{
llm.SystemMessage("你是一个数据提取专家"),
llm.UserMessage("提取用户信息:张三,25岁"),
}
user, err := structured.GenerateWithMessages[User](ctx, provider, messages)
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Generate ¶
func Generate[T any](ctx context.Context, provider llm.Provider, prompt string, opts ...Option) (T, error)
Generate 从 LLM 生成结构化输出
这是本包的核心函数,完整流程:
- 从类型参数 T 自动生成 JSON Schema
- 构建包含格式指令的系统消息和用户消息
- 调用 LLM Provider 获取响应
- 使用 JSONParser 解析响应为类型 T
- 解析失败时自动重试,附带错误信息帮助 LLM 修正
类型参数 T 必须是可 JSON 序列化的结构体类型。 支持使用 `json` tag 指定字段名,`desc` tag 添加字段描述
参数:
- ctx: 上下文,支持超时和取消
- provider: LLM 提供者实例
- prompt: 用户提示词,描述要提取/生成的内容
- opts: 可选配置项
返回:
- T: 解析后的结构化结果
- error: 失败时返回 *Error 类型,包含所有尝试的详细信息
示例:
type Movie struct {
Title string `json:"title" desc:"电影名称"`
Year int `json:"year" desc:"上映年份"`
Genres []string `json:"genres" desc:"类型列表"`
Rating float64 `json:"rating" desc:"评分 (0-10)"`
}
movie, err := structured.Generate[Movie](ctx, provider,
"告诉我关于电影《肖申克的救赎》的信息",
structured.WithModel("gpt-4o"),
structured.WithTemperature(0.1),
)
func GenerateWithMessages ¶
func GenerateWithMessages[T any](ctx context.Context, provider llm.Provider, messages []llm.Message, opts ...Option) (T, error)
GenerateWithMessages 使用自定义消息列表生成结构化输出
与 Generate 类似,但允许传入完整的消息列表,适用于:
- 需要多轮对话上下文
- 需要自定义系统提示词
- 需要包含示例对话 (few-shot)
格式指令会作为系统消息插入到消息列表的最前面, 确保 LLM 始终知道输出格式要求
参数:
- ctx: 上下文,支持超时和取消
- provider: LLM 提供者实例
- messages: 自定义消息列表
- opts: 可选配置项
返回:
- T: 解析后的结构化结果
- error: 失败时返回 *Error 类型
示例:
messages := []llm.Message{
llm.SystemMessage("你是一个数据提取专家,擅长从文本中提取结构化信息"),
llm.UserMessage("请提取以下简历中的个人信息:\n张三,男,30岁,高级工程师..."),
}
profile, err := structured.GenerateWithMessages[Profile](ctx, provider, messages)
Types ¶
type Error ¶
type Error struct {
// Attempts 所有尝试的错误记录
Attempts []AttemptError
}
Error 结构化输出错误
当所有重试均失败时返回此错误。包含每次尝试的详细信息, 便于调试和排查问题。
可通过 errors.As 进行类型断言:
var structErr *structured.Error
if errors.As(err, &structErr) {
for i, attempt := range structErr.Attempts {
fmt.Printf("第 %d 次尝试: 输出=%s, 错误=%v\n", i+1, attempt.Output, attempt.Err)
}
}
type Option ¶
type Option func(*config)
Option 配置选项函数类型
使用函数式选项模式,支持链式配置:
structured.Generate[T](ctx, provider, prompt,
structured.WithModel("gpt-4o"),
structured.WithMaxRetries(5),
)
func WithMaxRetries ¶
WithMaxRetries 设置最大重试次数
当 JSON 解析或验证失败时,会自动重试并在消息中附带错误信息, 让 LLM 有机会纠正输出。默认值为 3
func WithNativeJSONSchema ¶
WithNativeJSONSchema 启用 provider 原生 JSON Schema 强制解码
开启后把从类型 T 生成的(严格化)Schema 经 ResponseFormat 下发给 provider, 由 provider 端约束解码,而非仅靠 prompt 注入 + 解析重试。对支持的 provider 能从根本上保证输出合法;不支持的 provider 忽略该字段、自动退化为 prompt 注入。 name 为可选的 schema 名称(空则用 "structured_output")。
func WithStrictMode ¶
WithStrictMode 设置严格解析模式
开启后 JSON 解析不允许多余字段(DisallowUnknownFields)。 默认关闭,适用于 LLM 可能返回额外说明字段的场景