prompt

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: Apache-2.0 Imports: 20 Imported by: 8

Documentation

Overview

Package prompt provides template-based prompt management and assembly.

This package implements a registry system for loading, caching, and assembling prompt templates via repository interfaces:

  • Fragment-based prompt composition
  • Variable substitution with required/optional vars
  • Model-specific overrides (template modifications only)
  • Tool allowlist integration
  • Version tracking and content hashing

The Registry uses the repository pattern to load prompt configs, avoiding direct file I/O. It resolves fragment references, performs template variable substitution, and generates AssembledPrompt objects ready for LLM execution.

Architecture

For system architecture and design patterns, see:

Usage

Create a registry with a repository (config-first pattern):

repo := memory.NewRepository()
registry := prompt.NewRegistryWithRepository(repo)
assembled := registry.LoadWithVars("task_type", vars, "gpt-4")

See package github.com/AltairaLabs/PromptKit/sdk for higher-level APIs.

Index

Constants

View Source
const (
	// AutonomyLevelSuggests — produces output, a human performs any action.
	AutonomyLevelSuggests = "suggests"
	// AutonomyLevelActsWithApproval — acts, but each consequential action is
	// approved first.
	AutonomyLevelActsWithApproval = "acts_with_approval"
	// AutonomyLevelActsWithOversight — acts on its own; a human monitors and
	// can intervene or reverse.
	AutonomyLevelActsWithOversight = "acts_with_oversight"
	// AutonomyLevelActsAutonomously — acts without a human in the loop.
	AutonomyLevelActsAutonomously = "acts_autonomously"
)

AutonomyLevel values named by RFC 0013. The schema closes this enum, so a value outside these four fails validation.

View Source
const (
	// RequirementKeyDefault is reserved for the primary LLM.
	RequirementKeyDefault = "default"
	// RequirementRoleLLM is the role a bare string shorthand expands to.
	RequirementRoleLLM = "llm"
	// AnyKey marks a role the host can satisfy under any key, for providers
	// supplied without an identifier to match on.
	AnyKey = "*"
)

Reserved requirement keys and roles named by RFC 0012.

View Source
const DefaultBlockedMessage = "Sorry, we can't provide this response as it would violate our content policy."

DefaultBlockedMessage is the user-facing message shown when a content guardrail blocks output.

View Source
const PromptPackSchemaURL = "https://promptpack.org/schema/latest/promptpack.schema.json"

PromptPackSchemaURL is the JSON Schema URL for validating PromptPack files

Variables

This section is empty.

Functions

func DescribeGovernance added in v1.8.0

func DescribeGovernance(g *Governance) string

DescribeGovernance renders a governance declaration as a short human-readable summary, for logs and for the operator who has to answer "what does this thing claim about itself".

Only declared fields appear: an undeclared field is not the same as a default, and printing "autonomy: unknown" invites reading absence as a value.

func DescribeUnsatisfied added in v1.8.0

func DescribeUnsatisfied(reqs []ResolvedRequirement) string

DescribeUnsatisfied renders requirements for an error or log message, naming what the pack asked for and why, so an operator can act without opening the pack. The description exists in the spec for exactly this purpose.

func ExtractVariablesFromTemplate

func ExtractVariablesFromTemplate(template string) []string

ExtractVariablesFromTemplate analyzes a template string and extracts variable names This helps auto-generate variable metadata when not explicitly specified

func GetDefaultPipelineConfig

func GetDefaultPipelineConfig() *packspec.PipelineConfig

GetDefaultPipelineConfig returns the default Arena pipeline configuration Returns as map to avoid import cycle with pipeline package GetDefaultPipelineConfig returns the pipeline a pack gets when it declares none: template, provider and validator stages with their default middleware.

Typed now that PackPrompt.Pipeline is the generated *PipelineConfig rather than a map[string]any.

func GetUsedVars deprecated

func GetUsedVars(vars map[string]string) []string

GetUsedVars returns a list of variable names that had non-empty values

Deprecated: Use template.GetUsedVars instead

func SetMetadataChangelog added in v1.8.0

func SetMetadataChangelog(m *Metadata, entries []ChangelogEntry)

SetMetadataChangelog stores the version history in the metadata envelope. An empty changelog removes the key.

func SetMetadataPerformance added in v1.8.0

func SetMetadataPerformance(m *Metadata, p *PerformanceMetrics)

SetMetadataPerformance stores performance benchmarks in the metadata envelope. A nil value removes the key rather than writing a null, so a pack does not gain a meaningless `"performance": null`.

func SkillPath added in v1.8.0

func SkillPath(s *SkillSourceConfig) string

SkillPath returns the path a skill source points at, resolving the bare-string shorthand. A free function because SkillSourceConfig is the generated type and an alias cannot carry methods.

func SupportsMediaType added in v1.1.0

func SupportsMediaType(config *MediaConfig, mediaType string) bool

SupportsMediaType checks if a MediaConfig supports a specific media type

func ValidateMediaConfig added in v1.1.0

func ValidateMediaConfig(config *MediaConfig) error

ValidateMediaConfig validates a MediaConfig for correctness and completeness

Types

type AgentDef added in v1.3.1

type AgentDef = packspec.AgentDef

AgentDef provides A2A Agent Card metadata for a single prompt.

Generated from the schema: this is an ALIAS for packspec.AgentDef, not a copy. An alias keeps every call site, tag and behavior identical while making the schema the single source of the shape — a defined type would not, and the two would be free to drift again.

The hand-written struct it replaced was already field-for-field identical to $defs/AgentDef, which is why it is first: the switch is provably a no-op.

type AgentsConfig added in v1.3.1

type AgentsConfig = packspec.AgentsConfig

AgentsConfig maps prompts to A2A-compatible agent definitions.

Generated from the schema: an ALIAS for packspec.AgentsConfig.

type AssembledPrompt

type AssembledPrompt struct {
	TaskType     string            `json:"task_type"`
	SystemPrompt string            `json:"system_prompt"`
	AllowedTools []string          `json:"allowed_tools,omitempty"` // Tools this prompt can use
	Validators   []ValidatorConfig `json:"validators,omitempty"`    // Validators to apply at runtime
}

AssembledPrompt represents a complete prompt ready for LLM execution.

func (*AssembledPrompt) UsesTools

func (ap *AssembledPrompt) UsesTools() bool

UsesTools returns true if this prompt has tools configured

type AudioConfig added in v1.1.0

type AudioConfig = packspec.AudioConfig

AudioConfig contains audio-specific configuration AudioConfig is generated from the schema: an ALIAS for packspec.AudioConfig, not a copy. The hand-written struct was field-for-field identical to $defs/AudioConfig.

func GetAudioConfig added in v1.1.0

func GetAudioConfig(config *MediaConfig) *AudioConfig

GetAudioConfig returns the audio configuration if audio is supported

type ChangelogEntry

type ChangelogEntry struct {
	// Version number
	Version string `yaml:"version" json:"version"`
	// Date of change (YYYY-MM-DD)
	Date string `yaml:"date" json:"date"`
	// Author of change
	Author string `yaml:"author,omitempty" json:"author,omitempty"`
	// Description of change
	Description string `yaml:"description" json:"description"`
}

ChangelogEntry records a change in the prompt configuration

func MetadataChangelog added in v1.8.0

func MetadataChangelog(m *Metadata) []ChangelogEntry

MetadataChangelog returns the version history a pack declares, or nil. See MetadataPerformance for why this is not a struct field.

type CompilationInfo

type CompilationInfo = packspec.PackCompilation

CompilationInfo records when and how a pack was compiled.

Generated. `compilation` is a spec property with a defined shape (compiled_with, created_at and schema are all required), not a promptkit extension — it was hand-written here on the false premise that it was one.

type CompileOption added in v1.3.1

type CompileOption func(*compileOptions)

CompileOption configures optional fields for CompileFromRegistryWithOptions.

func WithAgents added in v1.3.1

func WithAgents(a *AgentsConfig) CompileOption

WithAgents sets the agents config on the compiled pack.

func WithCompositions added in v1.5.0

func WithCompositions(c map[string]*composition.Composition) CompileOption

WithCompositions sets the compositions map on the compiled pack.

func WithSkills added in v1.4.5

func WithSkills(s []SkillSourceConfig) CompileOption

WithSkills sets the skills config on the compiled pack.

func WithWorkflow added in v1.3.1

func WithWorkflow(w *workflow.Spec) CompileOption

WithWorkflow sets the workflow config on the compiled pack.

type Config added in v1.1.3

type Config struct {
	APIVersion string            `yaml:"apiVersion" json:"apiVersion"`
	Kind       string            `yaml:"kind" json:"kind"`
	Metadata   metav1.ObjectMeta `yaml:"metadata,omitempty" json:"metadata,omitempty"`
	Spec       Spec              `yaml:"spec" json:"spec"`
}

Config represents a YAML prompt configuration file in K8s-style manifest format

func ParseConfig added in v1.1.3

func ParseConfig(data []byte) (*Config, error)

ParseConfig parses a prompt config from YAML data. This is a package-level utility function for parsing prompt configs in the config layer. The config layer should read files using os.ReadFile and pass the data to this function. Returns the parsed Config or an error if parsing/validation fails.

func ToConfig added in v1.8.0

func ToConfig(pr *PackPrompt, taskType string) *Config

ToConfig converts a pack prompt into a prompt.Config suitable for registration in a prompt.Registry. It carries the fields the prompt-assembly pipeline needs; tools and validators are wired separately by the caller.

func (*Config) GetAllowedTools added in v1.1.5

func (c *Config) GetAllowedTools() []string

GetAllowedTools returns the allowed tools from the prompt config

func (*Config) GetTaskType added in v1.1.5

func (c *Config) GetTaskType() string

GetTaskType returns the task type from the prompt config

type CostEstimate

type CostEstimate = packspec.PackMetadataCostEstimate

CostEstimate provides estimated costs for prompt execution.

Generated, for the same reason as Metadata. Note the fields are *float64: the spec makes all three optional, and a plain float64 cannot tell "no estimate" from "estimated at zero".

type DocumentConfig added in v1.8.0

type DocumentConfig = packspec.DocumentConfig

DocumentConfig configures document media (PDFs, CAD files, spreadsheets). Reachable now that MediaConfig is the generated type.

type ExampleContentPart added in v1.1.0

type ExampleContentPart = packspec.ContentPart

ExampleContentPart is one content part of a multimodal example.

Generated. This is $defs/ContentPart, the PACK authoring type — distinct from types.ContentPart, which is the runtime message type and a different graph.

type ExampleMedia added in v1.1.0

type ExampleMedia = packspec.MediaReference

ExampleMedia is a media reference inside a multimodal example.

Generated. The hand-written version was identical property-for-property except that it lacked `base64`, so a pack embedding media inline lost it.

Note the Go field is MimeType, not MIMEType: the generator derives names from the schema, and renaming it by hand would put this type back outside the generated guarantee for the sake of two characters.

type FileWriter added in v1.1.0

type FileWriter interface {
	WriteFile(path string, data []byte, perm os.FileMode) error
}

FileWriter abstracts file writing for testing

type Fragment

type Fragment struct {
	Type              string `yaml:"fragment_type"`
	Version           string `yaml:"version"`
	Description       string `yaml:"description"`
	Content           string `yaml:"content"`
	SourceFile        string `yaml:"source_file,omitempty"`         // Source file path (for pack compilation)
	ResolvedAtCompile bool   `yaml:"resolved_at_compile,omitempty"` // Whether resolved at compile time
}

Fragment represents a reusable prompt fragment

type FragmentRef

type FragmentRef struct {
	Name     string `yaml:"name"`
	Path     string `yaml:"path,omitempty"` // Optional: relative path to fragment file
	Required bool   `yaml:"required"`
}

FragmentRef references a prompt fragment for assembly

type FragmentRepository

type FragmentRepository interface {
	LoadFragment(name, relativePath, baseDir string) (*Fragment, error)
}

FragmentRepository interface for loading fragments (to avoid import cycles)

type FragmentResolver

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

FragmentResolver handles fragment loading, resolution, and variable substitution using the repository pattern

func NewFragmentResolverWithRepository

func NewFragmentResolverWithRepository(repository FragmentRepository) *FragmentResolver

NewFragmentResolverWithRepository creates a new fragment resolver with a repository

func (*FragmentResolver) AssembleFragments

func (fr *FragmentResolver) AssembleFragments(
	fragments []FragmentRef,
	vars map[string]string,
	configFilePath string,
) (map[string]string, error)

AssembleFragments loads and assembles prompt fragments into variables. Resolves dynamic names and paths using the provided variable map.

func (*FragmentResolver) LoadFragment

func (fr *FragmentResolver) LoadFragment(name, relativePath, configFilePath string) (*Fragment, error)

LoadFragment loads a fragment from the repository with caching. Uses name as cache key, or path if provided.

type Governance added in v1.8.0

type Governance = packspec.Governance

Governance is a governance declaration, at pack or agent level.

func AgentGovernance added in v1.8.0

func AgentGovernance(pack *Pack, agent string) (*Governance, error)

AgentGovernance returns an agent's own governance declaration as written, without inheriting anything from the pack. Use ResolveGovernance for the effective values; this is for reporting what the pack actually says.

The error distinguishes "this agent declares no governance" from "there is no such agent" — see ResolveGovernance.

func PackGovernance added in v1.8.0

func PackGovernance(pack *Pack) *Governance

PackGovernance returns the pack-level governance declaration, or nil.

Returns a copy: the result is a statement about the pack, and a caller that adjusted it in place would rewrite the loaded pack for everyone else.

func ResolveGovernance added in v1.8.0

func ResolveGovernance(pack *Pack, agent string) (*Governance, error)

ResolveGovernance returns the effective governance for one agent: the pack declaration with the agent's own fields laid over it.

An unknown agent is an error rather than a fallback to the pack values. For most lookups a quiet fallback is a convenience; for governance it is a lie — a caller asking about "billing-agent" and getting the pack's autonomy level because it typed the name wrong would be told the agent needs no approval when nothing had been checked at all.

An empty agent name returns the pack-level declaration, so callers that may or may not be scoped to an agent need no special case.

type ImageConfig added in v1.1.0

type ImageConfig = packspec.ImageConfig

ImageConfig contains image-specific configuration Generated from the schema: an ALIAS for packspec.ImageConfig. default_detail is *string: the spec defaults it to "auto", so absent and empty differ.

func GetImageConfig added in v1.1.0

func GetImageConfig(config *MediaConfig) *ImageConfig

GetImageConfig returns the image configuration if images are supported

type Info added in v1.1.3

type Info struct {
	TaskType       string
	Version        string
	Description    string
	FragmentCount  int
	RequiredVars   []string
	OptionalVars   []string
	ToolAllowlist  []string
	ModelOverrides []string
}

Info provides summary information about a prompt configuration

type Loader added in v1.1.3

type Loader interface {
	LoadConfig(taskType string) (*Config, error)
	ListTaskTypes() []string
}

Loader interface abstracts the registry for testing

type MediaConfig added in v1.1.0

type MediaConfig = packspec.MediaConfig

MediaConfig configures multimodal support for a prompt.

Generated. It was hand-written, and dropped $defs/MediaConfig's `document` property entirely — a prompt declaring document media round-tripped to nothing. Same failure as metadata.governance, same fix.

type Metadata added in v1.1.3

type Metadata = packspec.PackMetadata

Metadata contains additional metadata for the pack format.

This is the generated type: metadata is where the PromptPack spec puts the facts a pack declares ABOUT itself rather than about its execution, so it is where formalization lands as the spec grows — v1.6.0 added `governance` (RFC 0013: accountable owner, autonomy level, risk classification), and more of that shape is coming. A hand-written struct here dropped `governance` silently on load: the field validated, round-tripped clean, and vanished.

Generated means new spec properties arrive by regeneration, and `make packspec-check` fails if they have not.

Performance and Changelog are NOT spec properties. They live in Extra, which the spec permits (metadata is additionalProperties:true), and are reached through the accessors below rather than as struct fields.

type MetadataBuilder

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

MetadataBuilder helps construct pack format metadata from prompt configs and test results

func NewMetadataBuilder

func NewMetadataBuilder(spec *Spec) *MetadataBuilder

NewMetadataBuilder creates a new metadata builder for a prompt spec

func (*MetadataBuilder) AddChangelogEntry

func (mb *MetadataBuilder) AddChangelogEntry(version, author, description string)

AddChangelogEntry adds a new entry to the prompt's changelog

func (*MetadataBuilder) BuildCompilationInfo

func (mb *MetadataBuilder) BuildCompilationInfo(compilerVersion string) *CompilationInfo

BuildCompilationInfo generates compilation metadata

func (*MetadataBuilder) BuildMetadata added in v1.1.3

func (mb *MetadataBuilder) BuildMetadata(domain, language string, tags []string, testResults []TestResultSummary) *Metadata

BuildMetadata generates Metadata from test execution results

func (*MetadataBuilder) SetDomain

func (mb *MetadataBuilder) SetDomain(domain string)

SetDomain sets the domain for the prompt metadata

func (*MetadataBuilder) SetLanguage

func (mb *MetadataBuilder) SetLanguage(language string)

SetLanguage sets the language for the prompt metadata

func (*MetadataBuilder) SetTags

func (mb *MetadataBuilder) SetTags(tags []string)

SetTags sets the tags for the prompt metadata

func (*MetadataBuilder) UpdateFromCostInfo

func (mb *MetadataBuilder) UpdateFromCostInfo(costs []types.CostInfo)

UpdateFromCostInfo updates cost estimate from types.CostInfo

func (*MetadataBuilder) ValidateMetadata

func (mb *MetadataBuilder) ValidateMetadata() []string

ValidateMetadata checks that metadata fields are properly populated

type ModelOverride

type ModelOverride = packspec.ModelOverride

ModelOverride contains model-specific template modifications. Note: Temperature and MaxTokens should be configured at the scenario or provider level, not in the prompt configuration.

The spec's $defs/ModelOverride also defines system_template_prefix and parameters. Neither is added here: nothing in the runtime assembles a prefix or applies per-model parameters, so declaring them would be vocabulary with a consumer and no producer. They are recorded as codegen candidates in docs/local-backlog/PACK_TYPES_FROM_SCHEMA_CODEGEN.md rather than added blind. Generated from the schema: an ALIAS for packspec.ModelOverride. Gains system_template_prefix and parameters from the spec.

type ModelTestResultRef

type ModelTestResultRef = packspec.TestedModel

ModelTestResultRef is a simplified reference to model test results The full ModelTestResult type is in pkg/engine for tracking test execution ModelTestResultRef is the Go form of the spec's $defs/TestedModel. It is pinned to that def by TestedModelStructMatchesPromptPackSpec.

provider, model and date are required by the spec, so they carry no omitempty — a required field that vanishes on serialize produces a pack that fails its own validation. Generated from the schema: an ALIAS for packspec.TestedModel. avg_tokens/avg_latency_ms are float64: the spec types them as number, not integer.

func AggregateTestResults

func AggregateTestResults(results []TestResultSummary, provider, model string) *ModelTestResultRef

AggregateTestResults computes ModelTestResultRef from test execution summaries

type MultimodalExample added in v1.1.0

type MultimodalExample = packspec.MultimodalExample

MultimodalExample is a few-shot example carrying media.

Generated, so that MediaConfig.Examples is the generated slice type.

type Pack

type Pack struct {
	packspec.Pack `yaml:",inline"`

	// FilePath is the on-disk path this pack was loaded from, if any. It is
	// never serialized; loaders set it so schema/fragment resolution can
	// resolve paths relative to the pack file.
	FilePath string `json:"-" yaml:"-"`
}

Pack represents a compiled PromptPack.

EMBEDS the generated type rather than aliasing it. Go has no partial classes, and a type alias cannot carry methods — but an embedded type can, and Pack has eighteen (Validate, ValidateWorkflow, ValidateAgents, GetPrompt, ...). Every spec property is promoted from packspec.Pack, so the properties cannot drift even though the methods live here.

This is the general answer for a pack type with behavior attached. An alias is still preferable where the methods are few enough to become free functions, because an alias gives true identity with the generated type; embedding needs .Pack to extract it. Types with a method set that IS their API embed instead.

FilePath is the only field of our own, and it is the reason a bare alias would not do even without the methods.

func LoadPack

func LoadPack(filePath string) (*Pack, error)

LoadPack loads a pack from a JSON file

func (*Pack) GetOptionalVariables

func (p *Pack) GetOptionalVariables(taskType string) map[string]string

GetOptionalVariables returns all optional variable names with defaults for a specific prompt

func (*Pack) GetPrompt

func (p *Pack) GetPrompt(taskType string) *PackPrompt

GetPrompt returns a specific prompt by task type

func (*Pack) GetRequiredVariables

func (p *Pack) GetRequiredVariables(taskType string) []string

GetRequiredVariables returns all required variable names for a specific prompt

func (*Pack) GetTool added in v1.5.5

func (p *Pack) GetTool(name string) *PackTool

GetTool returns a specific tool by name, or nil if not found.

func (*Pack) GetToolNames

func (p *Pack) GetToolNames(taskType string) []string

GetToolNames returns the list of allowed tool names for a specific prompt

func (*Pack) ListPrompts

func (p *Pack) ListPrompts() []string

ListPrompts returns all prompt task types in the pack

func (*Pack) ListTools added in v1.5.5

func (p *Pack) ListTools() []string

ListTools returns all tool names defined in the pack.

func (*Pack) Summary

func (p *Pack) Summary() string

Summary returns a brief summary of the pack

func (*Pack) Validate

func (p *Pack) Validate() []string

Validate validates a pack format

func (*Pack) ValidateAgents added in v1.3.1

func (p *Pack) ValidateAgents() (errors, warnings []string)

ValidateAgents validates the agents section of the pack. Returns errors (which block compilation) and warnings (informational).

func (*Pack) ValidateCompositions added in v1.5.0

func (p *Pack) ValidateCompositions() *composition.ValidationResult

ValidateCompositions validates the pack's compositions (RFC 0010): each composition's internal rules + reference resolution against the pack's prompts/tools/evals, plus pack-level cross-checks against the workflow.

func (*Pack) ValidateWorkflow added in v1.3.1

func (p *Pack) ValidateWorkflow() *workflow.ValidationResult

ValidateWorkflow validates the workflow section and returns a detailed result with separate errors and warnings. Returns an empty result if no workflow is present.

type PackCompiler

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

PackCompiler compiles Config to Pack format

func NewPackCompiler

func NewPackCompiler(registry *Registry) *PackCompiler

NewPackCompiler creates a new pack compiler with default dependencies

func NewPackCompilerWithDeps added in v1.1.0

func NewPackCompilerWithDeps(loader Loader, timeProvider TimeProvider, fileWriter FileWriter) *PackCompiler

NewPackCompilerWithDeps creates a pack compiler with injected dependencies (for testing)

func (*PackCompiler) Compile

func (pc *PackCompiler) Compile(taskType, compilerVersion string) (*Pack, error)

Compile compiles a single prompt config to Pack format (for backward compatibility)

func (*PackCompiler) CompileFromRegistry

func (pc *PackCompiler) CompileFromRegistry(packID, compilerVersion string) (*Pack, error)

CompileFromRegistry compiles ALL prompts from the registry into a single Pack

func (*PackCompiler) CompileFromRegistryWithOptions added in v1.1.11

func (pc *PackCompiler) CompileFromRegistryWithOptions(
	packID, compilerVersion string,
	parsedTools []ParsedTool,
	packEvals []evals.EvalDef,
	opts ...CompileOption,
) (*Pack, error)

CompileFromRegistryWithOptions compiles ALL prompts from the registry into a single Pack with pre-parsed tool definitions, pack-level eval definitions, and optional workflow/agents config.

func (*PackCompiler) CompileFromRegistryWithParsedTools added in v1.1.5

func (pc *PackCompiler) CompileFromRegistryWithParsedTools(
	packID, compilerVersion string,
	parsedTools []ParsedTool,
) (*Pack, error)

CompileFromRegistryWithParsedTools compiles ALL prompts from the registry into a single Pack and includes pre-parsed tool definitions. Use this when YAML parsing happens externally.

func (*PackCompiler) CompileFromRegistryWithTools added in v1.1.5

func (pc *PackCompiler) CompileFromRegistryWithTools(
	packID, compilerVersion string,
	toolData []ToolData,
) (*Pack, error)

CompileFromRegistryWithTools compiles ALL prompts from the registry into a single Pack and includes tool definitions from the provided tool data. This method satisfies PromptPack spec Section 9 which requires tools to be defined at pack level with name, description, and parameters.

func (*PackCompiler) CompileToFile

func (pc *PackCompiler) CompileToFile(taskType, outputPath, compilerVersion string) error

CompileToFile compiles a prompt config to a JSON pack file

func (*PackCompiler) MarshalPack added in v1.1.0

func (pc *PackCompiler) MarshalPack(pack *Pack) ([]byte, error)

MarshalPack marshals pack to JSON (testable without I/O)

func (*PackCompiler) WritePack added in v1.1.0

func (pc *PackCompiler) WritePack(pack *Pack, outputPath string) error

WritePack writes a pack to a file

type PackPrompt

type PackPrompt = packspec.Prompt

PackPrompt is a single prompt definition within a pack.

Generated. It is the hub every prompt hangs off, so adopting it was left until everything reachable from it was generated first — validators, evals, variables, tested_models, model_overrides, media and parameters are all packspec types now, and the generated Prompt holds them as slices and maps of POINTERS, which is the shape the schema implies for optional objects.

ToPromptConfig() was a method. A type alias cannot carry methods, so it is the free function ToConfig below.

type PackTool added in v1.1.5

type PackTool = packspec.Tool

PackTool represents a tool definition in the pack (per PromptPack spec Section 9). Tools are defined at pack level and referenced by prompts via the tools array.

Generated from the schema: an ALIAS for packspec.Tool.

Parameters is *ToolParameters rather than the interface{} the hand-written type used. The spec defines a shape here (type/properties/required) and interface{} ignored it; the generated type keeps that shape while remaining extensible, since Tool.parameters omits additionalProperties and JSON Schema defaults it to true. So a tool schema using $defs, oneOf or any other keyword still round-trips, through ToolParameters.Extra.

func ConvertToolToPackTool added in v1.1.5

func ConvertToolToPackTool(name, description string, inputSchema json.RawMessage) *PackTool

ConvertToolToPackTool converts a tool descriptor to a PackTool This is the preferred method when tool parsing happens externally

type ParametersPack

type ParametersPack = packspec.Parameters

ParametersPack represents model parameters in pack format Generated from the schema: an ALIAS for packspec.Parameters. Gains frequency_penalty and presence_penalty, which the spec defines and the hand-written type omitted.

type ParsedTool added in v1.1.5

type ParsedTool struct {
	Name        string
	Description string
	InputSchema json.RawMessage
}

ParsedTool holds pre-parsed tool information for compilation Use this when YAML parsing happens in the calling package

type PerformanceMetrics

type PerformanceMetrics struct {
	// Average latency in milliseconds
	AvgLatencyMs int `yaml:"avg_latency_ms" json:"avg_latency_ms"`
	// 95th percentile latency
	P95LatencyMs int `yaml:"p95_latency_ms" json:"p95_latency_ms"`
	// Average tokens used
	AvgTokens int `yaml:"avg_tokens" json:"avg_tokens"`
	// Success rate (0.0-1.0)
	SuccessRate float64 `yaml:"success_rate" json:"success_rate"`
}

PerformanceMetrics provides performance benchmarks

func MetadataPerformance added in v1.8.0

func MetadataPerformance(m *Metadata) *PerformanceMetrics

MetadataPerformance returns the performance benchmarks a pack declares, or nil.

performance is not a PromptPack property — it is a PromptKit extension carried in the metadata envelope the spec leaves open. Keeping the type assertion here rather than at each call site is what stops a silent nil creeping in; a value of the wrong shape yields nil rather than a half-populated struct.

type ProviderInventory added in v1.8.0

type ProviderInventory map[string][]string

ProviderInventory is what a host can supply, as role -> available keys.

type ProviderRequirement added in v1.8.0

type ProviderRequirement = packspec.ProviderRequirement

ProviderRequirement is a single logical provider dependency.

type Registry

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

Registry manages prompt templates, versions, and variable substitution.

func NewRegistryWithRepository

func NewRegistryWithRepository(repository Repository) *Registry

NewRegistryWithRepository creates a registry with a repository (new preferred method). This constructor uses the repository pattern for loading prompts, avoiding direct file I/O.

func (*Registry) ClearCache

func (r *Registry) ClearCache()

ClearCache clears all cached prompts and fragments

func (*Registry) GetAvailableRegions

func (r *Registry) GetAvailableRegions() []string

GetAvailableRegions returns a list of all available regions from prompt fragments

func (*Registry) GetAvailableTaskTypes

func (r *Registry) GetAvailableTaskTypes() []string

GetAvailableTaskTypes is deprecated: use ListTaskTypes instead

func (*Registry) GetCachedFragments

func (r *Registry) GetCachedFragments() []string

GetCachedFragments returns a list of currently cached fragment keys.

func (*Registry) GetCachedPrompts

func (r *Registry) GetCachedPrompts() []string

GetCachedPrompts returns a list of currently cached prompt task types. For a complete list including uncached prompts, use ListTaskTypes instead.

func (*Registry) GetInfo added in v1.1.3

func (r *Registry) GetInfo(taskType string) (*Info, error)

GetInfo returns detailed information about a prompt configuration

func (*Registry) GetLoadedFragments

func (r *Registry) GetLoadedFragments() []string

GetLoadedFragments is deprecated: use GetCachedFragments instead

func (*Registry) GetLoadedPrompts

func (r *Registry) GetLoadedPrompts() []string

GetLoadedPrompts is deprecated: use GetCachedPrompts instead

func (*Registry) ListTaskTypes

func (r *Registry) ListTaskTypes() []string

ListTaskTypes returns all available task types from the repository. Falls back to cached task types if repository is unavailable or returns empty.

func (*Registry) Load

func (r *Registry) Load(activity string) *AssembledPrompt

Load returns an assembled prompt for the specified activity with variable substitution.

func (*Registry) LoadConfig

func (r *Registry) LoadConfig(activity string) (*Config, error)

LoadConfig is deprecated: use loadConfig directly (internal use) or use Load/LoadWithVars

func (*Registry) LoadTemplate added in v1.3.26

func (r *Registry) LoadTemplate(activity string, vars map[string]string, model string) (*Template, error)

LoadTemplate loads a prompt without rendering, returning the raw template and all metadata needed to render it later. This is the preferred path for pipeline stages that separate assembly from rendering (e.g. PromptAssemblyStage + TemplateStage). The returned Template is safe to cache across requests.

func (*Registry) LoadWithVars

func (r *Registry) LoadWithVars(activity string, vars map[string]string, model string) *AssembledPrompt

LoadWithVars loads a prompt with variable substitution and optional model override.

func (*Registry) RegisterConfig

func (r *Registry) RegisterConfig(taskType string, config *Config) error

RegisterConfig registers a Config directly into the registry. This allows programmatic registration of prompts without requiring disk files. Useful for loading prompts from compiled packs or other in-memory sources. If a repository is configured, the config is persisted there as well.

type Repository added in v1.1.3

type Repository interface {
	LoadPrompt(taskType string) (*Config, error)
	LoadFragment(name, relativePath, baseDir string) (*Fragment, error)
	ListPrompts() ([]string, error)
	SavePrompt(config *Config) error
}

Repository interface defines methods for loading prompts (to avoid import cycles) This should match persistence.Repository interface

type Requires added in v1.8.0

type Requires = packspec.PackRequires

Requires is the pack-level requirements block.

type ResolvedRequirement added in v1.8.0

type ResolvedRequirement struct {
	Key         string
	Role        string
	Description string
	Required    bool
}

ResolvedRequirement is a requirement with the spec's defaults applied, so consumers never have to know which fields were written and which were implied.

func ResolveRequirements added in v1.8.0

func ResolveRequirements(p *Pack) ([]ResolvedRequirement, error)

ResolveRequirements expands a pack's requirements into their full form and reports the spec's structural rules.

Two rules the JSON Schema cannot express, both stated in prose by RFC 0012:

  • a bare string is shorthand for {key: <string>, role: "llm", required: true}
  • key values MUST be unique, key being the sole discriminator between requirements

A duplicate key is an error rather than a last-one-wins merge: two entries with one key means the author intended two providers and will get one, which is the kind of silent loss this whole area keeps producing.

func Unsatisfied added in v1.8.0

func Unsatisfied(reqs []ResolvedRequirement, have ProviderInventory) (required, optional []ResolvedRequirement)

Unsatisfied splits a pack's requirements into those the inventory cannot satisfy, separating required from optional so the caller can apply the spec's error-versus-warning distinction.

Matching is on key AND role: a requirement for an `embedding` named "judge" is not satisfied by an `llm` named "judge". Resolution beyond that — which concrete model, from where — is explicitly the host's business, not the spec's.

A host may list AnyKey for a role to mean "one provider of this role is wired, but it has no name to match on". That covers providers supplied programmatically rather than by key; without it the check rejects a host that has wired a working provider, and a false failure at Open is worse than no check, because it blocks a correct setup rather than an incorrect one.

type SkillSourceConfig added in v1.3.1

type SkillSourceConfig = packspec.SkillSource

SkillSourceConfig declares a skill source for the pack.

Generated. $defs/SkillSource is a oneOf over a bare string, a SkillPathSource and an InlineSkill; the generator flattens that into one struct AND emits the Marshal/Unmarshal pair that keeps the scalar form in Shorthand, so the union needed no hand-written code at all.

The legacy `dir` alias is GONE. It was promptkit-only, and because $defs/SkillPathSource is additionalProperties:false and requires `path`, a pack emitted from `dir` failed validation three ways at once. No shipped pack used it. Author `path` instead, or the bare-string shorthand.

type Spec added in v1.1.3

type Spec struct {
	TaskType       string                   `yaml:"task_type" json:"task_type"`
	Version        string                   `yaml:"version" json:"version"`
	Description    string                   `yaml:"description" json:"description"`
	TemplateEngine *TemplateEngineInfo      `yaml:"template_engine,omitempty" json:"template_engine,omitempty"` // Template engine configuration
	Fragments      []FragmentRef            `yaml:"fragments,omitempty" json:"fragments,omitempty"`             // New: fragment assembly
	SystemTemplate string                   `yaml:"system_template" json:"system_template"`
	Variables      []VariableMetadata       `yaml:"variables,omitempty" json:"variables,omitempty"` // Variable definitions with rich metadata
	ModelOverrides map[string]ModelOverride `yaml:"model_overrides,omitempty" json:"model_overrides,omitempty"`
	AllowedTools   []string                 `yaml:"allowed_tools,omitempty" json:"allowed_tools,omitempty"` // Tools this prompt can use
	MediaConfig    *MediaConfig             `yaml:"media,omitempty" json:"media,omitempty"`                 // Multimodal media configuration
	Validators     []ValidatorConfig        `yaml:"validators,omitempty" json:"validators,omitempty"`       // Validators/Guardrails for production runtime
	TestedModels   []ModelTestResultRef     `yaml:"tested_models,omitempty" json:"tested_models,omitempty"` // Model testing metadata
	ToolPolicy     *ToolPolicyPack          `yaml:"tool_policy,omitempty" json:"tool_policy,omitempty"`
	Parameters     *ParametersPack          `yaml:"parameters,omitempty" json:"parameters,omitempty"`
	Evals          []evals.EvalDef          `yaml:"evals,omitempty" json:"evals,omitempty"`
	Metadata       *Metadata                `yaml:"metadata,omitempty" json:"metadata,omitempty"`
	Compilation    *CompilationInfo         `yaml:"compilation,omitempty" json:"compilation,omitempty"`
}

Spec contains the actual prompt configuration

type Template added in v1.3.26

type Template struct {
	TaskType      string            `json:"task_type"`
	RawTemplate   string            `json:"raw_template"`
	DefaultVars   map[string]string `json:"default_vars,omitempty"`
	RequiredVars  []string          `json:"required_vars,omitempty"`
	FragmentVars  map[string]string `json:"fragment_vars,omitempty"`
	AllowedTools  []string          `json:"allowed_tools,omitempty"`
	Validators    []ValidatorConfig `json:"validators,omitempty"`
	ModelOverride string            `json:"model_override,omitempty"`
}

Template holds an unrendered prompt template with all metadata required to render it later. This is the intermediate form produced by LoadTemplate, consumed by the TemplateStage to perform deferred variable substitution.

type TemplateEngineInfo

type TemplateEngineInfo = packspec.PackTemplateEngine

TemplateEngineInfo is the pack's template engine configuration.

Generated. template_engine is an inline object under the root's properties rather than a $def, but the generator emits types for those too — this is packspec.PackTemplateEngine, and it was field-for-field identical to the hand-written struct it replaced.

type TestResultSummary

type TestResultSummary struct {
	Success   bool
	Cost      float64
	LatencyMs int
	Tokens    int
}

TestResultSummary contains summarized test execution data

type TimeProvider added in v1.1.0

type TimeProvider interface {
	Now() time.Time
}

TimeProvider allows injecting time for deterministic tests

type ToolData added in v1.1.5

type ToolData struct {
	FilePath string
	Data     []byte
}

ToolData holds raw tool configuration data for compilation

type ToolPolicyPack

type ToolPolicyPack = packspec.ToolPolicy

ToolPolicyPack represents tool policy in pack format Generated from the schema: an ALIAS for packspec.ToolPolicy. max_rounds, max_tool_calls_per_turn and tool_choice are pointers for the same reason.

type Validator added in v1.5.5

type Validator = packspec.Validator

Validator is a compiled pack validator.

Generated. It carries the spec's `message`, which the COMPILED form does not use — foldValidatorMessages folds it into params at compile time, so nothing populates it and omitempty keeps it out of the emitted pack. Carrying an unused field is cheaper than maintaining a second definition of this type.

func ValidatorValues added in v1.8.0

func ValidatorValues(in []*Validator) []Validator

ValidatorValues dereferences a slice of validator pointers into values, at the boundary between the generated Prompt (which holds pointers) and the APIs that take values. A nil entry is skipped.

type ValidatorConfig

type ValidatorConfig struct {
	Type   string                 `yaml:"type" json:"type"`
	Params map[string]interface{} `yaml:"params" json:"params"`
	// Enable/disable validator (default: true)
	Enabled *bool `yaml:"enabled,omitempty" json:"enabled,omitempty"`
	// FailOnViolation is part of the PromptPack spec but is ignored by
	// this runtime — guardrails always enforce. Authors wanting
	// observe-only behavior should declare an eval and assert on it
	// instead. Tracked upstream:
	// https://github.com/AltairaLabs/promptpack-spec/issues/46
	FailOnViolation *bool `yaml:"fail_on_violation,omitempty" json:"fail_on_violation,omitempty"`
	// User-facing message shown when content is blocked (default: DefaultBlockedMessage)
	Message string `yaml:"message,omitempty" json:"message,omitempty"`
}

ValidatorConfig describes a validator/guardrail configuration from a prompt pack.

type Variable added in v1.5.5

type Variable = packspec.Variable

Variable is a spec-exact compiled prompt template variable.

Generated. It deliberately omits nothing of its own: Binding IS on the generated type, but compileVariables never populates it, because variable binding (auto-population from platform resources) is a runtime concern resolved at compile time and not part of the portable pack. The authoring type VariableMetadata carries it; omitempty keeps it out of the emitted pack.

toMetadata() was a method. A type alias cannot carry methods, so it is VariableToMetadata below.

type VariableBinding added in v1.1.10

type VariableBinding struct {
	// Kind specifies the type of resource to bind to.
	Kind VariableBindingKind `yaml:"kind" json:"kind"`
	// Field specifies which field of the resource to bind (e.g., "name", "model").
	Field string `yaml:"field,omitempty" json:"field,omitempty"`
	// AutoPopulate enables automatic population of this variable from the bound resource.
	// When true, the variable may be auto-filled and optionally hidden from the wizard.
	AutoPopulate bool `yaml:"autoPopulate,omitempty" json:"autoPopulate,omitempty"`
	// Filter specifies criteria for filtering bound resources.
	Filter *VariableBindingFilter `yaml:"filter,omitempty" json:"filter,omitempty"`
}

VariableBinding defines how a variable binds to system resources. This enables automatic population from system resources and type-safe UI selection.

type VariableBindingFilter added in v1.1.10

type VariableBindingFilter struct {
	// Capability filters resources by capability (e.g., "chat", "embeddings").
	Capability string `yaml:"capability,omitempty" json:"capability,omitempty"`
	// Labels filters resources by label selectors.
	Labels map[string]string `yaml:"labels,omitempty" json:"labels,omitempty"`
}

VariableBindingFilter specifies criteria for filtering bound resources.

type VariableBindingKind added in v1.1.10

type VariableBindingKind string

VariableBindingKind defines the type of resource a variable binds to.

const (
	// BindingKindProject binds to project metadata (name, description, tags).
	BindingKindProject VariableBindingKind = "project"
	// BindingKindProvider binds to provider/model selection.
	BindingKindProvider VariableBindingKind = "provider"
	// BindingKindWorkspace binds to current workspace (name, namespace).
	BindingKindWorkspace VariableBindingKind = "workspace"
	// BindingKindSecret binds to Kubernetes Secret resources.
	BindingKindSecret VariableBindingKind = "secret"
	// BindingKindConfigMap binds to Kubernetes ConfigMap resources.
	BindingKindConfigMap VariableBindingKind = "configmap"
)

type VariableMetadata

type VariableMetadata struct {
	Name        string                 `yaml:"name" json:"name"`
	Type        string                 `yaml:"type,omitempty" json:"type,omitempty"` // "string", "number", "boolean", "object", "array"
	Required    bool                   `yaml:"required" json:"required"`
	Default     interface{}            `yaml:"default,omitempty" json:"default,omitempty"`
	Description string                 `yaml:"description,omitempty" json:"description,omitempty"`
	Example     interface{}            `yaml:"example,omitempty" json:"example,omitempty"`
	Validation  map[string]interface{} `yaml:"validation,omitempty" json:"validation,omitempty"`
	// Binding enables automatic population from system resources and type-safe UI selection.
	// This allows prompts to declare semantic meaning for variables beyond just their data type.
	Binding *VariableBinding `yaml:"binding,omitempty" json:"binding,omitempty"`
}

VariableMetadata contains enhanced metadata for a variable VariableMetadata defines a template variable with validation rules This struct matches the SDK Variable type for PromptPack spec compliance

func VariableToMetadata added in v1.8.0

func VariableToMetadata(v Variable) VariableMetadata

VariableToMetadata converts a compiled variable back to the authoring metadata form. Binding is always nil — it is not carried in the pack.

A free function rather than a method: Variable is the generated type now, and a type alias cannot carry methods.

type VariableValidation

type VariableValidation = packspec.VariableValidation

VariableValidation is the validation rule set on a Variable.

type VideoConfig added in v1.1.0

type VideoConfig = packspec.VideoConfig

VideoConfig contains video-specific configuration Generated from the schema: an ALIAS for packspec.VideoConfig. Optional numeric and boolean fields are pointers: zero is a real setting.

func GetVideoConfig added in v1.1.0

func GetVideoConfig(config *MediaConfig) *VideoConfig

GetVideoConfig returns the video configuration if video is supported

type WorkflowConfig added in v1.3.1

type WorkflowConfig = workflow.Spec

WorkflowConfig is an alias for workflow.Spec for backward compatibility.

type WorkflowState added in v1.3.1

type WorkflowState = workflow.State

WorkflowState is an alias for workflow.State for backward compatibility.

Directories

Path Synopsis
Package agentcard generates A2A Agent Cards from a compiled Pack's agents section.
Package agentcard generates A2A Agent Cards from a compiled Pack's agents section.
Package schema provides embedded PromptPack schema for offline validation.
Package schema provides embedded PromptPack schema for offline validation.

Jump to

Keyboard shortcuts

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