prompt

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2026 License: MIT Imports: 6 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var TemplateRegistry = NewTemplateSet()

TemplateRegistry is a global template registry. Use RegisterGlobal/ParseAndRegisterGlobal for convenience.

Functions

func ParseAndRegisterGlobal

func ParseAndRegisterGlobal(name, source string) error

ParseAndRegisterGlobal parses and registers in global registry.

func RegisterGlobal

func RegisterGlobal(name string, tpl *Template)

RegisterGlobal registers a template in the global registry.

func RenderGlobal

func RenderGlobal(name string, data map[string]any) (string, error)

RenderGlobal renders a template from the global registry.

Types

type Block

type Block interface {
	String() string
}

Block represents a parsed block in the template.

type CaseBlock

type CaseBlock struct {
	Value  string
	Blocks []Block
}

CaseBlock represents a single case in switch.

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) Render

func (c *Conversation) Render(data map[string]any) ([]protocol.Message, error)

Render renders all messages in the conversation.

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

type DynamicExampleProvider interface {
	GetExamples(ctx map[string]any) ([]Example, error)
}

DynamicExampleProvider allows dynamic example selection.

type EachBlock

type EachBlock struct {
	Path        string
	ItemName    string
	KeyName     string
	InnerBlocks []Block
}

EachBlock represents iteration over a collection.

func (*EachBlock) String

func (b *EachBlock) String() string

type Example

type Example struct {
	Input  map[string]any
	Output any
}

Example represents a single example in few-shot learning.

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 IfBlock

type IfBlock struct {
	Condition  string
	ThenBlocks []Block
	ElseBlocks []Block
	Negate     bool
}

IfBlock represents conditional logic.

func (*IfBlock) String

func (b *IfBlock) String() string

type IncludeBlock

type IncludeBlock struct {
	TemplateName string
	Params       map[string]any
}

IncludeBlock represents template composition (include another template).

func (*IncludeBlock) String

func (b *IncludeBlock) String() string

type MapFuncs

type MapFuncs map[string]any

MapFuncs contains custom functions available in templates.

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) Render

func (mt *MessageTemplate) Render(data map[string]any) (*protocol.Message, error)

Render renders the message template to a protocol.Message.

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 Role

type Role string

Role represents the role in a conversation.

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

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

type SwitchBlock struct {
	Variable string
	Cases    []CaseBlock
	Default  []Block
}

SwitchBlock represents switch/case logic.

type Template

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

Template represents a compiled prompt template.

func MustNewTemplate

func MustNewTemplate(name, source string) *Template

MustNewTemplate creates a new template and panics on error.

func NewTemplate

func NewTemplate(name, source string) (*Template, error)

NewTemplate creates a new template from a source string.

func (*Template) Name

func (t *Template) Name() string

Name returns the template name.

func (*Template) Render

func (t *Template) Render(data map[string]any) (string, error)

Render renders the template with the given data.

func (*Template) Source

func (t *Template) Source() string

Source returns the original 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 NewTemplateSet

func NewTemplateSet() *TemplateSet

NewTemplateSet creates a new template set.

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) Render

func (ts *TemplateSet) Render(name string, data map[string]any) (string, error)

Render renders a named template with data.

func (*TemplateSet) ValidateAll

func (ts *TemplateSet) ValidateAll() map[string][]ValidationError

ValidateAll validates all templates in the set.

type TextBlock

type TextBlock struct {
	Content string
}

TextBlock represents static text content.

func (*TextBlock) String

func (b *TextBlock) String() string

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.

func (*ToTNode) AddChild

func (n *ToTNode) AddChild(thought string, score float32) *ToTNode

AddChild adds a child node to a parent.

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

type ValidationError struct {
	Path    string
	Message string
}

ValidationError represents a template validation error.

func (ValidationError) Error

func (e ValidationError) Error() string

type VariableBlock

type VariableBlock struct {
	Path    string
	Default string
}

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

Jump to

Keyboard shortcuts

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