template

package
v0.5.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 13, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package template 提供 LLM 提示词模板引擎

本包实现了完整的提示词模板系统:

  • 变量替换:{{ variable }}

  • 条件语句:{% if condition %}...{% endif %}

  • 循环语句:{% for item in items %}...{% endfor %}

  • 过滤器:{{ value | filter }}

  • 模板继承和包含

  • 提示词版本控制

  • Jinja2: 模板语法

  • Semantic Kernel: 语义函数模板

使用示例:

tpl := template.New("greeting", "Hello, {{ name }}!")
result, err := tpl.Execute(map[string]any{"name": "World"})
// result: "Hello, World!"

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrTemplateNotFound 模板未找到
	ErrTemplateNotFound = errors.New("template not found")

	// ErrInvalidTemplate 无效模板
	ErrInvalidTemplate = errors.New("invalid template")

	// ErrMissingVariable 缺少变量
	ErrMissingVariable = errors.New("missing required variable")

	// ErrExecutionFailed 执行失败
	ErrExecutionFailed = errors.New("template execution failed")
)
View Source
var (
	// SummarizeTemplate 摘要模板
	SummarizeTemplate = New("summarize", `Please summarize the following text in {{ language | default "English" }}:

{{ text }}

Requirements:
- Keep it concise ({{ max_length | default "200" }} words max)
- Preserve key information
- Use clear and professional language`)

	// TranslateTemplate 翻译模板
	TranslateTemplate = New("translate", `Please translate the following text to {{ target_language }}:

{{ text }}

Note: Maintain the original meaning and tone.`)

	// QATemplate 问答模板
	QATemplate = New("qa", `Based on the following context, answer the question.

Context:
{{ context }}

Question: {{ question }}

Please provide a clear and accurate answer based only on the given context.`)

	// CodeReviewTemplate 代码审查模板
	CodeReviewTemplate = New("code_review", "Please review the following {{ language | default \"code\" }} and provide feedback:\n\n```{{ language }}\n{{ code }}\n```\n\nFocus on:\n- Code quality and best practices\n- Potential bugs or issues\n- Performance considerations\n- Suggestions for improvement")

	// ExtractTemplate 信息提取模板
	ExtractTemplate = New("extract", `Extract the following information from the text:
{{ fields | join ", " }}

Text:
{{ text }}

Respond in JSON format.`)
)

常用提示词模板

Functions

func RegisterBuiltinTemplates

func RegisterBuiltinTemplates(lib *TemplateLibrary)

RegisterBuiltinTemplates 注册内置模板

Types

type ChatTemplate

type ChatTemplate struct {
	// contains filtered or unexported fields
}

ChatTemplate 对话模板

func NewChatTemplate

func NewChatTemplate(name string) *ChatTemplate

NewChatTemplate 创建对话模板

func (*ChatTemplate) AddAssistantMessage

func (ct *ChatTemplate) AddAssistantMessage(template string) *ChatTemplate

AddAssistantMessage 添加助手消息

func (*ChatTemplate) AddSystemMessage

func (ct *ChatTemplate) AddSystemMessage(template string) *ChatTemplate

AddSystemMessage 添加系统消息

func (*ChatTemplate) AddUserMessage

func (ct *ChatTemplate) AddUserMessage(template string) *ChatTemplate

AddUserMessage 添加用户消息

func (*ChatTemplate) Execute

func (ct *ChatTemplate) Execute(variables map[string]any) ([]Message, error)

Execute 执行对话模板

type Example

type Example struct {
	Input  string `json:"input"`
	Output string `json:"output"`
}

Example 示例

type FewShotTemplate

type FewShotTemplate struct {
	// contains filtered or unexported fields
}

FewShotTemplate Few-Shot 学习模板

func NewFewShotTemplate

func NewFewShotTemplate(name string) *FewShotTemplate

NewFewShotTemplate 创建 Few-Shot 模板

func (*FewShotTemplate) Execute

func (ft *FewShotTemplate) Execute(variables map[string]any) (string, error)

Execute 执行模板

func (*FewShotTemplate) Name

func (ft *FewShotTemplate) Name() string

Name 返回模板名称

func (*FewShotTemplate) Validate

func (ft *FewShotTemplate) Validate(variables map[string]any) error

Validate 验证变量

func (*FewShotTemplate) Variables

func (ft *FewShotTemplate) Variables() []Variable

Variables 获取变量列表

func (*FewShotTemplate) WithExampleTemplate

func (ft *FewShotTemplate) WithExampleTemplate(template string) *FewShotTemplate

WithExampleTemplate 设置示例模板

func (*FewShotTemplate) WithExamples

func (ft *FewShotTemplate) WithExamples(examples []Example) *FewShotTemplate

WithExamples 设置示例

func (*FewShotTemplate) WithPrefix

func (ft *FewShotTemplate) WithPrefix(prefix string) *FewShotTemplate

WithPrefix 设置前缀

func (*FewShotTemplate) WithSeparator

func (ft *FewShotTemplate) WithSeparator(sep string) *FewShotTemplate

WithSeparator 设置分隔符

func (*FewShotTemplate) WithSuffix

func (ft *FewShotTemplate) WithSuffix(suffix string) *FewShotTemplate

WithSuffix 设置后缀

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message 消息

type MessageTemplate

type MessageTemplate struct {
	// Role 消息角色
	Role string `json:"role"`

	// Template 内容模板
	Template *PromptTemplate `json:"-"`

	// Content 静态内容(如果不使用模板)
	Content string `json:"content,omitempty"`
}

MessageTemplate 消息模板

func (*MessageTemplate) Execute

func (mt *MessageTemplate) Execute(variables map[string]any) (string, string, error)

Execute 执行消息模板

type PromptTemplate

type PromptTemplate struct {
	// contains filtered or unexported fields
}

PromptTemplate 基础提示词模板

func New

func New(name, tmpl string, variables ...Variable) *PromptTemplate

New 创建新模板

func (*PromptTemplate) Execute

func (pt *PromptTemplate) Execute(variables map[string]any) (string, error)

Execute 执行模板

func (*PromptTemplate) ExecuteContext

func (pt *PromptTemplate) ExecuteContext(ctx context.Context, variables map[string]any) (string, error)

ExecuteContext 带上下文执行模板

在执行前检查 ctx 的取消/超时信号:若 ctx 已取消(或超时),直接返回该错误, 不再进行后续校验与渲染,以尊重调用方的取消语义。

func (*PromptTemplate) Name

func (pt *PromptTemplate) Name() string

Name 返回模板名称

func (*PromptTemplate) Validate

func (pt *PromptTemplate) Validate(variables map[string]any) error

Validate 验证变量

func (*PromptTemplate) Variables

func (pt *PromptTemplate) Variables() []Variable

Variables 获取变量列表

type Template

type Template interface {
	// Name 模板名称
	Name() string

	// Execute 执行模板
	Execute(variables map[string]any) (string, error)

	// ExecuteContext 带上下文执行
	ExecuteContext(ctx context.Context, variables map[string]any) (string, error)

	// Variables 获取所有变量
	Variables() []Variable

	// Validate 验证变量
	Validate(variables map[string]any) error
}

Template 提示词模板接口

type TemplateLibrary

type TemplateLibrary struct {
	// contains filtered or unexported fields
}

TemplateLibrary 模板库

func NewTemplateLibrary

func NewTemplateLibrary() *TemplateLibrary

NewTemplateLibrary 创建模板库

func (*TemplateLibrary) Execute

func (lib *TemplateLibrary) Execute(name string, variables map[string]any) (string, error)

Execute 执行指定模板

func (*TemplateLibrary) Get

func (lib *TemplateLibrary) Get(name string) (Template, error)

Get 获取模板

func (*TemplateLibrary) List

func (lib *TemplateLibrary) List() []string

List 列出所有模板

func (*TemplateLibrary) Register

func (lib *TemplateLibrary) Register(tmpl Template)

Register 注册模板

type Variable

type Variable struct {
	// Name 变量名
	Name string `json:"name"`

	// Type 变量类型
	Type string `json:"type"`

	// Description 描述
	Description string `json:"description"`

	// Required 是否必需
	Required bool `json:"required"`

	// Default 默认值
	Default any `json:"default,omitempty"`

	// Examples 示例值
	Examples []any `json:"examples,omitempty"`
}

Variable 模板变量定义

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL