Documentation
¶
Overview ¶
Package prompt provides comprehensive prompt template management for LLM applications.
Core Features ¶
- Variable substitution: {{variable}}, {{nested.key}}
- Conditional logic: {{#if condition}}...{{/if}}, {{#else}}...{{/else}}
- Loop iteration: {{#each items}}...{{/each}}, {{@index}}, {{@key}}
- Template composition: include, extend, partials
- Message templates: system, user, assistant
- Few-shot examples with demonstrations
- Chain of thought (CoT) prompting
- Tree of thought (ToT) reasoning
- Self-reflection prompting
Quick Start ¶
renderer, err := prompt.NewTemplate("hello", "Hello, {{name}}!")
result, err := renderer.Render(map[string]any{"name": "World"})
// result = "Hello, World!"
Variable Substitution ¶
Templates support dot notation for nested values:
"User: {{user.name}}, Age: {{user.profile.age}}"
Array access is also supported:
"First item: {{items[0]}}"
Default values:
"Hello, {{name|Anonymous}}!"
Conditionals ¶
"{{#if user.isAdmin}}Admin Panel{{/if}}"
"{{#if count > 0}}{{count}} items{{#else}}No items{{/if}}"
Loops ¶
"{{#each items as item}}[{{@index}}] {{item}}{{/each}}"
"{{#each users as user key idx}}User {{key}}: {{user.name}}{{/each}}"
Template Sets ¶
Organize and reuse templates with a TemplateSet:
ts := prompt.NewTemplateSet()
ts.ParseAndRegister("greeting", "Hello, {{name}}!")
ts.ParseAndRegister("farewell", "Goodbye, {{name}}!")
result, err := ts.Render("greeting", map[string]any{"name": "Alice"})
Few-Shot Learning ¶
fst := prompt.NewFewShotTemplate()
fst.AddExample(map[string]any{"input": "Hello"}, "Hi there!")
fst.AddExample(map[string]any{"input": "Goodbye"}, "See you later!")
fewShotContent, _ := fst.Render()
Chain of Thought ¶
rt := prompt.NewReasoningTemplate() rt.WithFormat(prompt.FormatXML) systemPrompt := rt.BuildSystemPrompt()
Message Templates ¶
Build structured conversations:
conv := prompt.NewConversation("assistant")
conv.AddSystem(prompt.MustNewTemplate("sys", "You are a helpful assistant."))
conv.AddUser(prompt.MustNewTemplate("user", "{{question}}"))
messages, _ := conv.Render(map[string]any{"question": "What is Go?"})
Global Registry ¶
Use the global registry for convenience:
prompt.ParseAndRegisterGlobal("hello", "Hello, {{name}}!")
result, _ := prompt.RenderGlobal("hello", map[string]any{"name": "World"})
Index ¶
- Variables
- func ParseAndRegisterGlobal(name, source string) error
- func RegisterGlobal(name string, tpl *Template)
- func RenderGlobal(name string, data map[string]any) (string, error)
- type Block
- type CaseBlock
- type Conversation
- func (c *Conversation) AddAssistant(template *Template) *Conversation
- func (c *Conversation) AddConditional(msg *MessageTemplate) *Conversation
- func (c *Conversation) AddMessage(msg *MessageTemplate) *Conversation
- func (c *Conversation) AddSystem(template *Template) *Conversation
- func (c *Conversation) AddUser(template *Template) *Conversation
- func (c *Conversation) Name() string
- func (c *Conversation) Render(data map[string]any) ([]protocol.Message, error)
- func (c *Conversation) ToChatRequest(model string, data map[string]any) (*protocol.ChatRequest, error)
- func (c *Conversation) WithMetadata(key string, value any) *Conversation
- func (c *Conversation) WithStrictOrder() *Conversation
- type DynamicExampleProvider
- type EachBlock
- type Example
- type ExampleFormatter
- func (ef *ExampleFormatter) Format(example Example) (string, error)
- func (ef *ExampleFormatter) FormatAll(examples []Example) (string, error)
- func (ef *ExampleFormatter) WithInputFormat(format string) *ExampleFormatter
- func (ef *ExampleFormatter) WithOutputFormat(format string) *ExampleFormatter
- func (ef *ExampleFormatter) WithSeparator(sep string) *ExampleFormatter
- type ExampleSelector
- func (es *ExampleSelector) AddExamples(examples ...Example) *ExampleSelector
- func (es *ExampleSelector) AddProvider(provider DynamicExampleProvider) *ExampleSelector
- func (es *ExampleSelector) Select(ctx map[string]any) ([]Example, error)
- func (es *ExampleSelector) WithLimit(limit int) *ExampleSelector
- type FewShotTemplate
- func (fst *FewShotTemplate) AddExample(input map[string]any, output any) *FewShotTemplate
- func (fst *FewShotTemplate) AddExamplesFromData(data []map[string]any) *FewShotTemplate
- func (fst *FewShotTemplate) ExampleCount() int
- func (fst *FewShotTemplate) Merge(other *FewShotTemplate) *FewShotTemplate
- func (fst *FewShotTemplate) Render() (string, error)
- func (fst *FewShotTemplate) WithExampleTemplate(tpl *Template) *FewShotTemplate
- func (fst *FewShotTemplate) WithInputPrefix(prefix string) *FewShotTemplate
- func (fst *FewShotTemplate) WithSeparator(sep string) *FewShotTemplate
- type IfBlock
- type IncludeBlock
- type MapFuncs
- type MessageCondition
- type MessageTemplate
- func (mt *MessageTemplate) Render(data map[string]any) (*protocol.Message, error)
- func (mt *MessageTemplate) ShouldInclude(data map[string]any) bool
- func (mt *MessageTemplate) WithCondition(field, operator string, value any) *MessageTemplate
- func (mt *MessageTemplate) WithMetadata(key string, value any) *MessageTemplate
- type ReasoningFormat
- type ReasoningTemplate
- func (rt *ReasoningTemplate) BuildSystemPrompt() string
- func (rt *ReasoningTemplate) ParseSteps(response string) ([]Step, error)
- func (rt *ReasoningTemplate) ToConversation(userInput string) *Conversation
- func (rt *ReasoningTemplate) WithFormat(format ReasoningFormat) *ReasoningTemplate
- func (rt *ReasoningTemplate) WithStepsTemplate(tpl *Template) *ReasoningTemplate
- func (rt *ReasoningTemplate) WithStopAtStep(step int) *ReasoningTemplate
- type ReflectionTemplate
- type Role
- type SemanticSimilaritySelector
- type Step
- type SwitchBlock
- type Template
- type TemplateSet
- func (ts *TemplateSet) AddDefaultFuncs()
- func (ts *TemplateSet) Extend(name, parentName, childSource string) error
- func (ts *TemplateSet) Get(name string) (*Template, bool)
- func (ts *TemplateSet) List() []string
- func (ts *TemplateSet) MustGet(name string) *Template
- func (ts *TemplateSet) MustRender(name string, data map[string]any) string
- func (ts *TemplateSet) ParseAndRegister(name, source string) error
- func (ts *TemplateSet) Register(name string, tpl *Template)
- func (ts *TemplateSet) RegisterFunc(name string, fn any)
- func (ts *TemplateSet) RegisterPartial(name string, tpl *Template)
- func (ts *TemplateSet) Render(name string, data map[string]any) (string, error)
- func (ts *TemplateSet) ValidateAll() map[string][]ValidationError
- type TextBlock
- type ToTNode
- type TreeOfThought
- type ValidationError
- type VariableBlock
Constants ¶
This section is empty.
Variables ¶
var TemplateRegistry = NewTemplateSet()
TemplateRegistry is a global template registry. Use RegisterGlobal/ParseAndRegisterGlobal for convenience.
Functions ¶
func ParseAndRegisterGlobal ¶
ParseAndRegisterGlobal parses and registers in global registry.
func RegisterGlobal ¶
RegisterGlobal registers a template in the global registry.
Types ¶
type Block ¶
type Block interface {
String() string
}
Block represents a parsed block in the template.
type Conversation ¶
type Conversation struct {
// contains filtered or unexported fields
}
Conversation represents a complete conversation with multiple message templates.
func NewConversation ¶
func NewConversation(name string) *Conversation
NewConversation creates a new conversation.
func (*Conversation) AddAssistant ¶
func (c *Conversation) AddAssistant(template *Template) *Conversation
AddAssistant adds an assistant message.
func (*Conversation) AddConditional ¶
func (c *Conversation) AddConditional(msg *MessageTemplate) *Conversation
AddConditional adds a message with a condition.
func (*Conversation) AddMessage ¶
func (c *Conversation) AddMessage(msg *MessageTemplate) *Conversation
AddMessage adds a message template to the conversation.
func (*Conversation) AddSystem ¶
func (c *Conversation) AddSystem(template *Template) *Conversation
AddSystem adds a system message.
func (*Conversation) AddUser ¶
func (c *Conversation) AddUser(template *Template) *Conversation
AddUser adds a user message.
func (*Conversation) Name ¶
func (c *Conversation) Name() string
Name returns the conversation name.
func (*Conversation) ToChatRequest ¶
func (c *Conversation) ToChatRequest(model string, data map[string]any) (*protocol.ChatRequest, error)
ToChatRequest converts the conversation to a ChatRequest.
func (*Conversation) WithMetadata ¶
func (c *Conversation) WithMetadata(key string, value any) *Conversation
WithMetadata adds conversation metadata.
func (*Conversation) WithStrictOrder ¶
func (c *Conversation) WithStrictOrder() *Conversation
WithStrictOrder enforces strict message ordering.
type DynamicExampleProvider ¶
DynamicExampleProvider allows dynamic example selection.
type ExampleFormatter ¶
type ExampleFormatter struct {
// contains filtered or unexported fields
}
ExampleFormatter formats examples for output.
func NewExampleFormatter ¶
func NewExampleFormatter() *ExampleFormatter
NewExampleFormatter creates a new example formatter.
func (*ExampleFormatter) Format ¶
func (ef *ExampleFormatter) Format(example Example) (string, error)
Format formats a single example.
func (*ExampleFormatter) FormatAll ¶
func (ef *ExampleFormatter) FormatAll(examples []Example) (string, error)
FormatAll formats multiple examples.
func (*ExampleFormatter) WithInputFormat ¶
func (ef *ExampleFormatter) WithInputFormat(format string) *ExampleFormatter
WithInputFormat sets the input format template.
func (*ExampleFormatter) WithOutputFormat ¶
func (ef *ExampleFormatter) WithOutputFormat(format string) *ExampleFormatter
WithOutputFormat sets the output format template.
func (*ExampleFormatter) WithSeparator ¶
func (ef *ExampleFormatter) WithSeparator(sep string) *ExampleFormatter
WithSeparator sets the separator between examples.
type ExampleSelector ¶
type ExampleSelector struct {
// contains filtered or unexported fields
}
ExampleSelector selects examples based on input.
func NewExampleSelector ¶
func NewExampleSelector() *ExampleSelector
NewExampleSelector creates a new example selector.
func (*ExampleSelector) AddExamples ¶
func (es *ExampleSelector) AddExamples(examples ...Example) *ExampleSelector
AddExamples adds static examples.
func (*ExampleSelector) AddProvider ¶
func (es *ExampleSelector) AddProvider(provider DynamicExampleProvider) *ExampleSelector
AddProvider adds a dynamic example provider.
func (*ExampleSelector) Select ¶
func (es *ExampleSelector) Select(ctx map[string]any) ([]Example, error)
Select returns selected examples for the given context.
func (*ExampleSelector) WithLimit ¶
func (es *ExampleSelector) WithLimit(limit int) *ExampleSelector
WithLimit sets the maximum number of examples to select.
type FewShotTemplate ¶
type FewShotTemplate struct {
// contains filtered or unexported fields
}
FewShotTemplate manages few-shot examples in prompt templates.
func NewFewShotTemplate ¶
func NewFewShotTemplate() *FewShotTemplate
NewFewShotTemplate creates a new few-shot template.
func (*FewShotTemplate) AddExample ¶
func (fst *FewShotTemplate) AddExample(input map[string]any, output any) *FewShotTemplate
AddExample adds a static example.
func (*FewShotTemplate) AddExamplesFromData ¶
func (fst *FewShotTemplate) AddExamplesFromData(data []map[string]any) *FewShotTemplate
AddExamplesFromData adds examples from a data source. Each item should have "input" and "output" keys.
func (*FewShotTemplate) ExampleCount ¶
func (fst *FewShotTemplate) ExampleCount() int
ExampleCount returns the number of examples.
func (*FewShotTemplate) Merge ¶
func (fst *FewShotTemplate) Merge(other *FewShotTemplate) *FewShotTemplate
Merge combines another few-shot template.
func (*FewShotTemplate) Render ¶
func (fst *FewShotTemplate) Render() (string, error)
Render renders all examples as a string.
func (*FewShotTemplate) WithExampleTemplate ¶
func (fst *FewShotTemplate) WithExampleTemplate(tpl *Template) *FewShotTemplate
WithExampleTemplate sets a template for rendering examples. Variables like {{input.key}} and {{output}} are available.
func (*FewShotTemplate) WithInputPrefix ¶
func (fst *FewShotTemplate) WithInputPrefix(prefix string) *FewShotTemplate
WithInputPrefix sets the prefix for input sections.
func (*FewShotTemplate) WithSeparator ¶
func (fst *FewShotTemplate) WithSeparator(sep string) *FewShotTemplate
WithSeparator sets the separator between examples.
type IncludeBlock ¶
IncludeBlock represents template composition (include another template).
func (*IncludeBlock) String ¶
func (b *IncludeBlock) String() string
type MessageCondition ¶
type MessageCondition struct {
Field string
Operator string // "eq", "ne", "gt", "lt", "exists", "not_exists"
Value any
}
MessageCondition defines when a message should be included.
func (*MessageCondition) ConditionMet ¶
func (c *MessageCondition) ConditionMet(data map[string]any) bool
ConditionMet checks if the condition is met.
type MessageTemplate ¶
type MessageTemplate struct {
Role Role
Template *Template
Metadata map[string]any
Conditions []MessageCondition
}
MessageTemplate represents a template for a single message.
func AssistantMessage ¶
func AssistantMessage(template *Template) *MessageTemplate
AssistantMessage creates an assistant message template.
func NewMessageTemplate ¶
func NewMessageTemplate(role Role, template *Template) *MessageTemplate
NewMessageTemplate creates a new message template.
func SystemMessage ¶
func SystemMessage(template *Template) *MessageTemplate
SystemMessage creates a system message template.
func UserMessage ¶
func UserMessage(template *Template) *MessageTemplate
UserMessage creates a user message template.
func (*MessageTemplate) ShouldInclude ¶
func (mt *MessageTemplate) ShouldInclude(data map[string]any) bool
ShouldInclude checks if this message template should be included.
func (*MessageTemplate) WithCondition ¶
func (mt *MessageTemplate) WithCondition(field, operator string, value any) *MessageTemplate
WithCondition adds a condition for when this message should be included.
func (*MessageTemplate) WithMetadata ¶
func (mt *MessageTemplate) WithMetadata(key string, value any) *MessageTemplate
WithMetadata adds metadata to the message template.
type ReasoningFormat ¶
type ReasoningFormat int
ReasoningFormat defines how reasoning steps are formatted.
const ( FormatXML ReasoningFormat = iota FormatJSON FormatPlain FormatNumbered )
type ReasoningTemplate ¶
type ReasoningTemplate struct {
// contains filtered or unexported fields
}
ReasoningTemplate provides chain-of-thought prompting.
func NewReasoningTemplate ¶
func NewReasoningTemplate() *ReasoningTemplate
NewReasoningTemplate creates a new reasoning template.
func (*ReasoningTemplate) BuildSystemPrompt ¶
func (rt *ReasoningTemplate) BuildSystemPrompt() string
BuildSystemPrompt builds the system prompt for chain-of-thought.
func (*ReasoningTemplate) ParseSteps ¶
func (rt *ReasoningTemplate) ParseSteps(response string) ([]Step, error)
ParseSteps extracts reasoning steps from the model's response.
func (*ReasoningTemplate) ToConversation ¶
func (rt *ReasoningTemplate) ToConversation(userInput string) *Conversation
ToConversation converts the reasoning template to a conversation.
func (*ReasoningTemplate) WithFormat ¶
func (rt *ReasoningTemplate) WithFormat(format ReasoningFormat) *ReasoningTemplate
WithFormat sets the reasoning format.
func (*ReasoningTemplate) WithStepsTemplate ¶
func (rt *ReasoningTemplate) WithStepsTemplate(tpl *Template) *ReasoningTemplate
WithStepsTemplate sets a custom template for rendering steps. Available variables: {{thought}}, {{action}}, {{result}}, {{@index}}
func (*ReasoningTemplate) WithStopAtStep ¶
func (rt *ReasoningTemplate) WithStopAtStep(step int) *ReasoningTemplate
WithStopAtStep sets when to stop the reasoning (0 = no limit).
type ReflectionTemplate ¶
type ReflectionTemplate struct {
// contains filtered or unexported fields
}
ReflectionTemplate provides self-reflection prompting.
func NewReflectionTemplate ¶
func NewReflectionTemplate() *ReflectionTemplate
NewReflectionTemplate creates a new reflection template.
func (*ReflectionTemplate) BuildCritiqueRequest ¶
func (rt *ReflectionTemplate) BuildCritiqueRequest(response string) *protocol.ChatRequest
BuildCritiqueRequest creates a critique request.
func (*ReflectionTemplate) BuildImprovementRequest ¶
func (rt *ReflectionTemplate) BuildImprovementRequest(critique string) *protocol.ChatRequest
BuildImprovementRequest creates an improvement request.
type SemanticSimilaritySelector ¶
type SemanticSimilaritySelector struct {
// contains filtered or unexported fields
}
SemanticSimilaritySelector selects examples based on semantic similarity. This requires an embedding model.
func NewSemanticSimilaritySelector ¶
func NewSemanticSimilaritySelector(embedder func(string) ([]float32, error)) *SemanticSimilaritySelector
NewSemanticSimilaritySelector creates a new semantic similarity selector.
func (*SemanticSimilaritySelector) SelectBySimilarity ¶
func (ss *SemanticSimilaritySelector) SelectBySimilarity(query string, k int) ([]Example, error)
SelectBySimilarity selects top-k most similar examples.
type Step ¶
type Step struct {
Thought string // The reasoning thought
Action string // The action taken
Result string // The result of the action
}
Step represents a single reasoning step in chain-of-thought.
type SwitchBlock ¶
SwitchBlock represents switch/case logic.
type Template ¶
type Template struct {
// contains filtered or unexported fields
}
Template represents a compiled prompt template.
func MustNewTemplate ¶
MustNewTemplate creates a new template and panics on error.
func NewTemplate ¶
NewTemplate creates a new template from a source string.
func (*Template) Validate ¶
func (t *Template) Validate() []ValidationError
Validate validates the template for common issues.
type TemplateSet ¶
type TemplateSet struct {
// contains filtered or unexported fields
}
TemplateSet manages a collection of templates with shared partials.
func (*TemplateSet) AddDefaultFuncs ¶
func (ts *TemplateSet) AddDefaultFuncs()
AddDefaultFuncs adds default utility functions.
func (*TemplateSet) Extend ¶
func (ts *TemplateSet) Extend(name, parentName, childSource string) error
Extend creates a new template by extending a parent. The parent block can be referenced as {{$super}}.
func (*TemplateSet) Get ¶
func (ts *TemplateSet) Get(name string) (*Template, bool)
Get retrieves a template by name.
func (*TemplateSet) List ¶
func (ts *TemplateSet) List() []string
List returns all registered template names.
func (*TemplateSet) MustGet ¶
func (ts *TemplateSet) MustGet(name string) *Template
MustGet retrieves a template or panics.
func (*TemplateSet) MustRender ¶
func (ts *TemplateSet) MustRender(name string, data map[string]any) string
MustRender renders a named template and panics on error.
func (*TemplateSet) ParseAndRegister ¶
func (ts *TemplateSet) ParseAndRegister(name, source string) error
ParseAndRegister parses a source string and registers it as a template.
func (*TemplateSet) Register ¶
func (ts *TemplateSet) Register(name string, tpl *Template)
Register registers a template in the set.
func (*TemplateSet) RegisterFunc ¶
func (ts *TemplateSet) RegisterFunc(name string, fn any)
RegisterFunc registers a custom function for use in templates.
func (*TemplateSet) RegisterPartial ¶
func (ts *TemplateSet) RegisterPartial(name string, tpl *Template)
RegisterPartial registers a partial template that can be included.
func (*TemplateSet) ValidateAll ¶
func (ts *TemplateSet) ValidateAll() map[string][]ValidationError
ValidateAll validates all templates in the set.
type ToTNode ¶
type ToTNode struct {
Thought string
Score float32
Parent *ToTNode
Children []*ToTNode
Depth int
Visited bool
}
ToTNode represents a single node in the reasoning tree.
type TreeOfThought ¶
type TreeOfThought struct {
// contains filtered or unexported fields
}
TreeOfThought represents branching reasoning paths.
func NewTreeOfThought ¶
func NewTreeOfThought() *TreeOfThought
NewTreeOfThought creates a new tree of thought.
func (*TreeOfThought) AddRoot ¶
func (tot *TreeOfThought) AddRoot(thought string) *ToTNode
AddRoot adds a root thought.
func (*TreeOfThought) BestPath ¶
func (tot *TreeOfThought) BestPath() []*ToTNode
BestPath returns the best reasoning path based on scores.
func (*TreeOfThought) String ¶
func (tot *TreeOfThought) String() string
String returns a string representation of the path.
func (*TreeOfThought) WithBranchLimit ¶
func (tot *TreeOfThought) WithBranchLimit(limit int) *TreeOfThought
WithBranchLimit sets the maximum branches per node.
func (*TreeOfThought) WithMaxDepth ¶
func (tot *TreeOfThought) WithMaxDepth(depth int) *TreeOfThought
WithMaxDepth sets the maximum reasoning depth.
type ValidationError ¶
ValidationError represents a template validation error.
func (ValidationError) Error ¶
func (e ValidationError) Error() string
type VariableBlock ¶
VariableBlock represents a variable substitution.
func (*VariableBlock) Interpolate ¶
func (b *VariableBlock) Interpolate(data map[string]any) string
Interpolate evaluates the block and returns the result.
func (*VariableBlock) String ¶
func (b *VariableBlock) String() string