prompty

package module
v0.17.3 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 36 Imported by: 9 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

prompty

Go Reference

TL;DR — prompty is a library for prompt management, templating, and unified interaction with LLMs in Go. It supports loading prompts from files, Git, or HTTP and works with multiple backends (OpenAI, Anthropic, Gemini, Ollama) without locking you to a single vendor.

Current guarantees and ownership rules are indexed in Current contracts.

Modules and installation

The project is split into multiple Go modules. Install only what you need:

Layer Package Install
Core prompty (templates, registries in-tree) go get github.com/skosovsky/prompty
Adapters OpenAI go get github.com/skosovsky/prompty/adapter/openai
Gemini go get github.com/skosovsky/prompty/adapter/gemini
Anthropic go get github.com/skosovsky/prompty/adapter/anthropic
Ollama go get github.com/skosovsky/prompty/adapter/ollama
Registries Git (remote) go get github.com/skosovsky/prompty/remoteregistry/git

fileregistry and embedregistry are part of the core module (github.com/skosovsky/prompty).

Full caller-owned dispatch and pure batch admission are documented in Host tool dispatch, with an optional executable recipe.

Tool scope, cancellation, partial results and the breaking handler/wire API are documented in Tool execution contract.

Deterministic context budgeting, protected turns/exchanges and the breaking extension API are documented in Execution budgeting and budget middleware.

Quick Start

Start with your own input type, a template and the checked adapter client. No generated package or manifest is required. The complete example is tested with a local SDK HTTP fixture; running it against a provider requires your key and chosen model.

Requires Go 1.27.1 or newer.

OPENAI_MODEL=<host-selected-model> OPENAI_API_KEY=<key> go run ./examples/basic_chat/direct
// Direct BYOT example. No manifest or generator is required.
// Run: OPENAI_MODEL=<host-selected-model> OPENAI_API_KEY=<key> go run ./examples/basic_chat/direct
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	openaisdk "github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"

	"github.com/skosovsky/prompty"
	"github.com/skosovsky/prompty/adapter"
	openaiadapter "github.com/skosovsky/prompty/adapter/openai"
)

type Question struct {
	Text string `prompt:"question"`
}

func materialize(ctx context.Context, question Question) (*prompty.PromptExecution, error) {
	tpl, err := prompty.NewChatPromptTemplate([]prompty.MessageTemplate{
		{Role: prompty.RoleSystem, Content: prompty.TextContent("Answer briefly.")},
		{Role: prompty.RoleUser, Content: prompty.TextContent("{{ .Input.question }}")},
	})
	if err != nil {
		return nil, err
	}
	input, err := prompty.PlanInputFrom(question)
	if err != nil {
		return nil, err
	}
	plan, err := prompty.NewRenderPlanFromPlanInput(tpl, input)
	if err != nil {
		return nil, err
	}
	return plan.Execute(ctx)
}

func main() {
	key, model := os.Getenv("OPENAI_API_KEY"), os.Getenv("OPENAI_MODEL")
	if key == "" || model == "" {
		log.Fatal("set OPENAI_API_KEY and OPENAI_MODEL to a host-selected model")
	}
	ctx := context.Background()
	execution, err := materialize(ctx, Question{Text: "What is 2+2?"})
	if err != nil {
		log.Fatal(err)
	}
	const endpoint = "https://api.openai.com/v1"
	sdk := openaisdk.NewClient(option.WithAPIKey(key), option.WithBaseURL(endpoint))
	client := adapter.NewClient(
		openaiadapter.New(
			openaiadapter.WithClient(&sdk),
			openaiadapter.WithModel(model),
			openaiadapter.WithProfiles(endpoint),
		),
	)
	response, err := client.Execute(ctx, execution)
	if err != nil {
		log.Fatal(err)
	}
	if response.Outcome != prompty.OutcomeCompleted {
		log.Fatal("provider did not complete")
	}
	text, err := response.StrictText()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(text)
}

Use prompty.SimpleChat(...), templates or your own PromptExecution builder when that fits your application. If an execution requests tools, constrained output, media, native streaming or another required guarantee, supply caller-verified endpoint/model profiles with WithProfiles; unknown required support fails before dispatch. Profile configuration must match the injected SDK transport and is not a model support catalog.

Optional manifest/codegen workflow

The repository contains a complete reproducible config, manifests and inputs, and typed consumer:

(cd cmd/prompty-gen && GOWORK=off go run . -config testdata/prompty.yaml generate)
(cd cmd/prompty-gen && GOWORK=off go test -race ./testdata/gen_out)
make test-e2e

The codegen e2e check regenerates fixtures in a temporary directory, compares their contents and file set with the checked-in output, then tests the generated consumer. A mismatch fails the check without modifying the working tree.

Use generated recipe/checkpoint APIs when source snapshots and serialized typed input fit your application. The generator guide explains caller-owned registry/config paths and restore policy. Model calls remain explicit.

Main abstractions

  • PromptRecipe / ManifestDescriptor — JSON-safe application checkpoint surface. A recipe stores typed input, optional late input, runtime compose values, and {ID, Digest}; restore it with PromptRecipeFromCheckpoint / generated NewXRecipeFromCheckpoint, then execute against a ManifestCheckpointRegistry.
  • Generated PromptCatalog / PromptIndex — typed recipe constructors and a static id index for known prompts. Use generated recipe APIs for optional manifest-backed materialization; use PromptIndex.NewRecipeFromJSON only for explicit serialized payload dispatch.
  • Registry — supplies plans from files, embed, remote or caller-owned BYOT materialization. Strong source verification belongs to the ManifestCheckpointRegistry/capture ports. Generated recipes capture one source snapshot, verify its identity, and build the plan from the same bytes. Direct Registry.Plan(ctx, id, input) is a low-level API for advanced integrations.
  • Adapter — maps PromptExecution to a provider request and parses a full Response. Checked path: adapter.NewClient(providerAdapter) → client.Execute(ctx, exec). Low-level Translate → SDK Execute → ParseResponse does not provide checked profile/schema guarantees. Streaming uses client.ExecuteStream(ctx, exec, mode) and a lazy, single-use handle; native adapters implement StreamerAdapter.StreamEvents. Runtime metadata and token budgets live behind adapter.NewRuntimeClient(providerAdapter); adapter.EstimateTokens(estimator, exec) returns ErrNoTokenEstimator without a provider estimator.
  • Templating — ChatPromptTemplate is built from message templates and optional tools. Generated recipes materialize it into PromptExecution at execution time. Template context is explicit: {{ .Input.<field> }} and {{ .LateVars.<field> }}. Registries load manifests (JSON or YAML), expand declarative imports/layers, and support WithPartials for shared {{ template "name" }} partials. Template functions (funcmaps) include truncate_chars, truncate_tokens, render_tools_as_xml, render_tools_as_json, escapeXML, and randomHex.

Optional manifest pipeline: generated recipe → checkpoint/restore → captured source verification + materialization → PromptExecution → Adapter → provider API.

Features

  • Domain model: ContentPart (text/media/tool call/result), ChatMessage, ToolDefinition, PromptExecution with metadata; open-ended roles in manifests (validation in adapters). CachePolicy declares an implicit-prefix or block-marker mechanism, advisory/required mode and provider-scoped controls on a message or part (cache_policy in manifests). Checked execution returns disposition diagnostics, not a cache-hit promise; required unknown/unsupported controls fail before dispatch. Execution-level provider knobs: use PromptExecution.ModelOptions.ProviderSettings (e.g. gemini_search_grounding for Gemini).
  • Media: exec.ResolvedMedia(ctx, fetcher) returns a cloned execution with MediaPart.Data filled via a Fetcher (e.g. mediafetch.DefaultFetcher{}); use it before Translate for adapters that require inline data (for example Ollama, and Anthropic for unsupported URL media shapes). OpenAI and Gemini accept URL natively.
  • Templating: text/template with fail-fast validation, PartialVariables, optional messages, chat history splicing. DRY: registries support WithPartials(pattern) so manifests can use {{ template "name" }} with shared partials (e.g. _partials/*.tmpl).
  • Template functions: truncate_chars, truncate_tokens, render_tools_as_xml / render_tools_as_json for tool injection.
  • Registries: load manifests from filesystem (fileregistry), embed (embedregistry), or remote HTTP/Git (remoteregistry). Remote cache is explicit via remoteregistry.WithCache(...) (unlimited entries) or remoteregistry.WithCacheLimit(base, ttl, maxEntries) (positive FIFO entry limit). Expired entries are cleaned on material lookup/publication; idle caches have no cleanup worker. See retention contract.
  • Adapters: map PromptExecution to provider request types (OpenAI, Anthropic, Gemini, Ollama); return ordered content, usage presence, outcome, annotations, scoped continuation state and checked diagnostics. Annotations has explicit content-part associations; MessageAnnotations carries whole-message metadata without invented part indices. Stream message metadata is an ordered update sequence, including late updates after finish, not independent merged snapshots. Both survive history/wire and remain subject to host redaction. Tool result is multimodal: ToolResultPart.Content is []ContentPart (text and/or images). Adapters that do not support media in tool results return ErrUnsupportedContentType when MediaPart is present in ToolResultPart.Content.
  • Exchange fidelity: exact Gemini arguments/IDs across observed IO and SDK serialization; Ollama thinking preserved in continuation. ID-less checked history requires confirmed name correlation, and unsupported error-result/interleaving shapes fail explicitly. See the provider exchange contract.
  • Observability: PromptMetadata (ID, version, description, tags, environment) on every execution.

Registries

Package Description
github.com/skosovsky/prompty/fileregistry Load manifests (JSON or YAML via WithParser) from a directory; lazy load with cache; Reload() to clear cache; WithPartials(relativePattern) for {{ template "name" }}
github.com/skosovsky/prompty/embedregistry Load from embed.FS at build time; source bytes sealed at construction; WithPartials(pattern) for shared partials
github.com/skosovsky/prompty/remoteregistry Fetch via Fetcher (HTTP or Git); explicit cache via WithCache; Close() for resource cleanup

All three registries also implement optional prompty.Lister (List(ctx)), prompty.Statter (Stat(ctx, id)), and prompty.ManifestResolver (ResolveManifest(ctx, id) — metadata only, no template AST). When you have a variable of type prompty.Registry and need list/stat/descriptor APIs, use a type assertion.

With WithEnvironment(env), only {name}.{env}.json|yaml|yml are resolved (strict, no fallback to base {name}). Without env, {name}.json|yaml|yml are tried. Name must not contain ':'.

Adapters

Package Translate result Notes
github.com/skosovsky/prompty/adapter/openai *openai.ChatCompletionNewParams Tools, MIME-routed media (image/audio/file), tool calls
github.com/skosovsky/prompty/adapter/anthropic *anthropic.MessageNewParams image/* and PDF media (base64 or URL), text/plain document blocks (base64), tool calls
github.com/skosovsky/prompty/adapter/gemini *gemini.Request Default model + overrides (WithModel, ModelOptions.Model); generic media URI/bytes
github.com/skosovsky/prompty/adapter/ollama *api.ChatRequest Native Ollama tools

Each adapter implements Translate(exec) (Req, error) where Req is the provider request type; ParseResponse(raw) returns *prompty.Response; use resp.StrictText() for fail-closed plain text. PromptExecution.ModelOptions carries typed model overrides such as Model, Temperature, MaxTokens, TopP, and Stop. Tool result: ToolResultPart.Content is []ContentPart (multimodal). Adapters that do not support media in tool results return adapter.ErrUnsupportedContentType when MediaPart is present. Media: OpenAI and Gemini can map URL media natively for supported types; Anthropic supports URL inputs for image/* and application/pdf; Ollama requires resolved inline images. Where the target mapping requires inline image data, call exec.ResolvedMedia(ctx, fetcher) explicitly; resolving a URL does not implement an unsupported MIME, role or tool-result shape. Media downloading is an explicit caller-owned step; mediafetch.DefaultFetcher provides an injectable HTTPS/image fetcher, not arbitrary document resolution or a host egress policy.

Provider settings

Use model_options.provider_settings for vendor-specific knobs. The core keeps this map as-is in ModelOptions.ProviderSettings; provider key mapping lives in adapters.

Clean break contract: vendor keys must be inside provider_settings. Unknown top-level keys in model_options are rejected with a parse error.

model_options:
  model: caller-verified-model
  provider_settings:
    reasoning_effort: low
    seed: 42

Supported provider_settings keys:

  • OpenAI Chat: presence_penalty, frequency_penalty, seed, logprobs, top_logprobs, reasoning_effort; separate Responses: reasoning_effort, reasoning_summary
  • Gemini: stream_function_call_arguments (Vertex native only), top_k, presence_penalty, frequency_penalty, stop_sequences, thinking, thinking_budget, thinking_level, gemini_search_grounding
  • Anthropic: top_k, stop_sequences, thinking_mode, thinking_budget, thinking_visibility, reasoning_effort
  • Ollama: top_k, seed, num_ctx, repeat_penalty, think (top-level native thinking control)

Provider settings validation is fail-closed: unknown keys or invalid values return adapter.ErrInvalidProviderSettings (no silent ignore).

Reasoning settings additionally require a caller-owned CapabilityProfile.ModelOptionsSchema for the effective endpoint/model on checked execution. It validates the full ModelOptions object and allowed combinations; absent knowledge is unknown and fails before dispatch. Declared schema/resources are local or explicitly injected, never fetched implicitly. SDK mappings are not a claim that all models support the listed settings. See migration for current clear-break contracts.

Architecture

flowchart LR
    Catalog[Generated PromptCatalog]
    Recipe[PromptRecipe]
    Checkpoint[Checkpoint DTO]
    Registry[ManifestCheckpointRegistry]
    Exec[PromptExecution]
    Adapter[ProviderAdapter]
    API[LLM API]

    Catalog -->|NewXRecipe| Recipe
    Recipe -->|Checkpoint / restore| Checkpoint
    Checkpoint --> Recipe
    Recipe -->|verify + materialize| Registry
    Registry --> Exec
    Exec -->|Translate| Adapter
    Adapter -->|request| API
    API -->|raw response| Adapter
    Adapter -->|ParseResponse| Response["*Response"]

Pipeline: PromptCatalog.NewXRecipe(...) → recipe.Checkpoint()/restore → recipe.ExecuteWithContract(...) → PromptExecution → Adapter → LLM API. Direct Registry.Plan(...) remains available as an advanced low-level path.

Checked execution and streaming

Core contracts do not own model routing, retries, agent loops, storage, IAM or scheduling. Inject profiles, validators, SDK transports, media fetchers and optional capture ports. Profiles describe the effective provider/endpoint/model with provenance; an override cannot implement an absent native stream or state port.

Output/tool definitions carry an optional Dialect, preserved by clone and execution wire. Empty selects SchemaDialect2020; set SchemaDialect7 explicitly for a schema declaring that dialect. Checked preparation and structured/tool helpers reject incompatible declarations or unavailable validation before dispatch. The runtime validator port is not persisted; rebind it after restore when using explicit resources or application-specific validation. Schema validation precedes domain Validate() and is not replaced by successful Go decoding.

Final source validation separates ErrSchemaJSONDecode (invalid/truncated/multiple documents) from ErrSchemaMismatch (valid JSON violating constraints). Invalid-document errors do not become repairable ValidationError or executor domain feedback. Incremental syntax remains ErrStructuredStream; provider refusal/incomplete remain outcome errors. See current schema/data contract.

stream := client.ExecuteStream(ctx, exec, prompty.StreamNative)
defer stream.Close()
for event, err := range stream.Events() {
    if err != nil {
        break // partial content/usage/error remain available through Status
    }
    if event.Kind == prompty.StreamTerminal {
        // This is lifecycle completion, unlike a provider finish marker.
    }
}
status := stream.Status()
_ = status // inspect State, Err and Result even after early consumer stop

Choose StreamBuffered explicitly for a synchronous request exposed through the stream lifecycle; it cannot satisfy native requirements. OpenAI, Anthropic, Gemini and Ollama adapters have native transports and offline protocol fixtures; endpoint/model support remains caller-owned. Gemini Vertex signed incremental arguments retain verified source ordering/state; Developer API incremental arguments remain unsupported. The capability matrix links implemented operations and offline fixtures. No automatic replay occurs after partial output.

Custom native sources use ResponseChunk.StateUpdates to explicitly replace opaque state for the same source-proven logical tool call. Bind each update to the current frame's tool part and preserve scope/codec/required/expiry semantics. Ordinary ProviderState remains append-only; a changed state-bound part without an explicit update fails. Final Result.ProviderState retains the latest accepted binding, while failed/canceled status retains partial state. The core never interprets signatures or certifies a producer's provider payload. See the executable update example.

event.Identity.MessageID identifies the local handle, not a provider request or physical attempt. PartIDs references each frame's logical content parts; in status/terminal it aligns with Result.Content, including repeated text-fragment references and materialized tool calls. Custom sources declare these references explicitly; missing/conflicting references fail with ErrStreamProtocol. Native and buffered canonical capture preserve them. Middleware attaches lazy observation to the original handle through ObserveLifecycle, retaining cancellation/finalizers/capture rather than reassembling a second stream. See the stream contract.

The executable SDK/local-SSE example demonstrates checked profile binding, trailing usage, response persistence and continuation without a paid provider request.

Read Response.Outcome before interpreting text as success, and Usage.Known/Availability() before interpreting zero counters. Save through MarshalResponse with explicit WirePolicy, restore through DecodeResponseJSON, and build continuation through AssistantMessage rather than copying Content alone. Required opaque state omitted for logging cannot be reused as a continuation checkpoint.

Message annotations may carry provider continuation data without an artificial content part. MessageAnnotation.Scope binds metadata to a provider/endpoint/model (or declared model family); Required:true requires that scope and an implemented annotation mapping on the receiving adapter. Checked execution verifies profile guarantees and calls the provider state validator even when there is no PartState. StateOmit removes scoped annotations and marks continuation unavailable when required data was removed. Unscoped optional metadata remains caller-owned; core never decodes provider annotation payloads.

Strict schema fidelity either preserves the original contract or fails before dispatch. Explicit lowering needs named permissions and final original-schema validation; JSON decode and provisional stream items are not that validation. Local tool helpers validate the whole execution-scoped batch before any handler. Capture is optional and host-projected; SDK JSON is semantic capture, not HTTP bytes or physical-attempt evidence. Request cache controls describe disposition, not hits or cache resource lifecycle.

Migration Notes

This change is a clear break: old iterator/IsFinished semantics, adjacency-based tool assembly, Type-only cache hints and implicit synthetic structured-output tools are removed. No compatibility bridge or lossy legacy-wire restore is supplied. See the current clear-break migration and capability matrix.

Regression gates: make lint and make test across all modules, including race checks and generator fixtures.

Checkpoint ops: compose manifests must list only resolvable import ids for RecommendManifestDescriptor / VerifyManifestDescriptor (all declared imports, including inactive conditional branches). Source caching: file and TTL registries retain whole immutable source bundles, including composition and partials. Reload/expiry/eviction selects a new generation; cache hits do not read current source. See the source snapshot contract.

Recipe-First Runtime

func buildExecution(ctx context.Context) (*prompty.PromptExecution, error) {
	reg, err := fileregistry.New("./prompts", fileregistry.WithParser(yaml.New()))
	if err != nil {
		return nil, err
	}

	catalog := prompts.NewPromptCatalog(reg)
	recipe, err := catalog.NewSupportAgentRecipe(ctx, prompts.SupportAgentInput{
		UserQuery: "Where is my order?",
	})
	if err != nil {
		return nil, err
	}

	checkpoint, err := recipe.Checkpoint() // JSON-safe DTO for storage.
	if err != nil {
		return nil, err
	}
	restored, err := prompts.NewSupportAgentRecipeFromCheckpoint(checkpoint)
	if err != nil {
		return nil, err
	}

	contract := prompty.ToolManifestContractFunc(func(name string) (prompty.ToolManifest, bool) {
		return runtimeTools.Manifest(name)
	})
	exec, err := restored.ExecuteWithContract(ctx, reg, contract)
	if err != nil {
		return nil, err
	}
	return exec, nil
}

Then execute exec via an adapter client (adapter.NewClient(...) or adapter.NewRuntimeClient(...)), including streaming if needed.

Compose-aware generated prompts require typed compose context:

recipe, err := catalog.NewComposedConditionalMainRecipeWithComposeContext(ctx, prompts.ComposedConditionalMainInput{
	Query: "Where is my order?",
}, prompts.NewComposedConditionalMainComposeContext(true))

Advanced low-level path: use Registry.Plan(...) directly only when the application intentionally owns the render-plan boundary:

type runtimeCompose struct {
	WorkspaceEnabled bool
}

func (c runtimeCompose) ComposeValues() prompty.ComposeValues {
	return prompty.NewComposeValuesFromPairs(
		prompty.ComposeBool("capabilities.workspace_enabled", c.WorkspaceEnabled),
	)
}

planInput, err := prompty.PlanInputFrom(struct {
	UserQuery string `prompt:"user_query"`
}{UserQuery: "Where is my order?"})
if err != nil {
	return err
}
planInput, err = prompty.PlanInputWithComposeContext(planInput, runtimeCompose{WorkspaceEnabled: true})
if err != nil {
	return err
}
plan, err := reg.Plan(ctx, "main_agent", planInput)
if err != nil {
	return err
}
exec, err := plan.ExecuteWithContract(ctx, contract)

Clean-break rules:

  • no Registry.GetTemplate(...) in production code
  • no ChatPromptTemplate.Format(...) / FormatStruct(...)
  • manifests must use model_options + contract-style inputs
  • message layers use layer_id (not source_id)
  • template context is explicit: .Input.* and .LateVars.*
  • provider message normalization runs in adapters, not in RenderPlan.Execute()
Runtime Binding, Wire DTO, And Render-Only

Use RuntimeRecipeCheckpoint + BindRuntime when the runtime boundary stores raw JSON recipe state instead of generated typed recipe values. BindRuntime verifies the manifest descriptor, applies RuntimeOverlay, validates late fields and attaches ToolScope before materialization.

Use MarshalExecution / UnmarshalExecution for storage or transport of PromptExecution. The wire DTO uses typed content-part variants and JSONDocument for schema/provider payloads.

For render-only use cases, call plan.RenderText(ctx) or exec.Text(strict) instead of creating a fake invoker.

Composition And Runtime Additions
  • Declarative composition: manifest imports + layers with condition.match; registries expand at Plan time using typed ComposeValues / generated ComposeContext.
  • Layers: tag messages with layer_id / layer_kind (or define layers in manifest).
  • Provenance: rendered messages carry Provenance *MessageProvenance (LayerID, ManifestID).
  • Late binding: typed WithLateInput at core level and generated *LateInput + recipe BindLate (no JSON tunnel).
  • Checkpoints: ManifestDescriptor{ID, Digest} instead of public compiled blobs.
  • Metadata: ResolveManifest / PromptCatalog.Descriptor for lightweight manifest introspection (WithResolveComposeContext for runtime layer view).
  • Compose fixtures: see fileregistry/testdata/prompts/composed_main.yaml and composed_conditional_main.yaml.
  • Runtime schema: WithResponseFormatDefinition / WithResponseFormatFromStruct overrides response format before execute.
  • Struct binding: struct fields bind via explicit prompt tags; generated inputs emit those tags from manifest contract fields.
Flat vs compose layers

Manifests use either top-level messages (flat) or layers with optional imports (compose). Declaring both is rejected — when migrating to compose, move every turn (including the user message) into layers:

layers:
  - id: user_turn
    role: user
    content: "{{ .Input.query }}"

Flat manifests keep messages + optional layer_id per message. Compose manifests resolve imports transitively and attach MessageProvenance per expanded layer.

Resilience, timeouts, and structured output

Separation of concerns: prompty focuses on the prompt domain and a single provider round-trip per call (Execute, ExecuteWithStructuredOutput, GenerateStructured). It does not implement retry loops, backoff, or transport-level timeouts inside the core.

  • GenerateStructured[T] runs one structured attempt (same as NewExecution + ExecuteWithStructuredOutput[T]). There is no WithRetries option: drive repetition from your own loop or middleware.
  • NewStructuredExecutor[T](invoker, exec) returns a closure func(context.Context) (*T, error) that keeps a working copy of exec. On *ValidationError or *ToolCallError, it appends the assistant turn and feedback/tool results to that copy, then returns the original error. The next call to the closure sees the updated history—useful for an outer orchestrator (see below) without baking policy into prompty.

Timeouts and HTTP: adapters do not set context.WithTimeout or client Timeout for you; the request honors only the context.Context you pass. Configure HTTP deadlines and transports when you construct the vendor SDK (for example OpenAI: openai.NewClient(option.WithHTTPClient(httpClient))). You can also wrap Invoker with timeouts or retries outside this library.

Illustrative outer retry (pseudo-code; use your own retry policy outside this library):

step := prompty.NewStructuredExecutor[MyDTO](invoker, exec)
var out *MyDTO
var err error
for attempt := 0; attempt < maxAttempts; attempt++ {
	out, err = step(ctx)
	if err == nil {
		break
	}
	if _, ok := err.(*prompty.ValidationError); ok {
		continue
	}
	if _, ok := err.(*prompty.ToolCallError); ok {
		continue
	}
	break
}

Template functions

  • truncate_chars .text 4000 — trim by rune count
  • truncate_tokens .text 2000 — trim by token count (uses TokenCounter from template options; default CharFallbackCounter)
  • render_tools_as_xml .Tools / render_tools_as_json .Tools — inject tool definitions into the prompt (e.g. for local Llama)
  • escapeXML — escape <, >, &, ", ' so user input does not break XML structure (see Prompt Security)
  • randomHex N — cryptographically random hex string of N bytes (2N chars); for randomized delimiters

Prompt Security (Data Isolation)

To prevent delimiter collisions (e.g. user input closing an XML-like tag), escape user content and use randomized delimiters to reduce accidental or exact delimiter reuse; this is data formatting, not an authorization boundary. Example in a message template:

{{ $delim := randomHex 8 }}
<data_{{ $delim }}>
{{ .Input.UserInput | escapeXML }}
</data_{{ $delim }}>
  • escapeXML — uses html.EscapeString; escapes markup characters; it does not prevent a model from following instructions inside that text.
  • randomHex — e.g. randomHex 8 yields a 16-character hex string; use in opening and closing tags so the delimiter is unpredictable.

See examples/secure_prompt for a runnable example.

Development

This repo uses Go Workspaces (go.work). The root and all adapter/registry submodules must be listed there so that changes to the core prompty package and adapters compile together in one PR without publishing intermediate versions.

Build and test (from repo root):

go work sync
go build ./...
go test ./...
cd adapter/openai && go build . && go test . && cd ../..
cd adapter/anthropic && go build . && go test . && cd ../..
cd adapter/gemini && go build . && go test . && cd ../..
cd adapter/ollama && go build . && go test . && cd ../..
cd remoteregistry/git && go build . && go test . && cd ../..

go.work is the authoritative module inventory; make lint and make test cover all workspace modules and generated consumers.

Benchmarks: allocations depend on binding, cloning and rendering paths. Pools reuse selected scratch buffers/maps; they do not make the whole API allocation-free. Measure allocs/op and B/op for the relevant benchmark:

go test -bench=BenchmarkRenderPlanExecute -benchmem ./...

Running examples locally: go.work includes ./examples/basic_chat, ./examples/git_prompts, ./examples/funcmap_tools, and ./examples/secure_prompt. Run basic_chat from its manifest directory: cd examples/basic_chat && go run .. From the repo root, go run ./examples/secure_prompt runs the data-isolation example. The secure_prompt example embeds its manifest and works from any working directory; it demonstrates both escapeXML and randomHex (randomized delimiters). Each example’s go.mod uses replace for local development; remove those when using a published module.

Release transaction contract (task45)

Release preparation uses an explicit committed source in an isolated staging checkout; the user's branch/detached HEAD, index, tracked/untracked files and unrelated tags remain untouched. Synthetic release commits are unsigned and do not invoke the user's signing agent; signing/tag-attestation policy requires a separate explicit workflow. Only inventoried module manifests may change, and their complete diff is checked before creating the release commit. Validate publishable module graphs with GOWORK=off separately from workspace checks, including same-release intermodule dependencies. Workspace-only success is insufficient.

Publish only the exact newly prepared root/submodule tag refs, with automatic followed-tag publication disabled, preferably in one atomic push. Remotes without atomic support fail explicitly; there is no silent non-atomic fallback. Record source/release commits, intended refs and target version before publication. A failed or uncertain push requires remote-ref reconciliation: all expected refs at their intended commit means published; none means unpublished and explicitly retryable at the same version; a partial/conflicting/unknown set blocks a new version and requires explicit recovery. Never delete unrelated or potentially published refs blindly. Preparation never leaves stale version-calculation tags in the user's checkout.

Release state is retained under the repository Git directory in prompty-release/transaction.json and its staging checkout. Use bash scripts/release.sh reconcile to inspect remote evidence, resume to publish/reconcile the same prepared version, or abort only after proving all intended refs absent. A pending transaction blocks a fresh patch/break release. Standalone graph validation uses locally served archives of the prepared modules with GOWORK=off, no local replacements, and checks that compilation needs no manifest edits. This permits verification before remote tags exist.

The release tooling targets macOS and Linux with bash, Python 3.8+ (standard library), Git and the declared Go toolchain, using portable manifest edits. Current unversioned module paths support v0 releases only; crossing a major-version import boundary is rejected until module/import migration is explicitly implemented. Acceptance runs exclusively against disposable local bare remotes, including rejected publication and uncertain/reconciled outcomes; task45 does not authorize real publication.

Codegen inventories all output filenames and public Go identifiers (including shared helpers and normalized property names) before writing. Reject conflicting sources with actionable identities, never successful partial output. Validate configuration version and complete input documents. Generated files are staged before publication; only explicitly inventoried generator-owned files may be replaced or cleaned up. Arbitrary consumer files remain host-owned. A valid generated consumer must compile, and repeated generation must produce an empty diff.

License

MIT. See LICENSE.

Repository verification and releases

Use make modules to inspect the automatically discovered modules. All verification commands use GOWORK=off; development manifests link internal modules with local replace directives.

make lint
make test
make test-integration
make test-e2e

See verification for test profiles and prerequisites, and release runbook for isolated release candidates, atomic source/tag publication and inspect/resume/finish recovery. make test-live, benchmarks and fuzz campaigns are separate from CI/release gates.

The schema and JSON data contract defines exact dynamic numbers, reflection errors, input composition and generated presence validation. ExtractSchema returns both the schema and an error.

Provider feature gates and migration are documented in the capability matrix. Local SDK fixtures do not establish live model support.

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

Examples

Constants

View Source
const (
	BatchWireFormat        = "prompty.batch"
	CapabilityBatchSubmit  = "batch_submit"
	CapabilityBatchInspect = "batch_inspect"
	CapabilityBatchCancel  = "batch_cancel"
	CapabilityBatchResults = "batch_results"
)
View Source
const (
	CacheImplicitPrefix     CacheMechanism = "implicit_prefix"
	CacheBlockMarker        CacheMechanism = "block_marker"
	CacheAdvisory           CacheMode      = "advisory"
	CacheRequired           CacheMode      = "required"
	CapabilityCacheImplicit                = "cache_implicit_prefix"
	CapabilityCacheMarker                  = "cache_block_marker"
)
View Source
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"
)
View Source
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"
)
View Source
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"
)
View Source
const (
	SchemaDialect2020 = "https://json-schema.org/draft/2020-12/schema"
	SchemaDialect7    = "http://json-schema.org/draft-07/schema#"
)
View Source
const (
	ExecutionWireFormat       = "prompty.execution.v2"
	ContentPartWireText       = "text"
	ContentPartWireMedia      = "media"
	ContentPartWireReasoning  = "reasoning"
	ContentPartWireToolCall   = "tool_call"
	ContentPartWireToolResult = "tool_result"
)
View Source
const ProviderStateFormat = "prompty.provider-state"
View Source
const ResponseWireFormat = "prompty.response"

Variables

View Source
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")
	ErrBatchUnavailable = errors.New("prompty: batch results unavailable")
	ErrBatchResults     = errors.New("prompty: incomplete batch result retrieval")
)
View Source
var (
	ErrCachePolicy      = errors.New("prompty: invalid cache policy")
	ErrCacheRequirement = errors.New("prompty: cache requirement not satisfied")
)
View Source
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")
)
View Source
var (
	ErrCapture            = errors.New("prompty: capture failed")
	ErrCaptureUnsupported = errors.New("prompty: required capture coverage unavailable")
)
View Source
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 indicates the registry cannot supply raw manifest bytes.
	ErrManifestBytesUnavailable = errors.New("prompty: manifest bytes unavailable from registry")
	// ErrRegistryCapabilityUnavailable indicates an optional registry operation is unsupported.
	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.

View Source
var (
	ErrProviderState    = errors.New("prompty: invalid provider state")
	ErrStateDestination = errors.New("prompty: incompatible provider state destination")
	ErrStateExpired     = errors.New("prompty: expired provider state")
	ErrStateUnavailable = errors.New("prompty: required continuation state unavailable")
)
View Source
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")
	ErrRemoteResponseUnavailable = errors.New("prompty: remote response unavailable")
)
View Source
var (
	ErrWireFormat = errors.New("prompty: unsupported wire format; explicit migration required")
	ErrWirePolicy = errors.New("prompty: explicit state projection policy required")
)
View Source
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")
)
View Source
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")
)
View Source
var ErrAmbiguousTextExecution = errors.New("prompty: execution text is ambiguous")

ErrAmbiguousTextExecution indicates strict render-only extraction found multiple messages.

View Source
var ErrBatchFileUnknown = errors.New("prompty: batch file upload outcome unknown")
View Source
var ErrCapabilityProfile = errors.New("prompty: invalid capability profile")

ErrCapabilityProfile identifies malformed caller-owned profile knowledge.

View Source
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.

View Source
var ErrComposeValues = errors.New("prompty: invalid compose values")
View Source
var ErrEmptyTextResponse = errors.New("prompty: response contains no text")

ErrEmptyTextResponse indicates strict text extraction found no text content.

View Source
var ErrHostedToolRequest = errors.New("prompty: invalid hosted tool declaration")
View Source
var ErrIncompleteToolCallArgs = errors.New("prompty: tool call arguments incomplete")

ErrIncompleteToolCallArgs indicates incomplete or uncorrelated streaming arguments.

View Source
var ErrMissingRequiredTool = errors.New("prompt contract: missing required tool")

ErrMissingRequiredTool indicates that a prompt required a tool absent from the supplied manifest contract.

View Source
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.

View Source
var ErrOutputMode = errors.New("prompty: invalid structured output mode")

ErrOutputMode identifies an invalid or contradictory output selection.

View Source
var ErrResponseOutcome = errors.New("prompty: unsuccessful provider outcome")

ErrResponseOutcome indicates that the provider did not complete a successful output.

View Source
var ErrStructuredOutputUnavailable = errors.New("structured output contract: schema unavailable")

ErrStructuredOutputUnavailable indicates a prompt recipe has no structured output schema contract.

View Source
var ErrStructuredStream = errors.New("prompty: invalid structured stream")

ErrStructuredStream identifies invalid incremental JSON syntax/shape, not provider refusal or voluntary consumer cancellation.

View Source
var ErrToolContractMismatch = errors.New("prompt contract: tool manifest mismatch")

ErrToolContractMismatch indicates a runtime tool manifest does not satisfy the prompt contract.

View Source
var ErrToolScope = errors.New("prompty: tool call violates execution scope")

ErrToolScope indicates that definitions or calls violate the execution boundary.

View Source
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

func DecodeToolArgs[TArgs any](argsJSON string) (TArgs, error)

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

func ExecuteAsText(ctx context.Context, invoker Invoker, exec *PromptExecution) (string, error)

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

func ExtractSchema(v any) (map[string]any, error)

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

func GenerateStructured[T any](ctx context.Context, invoker Invoker, prompt string) (T, error)

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

func ManifestDigestSHA256(manifestBytes []byte) string

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

func ValidateEndpointIdentity(endpoint string) error

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

func ValidateID(id string) error

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

func ValidateName(name, env string) error

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

func ValidateResponseMetadata(response *Response) error

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

type BatchFileBinding struct {
	Provider       string
	Endpoint       string
	AccountBinding string
}

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 BatchFileUpload struct {
	Content   io.Reader
	Filename  string
	MediaType string
	Purpose   string
}

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 BatchItemBinding struct {
	ID              string          `json:"id"`
	OriginalID      string          `json:"original_id"`
	AttemptID       string          `json:"attempt_id"`
	ParentAttemptID string          `json:"parent_attempt_id,omitempty"`
	Identity        ProfileIdentity `json:"identity"`
	ExecutionDigest string          `json:"execution_digest"`
}

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 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 BatchResourceRef struct {
	Kind       string `json:"kind"`
	ProviderID string `json:"provider_id"`
}

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

type CacheResourceExpiry struct {
	TTL       time.Duration
	ExpiresAt time.Time
}

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

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"`
	ContinuationUnavailable bool                `json:"continuation_unavailable,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

Report returns an isolated compilation report.

func (*CompiledProviderSchema) Source added in v0.15.0

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.

func (ComposeValues) Lookup added in v0.13.0

func (v ComposeValues) Lookup(path string) (any, bool)

Lookup returns an owned copy of a runtime compose value by dot path.

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

type Lister interface {
	List(ctx context.Context) ([]string, error)
}

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

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"`
	ContinuationUnavailable bool                `json:"continuation_unavailable,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

type Middleware func(next Invoker) Invoker

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

type OutcomeError struct {
	Outcome      Outcome
	FinishReason string
}

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

func (p *RenderPlan) ExecuteAsText(ctx context.Context, invoker Invoker) (string, error)

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"`
	ContinuationUnavailable bool                 `json:"continuation_unavailable,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

func CloneResponse(resp *Response) *Response

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

func (r *Response) StrictText() (string, error)

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
	ContinuationUnavailable bool
	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"`
	ContinuationUnavailable bool                 `json:"continuation_unavailable,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).

const (
	RoleSystem    Role = "system"
	RoleDeveloper Role = "developer" // Replaces system for OpenAI o1/o3-style models
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

Chat message roles.

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

type SchemaFidelityError struct {
	Pointer string
	Reason  string
}

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

type SchemaSourceLocation struct {
	Resource string
	Pointer  string
}

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

func (s *Stream) Close() error

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

type StreamFinalizer func(context.Context, *Response) error

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

type TemplateInfo struct {
	ID        string
	Version   string
	UpdatedAt time.Time
}

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.

func (*ToolCallError) Unwrap added in v0.6.0

func (e *ToolCallError) Unwrap() error

Unwrap returns the wrapped error for errors.Is and errors.As.

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

type ToolDispatchError struct {
	Response *Response
	Err      error
}

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

type ToolScopeError struct {
	Tool   string
	Reason string
}

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

type ToolValidator interface {
	ValidateToolCall(name string, argsJSON string) error
}

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

type TypedTool[TArgs any, TResult any] struct {
	// contains filtered or unexported fields
}

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

func (t *TypedTool[TArgs, TResult]) Invoke(ctx context.Context, argsJSON string) (TResult, error)

Invoke decodes args and runs the handler (fail-closed on unknown JSON fields).

func (*TypedTool[TArgs, TResult]) Name added in v0.11.0

func (t *TypedTool[TArgs, TResult]) Name() string

Name returns the tool name exposed to the model.

func (*TypedTool[TArgs, TResult]) ValidateArgs added in v0.11.0

func (t *TypedTool[TArgs, TResult]) ValidateArgs(argsJSON string) error

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.

func (Usage) Validate added in v0.15.0

func (u Usage) Validate() error

Validate checks portable usage shape, not provider-specific total composition. Unknown-presence scalar estimates are preserved without promoting them to known.

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.

const (
	UsageCumulative UsageMode = "cumulative"
	UsageDelta      UsageMode = "delta"
)

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.

func (*ValidationError) Unwrap added in v0.6.0

func (e *ValidationError) Unwrap() error

Unwrap returns the wrapped error for errors.Is and errors.As.

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

type VariableError struct {
	Variable string
	Template string
	Err      error
}

VariableError wraps a sentinel error with variable and template context. Use errors.Is(err, ErrMissingVariable) and errors.As(err, &variableErr) to inspect.

func (*VariableError) Error

func (e *VariableError) Error() string

Error implements error.

func (*VariableError) Unwrap

func (e *VariableError) Unwrap() error

Unwrap returns the wrapped error for errors.Is and errors.As.

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.

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

Jump to

Keyboard shortcuts

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