Documentation
¶
Overview ¶
Package prompty provides caller-owned prompt materialization and canonical executions for LLM applications. Direct BYOT executions and optional manifest recipes share explicit JSON Schema, tool-scope and validation boundaries. Vendor SDKs live in separate adapter modules; the checked adapter client owns capability admission and canonical provider projection.
Captured source snapshots and render plans retain owned material; execution, recipe and wire DTOs remain mutable. Streams are lazy, single-consumer handles; Close requests cancellation and does not join or roll back remote work. Optional structured executors own one serial attempt chain. Retries, approval, persistence, routing and reconciliation remain caller responsibilities.
Current contracts: docs/schema-data-contract.md, docs/tool-execution-contract.md, docs/provider-exchange-contract.md and docs/source-snapshot-contract.md. See docs/migration.md for breaking changes.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/prompty"
)
func main() {
tpl, err := prompty.NewChatPromptTemplate(
[]prompty.MessageTemplate{
{Role: prompty.RoleSystem, Content: prompty.TextContent("You are {{ .Input.bot_name }}.")},
{Role: prompty.RoleUser, Content: prompty.TextContent("{{ .Input.query }}")},
},
prompty.MustWithPartialVariablesJSON(prompty.MustJSONDocumentFromMap(map[string]any{"bot_name": "HelperBot"})),
)
if err != nil {
panic(err)
}
planInput, err := prompty.PlanInputFrom(struct {
Query string `prompt:"query"`
}{Query: "What is 2+2?"})
if err != nil {
panic(err)
}
plan, err := prompty.NewRenderPlanFromPlanInput(tpl, planInput)
if err != nil {
panic(err)
}
exec, err := plan.Execute(context.Background())
if err != nil {
panic(err)
}
fmt.Println(exec.Messages[0].Content[0].(prompty.TextPart).Text)
fmt.Println(exec.Messages[1].Content[0].(prompty.TextPart).Text)
}
Output: You are HelperBot. What is 2+2?
Index ¶
- Constants
- Variables
- func BatchExecutionDigest(exec *PromptExecution) (string, error)
- func DecodeToolArgs[TArgs any](argsJSON string) (TArgs, error)
- func EqualCachePolicy(a, b *CachePolicy) bool
- func ExecuteAsText(ctx context.Context, invoker Invoker, exec *PromptExecution) (string, error)
- func ExecuteWithStructuredOutput[T any](ctx context.Context, invoker Invoker, exec *PromptExecution) (*T, error)
- func ExtractSchema(v any) (map[string]any, error)
- func GenerateStructured[T any](ctx context.Context, invoker Invoker, prompt string) (T, error)
- func GenerateText(ctx context.Context, invoker Invoker, prompt string, opts ...Option) (string, error)
- func HasScopedMessageAnnotations(annotations []MessageAnnotation) bool
- func JSONDocumentAsMap(doc JSONDocument) (map[string]any, error)
- func JoinAdapterTextParts(parts []ContentPart) (string, error)
- func ManifestDigestSHA256(manifestBytes []byte) string
- func MessageInheritsCachePolicy(message ChatMessage) (bool, error)
- func MustJSONDocumentAsMap(doc JSONDocument) map[string]any
- func NewStructuredExecutor[T any](invoker Invoker, exec *PromptExecution) func(context.Context) (*T, error)
- func ProviderSettingsMap(opts *ModelOptions) (map[string]any, error)
- func RegisterTool[TArgs any, TResult any](r *TypedToolRegistry, tool *TypedTool[TArgs, TResult]) error
- func RewriteCachePolicies(messages []ChatMessage, visit func(string, *CachePolicy) (bool, error)) error
- func SchemaDocumentAsMap(doc JSONDocument) (map[string]any, error)
- func SchemaMap(def *SchemaDefinition) (map[string]any, error)
- func StreamStructuredOutput[T any](ctx context.Context, invoker Invoker, exec *PromptExecution, mode StreamMode, ...) iter.Seq2[T, error]
- func StrictTextFromParts(parts []ContentPart) (string, error)
- func ToolCallArgsForTranslate(tc ToolCallPart) (string, error)
- func ValidateBatchHandle(handle BatchHandle) error
- func ValidateCachePolicies(messages []ChatMessage) error
- func ValidateCachePolicy(policy *CachePolicy) error
- func ValidateCacheResourceExpiry(expiry CacheResourceExpiry, now time.Time) error
- func ValidateCacheResourceHandle(handle CacheResourceHandle) error
- func ValidateCacheResourceReuse(handle CacheResourceHandle, destination ProfileIdentity, accountBinding string, ...) error
- func ValidateCapabilityProfile(profile CapabilityProfile) error
- func ValidateCaptureRequirement(req CaptureRequirement) error
- func ValidateContinuation(messages []ChatMessage, destination ProfileIdentity, now time.Time) error
- func ValidateEndpointIdentity(endpoint string) error
- func ValidateExecutionContract(exec *PromptExecution, contract ToolManifestContract) error
- func ValidateExecutionManifestContract(exec *PromptExecution, desc ManifestDescriptor, contract ToolManifestContract) error
- func ValidateExecutionToolScope(exec *PromptExecution) error
- func ValidateHostedToolRequests(tools []HostedToolRequest) error
- func ValidateID(id string) error
- func ValidateManifestDescriptor(desc ManifestDescriptor) error
- func ValidateMessageAnnotations(annotations []MessageAnnotation) error
- func ValidateName(name, env string) error
- func ValidateOutputMode(mode StructuredOutputMode, format *SchemaDefinition) error
- func ValidatePartAssociations(parts []ContentPart, states []PartState, annotations []PartAnnotation) error
- func ValidateRemoteResponseHandle(handle RemoteResponseHandle) error
- func ValidateRequestCachePolicy(policy *CachePolicy) error
- func ValidateResponseMetadata(response *Response) error
- func ValidateSchemaJSON(definition *SchemaDefinition, document JSONDocument) error
- func ValidateSchemaPolicy(policy SchemaPolicy) error
- func ValidateSchemaValue(definition *SchemaDefinition, value any) error
- func ValidateToolScope(desc ManifestDescriptor, scope ToolScope) error
- func ValidateWireJSON(document JSONDocument, format string) error
- func WireSchemaResources() map[string]JSONDocument
- type BatchCompleteness
- type BatchFileBinding
- type BatchFileCaptureDescriber
- type BatchFileDownload
- type BatchFileTransport
- type BatchFileUpload
- type BatchFileUploadResult
- type BatchHandle
- type BatchItem
- type BatchItemBinding
- type BatchItemOutcome
- type BatchItemResult
- type BatchManager
- type BatchOperationOptions
- type BatchResourceRef
- type BatchResult
- type BatchResultBinding
- type BatchResultsOptions
- type BatchStatus
- type BatchSubmitRequest
- type CacheDecision
- type CacheDisposition
- type CacheError
- type CacheMechanism
- type CacheMode
- type CachePolicy
- type CacheResourceCreateRequest
- type CacheResourceExpiry
- type CacheResourceHandle
- type CacheResourceManager
- type CacheResourceOperationOptions
- type CacheResourceResult
- type CacheResourceState
- type CapabilityProfile
- type CapabilitySupport
- type CaptureAccuracy
- type CaptureAck
- type CaptureBinding
- type CaptureCoverage
- type CaptureError
- type CaptureFailure
- type CaptureProjection
- type CaptureProjector
- type CaptureRecord
- type CaptureRecordMetadata
- type CaptureReport
- type CaptureRequirement
- type CaptureSchemaDigest
- type CaptureSession
- type CaptureSink
- type CaptureSinkCapabilities
- type CaptureStage
- type CaptureStageCoverage
- type CharFallbackCounter
- type ChatMessage
- type ChatPromptTemplate
- type ChatTemplateOption
- func MustWithPartialVariablesJSON(doc JSONDocument) ChatTemplateOption
- func WithInputSchema(schema *SchemaDefinition) ChatTemplateOption
- func WithMetadata(meta PromptMetadata) ChatTemplateOption
- func WithModelOptions(config *ModelOptions) ChatTemplateOption
- func WithPartialSources(sources map[string]string) ChatTemplateOption
- func WithPartialVariablesJSON(doc JSONDocument) (ChatTemplateOption, error)
- func WithPartialsFS(fsys fs.FS, pattern string) ChatTemplateOption
- func WithPartialsGlob(glob string) ChatTemplateOption
- func WithRequiredTools(tools []string) ChatTemplateOption
- func WithRequiredVars(vars []string) ChatTemplateOption
- func WithResponseFormat(schema *SchemaDefinition) ChatTemplateOption
- func WithTokenCounter(tc TokenCounter) ChatTemplateOption
- func WithTools(tools []ToolDefinition) ChatTemplateOption
- type CompiledProviderSchema
- type ComposeContext
- type ComposeValue
- type ComposeValues
- type ContentPart
- type ContentPartWire
- type DescribingRegistry
- type ExecutionDiagnostics
- type ExecutionRequirements
- type Fetcher
- type HostedToolRequest
- type Invoker
- type JSONDocument
- func CloneJSONDocument(doc JSONDocument) JSONDocument
- func EncodeBatchHandle(handle BatchHandle) (JSONDocument, error)
- func EncodeCacheResourceHandle(handle CacheResourceHandle) (JSONDocument, error)
- func EncodeRemoteResponseHandle(handle RemoteResponseHandle) (JSONDocument, error)
- func JSONSchemaFromStruct[T any]() (JSONDocument, error)
- func MapToJSONDocument(m map[string]any) (JSONDocument, error)
- func MarshalJSONDocument(v any) (JSONDocument, error)
- func MustJSONDocumentFromMap(m map[string]any) JSONDocument
- type JSONSchemaValidator
- type LayerKind
- type Lister
- type ManifestBytesReader
- type ManifestCheckpointRegistry
- type ManifestComposeChecker
- type ManifestDescriptor
- type ManifestDescriptorVerifier
- type ManifestResolver
- type ManifestSnapshot
- type ManifestSnapshotRegistry
- type MediaPart
- type MessageAnnotation
- type MessageProvenance
- type MessageTemplate
- type MessageWire
- type Middleware
- type ModelOptions
- type ModelOptionsWire
- type NonTextResponseError
- type Option
- type Outcome
- type OutcomeError
- type PartAnnotation
- type PartState
- type ProfileIdentity
- type PromptCatalogRegistry
- type PromptDescriber
- type PromptExecution
- func DecodeExecutionJSON(document JSONDocument) (*PromptExecution, error)
- func ExecuteWithTypedTools(ctx context.Context, invoker Invoker, exec *PromptExecution, tools ToolInvoker) (*PromptExecution, error)
- func NewExecution(messages []ChatMessage) *PromptExecution
- func SimpleChat(system, user string) *PromptExecution
- func SimplePrompt(user string) *PromptExecution
- func UnmarshalExecution(wire PromptExecutionWire) (*PromptExecution, error)
- func (e *PromptExecution) AddMessage(msg ChatMessage) *PromptExecution
- func (e *PromptExecution) Clone() *PromptExecution
- func (e *PromptExecution) Normalize() *PromptExecution
- func (e *PromptExecution) ResolvedMedia(ctx context.Context, fetcher Fetcher) (*PromptExecution, error)
- func (e *PromptExecution) Text(strict bool) (string, error)
- func (e *PromptExecution) ToolScope() *ToolScope
- func (e *PromptExecution) WithHistory(history []ChatMessage) *PromptExecution
- func (e *PromptExecution) WithMessages(messages []ChatMessage) *PromptExecution
- func (e *PromptExecution) WithToolScope(scope ToolScope) (*PromptExecution, error)
- type PromptExecutionWire
- type PromptMetadata
- type PromptRecipe
- func (r PromptRecipe[TInput, TLate]) BindLate(late TLate) (PromptRecipe[TInput, TLate], error)
- func (r PromptRecipe[TInput, TLate]) Checkpoint() (PromptRecipeCheckpoint[TInput, TLate], error)
- func (r PromptRecipe[TInput, TLate]) Execute(ctx context.Context, registry ManifestSnapshotRegistry) (*PromptExecution, error)
- func (r PromptRecipe[TInput, TLate]) ExecuteWithContract(ctx context.Context, registry ManifestSnapshotRegistry, ...) (*PromptExecution, error)
- func (r PromptRecipe[TInput, TLate]) Plan(ctx context.Context, registry ManifestSnapshotRegistry) (*RenderPlan, error)
- func (r PromptRecipe[TInput, TLate]) Verify(ctx context.Context, verifier ManifestDescriptorVerifier) error
- func (r PromptRecipe[TInput, TLate]) WithComposeContext(ctx ComposeContext) (PromptRecipe[TInput, TLate], error)
- type PromptRecipeCheckpoint
- type PromptRecipeNoLate
- func (r PromptRecipeNoLate[TInput]) Checkpoint() (PromptRecipeNoLateCheckpoint[TInput], error)
- func (r PromptRecipeNoLate[TInput]) Execute(ctx context.Context, registry ManifestSnapshotRegistry) (*PromptExecution, error)
- func (r PromptRecipeNoLate[TInput]) ExecuteWithContract(ctx context.Context, registry ManifestSnapshotRegistry, ...) (*PromptExecution, error)
- func (r PromptRecipeNoLate[TInput]) Plan(ctx context.Context, registry ManifestSnapshotRegistry) (*RenderPlan, error)
- func (r PromptRecipeNoLate[TInput]) Verify(ctx context.Context, verifier ManifestDescriptorVerifier) error
- func (r PromptRecipeNoLate[TInput]) WithComposeContext(ctx ComposeContext) (PromptRecipeNoLate[TInput], error)
- type PromptRecipeNoLateCheckpoint
- type PromptRuntimeOptions
- type ProviderEnvelope
- type ProviderSchemaMapper
- type ReasoningPart
- type Registry
- type RegistryPlanInput
- type RemoteResponseHandle
- type RemoteResponseManager
- type RemoteResponseOperationOptions
- type RemoteResponseRequest
- type RemoteResponseResult
- type RemoteResponseStatus
- type RemoteResponseStream
- type RemoteResponseStreamer
- type RenderPlan
- func BindRuntime(ctx context.Context, registry ManifestSnapshotRegistry, ...) (*RenderPlan, error)
- func NewRenderPlan(tpl *ChatPromptTemplate) *RenderPlan
- func NewRenderPlanFromPlanInput(tpl *ChatPromptTemplate, input RegistryPlanInput) (*RenderPlan, error)
- func NewRenderPlanFromStruct[T any](tpl *ChatPromptTemplate, input T) (*RenderPlan, error)
- func VerifiedManifestPlan(ctx context.Context, registry ManifestSnapshotRegistry, ...) (*RenderPlan, error)
- func WithResponseFormatFromStruct[T any](p *RenderPlan) (*RenderPlan, error)
- func (p *RenderPlan) Execute(ctx context.Context) (*PromptExecution, error)
- func (p *RenderPlan) ExecuteAsText(ctx context.Context, invoker Invoker) (string, error)
- func (p *RenderPlan) ExecuteWithContract(ctx context.Context, contract ToolManifestContract) (*PromptExecution, error)
- func (p *RenderPlan) ExecuteWithManifestContract(ctx context.Context, desc ManifestDescriptor, contract ToolManifestContract) (*PromptExecution, error)
- func (p *RenderPlan) RenderText(ctx context.Context) (string, error)
- func (p *RenderPlan) SourceDescriptor() (ManifestDescriptor, bool)
- func (p *RenderPlan) Template() *ChatPromptTemplate
- func (p *RenderPlan) ValidateRuntimeBindings() error
- func (p *RenderPlan) WithLateInput(input any) (*RenderPlan, error)
- func (p *RenderPlan) WithLateInputJSON(doc JSONDocument) (*RenderPlan, error)
- func (p *RenderPlan) WithResponseFormatDefinition(def *SchemaDefinition) (*RenderPlan, error)
- func (p *RenderPlan) WithToolScope(scope ToolScope) (*RenderPlan, error)
- type RequirementCheck
- type ResolveManifestOption
- type ResolveManifestOpts
- type Response
- type ResponseChunk
- type ResponseFormatWire
- type ResponseWire
- type Role
- type RuntimeOverlay
- type RuntimeRecipeCheckpoint
- type RuntimeRecipeState
- type SchemaCompilationError
- type SchemaCompilationReport
- type SchemaCompileRequest
- type SchemaDefinition
- type SchemaFidelityError
- type SchemaMapping
- type SchemaMappingRequest
- type SchemaMode
- type SchemaPolicy
- type SchemaProvider
- type SchemaRole
- type SchemaSourceLocation
- type SchemaTransformation
- type SchemaValidator
- type SnapshotMaterializer
- type SourceBundle
- type StateProjection
- type Statter
- type Stream
- type StreamCaptureObserver
- type StreamEventKind
- type StreamFinalizer
- type StreamFrameObserver
- type StreamIdentity
- type StreamLifecycleObserver
- type StreamMode
- type StreamOption
- type StreamPartFinalization
- type StreamState
- type StreamStatus
- type StreamStopReason
- type StructuredOutputContract
- type StructuredOutputMode
- type StructuredStreamOptions
- type TemplateDescriptor
- type TemplateInfo
- type TemplatePart
- type TextPart
- type TokenCounter
- type ToolCallError
- type ToolCallPart
- type ToolContractError
- type ToolDefinition
- type ToolDispatchError
- type ToolInvoker
- type ToolManifest
- type ToolManifestContract
- type ToolManifestContractFunc
- type ToolRequirement
- type ToolResultPart
- type ToolScope
- type ToolScopeError
- type ToolValidator
- type ToolWire
- type TypedTool
- type TypedToolRegistry
- type Usage
- type UsageAvailability
- type UsageCounter
- type UsageMode
- type Validatable
- type ValidationError
- type ValueValidator
- type VariableError
- type WirePolicy
Examples ¶
Constants ¶
const ( BatchWireFormat = "prompty.batch" CapabilityBatchSubmit = "batch_submit" CapabilityBatchInspect = "batch_inspect" CapabilityBatchCancel = "batch_cancel" CapabilityBatchResults = "batch_results" )
const ( CacheImplicitPrefix CacheMechanism = "implicit_prefix" CacheBlockMarker CacheMechanism = "block_marker" CacheAdvisory CacheMode = "advisory" CacheRequired CacheMode = "required" CapabilityCacheImplicit = "cache_implicit_prefix" CapabilityCacheMarker = "cache_block_marker" )
const ( CacheResourceWireFormat = "prompty.cache_resource" CapabilityCacheCreate = "cache_resource_create" CapabilityCacheInspect = "cache_resource_inspect" CapabilityCacheUpdate = "cache_resource_update_expiry" CapabilityCacheDelete = "cache_resource_delete" CapabilityCacheReuse = "cache_resource_reuse" )
const ( CapabilitySupported CapabilitySupport = "supported" CapabilityUnsupported CapabilitySupport = "unsupported" CapabilityUnknown CapabilitySupport = "unknown" CapabilityTools = "tools" CapabilityForcedToolSelection = "forced_tool_selection" // CapabilityToolNameCorrelation permits complete ID-less calls with unique // names in one batch, when the adapter preserves those names in tool results. CapabilityToolNameCorrelation = "tool_name_correlation" CapabilityNativeStream = "native_stream" CapabilityStructuredOutput = "native_json_schema" CapabilitySyntheticOutput = "synthetic_tool_output" CapabilityUsage = "usage" CapabilityProviderState = "provider_state" CapabilityReasoning = "reasoning" )
const ( RemoteResponseWireFormat = "prompty.remote_response" CapabilityResponseCreate = "response_create" CapabilityResponseRetrieve = "response_retrieve" CapabilityResponseCancel = "response_cancel" CapabilityResponseContinuation = "response_continuation" CapabilityResponseBackground = "response_background" CapabilityHostedWebSearch = "hosted_web_search" CapabilityHostedWebFetch = "hosted_web_fetch" CapabilityHostedFileSearch = "hosted_file_search" // CapabilityStrictTools declares provider-native conformance to local tool schemas. CapabilityStrictTools = "strict_tools" )
const ( SchemaDialect2020 = "https://json-schema.org/draft/2020-12/schema" SchemaDialect7 = "http://json-schema.org/draft-07/schema#" )
const ( ExecutionWireFormat = "prompty.execution.v2" ContentPartWireText = "text" ContentPartWireMedia = "media" ContentPartWireReasoning = "reasoning" ContentPartWireToolCall = "tool_call" ContentPartWireToolResult = "tool_result" )
const ProviderStateFormat = "prompty.provider-state"
const ResponseWireFormat = "prompty.response"
Variables ¶
var ( ErrBatch = errors.New("prompty: invalid batch contract") ErrBatchScope = errors.New("prompty: incompatible batch binding") ErrBatchUnknown = errors.New("prompty: batch mutation outcome unknown") ErrBatchRejected = errors.New("prompty: batch mutation rejected") ErrBatchResults = errors.New("prompty: incomplete batch result retrieval") )
var ( ErrCachePolicy = errors.New("prompty: invalid cache policy") ErrCacheRequirement = errors.New("prompty: cache requirement not satisfied") )
var ( ErrCacheResource = errors.New("prompty: invalid cache resource handle") ErrCacheResourceScope = errors.New("prompty: incompatible cache resource binding") ErrCacheResourceExpired = errors.New("prompty: cache resource expired or unavailable") ErrCacheResourceExpiry = errors.New("prompty: invalid cache resource expiry") ErrCacheResourceUnknown = errors.New("prompty: cache resource operation outcome unknown") )
var ( ErrCapture = errors.New("prompty: capture failed") ErrCaptureUnsupported = errors.New("prompty: required capture coverage unavailable") )
var ( ErrMissingVariable = errors.New("prompty: required template variable not provided") ErrTemplateRender = errors.New("prompty: template rendering failed") ErrTemplateParse = errors.New("prompty: template parsing failed") ErrInvalidPayload = errors.New( "prompty: render plan input must be a struct with prompt fields or history-only payload", ) ErrTemplateNotFound = errors.New("prompty: template not found in registry") ErrInvalidManifest = errors.New("prompty: manifest file is malformed") ErrLegacyManifestVersion = errors.New("prompty: legacy manifest version is not supported") ErrNoFetcher = errors.New("prompty: fetcher is required but not provided") ErrNilRenderPlan = errors.New("prompty: render plan is nil") ErrReservedVariable = errors.New( "prompty: reserved variable name in payload (use a different prompt tag than Tools)", ) // ErrInvalidName indicates template name or env contains invalid characters (e.g. ':', path separators). ErrInvalidName = errors.New("prompty: invalid template name") // ErrNoParser indicates that a registry was created without a manifest parser (use WithParser when creating the registry). ErrNoParser = errors.New("prompty: parser is required but not provided") // ErrConflictingDirectives indicates conflicting execution directives (e.g. Tools and ResponseFormat together). ErrConflictingDirectives = errors.New( "prompty: conflicting directives (e.g. Tools and ResponseFormat cannot be used together)", ) ErrManifestBytesUnavailable = errors.New("prompty: manifest bytes unavailable from registry") ErrRegistryCapabilityUnavailable = errors.New("prompty: registry capability unavailable") // ErrManifestBytesRequired indicates compile requires raw manifest bytes (strict default). ErrManifestBytesRequired = errors.New("prompty: manifest bytes required for compiled prompt digest") // ErrManifestDigestMismatch indicates checkpoint digest does not match current manifest bytes. ErrManifestDigestMismatch = errors.New("prompty: manifest digest mismatch") )
Sentinel errors for template and registry operations. All use prefix "prompty:" for identification. Callers should use errors.Is and errors.As.
var ( ErrProviderState = errors.New("prompty: invalid provider state") ErrStateDestination = errors.New("prompty: incompatible provider state destination") ErrStateExpired = errors.New("prompty: expired provider state") )
var ( ErrRemoteResponse = errors.New("prompty: invalid remote response contract") ErrRemoteResponseScope = errors.New("prompty: incompatible remote response binding") ErrRemoteResponseUnknown = errors.New("prompty: remote response operation outcome unknown") )
var ( ErrWireFormat = errors.New("prompty: unsupported wire format; explicit migration required") ErrWirePolicy = errors.New("prompty: explicit state projection policy required") )
var ( ErrSchemaMismatch = errors.New("prompty: response violates original JSON Schema") ErrSchemaJSONDecode = errors.New("prompty: schema validation input is not one complete JSON document") ErrSchemaUnsupported = errors.New("prompty: unsupported JSON Schema contract") ErrSchemaValidatorRequired = errors.New("prompty: schema validator required") )
var ( ErrStreamConsumed = errors.New("prompty: stream is single-use") ErrStreamProtocol = errors.New("prompty: invalid or incomplete stream protocol") ErrStreamMode = errors.New("prompty: explicit native or buffered stream mode required") )
var ErrAmbiguousTextExecution = errors.New("prompty: execution text is ambiguous")
ErrAmbiguousTextExecution indicates strict render-only extraction found multiple messages.
var ErrBatchFileUnknown = errors.New("prompty: batch file upload outcome unknown")
var ErrCapabilityProfile = errors.New("prompty: invalid capability profile")
ErrCapabilityProfile identifies malformed caller-owned profile knowledge.
var ErrCaptureReport = errors.New("prompty: invalid capture report")
ErrCaptureReport identifies an inconsistent diagnostic snapshot, not a provider execution failure or an instruction to retry a dispatched request.
var ErrComposeValues = errors.New("prompty: invalid compose values")
var ErrEmptyTextResponse = errors.New("prompty: response contains no text")
ErrEmptyTextResponse indicates strict text extraction found no text content.
var ErrHostedToolRequest = errors.New("prompty: invalid hosted tool declaration")
var ErrIncompleteToolCallArgs = errors.New("prompty: tool call arguments incomplete")
ErrIncompleteToolCallArgs indicates incomplete or uncorrelated streaming arguments.
var ErrMissingRequiredTool = errors.New("prompt contract: missing required tool")
ErrMissingRequiredTool indicates that a prompt required a tool absent from the supplied manifest contract.
var ErrNonTextResponse = errors.New("prompty: response is not plain text")
ErrNonTextResponse indicates the model returned non-text content (tool calls, media, etc.) when a strict textual output was required.
var ErrOutputMode = errors.New("prompty: invalid structured output mode")
ErrOutputMode identifies an invalid or contradictory output selection.
var ErrResponseOutcome = errors.New("prompty: unsuccessful provider outcome")
ErrResponseOutcome indicates that the provider did not complete a successful output.
ErrStructuredOutputUnavailable indicates a prompt recipe has no structured output schema contract.
var ErrStructuredStream = errors.New("prompty: invalid structured stream")
ErrStructuredStream identifies invalid incremental JSON syntax/shape, not provider refusal or voluntary consumer cancellation.
var ErrToolContractMismatch = errors.New("prompt contract: tool manifest mismatch")
ErrToolContractMismatch indicates a runtime tool manifest does not satisfy the prompt contract.
var ErrToolScope = errors.New("prompty: tool call violates execution scope")
ErrToolScope indicates that definitions or calls violate the execution boundary.
var ErrUsage = errors.New("prompty: invalid usage metadata")
ErrUsage indicates malformed presence/mode/counters or accumulation overflow.
Functions ¶
func BatchExecutionDigest ¶ added in v0.15.0
func BatchExecutionDigest(exec *PromptExecution) (string, error)
BatchExecutionDigest binds portable input; validators/capture ports are rebound. Capture belongs to the operation, so capture intent does not change item identity.
func DecodeToolArgs ¶ added in v0.11.0
DecodeToolArgs parses tool call JSON into TArgs with unknown-field rejection. Dynamic interface/map values retain json.Number; explicit numeric DTO fields retain the caller's selected Go conversion semantics.
func EqualCachePolicy ¶ added in v0.15.0
func EqualCachePolicy(a, b *CachePolicy) bool
EqualCachePolicy compares all intent and scoped controls. Different JSON encodings conservatively prevent merging, even if semantically equivalent.
func ExecuteAsText ¶ added in v0.11.0
ExecuteAsText runs a prepared execution through the invoker and returns strict plain text.
func ExecuteWithStructuredOutput ¶ added in v0.5.0
func ExecuteWithStructuredOutput[T any]( ctx context.Context, invoker Invoker, exec *PromptExecution, ) (*T, error)
ExecuteWithStructuredOutput performs a single request to the LLM and parses the response as JSON into type T.
func ExtractSchema ¶ added in v0.6.0
ExtractSchema returns the explicit or inferred JSON Schema for the caller's type. Unsupported codecs, recursion and invalid explicit schemas return an error.
func GenerateStructured ¶ added in v0.6.0
GenerateStructured builds a one-message PromptExecution and returns typed structured output in a single model call. For self-correction across attempts, use NewStructuredExecutor and an outer orchestrator (timeouts, retries).
Example ¶
ExampleGenerateStructured shows a single structured call. For multiple attempts with self-correction history, use prompty.NewStructuredExecutor and an outer loop (see README).
package main
import (
"context"
"fmt"
"iter"
"github.com/skosovsky/prompty"
)
type exampleStructuredInvoker struct{}
func (exampleStructuredInvoker) Execute(context.Context, *prompty.PromptExecution) (*prompty.Response, error) {
return prompty.NewResponse([]prompty.ContentPart{
prompty.TextPart{Text: `{"name":"Alice"}`},
}), nil
}
func (exampleStructuredInvoker) ExecuteStream(
ctx context.Context,
exec *prompty.PromptExecution,
mode prompty.StreamMode,
) *prompty.Stream {
return prompty.NewStream(ctx, mode, func(ctx context.Context) iter.Seq2[*prompty.ResponseChunk, error] {
return func(yield func(*prompty.ResponseChunk, error) bool) {
resp, err := exampleStructuredInvoker{}.Execute(ctx, exec)
if err != nil {
yield(nil, err)
return
}
yield(&prompty.ResponseChunk{
Identity: prompty.StreamIdentity{MessageID: "", PartIDs: []string{"result:0"}},
Content: resp.Content, Kind: prompty.StreamFinish, Outcome: resp.Outcome,
}, nil)
}
})
}
func main() {
type Result struct {
Name string `json:"name"`
}
result, err := prompty.GenerateStructured[Result](context.Background(), exampleStructuredInvoker{}, "Extract name")
if err != nil {
panic(err)
}
fmt.Println(result.Name)
}
Output: Alice
func GenerateText ¶ added in v0.5.6
func GenerateText(ctx context.Context, invoker Invoker, prompt string, opts ...Option) (string, error)
GenerateText is intended for prototyping, scripts, and simple tasks. For production, use prompty-gen and typed facade executions to maintain observability.
func HasScopedMessageAnnotations ¶ added in v0.15.0
func HasScopedMessageAnnotations(annotations []MessageAnnotation) bool
HasScopedMessageAnnotations identifies opaque message-level dependencies without decoding provider payloads. It does not validate shape or grant support.
func JSONDocumentAsMap ¶ added in v0.11.0
func JSONDocumentAsMap(doc JSONDocument) (map[string]any, error)
JSONDocumentAsMap decodes one object, preserving dynamic numbers as json.Number.
func JoinAdapterTextParts ¶ added in v0.11.0
func JoinAdapterTextParts(parts []ContentPart) (string, error)
JoinAdapterTextParts concatenates TextPart values for provider translation. MediaPart and parts handled elsewhere (tool_call, reasoning) are skipped.
func ManifestDigestSHA256 ¶ added in v0.11.0
ManifestDigestSHA256 returns hex-encoded SHA-256 of raw manifest bytes.
func MessageInheritsCachePolicy ¶ added in v0.15.0
func MessageInheritsCachePolicy(message ChatMessage) (bool, error)
MessageInheritsCachePolicy reports whether any top-level block uses the message default. Empty content or an explicit policy on every block means false. A tool-result block itself inherits independently of its children. This does not establish provider support for a part type and does not mutate the message.
func MustJSONDocumentAsMap ¶ added in v0.11.0
func MustJSONDocumentAsMap(doc JSONDocument) map[string]any
MustJSONDocumentAsMap decodes doc and panics on error (tests/examples).
func NewStructuredExecutor ¶ added in v0.7.0
func NewStructuredExecutor[T any](invoker Invoker, exec *PromptExecution) func(context.Context) (*T, error)
NewStructuredExecutor returns a stateful closure that runs one structured-output attempt per call. On *ValidationError or *ToolCallError it mutates internal scratchpad state (assistant + follow-up message) before returning the same error, so an outer orchestrator (e.g. retry with RetryIf) can invoke the closure again. The signature matches common infra patterns such as func(context.Context) (T, error) without importing them.
This optional helper owns one serial attempt chain. Do not call it concurrently. The host controls bounds, retries, delay and eventual reconciliation; each call performs one attempt and there is no internal loop or worker.
If RawAssistantMessage on the error is nil, only the follow-up message (user feedback or tool results) is appended.
func ProviderSettingsMap ¶ added in v0.11.0
func ProviderSettingsMap(opts *ModelOptions) (map[string]any, error)
ProviderSettingsMap decodes ModelOptions.ProviderSettings for adapter translation.
func RegisterTool ¶ added in v0.11.0
func RegisterTool[TArgs any, TResult any](r *TypedToolRegistry, tool *TypedTool[TArgs, TResult]) error
RegisterTool adds a typed tool to the registry.
func RewriteCachePolicies ¶ added in v0.15.0
func RewriteCachePolicies( messages []ChatMessage, visit func(string, *CachePolicy) (bool, error), ) error
RewriteCachePolicies visits message and nested part policies at stable JSON pointer paths. It mutates caller-owned messages; use a clone for preflight. Returned part values use the canonical value representation, preserving order and associations. The visitor returns true to keep a policy, false to omit it, and must not retain or mutate unrelated content.
func SchemaDocumentAsMap ¶ added in v0.15.0
func SchemaDocumentAsMap(doc JSONDocument) (map[string]any, error)
SchemaDocumentAsMap preserves JSON numbers exactly for SDK schema mapping. Unlike general metadata decoding, it must not round large numeric constraints.
func SchemaMap ¶ added in v0.11.0
func SchemaMap(def *SchemaDefinition) (map[string]any, error)
SchemaMap decodes SchemaDefinition.Schema for adapter translation.
func StreamStructuredOutput ¶ added in v0.5.6
func StreamStructuredOutput[T any]( ctx context.Context, invoker Invoker, exec *PromptExecution, mode StreamMode, options ...StructuredStreamOptions, ) iter.Seq2[T, error]
StreamStructuredOutput yields provisional JSON objects. They are final only after successful iterator exhaustion and whole-document validation.
func StrictTextFromParts ¶ added in v0.11.0
func StrictTextFromParts(parts []ContentPart) (string, error)
StrictTextFromParts concatenates text parts and returns an error if any non-text part is present.
func ToolCallArgsForTranslate ¶ added in v0.11.0
func ToolCallArgsForTranslate(tc ToolCallPart) (string, error)
ToolCallArgsForTranslate resolves complete tool-call JSON, rejecting unassembled deltas.
func ValidateBatchHandle ¶ added in v0.15.0
func ValidateBatchHandle(handle BatchHandle) error
func ValidateCachePolicies ¶ added in v0.15.0
func ValidateCachePolicies(messages []ChatMessage) error
ValidateCachePolicies checks every message/part policy without mutating input.
func ValidateCachePolicy ¶ added in v0.15.0
func ValidateCachePolicy(policy *CachePolicy) error
ValidateCachePolicy checks portable shape without interpreting provider keys.
func ValidateCacheResourceExpiry ¶ added in v0.15.0
func ValidateCacheResourceExpiry(expiry CacheResourceExpiry, now time.Time) error
ValidateCacheResourceExpiry validates explicit request lifetime at one instant.
func ValidateCacheResourceHandle ¶ added in v0.15.0
func ValidateCacheResourceHandle(handle CacheResourceHandle) error
ValidateCacheResourceHandle checks persisted shape without asserting remote existence.
func ValidateCacheResourceReuse ¶ added in v0.15.0
func ValidateCacheResourceReuse( handle CacheResourceHandle, destination ProfileIdentity, accountBinding string, now time.Time, ) error
ValidateCacheResourceReuse checks binding and current availability, not IAM.
func ValidateCapabilityProfile ¶ added in v0.15.0
func ValidateCapabilityProfile(profile CapabilityProfile) error
ValidateCapabilityProfile checks shape, not the truth of provider knowledge. Extension capability names remain caller-owned. Errors never echo values.
func ValidateCaptureRequirement ¶ added in v0.15.0
func ValidateCaptureRequirement(req CaptureRequirement) error
ValidateCaptureRequirement checks portable intent without requiring runtime ports.
func ValidateContinuation ¶ added in v0.15.0
func ValidateContinuation(messages []ChatMessage, destination ProfileIdentity, now time.Time) error
ValidateContinuation is a local scope/expiry gate, not provider account authorization.
func ValidateEndpointIdentity ¶ added in v0.15.0
ValidateEndpointIdentity rejects authentication-bearing URL components without echoing values. Empty optional identity is allowed; required fields are checked by their owner. Opaque references and URI paths remain the host's responsibility.
func ValidateExecutionContract ¶ added in v0.13.0
func ValidateExecutionContract(exec *PromptExecution, contract ToolManifestContract) error
ValidateExecutionContract verifies PromptExecution.RequiredTools against a runtime tool manifest contract.
func ValidateExecutionManifestContract ¶ added in v0.14.0
func ValidateExecutionManifestContract( exec *PromptExecution, desc ManifestDescriptor, contract ToolManifestContract, ) error
ValidateExecutionManifestContract verifies required tools against a runtime tool manifest contract.
func ValidateExecutionToolScope ¶ added in v0.15.0
func ValidateExecutionToolScope(exec *PromptExecution) error
ValidateExecutionToolScope validates the current definitions against the bound runtime declaration. Call it at every dispatch boundary after caller overrides.
func ValidateHostedToolRequests ¶ added in v0.15.0
func ValidateHostedToolRequests(tools []HostedToolRequest) error
ValidateHostedToolRequests checks only portable shape. It grants no provider support and interprets no vendor options; adapters validate their own whitelist.
func ValidateID ¶ added in v0.3.0
ValidateID checks that id is a valid io/fs-style path (slash-separated, no extensions). Canonical ID format: slash-only (e.g. "internal/router"). Rejects dotted IDs (Clean Break). Rejects ids containing ':', '\', ".", ".." for cross-platform safety. Use fs.ValidPath for path safety; rejects IDs with file extensions.
func ValidateManifestDescriptor ¶ added in v0.15.0
func ValidateManifestDescriptor(desc ManifestDescriptor) error
ValidateManifestDescriptor rejects incomplete legacy identities.
func ValidateMessageAnnotations ¶ added in v0.15.0
func ValidateMessageAnnotations(annotations []MessageAnnotation) error
ValidateMessageAnnotations validates the envelope, not provider payloads.
func ValidateName ¶
ValidateName checks that name and env are safe for use in paths and cache keys. Rejects empty name and names containing '/', '\\', "..", or ':'. Call before registry Plan or path resolution.
func ValidateOutputMode ¶ added in v0.15.0
func ValidateOutputMode(mode StructuredOutputMode, format *SchemaDefinition) error
ValidateOutputMode checks portable shape, not provider support.
func ValidatePartAssociations ¶ added in v0.15.0
func ValidatePartAssociations(parts []ContentPart, states []PartState, annotations []PartAnnotation) error
ValidatePartAssociations rejects corrupt envelopes without interpreting their payload.
func ValidateRemoteResponseHandle ¶ added in v0.15.0
func ValidateRemoteResponseHandle(handle RemoteResponseHandle) error
func ValidateRequestCachePolicy ¶ added in v0.15.0
func ValidateRequestCachePolicy(policy *CachePolicy) error
ValidateRequestCachePolicy checks whole-request shape, not provider knob support.
func ValidateResponseMetadata ¶ added in v0.15.0
ValidateResponseMetadata checks canonical result metadata without interpreting opaque payloads or inventing provider-specific token composition rules.
func ValidateSchemaJSON ¶ added in v0.15.0
func ValidateSchemaJSON(definition *SchemaDefinition, document JSONDocument) error
ValidateSchemaJSON validates a complete JSON value against an explicit local schema. References require resources declared inside the schema; no external IO is performed.
func ValidateSchemaPolicy ¶ added in v0.15.0
func ValidateSchemaPolicy(policy SchemaPolicy) error
ValidateSchemaPolicy checks intent and permissions, not adapter implementation. It does not prove that a provider can satisfy this policy.
func ValidateSchemaValue ¶ added in v0.15.0
func ValidateSchemaValue(definition *SchemaDefinition, value any) error
ValidateSchemaValue validates the JSON representation of a caller-owned value. Domain validation is a separate caller concern.
func ValidateToolScope ¶ added in v0.14.0
func ValidateToolScope(desc ManifestDescriptor, scope ToolScope) error
ValidateToolScope verifies that required runtime tools are inside the allowed scope.
func ValidateWireJSON ¶ added in v0.15.0
func ValidateWireJSON(document JSONDocument, format string) error
ValidateWireJSON validates the full serialized contract before DTO decoding. The compiler uses only bundled resources, with no network/filesystem loading.
func WireSchemaResources ¶ added in v0.15.0
func WireSchemaResources() map[string]JSONDocument
WireSchemaResources returns isolated executable schemas with explicit resources. Part association/scope/expiry checks are additional semantic invariants in Go.
Types ¶
type BatchCompleteness ¶ added in v0.15.0
type BatchCompleteness struct {
DownloadComplete bool
CorrelationComplete bool
MissingIDs []string
DuplicateIDs []string
UnexpectedIDs []string
}
func ReconcileBatchResults ¶ added in v0.15.0
func ReconcileBatchResults(handle BatchHandle, items []BatchItemResult, downloaded bool) BatchCompleteness
ReconcileBatchResults retains all observations while reporting correlation gaps.
type BatchFileBinding ¶ added in v0.15.0
BatchFileBinding declares host-owned transport destination, never IAM.
type BatchFileCaptureDescriber ¶ added in v0.15.0
type BatchFileCaptureDescriber interface {
CaptureAccuracy() CaptureAccuracy
}
BatchFileCaptureDescriber declares observable original source coverage. Host transport implementations without it do not inherit SDK capture capabilities.
type BatchFileDownload ¶ added in v0.15.0
type BatchFileDownload struct {
Body io.ReadCloser
HTTPStatus int
}
type BatchFileTransport ¶ added in v0.15.0
type BatchFileTransport interface {
Binding() BatchFileBinding
Upload(context.Context, BatchFileUpload) (*BatchFileUploadResult, error)
Download(context.Context, BatchResourceRef) (*BatchFileDownload, error)
}
BatchFileTransport supplies transport/auth/egress; no file storage is implied. Upload must not retry unknown acceptance. Download body ownership transfers to the operation, which closes it exactly once even on parsing/capture failure.
type BatchFileUpload ¶ added in v0.15.0
type BatchFileUploadResult ¶ added in v0.15.0
type BatchFileUploadResult struct {
Resource BatchResourceRef
SourceJSON JSONDocument
HTTPStatus int
}
type BatchHandle ¶ added in v0.15.0
type BatchHandle struct {
Format string `json:"format"`
Provider string `json:"provider"`
Endpoint string `json:"endpoint"`
AccountBinding string `json:"account_binding"`
ProviderID string `json:"provider_id"`
Status BatchStatus `json:"status"`
ProviderStatus string `json:"provider_status,omitempty"`
Items []BatchItemBinding `json:"items"`
Resources []BatchResourceRef `json:"resources,omitempty"`
}
func CloneBatchHandle ¶ added in v0.15.0
func CloneBatchHandle(handle BatchHandle) BatchHandle
func DecodeBatchHandle ¶ added in v0.15.0
func DecodeBatchHandle(document JSONDocument) (BatchHandle, error)
type BatchItem ¶ added in v0.15.0
type BatchItem struct {
ID string
OriginalID string
AttemptID string
ParentAttemptID string
Execution *PromptExecution
}
type BatchItemBinding ¶ added in v0.15.0
type BatchItemOutcome ¶ added in v0.15.0
type BatchItemOutcome string
const ( BatchItemSuccess BatchItemOutcome = "success" BatchItemError BatchItemOutcome = "error" BatchItemRefusal BatchItemOutcome = "refusal" BatchItemIncomplete BatchItemOutcome = "incomplete" BatchItemExpired BatchItemOutcome = "expired" BatchItemCanceled BatchItemOutcome = "canceled" BatchItemUnknown BatchItemOutcome = "unknown" )
type BatchItemResult ¶ added in v0.15.0
type BatchItemResult struct {
ID string
Binding *BatchItemBinding
Outcome BatchItemOutcome
Response *Response
SourceJSON JSONDocument
// ErrorKind is a safe category; provider error payload stays in SourceJSON.
ErrorKind string
}
type BatchManager ¶ added in v0.15.0
type BatchManager interface {
Submit(context.Context, BatchSubmitRequest) (*BatchResult, error)
Get(context.Context, BatchHandle, ...BatchOperationOptions) (*BatchResult, error)
Cancel(context.Context, BatchHandle, ...BatchOperationOptions) (*BatchResult, error)
Results(context.Context, BatchHandle, BatchResultsOptions) (*BatchResult, error)
}
type BatchOperationOptions ¶ added in v0.15.0
type BatchOperationOptions struct {
Capture CaptureRequirement `json:"capture,omitzero" yaml:"capture,omitempty"`
Binding *CaptureBinding `json:"-" yaml:"-"`
}
type BatchResourceRef ¶ added in v0.15.0
type BatchResult ¶ added in v0.15.0
type BatchResult struct {
Handle *BatchHandle
Items []BatchItemResult
Completeness BatchCompleteness
Diagnostics []ExecutionDiagnostics
Capture *CaptureReport
Resources []BatchResourceRef
SubmissionAttempted bool
}
type BatchResultBinding ¶ added in v0.15.0
type BatchResultBinding struct {
ID string
Execution *PromptExecution
}
type BatchResultsOptions ¶ added in v0.15.0
type BatchResultsOptions struct {
Options BatchOperationOptions
Bindings []BatchResultBinding
MaxLineBytes int
MaxBytes int64
}
type BatchStatus ¶ added in v0.15.0
type BatchStatus string
const ( BatchQueued BatchStatus = "queued" BatchRunning BatchStatus = "in_progress" BatchCanceling BatchStatus = "canceling" BatchEnded BatchStatus = "ended" BatchFailed BatchStatus = "failed" BatchExpired BatchStatus = "expired" BatchCanceled BatchStatus = "canceled" BatchUnknown BatchStatus = "unknown" )
type BatchSubmitRequest ¶ added in v0.15.0
type BatchSubmitRequest struct {
Items []BatchItem
Options BatchOperationOptions
}
type CacheDecision ¶ added in v0.15.0
type CacheDecision struct {
Path string `json:"path"`
Mechanism CacheMechanism `json:"mechanism"`
Disposition CacheDisposition `json:"disposition"`
Reason string `json:"reason"`
}
CacheDecision is a safe preflight diagnostic, with no raw control values.
type CacheDisposition ¶ added in v0.15.0
type CacheDisposition string
CacheDisposition describes selected request controls, never observed reuse.
const ( CacheAccepted CacheDisposition = "accepted" CacheUnsupported CacheDisposition = "unsupported" CacheNotApplicable CacheDisposition = "not_applicable" CacheUnknown CacheDisposition = "unknown" )
type CacheError ¶ added in v0.15.0
type CacheError struct {
Decision CacheDecision
Cause error
}
CacheError identifies a rejected policy without leaking provider options.
func (*CacheError) Error ¶ added in v0.15.0
func (e *CacheError) Error() string
func (*CacheError) Unwrap ¶ added in v0.15.0
func (e *CacheError) Unwrap() error
type CacheMechanism ¶ added in v0.15.0
type CacheMechanism string
CacheMechanism identifies request controls, not a cache hit or remote resource.
const CacheOmit CacheMechanism = "omit"
CacheOmit suppresses inherited block markers, not implicit caching or remote reuse.
type CacheMode ¶ added in v0.15.0
type CacheMode string
CacheMode selects advisory or required admission, not retention duration.
type CachePolicy ¶ added in v0.12.0
type CachePolicy struct {
Mechanism CacheMechanism `json:"mechanism" yaml:"mechanism"`
Mode CacheMode `json:"mode,omitempty" yaml:"mode,omitempty"`
Provider string `json:"provider,omitempty" yaml:"provider,omitempty"`
Controls JSONDocument `json:"controls,omitempty" yaml:"controls,omitempty"`
}
CachePolicy replaces unscoped Type hints. Controls are provider-specific JSON (for example {"ttl":"1h"}), never portable retention or deletion guarantees. Empty Mode is advisory. A provider is mandatory when Controls are present. CacheOmit has no Mode, Provider or Controls and suppresses block inheritance only.
type CacheResourceCreateRequest ¶ added in v0.15.0
type CacheResourceCreateRequest struct {
Execution *PromptExecution
Expiry CacheResourceExpiry
}
CacheResourceCreateRequest reuses the canonical prompt for immutable cached inputs.
type CacheResourceExpiry ¶ added in v0.15.0
CacheResourceExpiry selects exactly one positive TTL or future absolute expiry.
type CacheResourceHandle ¶ added in v0.15.0
type CacheResourceHandle struct {
Format string `json:"format"`
Identity ProfileIdentity `json:"identity"`
AccountBinding string `json:"account_binding"`
ProviderID string `json:"provider_id"`
ContentDigest string `json:"content_digest"`
ExpiresAt time.Time `json:"expires_at"`
State CacheResourceState `json:"state"`
}
CacheResourceHandle persists secret-free binding data, not credentials or content. AccountBinding is a host stable reference; comparison is not authorization.
func DecodeCacheResourceHandle ¶ added in v0.15.0
func DecodeCacheResourceHandle(document JSONDocument) (CacheResourceHandle, error)
DecodeCacheResourceHandle validates strict wire shape before restoring binding. The host must rebind transport/account and separately authorize access.
type CacheResourceManager ¶ added in v0.15.0
type CacheResourceManager interface {
Create(context.Context, CacheResourceCreateRequest) (*CacheResourceResult, error)
Get(context.Context, CacheResourceHandle, ...CacheResourceOperationOptions) (*CacheResourceResult, error)
UpdateExpiry(
context.Context,
CacheResourceHandle,
CacheResourceExpiry,
...CacheResourceOperationOptions,
) (*CacheResourceResult, error)
Delete(context.Context, CacheResourceHandle, ...CacheResourceOperationOptions) (*CacheResourceResult, error)
}
CacheResourceManager is an optional caller-driven remote lifecycle port. Implementations do not provide storage, renewal loops or automatic mutation retries.
type CacheResourceOperationOptions ¶ added in v0.15.0
type CacheResourceOperationOptions struct {
Capture CaptureRequirement `json:"capture,omitzero" yaml:"capture,omitempty"`
Binding *CaptureBinding `json:"-" yaml:"-"`
}
CacheResourceOperationOptions is runtime capture intent for inspect/update/delete. The host owns redaction, egress, persistence and concurrency of its ports.
type CacheResourceResult ¶ added in v0.15.0
type CacheResourceResult struct {
Handle *CacheResourceHandle `json:"handle,omitempty"`
Diagnostics ExecutionDiagnostics `json:"diagnostics"`
TokenCount *int64 `json:"token_count,omitempty"`
}
CacheResourceResult retains an observed handle even when a mutation is uncertain. TokenCount is an optional resource-size observation, not invocation billing usage.
type CacheResourceState ¶ added in v0.15.0
type CacheResourceState string
CacheResourceState is an observation, not a durable resource guarantee.
const ( CacheResourceActive CacheResourceState = "active" CacheResourceExpired CacheResourceState = "expired" CacheResourceDeleted CacheResourceState = "deleted" CacheResourceUnknown CacheResourceState = "unknown" )
type CapabilityProfile ¶ added in v0.15.0
type CapabilityProfile struct {
Identity ProfileIdentity `json:"identity"`
Provenance string `json:"provenance"`
Capabilities map[string]CapabilitySupport `json:"capabilities"`
ForbiddenCombinations [][]string `json:"forbidden_combinations,omitempty"`
InputMIME []string `json:"input_mime,omitempty"`
OutputMIME []string `json:"output_mime,omitempty"`
ModelOptionsSchema JSONDocument `json:"model_options_schema,omitempty"`
}
CapabilityProfile is a plain-data, provenance-bearing contract snapshot.
func CloneCapabilityProfile ¶ added in v0.15.0
func CloneCapabilityProfile(profile CapabilityProfile) CapabilityProfile
CloneCapabilityProfile isolates all mutable snapshot data.
type CapabilitySupport ¶ added in v0.15.0
type CapabilitySupport string
CapabilitySupport is knowledge about a profile, not a quality or availability promise.
type CaptureAccuracy ¶ added in v0.15.0
type CaptureAccuracy string
CaptureAccuracy describes the projection, not the quality of generated output.
const ( CaptureMetadata CaptureAccuracy = "metadata" CaptureSemantic CaptureAccuracy = "semantic" CaptureBytes CaptureAccuracy = "bytes" )
type CaptureAck ¶ added in v0.15.0
type CaptureAck struct{ Durable bool }
CaptureAck confirms acceptance; durable is not inferred from a successful write.
type CaptureBinding ¶ added in v0.15.0
type CaptureBinding struct {
Sink CaptureSink
Projector CaptureProjector
CorrelationID string
MaxBytes int // zero uses 64 KiB; this bounds delivered payload, not SDK response size
}
CaptureBinding contains non-persisted caller ports. No recorder is mandatory.
func CloneCaptureBinding ¶ added in v0.15.0
func CloneCaptureBinding(binding *CaptureBinding) *CaptureBinding
CloneCaptureBinding snapshots configuration; shared runtime ports remain caller-owned.
type CaptureCoverage ¶ added in v0.15.0
type CaptureCoverage struct {
Stages map[CaptureStage]CaptureAccuracy
PhysicalAttempts bool
SDKBuild string
}
CaptureCoverage is implementation knowledge, never inferred from provider names.
type CaptureError ¶ added in v0.15.0
type CaptureError struct {
Stage CaptureStage
AfterDispatch bool
Cause error
}
CaptureError distinguishes capture failure after possible execution from a pre-dispatch failure. Error strings never copy sink/projector secrets.
func (*CaptureError) Error ¶ added in v0.15.0
func (e *CaptureError) Error() string
func (*CaptureError) Unwrap ¶ added in v0.15.0
func (e *CaptureError) Unwrap() []error
type CaptureFailure ¶ added in v0.15.0
type CaptureFailure struct {
Stage CaptureStage `json:"stage"`
AfterDispatch bool `json:"after_dispatch"`
Kind string `json:"kind"`
}
CaptureFailure intentionally excludes raw error bodies and caller secrets.
type CaptureProjection ¶ added in v0.15.0
type CaptureProjection struct {
Metadata CaptureRecordMetadata
Payload []byte
MediaType string
Codec string
Accuracy CaptureAccuracy
Redacted bool
Truncated bool
Complete bool
}
CaptureProjection is the host-approved payload. Complete is false when source data was omitted.
type CaptureProjector ¶ added in v0.15.0
type CaptureProjector interface {
MaxAccuracy() CaptureAccuracy
ProjectCapture(context.Context, CaptureRecord) (CaptureProjection, error)
}
CaptureProjector owns redaction/egress policy. Capability is an upper bound; actual projection accuracy is checked for every event. It must honor context.
type CaptureRecord ¶ added in v0.15.0
type CaptureRecord struct {
InvocationID string
CorrelationID string
PhysicalAttemptID string
Sequence uint64
Stage CaptureStage
Profile ProfileIdentity
SDKBuild string
AfterDispatch bool
Projection CaptureProjection
}
CaptureRecord has stable invocation-local ordering. Empty PhysicalAttemptID means unobservable, not a synthetic attempt equal to the logical invocation.
type CaptureRecordMetadata ¶ added in v0.15.0
type CaptureRecordMetadata struct {
ProviderResponseID string `json:"provider_response_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
HTTPStatus *int `json:"http_status,omitempty"`
Usage *Usage `json:"usage,omitempty"`
Outcome Outcome `json:"outcome,omitempty"`
SchemaDigests []CaptureSchemaDigest `json:"schema_digests,omitempty"`
}
CaptureRecordMetadata describes observed fields, never inferred transport coverage. Provider response identity and HTTP request identity are distinct. It is carried inside the host-approved CaptureProjection.
func CloneCaptureRecordMetadata ¶ added in v0.15.0
func CloneCaptureRecordMetadata(m CaptureRecordMetadata) CaptureRecordMetadata
CloneCaptureRecordMetadata isolates callback-owned pointers and collections.
func (CaptureRecordMetadata) Validate ¶ added in v0.15.0
func (m CaptureRecordMetadata) Validate() error
Validate rejects malformed known usage/outcome/status before sink delivery. SchemaDigests and IDs are opaque trusted diagnostic strings, not admitted portable schema references; the host projector selects and redacts them.
type CaptureReport ¶ added in v0.15.0
type CaptureReport struct {
InvocationID string `json:"invocation_id"`
SDKBuild string `json:"sdk_build,omitempty"`
Coverage []CaptureStageCoverage `json:"coverage,omitempty"`
Observed []CaptureStage `json:"observed,omitempty"`
Failures []CaptureFailure `json:"failures,omitempty"`
Closed bool `json:"closed"`
Complete bool `json:"complete"`
}
CaptureReport is a cloned invocation snapshot, not a persistence promise after a crash.
func CloneCaptureReport ¶ added in v0.15.0
func CloneCaptureReport(report CaptureReport) CaptureReport
CloneCaptureReport isolates all mutable diagnostic collections.
func (CaptureReport) Validate ¶ added in v0.15.0
func (r CaptureReport) Validate() error
Validate checks semantic consistency without inventing required stages, physical attempts or durability evidence absent from the report.
type CaptureRequirement ¶ added in v0.15.0
type CaptureRequirement struct {
Stages []CaptureStage `json:"stages,omitempty"`
Accuracy CaptureAccuracy `json:"accuracy,omitempty"`
Durable bool `json:"durable,omitempty"`
PhysicalAttempts bool `json:"physical_attempts,omitempty"`
}
CaptureRequirement is portable intent; runtime ports are rebound after persistence.
type CaptureSchemaDigest ¶ added in v0.15.0
type CaptureSchemaDigest struct {
Role SchemaRole `json:"role"`
Name string `json:"name,omitempty"`
SourceDigest string `json:"source_digest"`
TranslatedDigest string `json:"translated_digest"`
}
CaptureSchemaDigest associates source/translated contracts without raw schema values, endpoint credentials or profile provenance.
func CaptureSchemaDigests ¶ added in v0.15.0
func CaptureSchemaDigests(reports []SchemaCompilationReport) []CaptureSchemaDigest
CaptureSchemaDigests projects immutable compilation associations, not schema content or provider scope. The host may omit these through its projector.
type CaptureSession ¶ added in v0.15.0
type CaptureSession struct {
// contains filtered or unexported fields
}
CaptureSession serializes synchronous callbacks. This does not bound latency, concurrent callers or the retained advisory failure list. Do not re-enter Emit from its callbacks. Report may safely be inspected from a callback.
func NewCaptureSession ¶ added in v0.15.0
func NewCaptureSession( req CaptureRequirement, binding *CaptureBinding, coverage CaptureCoverage, profile ProfileIdentity, ) (*CaptureSession, error)
NewCaptureSession validates all required coverage before any provider dispatch. Nil binding without requirements creates a disabled capture session.
func (*CaptureSession) Emit ¶ added in v0.15.0
func (s *CaptureSession) Emit(ctx context.Context, record CaptureRecord) error
Emit delivers an isolated host projection. Required errors stop the caller; advisory failures are retained in Report but do not change execution outcome.
func (*CaptureSession) Enabled ¶ added in v0.15.0
func (s *CaptureSession) Enabled() bool
Enabled distinguishes the ordinary no-sink execution path without serialization.
func (*CaptureSession) RecordFailure ¶ added in v0.15.0
func (s *CaptureSession) RecordFailure(stage CaptureStage, after bool, kind string, cause error) error
RecordFailure records projection-encoding or hook failure with safe classification.
func (*CaptureSession) Report ¶ added in v0.15.0
func (s *CaptureSession) Report() CaptureReport
Report returns a snapshot isolated from sink/projector mutations.
type CaptureSink ¶ added in v0.15.0
type CaptureSink interface {
Capabilities() CaptureSinkCapabilities
WriteCapture(context.Context, CaptureRecord) (CaptureAck, error)
}
CaptureSink must honor context cancellation and be safe across concurrent invocations.
type CaptureSinkCapabilities ¶ added in v0.15.0
type CaptureSinkCapabilities struct{ Durable bool }
CaptureSinkCapabilities promises only guarantees implemented by the caller's sink.
type CaptureStage ¶ added in v0.15.0
type CaptureStage string
CaptureStage distinguishes canonical data, SDK projections and actual transport boundaries.
const ( CaptureExecution CaptureStage = "canonical_execution" CaptureTranslatedRequest CaptureStage = "translated_request" CaptureTransportRequest CaptureStage = "transport_request" CaptureTransportResponse CaptureStage = "transport_response" CaptureProviderResponse CaptureStage = "provider_response" CaptureProviderChunk CaptureStage = "provider_chunk" CaptureCanonicalParts CaptureStage = "canonical_parts" CaptureTerminal CaptureStage = "canonical_terminal" )
type CaptureStageCoverage ¶ added in v0.15.0
type CaptureStageCoverage struct {
Stage CaptureStage `json:"stage"`
Accuracy CaptureAccuracy `json:"accuracy"`
}
CaptureStageCoverage is a conservative implementation snapshot, not observed bytes.
type CharFallbackCounter ¶
type CharFallbackCounter struct {
CharsPerToken int
}
CharFallbackCounter estimates tokens as runes/CharsPerToken. Zero value uses a heuristic of 4 runes per token, plus fixed media penalties. It is not a tokenizer or full provider request/context-window guarantee.
func (*CharFallbackCounter) Count ¶
func (c *CharFallbackCounter) Count(text string) (int, error)
Count returns estimated token count: ceil(rune_count / CharsPerToken). If CharsPerToken <= 0, uses 4.
func (*CharFallbackCounter) CountMessage ¶ added in v0.6.5
func (c *CharFallbackCounter) CountMessage(msg ChatMessage) (int, error)
CountMessage estimates tokens for a chat message, including media and nested tool content.
type ChatMessage ¶
type ChatMessage struct {
Role Role `json:"role"`
Content []ContentPart `json:"content"`
ProviderState []PartState `json:"-" yaml:"-"`
Annotations []PartAnnotation `json:"annotations,omitempty"`
MessageAnnotations []MessageAnnotation `json:"message_annotations,omitempty"`
CachePolicy *CachePolicy `json:"cache_policy,omitempty" yaml:"cache_policy,omitempty"`
Provenance *MessageProvenance `json:"provenance,omitempty" yaml:"provenance,omitempty"`
Metadata JSONDocument `json:"metadata,omitempty"`
LayerKind LayerKind `json:"layer_kind,omitempty" yaml:"layer_kind,omitempty"`
}
ChatMessage is a single message with role and content parts (supports multimodal). CachePolicy declares advisory/required scoped request controls, not a cache hit. Provenance records manifest/layer origin; Metadata is for provider-specific extras only.
func NewAssistantMessage ¶ added in v0.5.0
func NewAssistantMessage(text string) ChatMessage
NewAssistantMessage creates a single assistant message with text content.
func NewSystemMessage ¶ added in v0.5.0
func NewSystemMessage(text string) ChatMessage
NewSystemMessage creates a single system message with text content.
func NewUserMessage ¶ added in v0.5.0
func NewUserMessage(text string) ChatMessage
NewUserMessage creates a single user message with text content.
type ChatPromptTemplate ¶
type ChatPromptTemplate struct {
Messages []MessageTemplate
PartialVariables map[string]any
Tools []ToolDefinition
RequiredTools []string
ModelOptions *ModelOptions
Metadata PromptMetadata
ResponseFormat *SchemaDefinition // JSON Schema for structured output (passed to PromptExecution)
InputSchema *SchemaDefinition // JSON Schema for template input (prompty-gen, required/partial derivation)
RequiredVars []string // explicit required vars from manifest; merged with template-derived in RenderPlan.Execute
// contains filtered or unexported fields
}
ChatPromptTemplate holds message templates and options for rendering. Use NewChatPromptTemplate to construct; options are applied via ChatTemplateOption. Fields must not be mutated after construction to ensure goroutine safety.
func CloneTemplate ¶
func CloneTemplate(c *ChatPromptTemplate) *ChatPromptTemplate
CloneTemplate returns a copy of the template with cloned slice and map fields. Registries use this so callers cannot mutate the cached template.
func NewChatPromptTemplate ¶
func NewChatPromptTemplate( messages []MessageTemplate, opts ...ChatTemplateOption, ) (*ChatPromptTemplate, error)
NewChatPromptTemplate builds a template with defensive copies and applies options. Returns ErrTemplateParse if any message content fails to parse.
Example ¶
package main
import (
"fmt"
"github.com/skosovsky/prompty"
)
func main() {
msgs := []prompty.MessageTemplate{
{Role: prompty.RoleSystem, Content: prompty.TextContent("You are a helpful assistant.")},
{Role: prompty.RoleUser, Content: prompty.TextContent("Hello, {{ .Input.user_name }}!")},
}
tpl, err := prompty.NewChatPromptTemplate(msgs)
if err != nil {
panic(err)
}
fmt.Println(len(tpl.Messages))
}
Output: 2
type ChatTemplateOption ¶
type ChatTemplateOption func(*ChatPromptTemplate)
ChatTemplateOption configures ChatPromptTemplate (functional options pattern).
func MustWithPartialVariablesJSON ¶ added in v0.11.0
func MustWithPartialVariablesJSON(doc JSONDocument) ChatTemplateOption
MustWithPartialVariablesJSON is like WithPartialVariablesJSON but panics on decode error (tests).
func WithInputSchema ¶ added in v0.5.0
func WithInputSchema(schema *SchemaDefinition) ChatTemplateOption
WithInputSchema sets the JSON Schema for template input (used by prompty-gen and manifest inputs contract).
func WithMetadata ¶
func WithMetadata(meta PromptMetadata) ChatTemplateOption
WithMetadata sets prompt metadata for observability.
func WithModelOptions ¶ added in v0.6.5
func WithModelOptions(config *ModelOptions) ChatTemplateOption
WithModelOptions sets model options (e.g. temperature, max_tokens).
func WithPartialSources ¶ added in v0.15.0
func WithPartialSources(sources map[string]string) ChatTemplateOption
WithPartialSources compiles captured named partial bytes without source I/O. Names are sorted in lexical order; implicit template names use the basename.
func WithPartialVariablesJSON ¶ added in v0.11.0
func WithPartialVariablesJSON(doc JSONDocument) (ChatTemplateOption, error)
WithPartialVariablesJSON sets default input values from a JSON object (payload overrides).
func WithPartialsFS ¶ added in v0.3.0
func WithPartialsFS(fsys fs.FS, pattern string) ChatTemplateOption
WithPartialsFS sets an fs.FS and pattern for partials (e.g. embed FS and "partials/*.tmpl"); enables {{ template "name" }}.
func WithPartialsGlob ¶ added in v0.3.0
func WithPartialsGlob(glob string) ChatTemplateOption
WithPartialsGlob sets a glob pattern (e.g. "_partials/*.tmpl") to parse before message templates; enables {{ template "name" }}.
func WithRequiredTools ¶ added in v0.7.6
func WithRequiredTools(tools []string) ChatTemplateOption
WithRequiredTools sets tool names the prompt contract requires (from manifest required_tools).
func WithRequiredVars ¶
func WithRequiredVars(vars []string) ChatTemplateOption
WithRequiredVars sets explicit required input field names (e.g. from manifest input_schema.required). Merged with input fields inferred from template content in RenderPlan.Execute.
func WithResponseFormat ¶ added in v0.2.0
func WithResponseFormat(schema *SchemaDefinition) ChatTemplateOption
WithResponseFormat sets the JSON Schema for structured response format (used by OpenAI, Gemini).
func WithTokenCounter ¶
func WithTokenCounter(tc TokenCounter) ChatTemplateOption
WithTokenCounter sets the token counter for truncate_tokens in templates.
func WithTools ¶
func WithTools(tools []ToolDefinition) ChatTemplateOption
WithTools sets tool definitions available in templates as .Tools.
Example ¶
package main
import (
"fmt"
"github.com/skosovsky/prompty"
)
func main() {
tpl, _ := prompty.NewChatPromptTemplate(
[]prompty.MessageTemplate{
{Role: prompty.RoleSystem, Content: prompty.TextContent("Tools: {{ render_tools_as_json .Tools }}")},
},
prompty.WithTools([]prompty.ToolDefinition{
{Name: "get_weather", Description: "Get weather", Parameters: nil},
}),
)
fmt.Println(len(tpl.Tools))
}
Output: 1
type CompiledProviderSchema ¶ added in v0.15.0
type CompiledProviderSchema struct {
// contains filtered or unexported fields
}
CompiledProviderSchema retains immutable documents and original validation. A successful compile is not evidence that a live provider supports the profile.
func CompileProviderSchema ¶ added in v0.15.0
func CompileProviderSchema(request SchemaCompileRequest, mapper ProviderSchemaMapper) (*CompiledProviderSchema, error)
CompileProviderSchema validates before mapping and enforces explicit fidelity policy. No transport is owned by this function. Provider binding must call it before dispatch.
func (*CompiledProviderSchema) Report ¶ added in v0.15.0
func (c *CompiledProviderSchema) Report() SchemaCompilationReport
Report returns an isolated compilation report.
func (*CompiledProviderSchema) Source ¶ added in v0.15.0
func (c *CompiledProviderSchema) Source() JSONDocument
Source returns the original exact bytes without exposing mutable state.
func (*CompiledProviderSchema) Translated ¶ added in v0.15.0
func (c *CompiledProviderSchema) Translated() JSONDocument
Translated returns the canonical provider schema, not SDK or wire bytes.
func (*CompiledProviderSchema) ValidateOriginal ¶ added in v0.15.0
func (c *CompiledProviderSchema) ValidateOriginal(value JSONDocument) error
ValidateOriginal validates the complete result against the source schema. Domain validation and outcome checks are separate responsibilities.
type ComposeContext ¶ added in v0.13.0
type ComposeContext interface {
ComposeValues() ComposeValues
}
ComposeContext is the typed public contract generated prompt packages can implement. It keeps application code away from nested map construction.
type ComposeValue ¶ added in v0.13.0
type ComposeValue struct {
// contains filtered or unexported fields
}
ComposeValue is one typed condition.match value for ComposeValues.
func ComposeBool ¶ added in v0.13.0
func ComposeBool(path string, value bool) ComposeValue
ComposeBool builds one bool compose value.
func ComposeFloat ¶ added in v0.13.0
func ComposeFloat(path string, value float64) ComposeValue
ComposeFloat builds one number compose value.
func ComposeInt ¶ added in v0.13.0
func ComposeInt(path string, value int64) ComposeValue
ComposeInt builds one integer compose value.
func ComposeString ¶ added in v0.13.0
func ComposeString(path string, value string) ComposeValue
ComposeString builds one string compose value.
type ComposeValues ¶ added in v0.13.0
type ComposeValues struct {
// contains filtered or unexported fields
}
ComposeValues is an opaque typed token for manifest condition.match evaluation. The zero value means "unset". Values built through NewComposeValuesFromPairs are set, including an intentionally empty value set.
func CheckedComposeValuesFromPairs ¶ added in v0.15.0
func CheckedComposeValuesFromPairs(pairs ...ComposeValue) (ComposeValues, error)
CheckedComposeValuesFromPairs rejects invalid input atomically.
func NewComposeValuesFromPairs ¶ added in v0.13.0
func NewComposeValuesFromPairs(pairs ...ComposeValue) ComposeValues
NewComposeValuesFromPairs builds programmer-supplied compose values. It panics on invalid paths/collisions; use CheckedComposeValuesFromPairs for error-return admission of dynamic input.
func (ComposeValues) IsSet ¶ added in v0.13.0
func (v ComposeValues) IsSet() bool
IsSet reports whether compose values were intentionally provided.
type ContentPart ¶
type ContentPart interface {
// contains filtered or unexported methods
}
ContentPart is a sealed interface for message parts. Only package types implement it via isContentPart().
Contract: All ProviderAdapter implementations of ParseResponse MUST return a []ContentPart slice containing only value types (e.g. TextPart, not *TextPart). Consumers can rely on this and need no defensive checks for pointer vs value.
func AssembleToolCallParts ¶ added in v0.15.0
func AssembleToolCallParts(parts []ContentPart) ([]ContentPart, error)
AssembleToolCallParts materializes complete calls by stable identity. Text and other parts retain their positions; each call occupies its first delta position. It must be called after the provider has completed the calls, never on a prefix.
type ContentPartWire ¶ added in v0.14.0
type ContentPartWire struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
MediaType string `json:"media_type,omitempty"`
MIMEType string `json:"mime_type,omitempty"`
URL string `json:"url,omitempty"`
Data []byte `json:"data,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
Name string `json:"name,omitempty"`
Args string `json:"args,omitempty"`
ArgsChunk string `json:"args_chunk,omitempty"`
Content []ContentPartWire `json:"content,omitempty"`
IsError bool `json:"is_error,omitempty"`
CachePolicy *CachePolicy `json:"cache_policy,omitempty"`
}
ContentPartWire is a tagged union for all public content part variants.
type DescribingRegistry ¶ added in v0.11.0
type DescribingRegistry interface {
Registry
PromptDescriber
}
DescribingRegistry is required by prompty-gen NewPromptCatalog (plan + DescribePrompt).
type ExecutionDiagnostics ¶ added in v0.15.0
type ExecutionDiagnostics struct {
Profile ProfileIdentity `json:"profile"`
Snapshot string `json:"snapshot"`
Provenance string `json:"provenance,omitempty"`
Override bool `json:"override,omitempty"`
Checks []RequirementCheck `json:"checks,omitempty"`
Schemas []SchemaCompilationReport `json:"schemas,omitempty"`
Capture *CaptureReport `json:"capture,omitempty"`
Cache []CacheDecision `json:"cache,omitempty"`
}
ExecutionDiagnostics preserves the effective checked profile and provenance.
func CloneExecutionDiagnostics ¶ added in v0.15.0
func CloneExecutionDiagnostics(report ExecutionDiagnostics) ExecutionDiagnostics
CloneExecutionDiagnostics isolates the mutable checks of a prepared snapshot.
type ExecutionRequirements ¶ added in v0.15.0
type ExecutionRequirements struct {
OutputMode StructuredOutputMode `json:"output_mode,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
OutputMIME []string `json:"output_mime,omitempty"`
Override *CapabilityProfile `json:"override,omitempty"`
Schema SchemaPolicy `json:"schema,omitzero"`
Capture CaptureRequirement `json:"capture,omitzero"`
}
ExecutionRequirements contains caller guarantees and an explicit checked profile override.
type Fetcher ¶ added in v0.3.0
type Fetcher interface {
Fetch(ctx context.Context, url string) (data []byte, mimeType string, err error)
}
Fetcher defines how media URLs are resolved into raw bytes. Callers can use mediafetch.DefaultFetcher or provide a custom implementation (e.g. S3, local files).
type HostedToolRequest ¶ added in v0.15.0
type HostedToolRequest struct {
Kind string `json:"kind"`
Settings JSONDocument `json:"settings,omitempty"`
}
HostedToolRequest is explicit provider execution intent, never a local handler binding. Kind/settings semantics belong to the selected adapter.
func CloneHostedToolRequests ¶ added in v0.15.0
func CloneHostedToolRequests(tools []HostedToolRequest) []HostedToolRequest
type Invoker ¶ added in v0.5.0
type Invoker interface {
Execute(ctx context.Context, exec *PromptExecution) (*Response, error)
ExecuteStream(ctx context.Context, exec *PromptExecution, mode StreamMode) *Stream
}
Invoker defines the canonical model invocation port (sync + stream). Implementations must check required guarantees against their effective destination before dispatch and fail closed when they cannot establish them. Helpers enforce local schema/outcome/tool contracts but cannot independently inspect an arbitrary host implementation's transport, profile or SDK ports. Use a checked adapter client, or delegate unchanged executions to one, when provider preflight is required. Wrappers must not discard requirements or replace requested native streaming with buffered execution.
func Chain ¶ added in v0.5.0
func Chain(base Invoker, middlewares ...Middleware) Invoker
Chain combines multiple middlewares around the base Invoker. The leftmost middleware in the chain executes first.
type JSONDocument ¶ added in v0.11.0
type JSONDocument = json.RawMessage
JSONDocument is an opaque JSON payload for schema/metadata provider boundaries.
func CloneJSONDocument ¶ added in v0.11.0
func CloneJSONDocument(doc JSONDocument) JSONDocument
CloneJSONDocument returns a deep copy of doc.
func EncodeBatchHandle ¶ added in v0.15.0
func EncodeBatchHandle(handle BatchHandle) (JSONDocument, error)
func EncodeCacheResourceHandle ¶ added in v0.15.0
func EncodeCacheResourceHandle(handle CacheResourceHandle) (JSONDocument, error)
EncodeCacheResourceHandle validates and serializes the portable resource binding.
func EncodeRemoteResponseHandle ¶ added in v0.15.0
func EncodeRemoteResponseHandle(handle RemoteResponseHandle) (JSONDocument, error)
func JSONSchemaFromStruct ¶ added in v0.14.0
func JSONSchemaFromStruct[T any]() (JSONDocument, error)
JSONSchemaFromStruct returns a JSON schema document for T.
func MapToJSONDocument ¶ added in v0.11.0
func MapToJSONDocument(m map[string]any) (JSONDocument, error)
MapToJSONDocument encodes a map as JSONDocument.
func MarshalJSONDocument ¶ added in v0.11.0
func MarshalJSONDocument(v any) (JSONDocument, error)
MarshalJSONDocument encodes v as JSONDocument.
func MustJSONDocumentFromMap ¶ added in v0.11.0
func MustJSONDocumentFromMap(m map[string]any) JSONDocument
MustJSONDocumentFromMap encodes m as JSONDocument and panics on error (tests/examples).
type JSONSchemaValidator ¶ added in v0.15.0
type JSONSchemaValidator struct {
// contains filtered or unexported fields
}
JSONSchemaValidator uses the standard validator with an isolated, explicit resource set. It supports the declared dialects and never performs filesystem or network reference loading.
func NewJSONSchemaValidator ¶ added in v0.15.0
func NewJSONSchemaValidator(resources map[string]JSONDocument) *JSONSchemaValidator
NewJSONSchemaValidator clones caller-owned schema resources.
func (*JSONSchemaValidator) CompileSchema ¶ added in v0.15.0
func (v *JSONSchemaValidator) CompileSchema(source JSONDocument, dialect string) (ValueValidator, error)
CompileSchema checks the schema itself before any provider call.
type LayerKind ¶ added in v0.9.0
type LayerKind string
LayerKind identifies a prompt layer category for composition/replacement.
type Lister ¶ added in v0.4.0
Lister is optional. When implemented by a registry, List returns available template ids.
type ManifestBytesReader ¶ added in v0.11.0
type ManifestBytesReader interface {
ReadManifestBytes(ctx context.Context, id string) ([]byte, error)
}
ManifestBytesReader supplies raw manifest bytes for digest computation.
type ManifestCheckpointRegistry ¶ added in v0.12.0
type ManifestCheckpointRegistry interface {
ManifestSnapshotRegistry
Registry
RecommendManifestDescriptor(ctx context.Context, id string) (ManifestDescriptor, error)
VerifyManifestDescriptor(ctx context.Context, desc ManifestDescriptor) error
}
ManifestCheckpointRegistry supplies captured materialization and checkpoint identities.
type ManifestComposeChecker ¶ added in v0.12.0
type ManifestComposeChecker interface {
ManifestUsesComposeE(ctx context.Context, id string) (bool, error)
}
ManifestComposeChecker reports whether a manifest uses imports/layers (compose-aware caching). Corrupt manifest bytes must return a non-nil error (never silently report false).
type ManifestDescriptor ¶ added in v0.12.0
type ManifestDescriptor struct {
ID string `json:"id"`
Digest string `json:"digest"` // Versioned source-bundle identity; raw single-file digests are rejected.
}
ManifestDescriptor is the lightweight checkpoint token for application state (manifest id + digest).
func (*ManifestDescriptor) UnmarshalJSON ¶ added in v0.15.0
func (d *ManifestDescriptor) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects legacy descriptors instead of silently assigning them a new meaning.
type ManifestDescriptorVerifier ¶ added in v0.13.0
type ManifestDescriptorVerifier interface {
VerifyManifestDescriptor(ctx context.Context, desc ManifestDescriptor) error
}
ManifestDescriptorVerifier verifies that a stored manifest descriptor still matches registry state.
type ManifestResolver ¶ added in v0.10.0
type ManifestResolver interface {
ResolveManifest(ctx context.Context, id string, opts ...ResolveManifestOption) (TemplateDescriptor, error)
}
ManifestResolver resolves manifest metadata without rendering.
type ManifestSnapshot ¶ added in v0.15.0
type ManifestSnapshot struct {
// contains filtered or unexported fields
}
ManifestSnapshot is an immutable source bundle with its materializer. It is not a durable agent checkpoint or a serialized Go implementation.
func NewManifestSnapshot ¶ added in v0.15.0
func NewManifestSnapshot(id string, bundle SourceBundle, materialize SnapshotMaterializer) (*ManifestSnapshot, error)
NewManifestSnapshot seals caller-owned bytes and computes a versioned identity. Custom materializers are trusted implementations of the captured-source contract.
func (*ManifestSnapshot) Descriptor ¶ added in v0.15.0
func (s *ManifestSnapshot) Descriptor() ManifestDescriptor
Descriptor returns the identity of exactly the sources used by Plan.
func (*ManifestSnapshot) Plan ¶ added in v0.15.0
func (s *ManifestSnapshot) Plan(ctx context.Context, input RegistryPlanInput) (*RenderPlan, error)
Plan builds from captured bytes, even when the original source has disappeared.
func (*ManifestSnapshot) Sources ¶ added in v0.15.0
func (s *ManifestSnapshot) Sources() SourceBundle
Sources returns an isolated copy for host persistence or inspection.
type ManifestSnapshotRegistry ¶ added in v0.15.0
type ManifestSnapshotRegistry interface {
CaptureManifest(context.Context, string) (*ManifestSnapshot, error)
}
ManifestSnapshotRegistry captures one source generation for verification and planning. A plain Registry does not imply this stronger contract.
type MediaPart ¶ added in v0.2.0
type MediaPart struct {
MediaType string // "image", "audio", "video", "document"
MIMEType string // e.g. "application/pdf", "image/jpeg"
URL string // Optional: link (adapters may fetch and convert to inline)
Data []byte // Optional: raw bytes (base64 is decoded by adapters as needed)
CachePolicy *CachePolicy `json:"cache_policy,omitempty" yaml:"cache_policy,omitempty"`
}
MediaPart holds universal media (image, audio, video, document). URL or Data may be set. Adapters that do not accept URL natively may require callers to resolve URLs into inline data first.
type MessageAnnotation ¶ added in v0.15.0
type MessageAnnotation struct {
Kind string `json:"kind"`
Value JSONDocument `json:"value"`
Scope *ProfileIdentity `json:"scope,omitempty"`
Required bool `json:"required,omitempty"`
}
MessageAnnotation preserves metadata associated with the whole message. Stream updates are ordered, not merged snapshots. Provider-relative indices inside Value are not canonical content-part indices and are never inferred. Payload interpretation and redaction belong to the provider module and host. Scope binds opaque metadata to one destination. Required marks continuation data that a receiving adapter must understand and preserve; it needs Scope.
type MessageProvenance ¶ added in v0.12.0
type MessageProvenance struct {
ManifestID string `json:"manifest_id,omitempty" yaml:"manifest_id,omitempty"`
LayerID string `json:"layer_id,omitempty" yaml:"layer_id,omitempty"`
}
MessageProvenance tracks manifest/layer origin for a rendered message.
type MessageTemplate ¶
type MessageTemplate struct {
Role Role // RoleSystem, RoleUser, RoleAssistant (and others; see Role* constants)
Content []TemplatePart // Parts to render (text and/or media); each part is a Go text/template
Optional bool // true → skip if all referenced variables are zero-value
CachePolicy *CachePolicy `json:"cache_policy,omitempty" yaml:"cache_policy,omitempty"`
Metadata JSONDocument `json:"metadata,omitempty" yaml:"metadata,omitempty"`
LayerID string `json:"layer_id,omitempty" yaml:"layer_id,omitempty"`
LayerKind LayerKind `json:"layer_kind,omitempty" yaml:"layer_kind,omitempty"`
}
MessageTemplate is the raw template for one message before rendering. After RenderPlan.Execute it becomes a ChatMessage with substituted values. Optional: true skips the message if all referenced variables are zero-value. CachePolicy applies message-level cache hint; parts may override with their own cache_policy.
type MessageWire ¶ added in v0.14.0
type MessageWire struct {
ProviderState []PartState `json:"provider_state,omitempty"`
Annotations []PartAnnotation `json:"annotations,omitempty"`
MessageAnnotations []MessageAnnotation `json:"message_annotations,omitempty"`
Role Role `json:"role"`
Content []ContentPartWire `json:"content"`
CachePolicy *CachePolicy `json:"cache_policy,omitempty"`
Provenance *MessageProvenance `json:"provenance,omitempty"`
Metadata JSONDocument `json:"metadata,omitempty"`
LayerKind LayerKind `json:"layer_kind,omitempty"`
}
MessageWire is the JSON-safe representation of ChatMessage.
type Middleware ¶ added in v0.5.0
Middleware wraps Invoker, allowing cross-cutting behavior for Execute and ExecuteStream (logging, metrics, tracing, etc.).
type ModelOptions ¶ added in v0.6.5
type ModelOptions struct {
Model string `json:"model,omitempty" yaml:"model,omitempty"`
Temperature *float64 `json:"temperature,omitempty" yaml:"temperature,omitempty"`
MaxTokens *int64 `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`
TopP *float64 `json:"top_p,omitempty" yaml:"top_p,omitempty"`
Stop []string `json:"stop,omitempty" yaml:"stop,omitempty"`
ProviderSettings JSONDocument `json:"provider_settings,omitempty" yaml:"provider_settings,omitempty"`
}
ModelOptions holds typed, cross-provider model settings for one template/execution. ProviderSettings preserves provider-specific manifest keys without requiring generic SDK mapping.
type ModelOptionsWire ¶ added in v0.14.0
type ModelOptionsWire struct {
Model string `json:"model,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens *int64 `json:"max_tokens,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
Stop []string `json:"stop,omitempty"`
}
ModelOptionsWire carries cross-provider model options; provider-specific payload is PromptExecutionWire.Provider.
type NonTextResponseError ¶ added in v0.11.0
type NonTextResponseError struct {
PartKinds []string
}
NonTextResponseError describes which content types blocked strict text extraction.
func (*NonTextResponseError) Error ¶ added in v0.11.0
func (e *NonTextResponseError) Error() string
func (*NonTextResponseError) Unwrap ¶ added in v0.11.0
func (e *NonTextResponseError) Unwrap() error
type Option ¶ added in v0.5.6
type Option func(*PromptExecution)
Option configures a PromptExecution for convenience helpers.
type Outcome ¶ added in v0.15.0
type Outcome string
Outcome is a provider result, independent of transport completion.
const ( OutcomeCompleted Outcome = "completed" OutcomeToolCalls Outcome = "tool_calls" OutcomeRefusal Outcome = "refusal" OutcomeIncomplete Outcome = "incomplete" // OutcomePaused ends this provider operation while leaving model work resumable // by an explicit caller request. It grants neither output success nor tool execution. OutcomePaused Outcome = "paused" )
type OutcomeError ¶ added in v0.15.0
OutcomeError preserves provider refusal/incomplete semantics without JSON repair classification.
func (*OutcomeError) Error ¶ added in v0.15.0
func (e *OutcomeError) Error() string
func (*OutcomeError) Unwrap ¶ added in v0.15.0
func (*OutcomeError) Unwrap() error
type PartAnnotation ¶ added in v0.15.0
type PartAnnotation struct {
PartIndex int `json:"part_index"`
Kind string `json:"kind"`
Value JSONDocument `json:"value"`
}
PartAnnotation preserves provider-exposed citations/metadata with their association.
type PartState ¶ added in v0.15.0
type PartState struct {
PartIndex int `json:"part_index"`
Envelope ProviderEnvelope `json:"envelope"`
}
PartState binds one envelope to an exact content part; indices are never inferred.
type ProfileIdentity ¶ added in v0.15.0
type ProfileIdentity struct {
Provider string `json:"provider"`
Endpoint string `json:"endpoint"`
Model string `json:"model"`
ModelFamily string `json:"model_family,omitempty"`
}
ProfileIdentity describes the effective provider destination without SDK types.
type PromptCatalogRegistry ¶ added in v0.13.0
type PromptCatalogRegistry interface {
DescribingRegistry
ManifestCheckpointRegistry
}
PromptCatalogRegistry is required by prompty-gen recipe/index APIs.
type PromptDescriber ¶ added in v0.11.0
type PromptDescriber interface {
DescribePrompt(ctx context.Context, id string) (TemplateDescriptor, error)
}
PromptDescriber exposes declarative prompt introspection for host routing.
type PromptExecution ¶
type PromptExecution struct {
// RequestCache selects whole-request controls, never a block marker or remote resource.
RequestCache *CachePolicy `json:"request_cache,omitempty" yaml:"request_cache,omitempty"`
// CacheResource explicitly selects a scoped remote cache, not a request hint.
CacheResource *CacheResourceHandle `json:"cache_resource,omitempty" yaml:"cache_resource,omitempty"`
Messages []ChatMessage
Tools []ToolDefinition
// HostedTools declares provider execution, separate from local ToolScope/handlers.
HostedTools []HostedToolRequest
RequiredTools []string
ForcedTool string
ModelOptions *ModelOptions
Metadata PromptMetadata
ResponseFormat *SchemaDefinition `json:"response_format,omitempty" yaml:"response_format,omitempty"`
// Validator is a runtime port. Rebind it after wire restore; it is never persisted.
// Implementations must be immutable or safe for concurrent compilation.
Validator SchemaValidator `json:"-" yaml:"-"`
Capture *CaptureBinding `json:"-" yaml:"-"`
Requirements ExecutionRequirements `json:"requirements,omitzero" yaml:"requirements,omitempty"`
// contains filtered or unexported fields
}
PromptExecution is the result of formatting a template; immutable after creation.
func DecodeExecutionJSON ¶ added in v0.15.0
func DecodeExecutionJSON(document JSONDocument) (*PromptExecution, error)
DecodeExecutionJSON validates the schema, format and semantic associations.
func ExecuteWithTypedTools ¶ added in v0.11.0
func ExecuteWithTypedTools( ctx context.Context, invoker Invoker, exec *PromptExecution, tools ToolInvoker, ) (*PromptExecution, error)
ExecuteWithTypedTools performs one model call, validates tool args, and invokes handlers.
func NewExecution ¶ added in v0.5.0
func NewExecution(messages []ChatMessage) *PromptExecution
NewExecution creates a new prompt execution from a set of messages.
func SimpleChat ¶ added in v0.5.0
func SimpleChat(system, user string) *PromptExecution
SimpleChat builds a typical execution with one system instruction and one user message.
func SimplePrompt ¶ added in v0.5.0
func SimplePrompt(user string) *PromptExecution
SimplePrompt builds an execution with only one user message.
func UnmarshalExecution ¶ added in v0.14.0
func UnmarshalExecution(wire PromptExecutionWire) (*PromptExecution, error)
UnmarshalExecution converts a stable wire DTO into PromptExecution.
func (*PromptExecution) AddMessage ¶ added in v0.3.0
func (e *PromptExecution) AddMessage(msg ChatMessage) *PromptExecution
AddMessage returns a new execution with one cloned message appended.
func (*PromptExecution) Clone ¶ added in v0.5.6
func (e *PromptExecution) Clone() *PromptExecution
Clone returns a deep copy of the execution and all mutable nested structures.
func (*PromptExecution) Normalize ¶ added in v0.4.5
func (e *PromptExecution) Normalize() *PromptExecution
Normalize returns a new PromptExecution with consecutive system/developer messages merged into one. Content is merged: TextPart texts are concatenated with "\n\n"; other parts (e.g. MediaPart) are preserved in order. Provenance, Metadata, and LayerKind use first-wins semantics from the leading message; trailing values are dropped. Adjacent messages are not merged when LayerID differs (including empty vs non-empty). Call explicitly when history may have produced adjacent system messages (e.g. to avoid provider 400).
func (*PromptExecution) ResolvedMedia ¶ added in v0.6.5
func (e *PromptExecution) ResolvedMedia( ctx context.Context, fetcher Fetcher, ) (*PromptExecution, error)
ResolvedMedia returns a cloned execution where MediaParts with URL and empty Data are fetched via Fetcher. MIME type is populated from fetcher response; callers can use this for image/audio/video/document URLs.
func (*PromptExecution) Text ¶ added in v0.14.0
func (e *PromptExecution) Text(strict bool) (string, error)
Text returns rendered execution text without invoking a model.
func (*PromptExecution) ToolScope ¶ added in v0.15.0
func (e *PromptExecution) ToolScope() *ToolScope
ToolScope returns an isolated declaration, or nil when no additional scope exists.
func (*PromptExecution) WithHistory ¶ added in v0.3.0
func (e *PromptExecution) WithHistory(history []ChatMessage) *PromptExecution
WithHistory returns a new execution with cloned history messages appended.
func (*PromptExecution) WithMessages ¶ added in v0.6.5
func (e *PromptExecution) WithMessages(messages []ChatMessage) *PromptExecution
WithMessages returns a new execution with provided messages replacing current history.
func (*PromptExecution) WithToolScope ¶ added in v0.15.0
func (e *PromptExecution) WithToolScope(scope ToolScope) (*PromptExecution, error)
WithToolScope binds a cloned declaration to a cloned execution. It is not IAM. Empty Allowed is an explicit denial of all local tools.
type PromptExecutionWire ¶ added in v0.14.0
type PromptExecutionWire struct {
ToolScope *ToolScope `json:"tool_scope,omitempty"`
RequestCache *CachePolicy `json:"request_cache,omitempty"`
CacheResource *CacheResourceHandle `json:"cache_resource,omitempty"`
Format string `json:"format"`
Messages []MessageWire `json:"messages"`
Tools []ToolWire `json:"tools,omitempty"`
HostedTools []HostedToolRequest `json:"hosted_tools,omitempty"`
RequiredTools []string `json:"required_tools,omitempty"`
ForcedTool string `json:"forced_tool,omitempty"`
ModelOptions *ModelOptionsWire `json:"model_options,omitempty"`
Metadata PromptMetadata `json:"metadata"`
ResponseFormat *ResponseFormatWire `json:"response_format,omitempty"`
Provider JSONDocument `json:"provider,omitempty"`
Requirements ExecutionRequirements `json:"requirements,omitzero"`
}
PromptExecutionWire is the stable JSON-safe wire representation of PromptExecution.
func LoggingExecution ¶ added in v0.15.0
func LoggingExecution(exec *PromptExecution) (PromptExecutionWire, error)
LoggingExecution is a non-continuable logging projection, not persistence wire.
func MarshalExecution ¶ added in v0.14.0
func MarshalExecution(exec *PromptExecution, policy WirePolicy) (PromptExecutionWire, error)
MarshalExecution converts PromptExecution into a stable JSON-safe wire DTO.
type PromptMetadata ¶
type PromptMetadata struct {
ID string `json:"id"`
Version string `json:"version,omitempty"`
Description string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
Environment string `json:"environment,omitempty"`
Extras JSONDocument `json:"extras,omitempty"`
}
PromptMetadata holds observability metadata. Known fields: ID, Version, Description, Tags, Environment. Extras holds arbitrary keys from manifest metadata block for tracing/custom middleware.
type PromptRecipe ¶ added in v0.13.0
type PromptRecipe[TInput any, TLate any] struct { Descriptor ManifestDescriptor `json:"descriptor"` Input TInput `json:"input"` LateInput *TLate `json:"late_input,omitempty"` LateBound bool `json:"late_bound"` RuntimeOptions PromptRuntimeOptions `json:"runtime_options,omitzero"` }
PromptRecipe is a serializable prompt recipe that can rebuild and execute a render plan.
func NewPromptRecipe ¶ added in v0.13.0
func NewPromptRecipe[TInput any, TLate any]( desc ManifestDescriptor, input TInput, options ...PromptRuntimeOptions, ) (PromptRecipe[TInput, TLate], error)
NewPromptRecipe builds a prompt recipe from a manifest descriptor and early input.
func PromptRecipeFromCheckpoint ¶ added in v0.13.0
func PromptRecipeFromCheckpoint[TInput any, TLate any]( cp PromptRecipeCheckpoint[TInput, TLate], ) (PromptRecipe[TInput, TLate], error)
PromptRecipeFromCheckpoint restores a recipe from its checkpoint DTO.
func (PromptRecipe[TInput, TLate]) BindLate ¶ added in v0.13.0
func (r PromptRecipe[TInput, TLate]) BindLate(late TLate) (PromptRecipe[TInput, TLate], error)
BindLate returns a copy of the recipe with typed late input attached.
func (PromptRecipe[TInput, TLate]) Checkpoint ¶ added in v0.13.0
func (r PromptRecipe[TInput, TLate]) Checkpoint() (PromptRecipeCheckpoint[TInput, TLate], error)
Checkpoint returns a JSON-safe checkpoint DTO.
func (PromptRecipe[TInput, TLate]) Execute ¶ added in v0.13.0
func (r PromptRecipe[TInput, TLate]) Execute( ctx context.Context, registry ManifestSnapshotRegistry, ) (*PromptExecution, error)
Execute verifies, rebuilds, binds late input, and materializes a prompt execution.
func (PromptRecipe[TInput, TLate]) ExecuteWithContract ¶ added in v0.13.0
func (r PromptRecipe[TInput, TLate]) ExecuteWithContract( ctx context.Context, registry ManifestSnapshotRegistry, contract ToolManifestContract, ) (*PromptExecution, error)
ExecuteWithContract verifies, rebuilds, binds late input, materializes, and checks required tools.
func (PromptRecipe[TInput, TLate]) Plan ¶ added in v0.13.0
func (r PromptRecipe[TInput, TLate]) Plan( ctx context.Context, registry ManifestSnapshotRegistry, ) (*RenderPlan, error)
Plan rebuilds the deferred render plan from stored early input.
func (PromptRecipe[TInput, TLate]) Verify ¶ added in v0.13.0
func (r PromptRecipe[TInput, TLate]) Verify( ctx context.Context, verifier ManifestDescriptorVerifier, ) error
Verify checks the stored descriptor against current registry state.
func (PromptRecipe[TInput, TLate]) WithComposeContext ¶ added in v0.13.0
func (r PromptRecipe[TInput, TLate]) WithComposeContext( ctx ComposeContext, ) (PromptRecipe[TInput, TLate], error)
WithComposeContext returns a copy of the recipe with typed compose context attached.
type PromptRecipeCheckpoint ¶ added in v0.13.0
type PromptRecipeCheckpoint[TInput any, TLate any] struct { Descriptor ManifestDescriptor `json:"descriptor"` Input TInput `json:"input"` LateInput *TLate `json:"late_input,omitempty"` LateBound bool `json:"late_bound"` RuntimeOptions PromptRuntimeOptions `json:"runtime_options,omitzero"` }
PromptRecipeCheckpoint is a JSON-safe checkpoint DTO for a prompt recipe.
func (*PromptRecipeCheckpoint[TInput, TLate]) UnmarshalJSON ¶ added in v0.13.0
func (cp *PromptRecipeCheckpoint[TInput, TLate]) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects inconsistent checkpoint state and unknown checkpoint/input fields.
type PromptRecipeNoLate ¶ added in v0.13.0
type PromptRecipeNoLate[TInput any] struct { Descriptor ManifestDescriptor `json:"descriptor"` Input TInput `json:"input"` RuntimeOptions PromptRuntimeOptions `json:"runtime_options,omitzero"` }
PromptRecipeNoLate is a recipe variant for prompts that do not declare late input.
func NewPromptRecipeNoLate ¶ added in v0.13.0
func NewPromptRecipeNoLate[TInput any]( desc ManifestDescriptor, input TInput, options ...PromptRuntimeOptions, ) (PromptRecipeNoLate[TInput], error)
NewPromptRecipeNoLate builds a prompt recipe for prompts without late input.
func PromptRecipeNoLateFromCheckpoint ¶ added in v0.13.0
func PromptRecipeNoLateFromCheckpoint[TInput any]( cp PromptRecipeNoLateCheckpoint[TInput], ) (PromptRecipeNoLate[TInput], error)
PromptRecipeNoLateFromCheckpoint restores a no-late recipe from its checkpoint DTO.
func (PromptRecipeNoLate[TInput]) Checkpoint ¶ added in v0.13.0
func (r PromptRecipeNoLate[TInput]) Checkpoint() (PromptRecipeNoLateCheckpoint[TInput], error)
Checkpoint returns a JSON-safe checkpoint DTO.
func (PromptRecipeNoLate[TInput]) Execute ¶ added in v0.13.0
func (r PromptRecipeNoLate[TInput]) Execute( ctx context.Context, registry ManifestSnapshotRegistry, ) (*PromptExecution, error)
Execute verifies, rebuilds, and materializes a prompt execution.
func (PromptRecipeNoLate[TInput]) ExecuteWithContract ¶ added in v0.13.0
func (r PromptRecipeNoLate[TInput]) ExecuteWithContract( ctx context.Context, registry ManifestSnapshotRegistry, contract ToolManifestContract, ) (*PromptExecution, error)
ExecuteWithContract verifies, rebuilds, materializes, and checks required tools.
func (PromptRecipeNoLate[TInput]) Plan ¶ added in v0.13.0
func (r PromptRecipeNoLate[TInput]) Plan( ctx context.Context, registry ManifestSnapshotRegistry, ) (*RenderPlan, error)
Plan rebuilds the deferred render plan from stored early input.
func (PromptRecipeNoLate[TInput]) Verify ¶ added in v0.13.0
func (r PromptRecipeNoLate[TInput]) Verify( ctx context.Context, verifier ManifestDescriptorVerifier, ) error
Verify checks the stored descriptor against current registry state.
func (PromptRecipeNoLate[TInput]) WithComposeContext ¶ added in v0.13.0
func (r PromptRecipeNoLate[TInput]) WithComposeContext( ctx ComposeContext, ) (PromptRecipeNoLate[TInput], error)
WithComposeContext returns a copy of the recipe with typed compose context attached.
type PromptRecipeNoLateCheckpoint ¶ added in v0.13.0
type PromptRecipeNoLateCheckpoint[TInput any] struct { Descriptor ManifestDescriptor `json:"descriptor"` Input TInput `json:"input"` RuntimeOptions PromptRuntimeOptions `json:"runtime_options,omitzero"` }
PromptRecipeNoLateCheckpoint is a JSON-safe checkpoint DTO for prompts without late input.
func (*PromptRecipeNoLateCheckpoint[TInput]) UnmarshalJSON ¶ added in v0.13.0
func (cp *PromptRecipeNoLateCheckpoint[TInput]) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects unknown checkpoint/input fields.
type PromptRuntimeOptions ¶ added in v0.13.0
type PromptRuntimeOptions struct {
ComposeValues JSONDocument `json:"compose_values,omitempty"`
}
PromptRuntimeOptions stores compose-condition values for prompt materialization. It carries no session state, agent scheduling or persisted runtime ports.
func PromptRuntimeOptionsFromComposeContext ¶ added in v0.13.0
func PromptRuntimeOptionsFromComposeContext(ctx ComposeContext) (PromptRuntimeOptions, error)
PromptRuntimeOptionsFromComposeContext builds JSON-safe runtime options from a typed compose context.
func PromptRuntimeOptionsFromComposeValues ¶ added in v0.13.0
func PromptRuntimeOptionsFromComposeValues(values ComposeValues) (PromptRuntimeOptions, error)
PromptRuntimeOptionsFromComposeValues builds JSON-safe runtime options from typed compose values.
type ProviderEnvelope ¶ added in v0.15.0
type ProviderEnvelope struct {
Format string `json:"format"`
Scope ProfileIdentity `json:"scope"`
Codec string `json:"codec"`
Payload []byte `json:"payload"`
Required bool `json:"required"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
ProviderEnvelope carries provider-defined continuation bytes, not credentials. Codec and payload interpretation belong to the provider module. The host owns retention and account authorization; scope never grants access to an account.
type ProviderSchemaMapper ¶ added in v0.15.0
type ProviderSchemaMapper interface {
MapSchema(request SchemaMappingRequest) (SchemaMapping, error)
}
ProviderSchemaMapper is a trusted provider port, not a JSON Schema engine. It must report every semantic change and must not mutate or retain input aliases.
type ReasoningPart ¶ added in v0.2.0
type ReasoningPart struct {
Text string
CachePolicy *CachePolicy `json:"cache_policy,omitempty" yaml:"cache_policy,omitempty"`
}
ReasoningPart is provider-exposed reasoning content or a summary. It does not grant access to a model's hidden internal reasoning. Signed continuation state belongs to its provider-scoped envelope, not this text field.
type Registry ¶ added in v0.3.0
type Registry interface {
Plan(ctx context.Context, id string, input RegistryPlanInput) (*RenderPlan, error)
}
Registry returns a chat prompt template by id. id is a single identifier (e.g. "doctor", "doctor.prod"); environments are expressed via file layout.
type RegistryPlanInput ¶ added in v0.11.0
type RegistryPlanInput struct {
// contains filtered or unexported fields
}
RegistryPlanInput is an opaque token: payload already bound for template rendering.
func PlanInputFrom ¶ added in v0.11.1
func PlanInputFrom[T any](payload T) (RegistryPlanInput, error)
PlanInputFrom binds a typed payload for Registry.Plan (fail-fast before registry access).
func PlanInputWithComposeContext ¶ added in v0.13.0
func PlanInputWithComposeContext(in RegistryPlanInput, ctx ComposeContext) (RegistryPlanInput, error)
PlanInputWithComposeContext attaches runtime compose values from a typed compose context.
func (RegistryPlanInput) ComposeValues ¶ added in v0.13.0
func (r RegistryPlanInput) ComposeValues() ComposeValues
ComposeValues returns runtime compose values for declarative manifest composition. The zero value means unset; a set empty value enables strict condition evaluation.
type RemoteResponseHandle ¶ added in v0.15.0
type RemoteResponseHandle struct {
Format string `json:"format"`
Identity ProfileIdentity `json:"identity"`
AccountBinding string `json:"account_binding"`
ProviderID string `json:"provider_id"`
Status RemoteResponseStatus `json:"status"`
Background bool `json:"background"`
Store bool `json:"store"`
// ProviderStateRequired persists the retrieval guarantee, not provider data.
// It does not implicitly become a new Create's execution requirement.
ProviderStateRequired bool `json:"provider_state_required"`
OutputSchemaDigest string `json:"output_schema_digest,omitempty"`
HostedTools []string `json:"hosted_tools,omitempty"`
ToolSchemaDigests map[string]string `json:"tool_schema_digests,omitempty"`
ForcedTool string `json:"forced_tool,omitempty"`
ToolCalls map[string]string `json:"tool_calls,omitempty"`
}
RemoteResponseHandle carries observed remote identity, not credentials or a lease. AccountBinding is a host-owned reference, not authorization.
func CloneRemoteResponseHandle ¶ added in v0.15.0
func CloneRemoteResponseHandle(handle RemoteResponseHandle) RemoteResponseHandle
CloneRemoteResponseHandle isolates caller-owned extension collections.
func DecodeRemoteResponseHandle ¶ added in v0.15.0
func DecodeRemoteResponseHandle(document JSONDocument) (RemoteResponseHandle, error)
type RemoteResponseManager ¶ added in v0.15.0
type RemoteResponseManager interface {
Create(context.Context, RemoteResponseRequest) (*RemoteResponseResult, error)
Get(context.Context, RemoteResponseHandle, ...RemoteResponseOperationOptions) (*RemoteResponseResult, error)
Cancel(context.Context, RemoteResponseHandle, ...RemoteResponseOperationOptions) (*RemoteResponseResult, error)
}
type RemoteResponseOperationOptions ¶ added in v0.15.0
type RemoteResponseOperationOptions struct {
Capture CaptureRequirement
Binding *CaptureBinding `json:"-" yaml:"-"`
OutputSchema *SchemaDefinition
Validator SchemaValidator `json:"-" yaml:"-"`
Tools []ToolDefinition
}
RemoteResponseOperationOptions contains runtime ports and original output schema for checked retrieval. Host must rebind these after restoring a handle.
type RemoteResponseRequest ¶ added in v0.15.0
type RemoteResponseRequest struct {
Execution *PromptExecution
Previous *RemoteResponseHandle
Background bool
Store *bool
// StrictTools requires native strict enforcement for all local tools in this
// Create. It never permits schema lowering or enables hosted/local execution.
StrictTools bool
}
type RemoteResponseResult ¶ added in v0.15.0
type RemoteResponseResult struct {
Handle *RemoteResponseHandle `json:"handle,omitempty"`
Response *Response `json:"-"`
Diagnostics ExecutionDiagnostics `json:"diagnostics"`
}
RemoteResponseResult separates remote lifecycle from canonical model outcome. Response can contain partial output on failed/incomplete operations.
type RemoteResponseStatus ¶ added in v0.15.0
type RemoteResponseStatus string
const ( RemoteResponseQueued RemoteResponseStatus = "queued" RemoteResponseRunning RemoteResponseStatus = "in_progress" RemoteResponseCompleted RemoteResponseStatus = "completed" RemoteResponseFailed RemoteResponseStatus = "failed" RemoteResponseIncomplete RemoteResponseStatus = "incomplete" RemoteResponseCanceled RemoteResponseStatus = "canceled" RemoteResponseUnknown RemoteResponseStatus = "unknown" )
type RemoteResponseStream ¶ added in v0.15.0
type RemoteResponseStream interface {
// ObserveLifecycle attaches to the original lazy stream without consuming it.
ObserveLifecycle(StreamLifecycleObserver) error
Events() iter.Seq2[*ResponseChunk, error]
Close() error
Status() StreamStatus
RemoteResult() *RemoteResponseResult
}
RemoteResponseStream reuses the common single-use lazy Stream lifecycle while exposing separately observed remote identity. RemoteResult and Status return owned snapshots; callers persist a known handle explicitly. An IO failure or cancellation does not erase a previously observed handle and does not authorize automatic retries, polling or continuation.
type RemoteResponseStreamer ¶ added in v0.15.0
type RemoteResponseStreamer interface {
CreateStream(context.Context, RemoteResponseRequest) RemoteResponseStream
}
RemoteResponseStreamer is an optional native foreground-create port. Creating the handle performs no dispatch. Background create, Get and Cancel remain explicit operations of RemoteResponseManager.
type RenderPlan ¶ added in v0.9.0
type RenderPlan struct {
// contains filtered or unexported fields
}
RenderPlan is the deferred rendering contract for prompt execution.
func BindRuntime ¶ added in v0.14.0
func BindRuntime( ctx context.Context, registry ManifestSnapshotRegistry, checkpoint RuntimeRecipeCheckpoint, overlay RuntimeOverlay, scope ToolScope, ) (*RenderPlan, error)
BindRuntime verifies a checkpoint, applies runtime overlay/tool scope, and returns a materializable plan.
func NewRenderPlan ¶ added in v0.9.0
func NewRenderPlan(tpl *ChatPromptTemplate) *RenderPlan
NewRenderPlan builds a deferred render plan with no template input (.Input is empty). It panics for a nil template. Use NewRenderPlanFromPlanInput for a checked constructor.
func NewRenderPlanFromPlanInput ¶ added in v0.11.1
func NewRenderPlanFromPlanInput(tpl *ChatPromptTemplate, input RegistryPlanInput) (*RenderPlan, error)
NewRenderPlanFromPlanInput builds a render plan from a bound registry payload.
func NewRenderPlanFromStruct ¶ added in v0.11.0
func NewRenderPlanFromStruct[T any](tpl *ChatPromptTemplate, input T) (*RenderPlan, error)
NewRenderPlanFromStruct builds a render plan from a struct payload (template .Input fields).
func VerifiedManifestPlan ¶ added in v0.15.0
func VerifiedManifestPlan( ctx context.Context, registry ManifestSnapshotRegistry, desc ManifestDescriptor, input RegistryPlanInput, ) (*RenderPlan, error)
VerifiedManifestPlan captures, verifies, and plans one immutable generation.
func WithResponseFormatFromStruct ¶ added in v0.11.0
func WithResponseFormatFromStruct[T any](p *RenderPlan) (*RenderPlan, error)
WithResponseFormatFromStruct overrides response schema using reflection/schema provider on T.
func (*RenderPlan) Execute ¶ added in v0.9.0
func (p *RenderPlan) Execute(ctx context.Context) (*PromptExecution, error)
Execute materializes plan into PromptExecution using `.Input` and `.LateVars` template context.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/prompty"
)
func main() {
tpl, _ := prompty.NewChatPromptTemplate([]prompty.MessageTemplate{
{Role: prompty.RoleSystem, Content: prompty.TextContent("Hello, {{ .Input.name }}!")},
})
planInput, err := prompty.PlanInputFrom(struct {
Name string `prompt:"name"`
}{Name: "Alice"})
if err != nil {
panic(err)
}
plan, err := prompty.NewRenderPlanFromPlanInput(tpl, planInput)
if err != nil {
panic(err)
}
exec, err := plan.Execute(context.Background())
if err != nil {
panic(err)
}
text := exec.Messages[0].Content[0].(prompty.TextPart).Text
fmt.Println(text)
}
Output: Hello, Alice!
func (*RenderPlan) ExecuteAsText ¶ added in v0.11.0
ExecuteAsText renders the plan, invokes the model, and returns plain text (fail-closed).
func (*RenderPlan) ExecuteWithContract ¶ added in v0.13.0
func (p *RenderPlan) ExecuteWithContract( ctx context.Context, contract ToolManifestContract, ) (*PromptExecution, error)
ExecuteWithContract materializes the render plan and validates required tools before returning it.
func (*RenderPlan) ExecuteWithManifestContract ¶ added in v0.14.0
func (p *RenderPlan) ExecuteWithManifestContract( ctx context.Context, desc ManifestDescriptor, contract ToolManifestContract, ) (*PromptExecution, error)
ExecuteWithManifestContract materializes the render plan and validates required tools with descriptor context.
func (*RenderPlan) RenderText ¶ added in v0.14.0
func (p *RenderPlan) RenderText(ctx context.Context) (string, error)
RenderText materializes the plan and returns joined rendered text without invoking a model.
func (*RenderPlan) SourceDescriptor ¶ added in v0.15.0
func (p *RenderPlan) SourceDescriptor() (ManifestDescriptor, bool)
SourceDescriptor reports the captured source identity, or false for an unverified plan.
func (*RenderPlan) Template ¶ added in v0.9.0
func (p *RenderPlan) Template() *ChatPromptTemplate
Template returns a cloned underlying template for adapter registries.
func (*RenderPlan) ValidateRuntimeBindings ¶ added in v0.14.0
func (p *RenderPlan) ValidateRuntimeBindings() error
ValidateRuntimeBindings verifies runtime late bindings without invoking a model.
func (*RenderPlan) WithLateInput ¶ added in v0.12.0
func (p *RenderPlan) WithLateInput(input any) (*RenderPlan, error)
WithLateInput returns a copy of the plan with typed late variables bound from a struct (prompt tags).
func (*RenderPlan) WithLateInputJSON ¶ added in v0.14.0
func (p *RenderPlan) WithLateInputJSON(doc JSONDocument) (*RenderPlan, error)
WithLateInputJSON returns a copy of the plan with late variables bound from a JSON object.
func (*RenderPlan) WithResponseFormatDefinition ¶ added in v0.11.0
func (p *RenderPlan) WithResponseFormatDefinition(def *SchemaDefinition) (*RenderPlan, error)
WithResponseFormatDefinition overrides response schema at runtime.
func (*RenderPlan) WithToolScope ¶ added in v0.14.0
func (p *RenderPlan) WithToolScope(scope ToolScope) (*RenderPlan, error)
WithToolScope returns a copy of the plan with a runtime tool scope attached.
type RequirementCheck ¶ added in v0.15.0
type RequirementCheck struct {
Requirement string `json:"requirement"`
Status CapabilitySupport `json:"status"`
Reason string `json:"reason,omitempty"`
}
RequirementCheck explains one profile decision without prompt or credentials.
type ResolveManifestOption ¶ added in v0.12.0
type ResolveManifestOption func(*ResolveManifestOpts)
ResolveManifestOption configures ResolveManifest. Without options, composed manifests use a conservative view (union of all imports) suitable for codegen.
func WithResolveComposeContext ¶ added in v0.13.0
func WithResolveComposeContext(ctx ComposeContext) ResolveManifestOption
WithResolveComposeContext sets typed runtime compose context during descriptor expansion.
func WithResolveComposeValues ¶ added in v0.13.0
func WithResolveComposeValues(values ComposeValues) ResolveManifestOption
WithResolveComposeValues sets typed runtime values for condition.match during descriptor expansion. Passing an intentionally empty ComposeValues enables strict runtime compose evaluation.
type ResolveManifestOpts ¶ added in v0.12.0
type ResolveManifestOpts struct {
// contains filtered or unexported fields
}
ResolveManifestOpts configures manifest metadata resolution (e.g. runtime compose context).
func ApplyResolveManifestOptions ¶ added in v0.12.0
func ApplyResolveManifestOptions(opts []ResolveManifestOption) ResolveManifestOpts
ApplyResolveManifestOptions merges resolve options.
func (ResolveManifestOpts) ComposeValues ¶ added in v0.13.0
func (o ResolveManifestOpts) ComposeValues() (ComposeValues, bool)
ComposeValues returns typed runtime compose values and whether they were set.
type Response ¶ added in v0.5.0
type Response struct {
// Model is the provider-reported response model; empty means unobserved.
Model string `json:"model,omitempty"`
Content []ContentPart `json:"content"`
ProviderState []PartState `json:"-" yaml:"-"`
Annotations []PartAnnotation `json:"annotations,omitempty"`
MessageAnnotations []MessageAnnotation `json:"message_annotations,omitempty"`
Usage Usage `json:"usage"`
FinishReason string `json:"finish_reason,omitempty"` // provider stop reason for telemetry
Outcome Outcome `json:"outcome"`
Diagnostics ExecutionDiagnostics `json:"diagnostics"`
}
Response is the canonical full model response for sync calls.
func CloneResponse ¶ added in v0.15.0
CloneResponse returns an isolated response including opaque state and diagnostics.
func DecodeResponseJSON ¶ added in v0.15.0
func DecodeResponseJSON(document JSONDocument) (*Response, error)
DecodeResponseJSON validates the schema, format and semantic associations.
func NewResponse ¶ added in v0.5.0
func NewResponse(parts []ContentPart) *Response
NewResponse creates a Response from content parts. Usage remains zero.
func UnmarshalResponse ¶ added in v0.15.0
func UnmarshalResponse(wire ResponseWire) (*Response, error)
UnmarshalResponse rejects legacy/corrupt wire and validates state associations.
func (*Response) AssistantMessage ¶ added in v0.15.0
func (r *Response) AssistantMessage() (ChatMessage, error)
AssistantMessage projects an isolated response into history without losing state.
func (*Response) StrictText ¶ added in v0.11.0
StrictText returns concatenated text or fail-closed error when response contains non-text parts.
type ResponseChunk ¶ added in v0.5.0
type ResponseChunk struct {
// Model preserves an observed response model independently of request/profile.
Model string
// Identity references the handle's local message and logical content parts.
// Sources declare PartIDs aligned with Content and leave MessageID empty.
// On terminal events PartIDs instead aligns with Result.Content.
Identity StreamIdentity
Content []ContentPart
ProviderState []PartState `json:"-" yaml:"-"`
// StateUpdates explicitly replace opaque state for the same logical tool call.
// Indices refer to Content in this frame. Other content kinds are invalid.
StateUpdates []PartState `json:"-" yaml:"-"`
// Finalizations collapse already observed logical fragments without adding
// content. Sources must preserve their exact semantic value and finalize before
// emitting source-order metadata that contains canonical part indices.
Finalizations []StreamPartFinalization `json:"-" yaml:"-"`
Annotations []PartAnnotation
MessageAnnotations []MessageAnnotation
Usage Usage
Kind StreamEventKind
Outcome Outcome
Diagnostics ExecutionDiagnostics
FinishReason string // provider stop reason (e.g. "stop", "length") for telemetry
// Result is populated only on the single terminal event.
Result *Response
}
ResponseChunk is one chunk of the stream. In streaming providers Usage and FinishReason are typically populated only in the final chunk.
Example (StateUpdates) ¶
A provider source explicitly binds each opaque state snapshot to the current tool part. Payload interpretation/continuation validation stays in its adapter.
package main
import (
"context"
"fmt"
"iter"
"github.com/skosovsky/prompty"
)
func main() {
envelope := prompty.ProviderEnvelope{
Format: prompty.ProviderStateFormat,
Scope: prompty.ProfileIdentity{Provider: "fixture", Endpoint: "https://fixture.invalid", Model: "fixture"},
Codec: "fixture.function", Required: true,
}
stream := prompty.NewStream(context.Background(), prompty.StreamNative,
func(context.Context) iter.Seq2[*prompty.ResponseChunk, error] {
return func(yield func(*prompty.ResponseChunk, error) bool) {
for _, snapshot := range []struct{ args, state string }{
{"", "pending"}, {`{"n":1}`, "complete"},
} {
state := envelope
state.Payload = []byte(snapshot.state)
if !yield(&prompty.ResponseChunk{
Kind: prompty.StreamDelta,
Identity: prompty.StreamIdentity{PartIDs: []string{"tool:0"}},
Content: []prompty.ContentPart{
prompty.ToolCallPart{ID: "call", Name: "lookup", Args: snapshot.args},
},
StateUpdates: []prompty.PartState{{PartIndex: 0, Envelope: state}},
}, nil) {
return
}
}
yield(&prompty.ResponseChunk{Kind: prompty.StreamFinish, Outcome: prompty.OutcomeToolCalls}, nil)
}
})
defer stream.Close()
for _, err := range stream.Events() {
if err != nil {
fmt.Println(err)
return
}
}
status := stream.Status()
fmt.Println(status.State)
fmt.Println(status.Result.Content[0].(prompty.ToolCallPart).Args)
fmt.Println(string(status.Result.ProviderState[0].Envelope.Payload))
}
Output: completed {"n":1} complete
type ResponseFormatWire ¶ added in v0.14.0
type ResponseFormatWire struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Dialect string `json:"dialect,omitempty"`
Schema JSONDocument `json:"schema"`
}
ResponseFormatWire is the JSON-safe representation of SchemaDefinition.
type ResponseWire ¶ added in v0.15.0
type ResponseWire struct {
Model string `json:"model,omitempty"`
Format string `json:"format"`
Content []ContentPartWire `json:"content"`
ProviderState []PartState `json:"provider_state,omitempty"`
Annotations []PartAnnotation `json:"annotations,omitempty"`
MessageAnnotations []MessageAnnotation `json:"message_annotations,omitempty"`
Usage Usage `json:"usage"`
FinishReason string `json:"finish_reason,omitempty"`
Outcome Outcome `json:"outcome"`
Diagnostics ExecutionDiagnostics `json:"diagnostics"`
}
func LoggingResponse ¶ added in v0.15.0
func LoggingResponse(response *Response) (ResponseWire, error)
LoggingResponse excludes opaque state and marks unavailable continuation. Canonical prompt/media/annotations still require the caller's redaction policy.
func MarshalResponse ¶ added in v0.15.0
func MarshalResponse(response *Response, policy WirePolicy) (ResponseWire, error)
MarshalResponse requires explicit preservation/omission of provider state.
type Role ¶
type Role string
Role is the message role in a chat (system, developer, user, assistant, tool).
type RuntimeOverlay ¶ added in v0.14.0
type RuntimeOverlay struct {
LateInput JSONDocument `json:"late_input,omitempty"`
Values ComposeValues `json:"-"`
}
RuntimeOverlay carries request-local late/compose bindings over a checkpoint. It does not represent a session or conversation-context overlay.
type RuntimeRecipeCheckpoint ¶ added in v0.14.0
type RuntimeRecipeCheckpoint struct {
Descriptor ManifestDescriptor `json:"descriptor"`
Input JSONDocument `json:"input,omitempty"`
LateInput JSONDocument `json:"late_input,omitempty"`
State RuntimeRecipeState `json:"state"`
RuntimeOptions PromptRuntimeOptions `json:"runtime_options,omitzero"`
}
RuntimeRecipeCheckpoint is a JSON-safe prompt-materialization checkpoint. Its raw input/late-input surface is distinct from generic typed recipes; it is not an agent-run/session checkpoint and carries no runtime ports.
type RuntimeRecipeState ¶ added in v0.14.0
type RuntimeRecipeState string
RuntimeRecipeState describes whether a raw runtime checkpoint carries late input.
const ( RuntimeRecipeStateNoLate RuntimeRecipeState = "no_late" RuntimeRecipeStateLateUnbound RuntimeRecipeState = "late_unbound" RuntimeRecipeStateLateBound RuntimeRecipeState = "late_bound" )
type SchemaCompilationError ¶ added in v0.15.0
type SchemaCompilationError struct {
Locations []SchemaSourceLocation
Cause error
}
SchemaCompilationError preserves the original compiler cause and known positions. Empty Locations means the compiler did not expose an authoritative source position. Error does not print schema values; Cause may contain caller data and needs host policy.
func (*SchemaCompilationError) Error ¶ added in v0.15.0
func (*SchemaCompilationError) Error() string
func (*SchemaCompilationError) Unwrap ¶ added in v0.15.0
func (e *SchemaCompilationError) Unwrap() error
type SchemaCompilationReport ¶ added in v0.15.0
type SchemaCompilationReport struct {
Profile ProfileIdentity `json:"profile"`
Role SchemaRole `json:"role"`
Name string `json:"name,omitempty"`
Dialect string `json:"dialect"`
Guarantee SchemaMode `json:"guarantee"`
SourceDigest string `json:"source_digest"`
TranslatedDigest string `json:"translated_digest"`
Transformations []SchemaTransformation `json:"transformations,omitempty"`
}
SchemaCompilationReport binds exact-byte SHA-256 digests to profile and role. Lowering never claims lossless provider constraints; original validation is required.
type SchemaCompileRequest ¶ added in v0.15.0
type SchemaCompileRequest struct {
Source JSONDocument
Dialect string
Role SchemaRole
Name string
Profile ProfileIdentity
Policy SchemaPolicy
Validator SchemaValidator
}
SchemaCompileRequest binds source-schema compilation to one destination and role. Validator is runtime-only and must not load implicit external references.
type SchemaDefinition ¶ added in v0.2.0
type SchemaDefinition struct {
Name string `json:"name,omitempty" yaml:"name,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
Dialect string `json:"dialect,omitempty" yaml:"dialect,omitempty"` // Empty selects SchemaDialect2020.
Schema JSONDocument `json:"schema" yaml:"schema"` // JSON Schema
}
SchemaDefinition describes a structured output (JSON Schema) for response format.
func ResponseFormatFromStruct ¶ added in v0.14.0
func ResponseFormatFromStruct[T any]() (*SchemaDefinition, error)
ResponseFormatFromStruct returns a response format schema for T.
type SchemaFidelityError ¶ added in v0.15.0
SchemaFidelityError identifies a source-schema construct that a provider mapper cannot preserve. Pointer is an RFC 6901 JSON pointer; the empty string is the root. It contains no schema values or request data and unwraps to ErrSchemaUnsupported.
func (*SchemaFidelityError) Error ¶ added in v0.15.0
func (e *SchemaFidelityError) Error() string
func (*SchemaFidelityError) Unwrap ¶ added in v0.15.0
func (*SchemaFidelityError) Unwrap() error
type SchemaMapping ¶ added in v0.15.0
type SchemaMapping struct {
Schema JSONDocument
Transformations []SchemaTransformation
}
SchemaMapping is an adapter's canonical translated schema and change ledger. SDK-specific shape conversion follows compilation in the adapter module.
type SchemaMappingRequest ¶ added in v0.15.0
type SchemaMappingRequest struct {
Source JSONDocument
Dialect string
Role SchemaRole
Profile ProfileIdentity
Policy SchemaPolicy
}
SchemaMappingRequest is isolated from caller-owned source and policy slices.
type SchemaMode ¶ added in v0.15.0
type SchemaMode string
SchemaMode selects fidelity, never provider availability or model routing.
const ( SchemaStrict SchemaMode = "strict" SchemaLowering SchemaMode = "lowering" )
type SchemaPolicy ¶ added in v0.15.0
type SchemaPolicy struct {
Mode SchemaMode `json:"mode,omitempty"`
AllowedTransforms []string `json:"allowed_transforms,omitempty"`
}
SchemaPolicy permits only named transformations. Its zero value is strict.
type SchemaProvider ¶ added in v0.5.6
type SchemaProvider interface {
JSONSchema() JSONDocument
}
SchemaProvider allows caller-owned types to provide a JSON Schema without reflection.
type SchemaRole ¶ added in v0.15.0
type SchemaRole string
SchemaRole identifies the canonical schema's use.
const ( SchemaOutput SchemaRole = "output" SchemaToolInput SchemaRole = "tool_input" )
type SchemaSourceLocation ¶ added in v0.15.0
SchemaSourceLocation identifies a position in a schema input document. Resource is empty for the supplied source, otherwise the explicit resource URI. Pointer is RFC 6901; empty denotes the document root, not an unknown position.
type SchemaTransformation ¶ added in v0.15.0
type SchemaTransformation struct {
ID string `json:"id"`
Pointer string `json:"pointer"`
Reason string `json:"reason"`
}
SchemaTransformation describes a semantic change without schema values. Pointer is an RFC 6901 source location; empty means the root.
type SchemaValidator ¶ added in v0.15.0
type SchemaValidator interface {
CompileSchema(source JSONDocument, dialect string) (ValueValidator, error)
}
SchemaValidator is an application-injectable schema compiler, separate from domain Validate. Implementations must not fetch external references without explicit caller policy. Source documents are read-only; compilation must not mutate their constraints. Successful compilation promises enforcement of the selected schema contract. Return an error rather than silently ignoring unsupported validation constraints, and never return a nil ValueValidator with a nil error.
type SnapshotMaterializer ¶ added in v0.15.0
type SnapshotMaterializer func(context.Context, SourceBundle, RegistryPlanInput) (*ChatPromptTemplate, error)
SnapshotMaterializer must build exclusively from the supplied captured sources. It must not read mutable source storage again. Runtime Go functions remain host-owned.
type SourceBundle ¶ added in v0.15.0
type SourceBundle struct {
Sources map[string][]byte `json:"sources"`
Config map[string]string `json:"config"`
}
SourceBundle contains captured sources and declarative resolution settings. Sources are opaque named bytes; the host owns their interpretation and trust.
type StateProjection ¶ added in v0.15.0
type StateProjection string
const ( StatePreserve StateProjection = "preserve" StateOmit StateProjection = "omit" )
type Statter ¶ added in v0.4.0
type Statter interface {
Stat(ctx context.Context, id string) (TemplateInfo, error)
}
Statter is optional. When implemented by a registry, Stat returns template metadata without parsing the body.
type Stream ¶ added in v0.15.0
type Stream struct {
// contains filtered or unexported fields
}
Stream owns a lazy, single-use source and its cancellation context. It creates no producer goroutine. Sources must honor context cancellation and release transport resources when yield returns false.
func ErrorStream ¶ added in v0.15.0
func ErrorStream(ctx context.Context, mode StreamMode, err error) *Stream
ErrorStream reports a pre-dispatch failure when consumed.
func NewStream ¶ added in v0.15.0
func NewStream( ctx context.Context, mode StreamMode, source func(context.Context) iter.Seq2[*ResponseChunk, error], options ...StreamOption, ) *Stream
NewStream constructs a lazy lifecycle handle. Creating a handle does not dispatch. The source emits data/control events and a finish marker, not a terminal event.
func (*Stream) Close ¶ added in v0.15.0
Close requests cancellation without waiting. A created handle becomes canceled immediately; a running iterator publishes final status after unwind/closeout. It is safe to call concurrently and repeatedly, including from a callback.
func (*Stream) Events ¶ added in v0.15.0
func (s *Stream) Events() iter.Seq2[*ResponseChunk, error]
Events starts dispatch on first consumption and yields exactly one terminal event unless the consumer stops. In that case Status retains the canceled outcome.
func (*Stream) ObserveLifecycle ¶ added in v0.15.0
func (s *Stream) ObserveLifecycle(observer StreamLifecycleObserver) error
ObserveLifecycle attaches middleware to this handle without replaying or reassembling its events. Attachment is permitted only before consumption.
func (*Stream) Status ¶ added in v0.15.0
func (s *Stream) Status() StreamStatus
Status returns an isolated partial/final result. Terminal state is immutable.
type StreamCaptureObserver ¶ added in v0.15.0
type StreamCaptureObserver func(context.Context, StreamStatus, error) (*CaptureReport, error)
StreamCaptureObserver records final/failed snapshots without changing content. It runs outside the status mutex and must honor invocation cancellation.
type StreamEventKind ¶ added in v0.15.0
type StreamEventKind string
StreamEventKind distinguishes content/control markers from lifecycle completion.
const ( StreamStart StreamEventKind = "start" StreamDelta StreamEventKind = "delta" StreamUsage StreamEventKind = "usage" StreamFinish StreamEventKind = "finish" StreamTerminal StreamEventKind = "terminal" )
type StreamFinalizer ¶ added in v0.15.0
StreamFinalizer validates a cloned assembled result after source EOF and trailing usage, before terminal success. It must honor cancellation and must not retry.
type StreamFrameObserver ¶ added in v0.15.0
type StreamFrameObserver func(context.Context, *ResponseChunk) error
StreamFrameObserver observes an isolated accepted frame with canonical identity. An observation failure retains and yields the frame before failing the stream. It must honor cancellation; it runs without the status mutex.
type StreamIdentity ¶ added in v0.15.0
type StreamIdentity struct {
MessageID string `json:"message_id"`
PartIDs []string `json:"part_ids,omitempty"`
}
StreamIdentity is local logical correlation, not a provider or physical-attempt ID. PartIDs aligns with frame Content, or with retained Result.Content in status/terminal. Repeated IDs across frames refer to the same logical part. Text/reasoning fragments stay distinct until the source explicitly finalizes their logical part.
type StreamLifecycleObserver ¶ added in v0.15.0
type StreamLifecycleObserver func(context.Context) (context.Context, func(StreamStatus))
StreamLifecycleObserver starts lazy observation and returns a context with added values and a closeout callback. It must retain the same Done channel. Closeout sees an isolated final/canceled status without the status mutex held.
type StreamMode ¶ added in v0.15.0
type StreamMode string
StreamMode is chosen explicitly; native never falls back to a buffered call.
const ( StreamNative StreamMode = "native" StreamBuffered StreamMode = "buffered" )
type StreamOption ¶ added in v0.15.0
type StreamOption func(*Stream)
StreamOption configures a handle before consumption.
func WithStreamCaptureObserver ¶ added in v0.15.0
func WithStreamCaptureObserver(observer StreamCaptureObserver) StreamOption
WithStreamCaptureObserver installs optional observation before terminal delivery.
func WithStreamFinalizer ¶ added in v0.15.0
func WithStreamFinalizer(finalizer StreamFinalizer) StreamOption
WithStreamFinalizer installs a final validation port. It never runs after partial transport/protocol failure or consumer cancellation, and does not mutate the result.
func WithStreamFrameObserver ¶ added in v0.15.0
func WithStreamFrameObserver(observer StreamFrameObserver) StreamOption
WithStreamFrameObserver binds optional canonical frame observation before consumption.
type StreamPartFinalization ¶ added in v0.15.0
type StreamPartFinalization struct {
PartID string
Content ContentPart
ProviderState *ProviderEnvelope
Annotations []PartAnnotation
}
StreamPartFinalization closes a previously observed logical part. Content must exactly match its accumulated text/reasoning or assembled tool arguments. ProviderState binds the complete Content; annotations refer to local index 0. It grants no continuation across transport failure and executes no handler.
type StreamState ¶ added in v0.15.0
type StreamState string
StreamState is the observed lifecycle of a single consumption.
const ( StreamCreated StreamState = "created" StreamRunning StreamState = "streaming" StreamCompleted StreamState = "completed" StreamFailed StreamState = "failed" StreamCanceled StreamState = "canceled" )
type StreamStatus ¶ added in v0.15.0
type StreamStatus struct {
StopReason StreamStopReason
Identity StreamIdentity
State StreamState
Mode StreamMode
Result *Response
Err error
}
StreamStatus remains readable after early termination. Result is a cloned snapshot.
type StreamStopReason ¶ added in v0.15.0
type StreamStopReason string
StreamStopReason records the observed cause of local stream interruption.
const ( StreamStopConsumer StreamStopReason = "consumer_stop" StreamStopClosed StreamStopReason = "closed" StreamStopCanceled StreamStopReason = "canceled" )
type StructuredOutputContract ¶ added in v0.14.0
type StructuredOutputContract interface {
ResponseFormat() (*SchemaDefinition, error)
JSONSchema() (JSONDocument, error)
}
StructuredOutputContract exposes a prompt output schema without rendering a fake prompt.
func NewStructuredOutputContract ¶ added in v0.14.0
func NewStructuredOutputContract(format *SchemaDefinition) StructuredOutputContract
NewStructuredOutputContract returns a static structured output contract.
type StructuredOutputMode ¶ added in v0.15.0
type StructuredOutputMode string
StructuredOutputMode selects output transport, independently of schema fidelity. Synthetic output validates a received result; it is not constrained decoding.
const ( OutputNative StructuredOutputMode = "native" OutputSyntheticTool StructuredOutputMode = "synthetic_tool" )
type StructuredStreamOptions ¶ added in v0.15.0
type StructuredStreamOptions struct {
MaxObjectBytes int
}
StructuredStreamOptions sets an invocation-local positive JSON object limit. It does not bound whole-document or upstream transport/SDK allocation.
type TemplateDescriptor ¶ added in v0.10.0
type TemplateDescriptor struct {
Metadata PromptMetadata
ModelOptions *ModelOptions
Tools []ToolDefinition
RequiredTools []string
RequiredInputVars []string
InputSchema *SchemaDefinition
ResponseFormat *SchemaDefinition
LayerIDs []string
Capabilities []string
Tags []string
}
TemplateDescriptor is manifest metadata without template compilation or input binding.
type TemplateInfo ¶ added in v0.3.0
TemplateInfo holds metadata about a template without parsing its body.
type TemplatePart ¶ added in v0.4.5
type TemplatePart struct {
Type string // "text" or "media"
Text string // Go text/template for type "text"
MediaType string // Go text/template for type "media" (for example: image, audio, video, document)
MIMEType string // Optional Go text/template for type "media" (for example: image/png)
URL string // Optional Go text/template for type "media"
CachePolicy *CachePolicy `json:"cache_policy,omitempty" yaml:"cache_policy,omitempty"`
}
TemplatePart is one part of a message template (text or media). Type determines which field set is the template source.
func TextContent ¶ added in v0.4.5
func TextContent(text string) []TemplatePart
TextContent returns a single text TemplatePart slice for convenience.
type TextPart ¶
type TextPart struct {
Text string
CachePolicy *CachePolicy `json:"cache_policy,omitempty" yaml:"cache_policy,omitempty"`
}
TextPart holds plain text content.
type TokenCounter ¶
type TokenCounter interface {
Count(text string) (int, error)
CountMessage(msg ChatMessage) (int, error)
}
TokenCounter estimates token count for text and canonical chat messages. Callers can plug in an exact tokenizer (e.g. tiktoken); default is CharFallbackCounter.
type ToolCallError ¶ added in v0.6.0
type ToolCallError struct {
// Response retains the known model result when batch validation fails.
Response *Response
RawAssistantMessage *ChatMessage
ToolResults []ContentPart
Err error
}
ToolCallError is returned when model-generated tool arguments fail validation.
func (*ToolCallError) Error ¶ added in v0.6.0
func (e *ToolCallError) Error() string
Error implements error.
type ToolCallPart ¶
type ToolCallPart struct {
ID string // Empty for models that do not support ID (e.g. base Gemini)
Name string
Args string // Full JSON string of arguments (non-stream response)
ArgsChunk string // Chunk of JSON arguments (streaming); client glues chunks
CachePolicy *CachePolicy `json:"cache_policy,omitempty" yaml:"cache_policy,omitempty"`
}
ToolCallPart represents an AI request to call a function (in assistant message). In streaming: ArgsChunk holds incremental JSON; Args is set in non-stream ParseResponse.
func AdmitToolCalls ¶ added in v0.16.0
func AdmitToolCalls( ctx context.Context, exec *PromptExecution, response *Response, validator ToolValidator, ) ([]ToolCallPart, error)
AdmitToolCalls validates an entire response batch without provider dispatch or handler invocation. It returns owned complete calls, or no calls on error. The execution's original schemas and scope remain the admission boundary. The validator must be pure; authorization and lifecycle policy belong to caller. Inputs may not be mutated concurrently. See docs/host-tool-dispatch.md.
type ToolContractError ¶ added in v0.14.0
type ToolContractError struct {
Descriptor ManifestDescriptor
ToolName string
Reason string
Err error
}
ToolContractError carries audit-friendly context for tool contract failures.
func (*ToolContractError) Error ¶ added in v0.14.0
func (e *ToolContractError) Error() string
func (*ToolContractError) Unwrap ¶ added in v0.14.0
func (e *ToolContractError) Unwrap() error
type ToolDefinition ¶
type ToolDefinition struct {
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Dialect string `json:"dialect,omitempty" yaml:"dialect,omitempty"` // Empty selects SchemaDialect2020.
Parameters JSONDocument `json:"parameters,omitempty" yaml:"parameters,omitempty"` // JSON Schema for parameters
Capabilities []string `json:"capabilities,omitempty" yaml:"capabilities,omitempty"`
}
ToolDefinition is the universal tool schema. JSON tags are required for template functions (e.g. render_tools_as_json) that marshal tools.
type ToolDispatchError ¶ added in v0.15.0
ToolDispatchError retains a known model response that was not accepted for tool execution. The host owns reconciliation and retry policy.
func (*ToolDispatchError) Error ¶ added in v0.15.0
func (e *ToolDispatchError) Error() string
func (*ToolDispatchError) Unwrap ¶ added in v0.15.0
func (e *ToolDispatchError) Unwrap() error
type ToolInvoker ¶ added in v0.11.0
type ToolInvoker interface {
ToolValidator
InvokeTool(ctx context.Context, name string, argsJSON string) (json.RawMessage, error)
}
ToolInvoker is a JSON-only one-shot handler port. It does not receive call IDs or interpret lifecycle controls; use a full Response for host-owned dispatch.
Example ¶
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
)
type exampleLookupArgs struct {
Name string `json:"name"`
}
// An application (or toolsy integration) supplies this port. It need not use
// TypedToolRegistry, and owns authorization, scheduling and downstream effects.
type exampleCallerToolPort struct{}
func (exampleCallerToolPort) ValidateToolCall(name, argsJSON string) error {
if name != "lookup" {
return errors.New("unknown caller tool")
}
args, err := DecodeToolArgs[exampleLookupArgs](argsJSON)
if err != nil {
return err
}
if args.Name == "" {
return errors.New("lookup name is required")
}
return nil
}
func (port exampleCallerToolPort) InvokeTool(ctx context.Context, name, argsJSON string) (json.RawMessage, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if err := port.ValidateToolCall(name, argsJSON); err != nil {
return nil, err
}
args, err := DecodeToolArgs[exampleLookupArgs](argsJSON)
if err != nil {
return nil, err
}
// Substitute the caller-owned context-aware service operation here.
return json.Marshal(map[string]string{"found": args.Name})
}
func main() {
var tools ToolInvoker = exampleCallerToolPort{}
// ExecuteWithTypedTools accepts this same port after original-schema/scope
// whole-batch preflight. This local example exercises only the caller port.
result, err := tools.InvokeTool(context.Background(), "lookup", `{"name":"known"}`)
if err != nil {
panic(err)
}
fmt.Println(string(result))
}
Output: {"found":"known"}
type ToolManifest ¶ added in v0.14.0
type ToolManifest struct {
Name string `json:"name"`
Dialect string `json:"dialect,omitempty"`
Description string `json:"description,omitempty"`
Parameters JSONDocument `json:"parameters,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
}
ToolManifest is the runtime tool contract visible to prompt materialization.
func ToolManifestFromDefinition ¶ added in v0.14.0
func ToolManifestFromDefinition(def ToolDefinition) ToolManifest
ToolManifestFromDefinition converts a prompt tool definition into a manifest contract.
type ToolManifestContract ¶ added in v0.14.0
type ToolManifestContract interface {
ToolManifest(name string) (ToolManifest, bool)
}
ToolManifestContract exposes full runtime tool manifests for fail-closed prompt validation.
type ToolManifestContractFunc ¶ added in v0.14.0
type ToolManifestContractFunc func(name string) (ToolManifest, bool)
ToolManifestContractFunc adapts a function to ToolManifestContract.
func (ToolManifestContractFunc) ToolManifest ¶ added in v0.14.0
func (f ToolManifestContractFunc) ToolManifest(name string) (ToolManifest, bool)
ToolManifest implements ToolManifestContract.
type ToolRequirement ¶ added in v0.14.0
type ToolRequirement struct {
Name string `json:"name"`
Dialect string `json:"dialect,omitempty"`
Parameters JSONDocument `json:"parameters,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
}
ToolRequirement describes a tool that must be available in a runtime scope.
type ToolResultPart ¶
type ToolResultPart struct {
ToolCallID string
Name string
Content []ContentPart
IsError bool
CachePolicy *CachePolicy `json:"cache_policy,omitempty" yaml:"cache_policy,omitempty"`
}
ToolResultPart is the result of a tool call (in message with Role "tool"). Content is a slice of multimodal parts (text, images, etc.).
type ToolScope ¶ added in v0.14.0
type ToolScope struct {
Required []ToolRequirement `json:"required"`
Allowed []ToolManifest `json:"allowed"`
}
ToolScope is the runtime allowed/required tool boundary for a prompt execution.
type ToolScopeError ¶ added in v0.15.0
ToolScopeError describes an execution-scoped contract violation, not an authorization decision.
func (*ToolScopeError) Error ¶ added in v0.15.0
func (e *ToolScopeError) Error() string
func (*ToolScopeError) Unwrap ¶ added in v0.15.0
func (*ToolScopeError) Unwrap() error
type ToolValidator ¶ added in v0.5.6
ToolValidator validates a tool call without coupling prompty to a concrete tool registry.
type ToolWire ¶ added in v0.14.0
type ToolWire struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Dialect string `json:"dialect,omitempty"`
Parameters JSONDocument `json:"parameters,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
}
ToolWire is the JSON-safe representation of ToolDefinition.
type TypedTool ¶ added in v0.11.0
TypedTool binds a handler to JSON Schema derived from TArgs.
func NewTypedTool ¶ added in v0.11.0
func NewTypedTool[TArgs any, TResult any]( name string, handler func(context.Context, TArgs) (TResult, error), ) (*TypedTool[TArgs, TResult], error)
NewTypedTool registers a tool with schema inferred from TArgs.
func (*TypedTool[TArgs, TResult]) Definition ¶ added in v0.11.0
func (t *TypedTool[TArgs, TResult]) Definition() ToolDefinition
Definition returns the tool definition for PromptExecution.
func (*TypedTool[TArgs, TResult]) Invoke ¶ added in v0.11.0
Invoke decodes args and runs the handler (fail-closed on unknown JSON fields).
func (*TypedTool[TArgs, TResult]) Name ¶ added in v0.11.0
Name returns the tool name exposed to the model.
func (*TypedTool[TArgs, TResult]) ValidateArgs ¶ added in v0.11.0
ValidateArgs parses tool call JSON into TArgs without invoking the handler.
type TypedToolRegistry ¶ added in v0.11.0
type TypedToolRegistry struct {
// contains filtered or unexported fields
}
TypedToolRegistry validates and dispatches tool calls for registered typed tools. Complete registration before concurrent invocation; calls do not retain contexts.
func NewTypedToolRegistry ¶ added in v0.11.0
func NewTypedToolRegistry() *TypedToolRegistry
NewTypedToolRegistry creates an empty registry.
func (*TypedToolRegistry) Definitions ¶ added in v0.11.0
func (r *TypedToolRegistry) Definitions() []ToolDefinition
Definitions returns tool definitions for all registered tools.
func (*TypedToolRegistry) InvokeTool ¶ added in v0.11.0
func (r *TypedToolRegistry) InvokeTool(ctx context.Context, name string, argsJSON string) (json.RawMessage, error)
InvokeTool decodes args and executes the registered handler.
func (*TypedToolRegistry) ValidateToolCall ¶ added in v0.11.0
func (r *TypedToolRegistry) ValidateToolCall(name string, argsJSON string) error
ValidateToolCall implements ToolValidator with strict JSON decoding (no handler execution).
type Usage ¶ added in v0.5.0
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
PromptTokensCached int `json:"cache_read_tokens"`
PromptTokensCacheCreation int `json:"cache_write_tokens"`
CompletionTokensReasoning int `json:"reasoning_tokens"`
// Known lists available counters, including known zero. An adapter may derive
// total only from fully known inputs under its documented provider semantics.
Known []UsageCounter `json:"known,omitempty"`
// Mode distinguishes cumulative snapshots from increments.
Mode UsageMode `json:"mode,omitempty"`
}
Usage contains token statistics for the model response.
func (Usage) Availability ¶ added in v0.15.0
func (u Usage) Availability() UsageAvailability
Availability never infers known zero from default scalar values.
type UsageAvailability ¶ added in v0.15.0
type UsageAvailability string
UsageAvailability describes presence of the primary prompt/completion/total counters; optional cache/reasoning breakdowns retain independent presence.
const ( UsageUnknown UsageAvailability = "unknown" UsagePartial UsageAvailability = "partial" UsageKnown UsageAvailability = "known" )
type UsageCounter ¶ added in v0.15.0
type UsageCounter string
UsageCounter identifies one independently known token counter.
const ( UsagePrompt UsageCounter = "prompt" UsageCompletion UsageCounter = "completion" UsageTotal UsageCounter = "total" UsageCacheRead UsageCounter = "cache_read" UsageCacheWrite UsageCounter = "cache_write" UsageReasoning UsageCounter = "reasoning" )
type UsageMode ¶ added in v0.15.0
type UsageMode string
UsageMode declares how an update combines with earlier counters.
type Validatable ¶ added in v0.5.6
type Validatable interface {
Validate() error
}
Validatable allows caller-owned types to enforce post-unmarshal business rules.
type ValidationError ¶ added in v0.6.0
type ValidationError struct {
RawAssistantMessage *ChatMessage
FeedbackPrompt string
Err error
}
ValidationError is returned when model output is invalid JSON or violates semantic validation.
func (*ValidationError) Error ¶ added in v0.6.0
func (e *ValidationError) Error() string
Error implements error.
type ValueValidator ¶ added in v0.15.0
type ValueValidator interface {
ValidateJSON(value JSONDocument) error
}
ValueValidator validates a complete JSON document against an already compiled schema.
type VariableError ¶
VariableError wraps a sentinel error with variable and template context. Use errors.Is(err, ErrMissingVariable) and errors.As(err, &variableErr) to inspect.
type WirePolicy ¶ added in v0.15.0
type WirePolicy struct{ State StateProjection }
WirePolicy requires an explicit host choice about opaque-state persistence. Omit is safe for logging state, but is not a secrets filter for prompt/media.
Source Files
¶
- batch.go
- batch_files.go
- binding.go
- cache.go
- cache_resource.go
- capabilities.go
- capability_profile.go
- capture.go
- capture_metadata.go
- capture_report.go
- client.go
- clone.go
- convenience.go
- doc.go
- endpoint_identity.go
- errors.go
- execution_tool_scope.go
- executor.go
- funcmap.go
- hosted_tools.go
- jsondoc.go
- jsondoc_test_helpers.go
- late_validation.go
- manifest_descriptor.go
- manifest_snapshot.go
- middleware.go
- option.go
- output_mode.go
- payload.go
- plan_input.go
- prompty.go
- provider_state.go
- recipe.go
- remote_response.go
- render_plan.go
- response.go
- response_wire.go
- runtime.go
- schema.go
- schema_compilation_error.go
- schema_compile.go
- schema_fidelity.go
- schema_reference_observation.go
- schema_reference_origin.go
- schema_reference_probe.go
- schema_reference_work.go
- schema_reflect.go
- schema_validation.go
- schema_value.go
- stream.go
- stream_finalization.go
- stream_identity.go
- stream_state_update.go
- stream_structured_output.go
- structured_output.go
- structured_output_contract.go
- template.go
- template_binder.go
- text_output.go
- token.go
- tool_admission.go
- tool_args.go
- tool_binding.go
- tool_contract.go
- tool_orchestration.go
- tool_validation.go
- usage.go
- wire.go
- wire_schema.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package adapter binds caller-owned executions to provider SDK request/response types.
|
Package adapter binds caller-owned executions to provider SDK request/response types. |
|
anthropic
module
|
|
|
gemini
module
|
|
|
ollama
module
|
|
|
openai
module
|
|
|
cmd
|
|
|
prompty-gen
module
|
|
|
Package embedregistry provides an embed.FS-based prompt registry that loads all YAML manifests at construction (eager).
|
Package embedregistry provides an embed.FS-based prompt registry that loads all YAML manifests at construction (eager). |
|
examples
|
|
|
context_budget
command
This offline example uses a local invoker; it makes no provider request.
|
This offline example uses a local invoker; it makes no provider request. |
|
ext
|
|
|
truncate
Package truncate provides deterministic, remove-only execution budgeting.
|
Package truncate provides deterministic, remove-only execution budgeting. |
|
Package fileregistry provides a filesystem-based prompt registry that loads YAML manifests on demand (lazy) and caches them.
|
Package fileregistry provides a filesystem-based prompt registry that loads YAML manifests on demand (lazy) and caches them. |
|
internal
|
|
|
cast
Package cast provides type conversion helpers for map[string]any and similar generic data.
|
Package cast provides type conversion helpers for map[string]any and similar generic data. |
|
compiled
Package compiled holds adapter-internal immutable prompt snapshots (not application state).
|
Package compiled holds adapter-internal immutable prompt snapshots (not application state). |
|
exactjson
Package exactjson compares JSON values without rounding decimal numbers.
|
Package exactjson compares JSON values without rounding decimal numbers. |
|
jsonfield
Package jsonfield defines the encoding/json field-name subset shared by schema inference and generated DTOs.
|
Package jsonfield defines the encoding/json field-name subset shared by schema inference and generated DTOs. |
|
operationtest
Package operationtest supplies deterministic SDK fault-injection transport fixtures.
|
Package operationtest supplies deterministic SDK fault-injection transport fixtures. |
|
streamtest
Package streamtest provides local protocol harnesses for adapter conformance tests.
|
Package streamtest provides local protocol harnesses for adapter conformance tests. |
|
Package manifest parses YAML/JSON prompt manifests into prompty.ChatPromptTemplate.
|
Package manifest parses YAML/JSON prompt manifests into prompty.ChatPromptTemplate. |
|
Package mediafetch downloads HTTPS image bodies with a size limit for inline adapters.
|
Package mediafetch downloads HTTPS image bodies with a size limit for inline adapters. |
|
middleware
|
|
|
contextx
Package contextx applies deterministic execution budgets before upstream IO.
|
Package contextx applies deterministic execution budgets before upstream IO. |
|
parser
|
|
|
yaml
Package yaml implements manifest.Unmarshaler for YAML manifests.
|
Package yaml implements manifest.Unmarshaler for YAML manifests. |
|
Package remoteregistry provides remote template loading via Fetcher (HTTP or Git).
|
Package remoteregistry provides remote template loading via Fetcher (HTTP or Git). |
|
git
module
|