Document core operation authoring with a working example

This commit is contained in:
2026-11-25 16:24:26 +00:00
parent 514f5a9692
commit 3826dce93b
8 changed files with 295 additions and 86 deletions

View File

@@ -33,11 +33,10 @@ registry normalizers are model-backed; current mergers and remaining normalizers
are deterministic. A model-backed module can still have an ordinary no-model are deterministic. A model-backed module can still have an ordinary no-model
branch. Registration does not construct engines or register prompt/schema assets. branch. Registration does not construct engines or register prompt/schema assets.
Each model producer receives the shared native engine, prepares fixed operation Each model producer prepares fixed operation inputs and returns an initial request,
inputs, and calls the common producer helper with initial request, interpretation, interpretation, correction builder, and supported fallback to core. Static prompt
correction builder, and supported fallback. Static prompt dependencies match its dependencies match its request constants. Core owns the shared engine and complete
request constants. The pipeline supplies complete candidate assessment; returning candidate assessment; modules do not run another producer loop.
from the helper does not trigger a duplicate validator pass.
Pure codecs, identities, reference resolvers, and deterministic transforms remain Pure codecs, identities, reference resolvers, and deterministic transforms remain
separate from execution integration. separate from execution integration.
@@ -137,13 +136,13 @@ The three registry normalizers retain their intentional model-assisted exception
[NPC](../../internal/modules/dnd/normalize/npcregistry/normalizer.go), [NPC](../../internal/modules/dnd/normalize/npcregistry/normalizer.go),
[item](../../internal/modules/dnd/normalize/itemregistry/normalizer.go), and [item](../../internal/modules/dnd/normalize/itemregistry/normalizer.go), and
[location](../../internal/modules/dnd/normalize/locationregistry/normalizer.go) [location](../../internal/modules/dnd/normalize/locationregistry/normalizer.go)
normalization use ordinary functions from normalization use the shared operation facility in
[semanticreconcile](../../internal/framework/semanticreconcile/preparation.go), [semanticreconcile](../../internal/framework/semanticreconcile/operation.go),
not a separate reconciliation engine/service. not a separate reconciliation engine/service.
The operation retains the incoming merged artifact separately, preprocesses The operation retains the incoming merged artifact separately, preprocesses
fixed originals once, and calls `Prepare` once. Preparation filters unusable fixed originals once; the shared facility prepares candidates once. Preparation
candidate evidence, assigns contiguous one-based request-local handles, declares filters unusable candidate evidence, assigns contiguous one-based request-local handles, declares
their inclusive range, and builds bounded transcript windows/material. their inclusive range, and builds bounded transcript windows/material.
Candidate handles are not transcript unit IDs or durable identity. Identical Candidate handles are not transcript unit IDs or durable identity. Identical
labels/evidence remain separately selectable. labels/evidence remain separately selectable.

View File

@@ -29,8 +29,7 @@ operation invokes a model.
## Requests And Fixed Operation Inputs ## Requests And Fixed Operation Inputs
Model modules receive the shared engine during typed preparation. A module Core owns the shared engine. A model module prepares transcript, references, contextual identity projections, and any
prepares transcript, references, contextual identity projections, and any
normalization candidate mapping once. It constructs a `promptkit.RunRequest` normalization candidate mapping once. It constructs a `promptkit.RunRequest`
with its selected prompt, profile/session, native artifact inputs, and variables. with its selected prompt, profile/session, native artifact inputs, and variables.
Response interpretation consumes `*promptkit.RunResult` and produces the Response interpretation consumes `*promptkit.RunResult` and produces the
@@ -49,14 +48,14 @@ acquire authority over durable IDs, citation meaning, or typed artifact shape.
recipes. recipes.
Native request overrides preserve supplied values without rewriting configured Native request overrides preserve supplied values without rewriting configured
profiles. The producer helper's request composition preserves operation-owned profiles. Core request composition preserves operation-owned
prompt/input/capture fields and existing callbacks; validators pass native prompt/input/capture fields and existing callbacks; validators pass native
execution options explicitly on their own requests. execution options explicitly on their own requests.
## Native Production And Application Assessment ## Native Production And Application Assessment
[RunProducer](../../internal/framework/pipeline/producer.go) connects ordinary [Core native execution](../../internal/framework/pipeline/operation_native.go)
module interpretation/correction/fallback functions to the pipeline assessor. connects prepared interpretation/correction/fallback functions to the pipeline assessor.
It uses native `Run`, or retained prepared execution on the cache path, then It uses native `Run`, or retained prepared execution on the cache path, then
checks errors and public validation status before interpretation. Failed native checks errors and public validation status before interpretation. Failed native
validation can accompany nil Go error and is not a usable semantic candidate. validation can accompany nil Go error and is not a usable semantic candidate.
@@ -124,7 +123,7 @@ counter around native coordination.
## Prepared Execution And Reuse ## Prepared Execution And Reuse
For eligible cacheable producers, the helper prepares the initial request once, For eligible cacheable operations, core prepares the initial request once,
retains its details and opaque message-content hash, and either discards the retains its details and opaque message-content hash, and either discards the
handle on a usable hit or executes that same handle with `RunPrepared`. handle on a usable hit or executes that same handle with `RunPrepared`.
Unused handles are discarded on exits. Continuation retains the initial key. Unused handles are discarded on exits. Continuation retains the initial key.

View File

@@ -20,8 +20,9 @@ modules. The resolver applies model-profile selections only to model roles.
Static initial/correction dependencies use the same constants as request builders; Static initial/correction dependencies use the same constants as request builders;
they are preflight declarations, not asset manifests or execution fingerprints. they are preflight declarations, not asset manifests or execution fingerprints.
[BuildRequest](../../internal/framework/pipeline/construction.go) supplies the [BuildRequest](../../internal/framework/pipeline/construction.go) supplies
shared native engine, option values, and prepared references. Option-aware dependencies, option values, and prepared references; one-shot validators may
use the shared native engine. Option-aware
modules provide a resolver validator and a builder using the same strict decoder. modules provide a resolver validator and a builder using the same strict decoder.
They do not rediscover configuration or reopen reference files. Generated They do not rediscover configuration or reopen reference files. Generated
references arrive through operation requests, not construction-time file reads. references arrive through operation requests, not construction-time file reads.
@@ -43,66 +44,68 @@ Preparation rejects incompatible types/registrations before parsing source.
Projectors do not inspect arbitrary domain JSON or publish files; the Projectors do not inspect arbitrary domain JSON or publish files; the
[evidence contract](../integrations/evidence-context.md) owns the excerpt. [evidence contract](../integrations/evidence-context.md) owns the excerpt.
## Native Producer Recipe ## Preparing Operations
Follow the actual [spell extractor](../../internal/modules/dnd/extract/spells/extractor.go) The [tested message-topic example](../../internal/framework/pipeline/author_example_test.go)
alongside [typed requests/results](../../internal/framework/contracts/typed_pipeline.go) shows a domain-neutral input, codec, registrar, text chunk, contextual
and [operation contracts](../../internal/framework/contracts/producer.go): interpretation, correction binding, and a deterministic branch. For production
adapters see [spell extraction](../../internal/modules/dnd/extract/spells/extractor.go)
and the [item registry normalizer](../../internal/modules/dnd/normalize/itemregistry/normalizer.go).
1. Validate operation input and prepare owned transcript/reference/contextual A typed stage implements its `PrepareExtraction`, `PrepareMerge`,
projections once. Retain those fixed bytes and resolution mappings locally. `PrepareNormalize`, or `PrepareChunk` method from
2. Build the initial `promptkit.RunRequest` using the declared prompt ID, [preparation contracts](../../internal/framework/contracts/preparation.go).
operation profile/session, native artifacts, and variables. Core invokes that method once with domain inputs, then executes the returned
3. Call [RunProducer](../../internal/framework/pipeline/producer.go) with the shared operation. The stage does not receive or choose an assessor, engine, cache,
engine and the supplied typed operation. Supply ordinary interpretation, capture, or terminal mode. The runner binds those privately; direct callers can
correction-request, and supported fallback functions. supply a [core execution context](../../internal/framework/pipeline/operation.go)
4. Interpret `*promptkit.RunResult` into the typed domain candidate. Attach and preparation function to the same executor.
deterministic identities and canonical source references here, not by asking
the model to reproduce opaque IDs. Return actionable interpretation guidance
separately from operator diagnostics where the module can correct a selection.
5. Build the follow-up request from new findings/assignment only. Preserve
profile/session selections; native coordination carries prior conversation.
Do not rerender source inputs, serialize a domain artifact as a previous
assistant response, or implement another turn loop.
6. Return the helper's value and outcome in the typed operation result. The
runner has already supplied assessment; do not validate again after the helper.
The helper checks native structural status before interpretation, binds native - Return a deterministic operation with one candidate when no model is needed.
execution overrides/observers, assesses every delivered usable candidate, and Core assesses it once; there is no native request or synthetic cache key.
handles prepared reuse. Modules do not replace its assessor/cache or infer - Return a native operation containing the selected `promptkit.RunRequest`,
acceptance from provider success. [Pipeline Internals](pipeline.md) owns the an interpreter, and, when supported, a correction builder and fallback.
complete assessment/disposition algorithm; [LLM Integration](llm.md) owns native Interpret into an evaluation with a candidate and any ordered guidance.
execution and [State Internals](state.md) owns storage/capture lifecycle. A correctable selection can provide guidance without a candidate. A candidate
is not an approval: core still runs every configured validator.
- Return an ordinary Go error for preparation failures. Use the explicit
preparation-limit operation only for an existing supported limit, not as
generic error recovery. Core selects strict/permissive handling.
- Supply fallback only when the family supports intrinsically usable output.
It receives the final eligible evaluation, or nil when none remains. It must
preserve domain/source/downstream invariants; core does not re-run ordinary
validators or claim acceptance for fallback.
Fallback construction is explicit and family-owned. It must satisfy intrinsic For the common correction form, `PromptCorrection` binds ordered guidance to
shape/source/downstream invariants, but does not rerun ordinary validators or an integration-chosen prompt input; a specialized builder can instead construct
claim semantic approval. Unsupported/invalid construction fails. No earlier the assignment directly. Native coordination retains the initial profile/session,
candidate is recovered after an unusable continuation; cancellation produces no resolved options, and conversation history. Modules do not replay source or
fallback. Modules do not pick a permissive default or hide an ordinary operation implement a continuation loop. See [Pipeline Internals](pipeline.md) for
error as recovery. assessment and terminal behavior and [LLM Integration](llm.md) for native ownership.
An evaluation and its candidate, diagnostics, guidance, and optional evidence
are one operation-local unit. Core replaces it on each delivered interpretation
and clears it before a selected correction; failed or unusable continuation
cannot restore a prior evaluation. Historical capture may retain prior evidence.
Preparation transfers returned values and callbacks to that operation; a shared
module must not store mutable operation state. Own mutable slices/maps that a
callback might modify and respect the existing detached input boundaries.
Optional evidence projections are lazy and only invoked when capture is enabled.
This does not promise thread safety for caller-supplied writers or observers.
## Validators And Deterministic Work ## Validators And Deterministic Work
Validators receive native execution options and detached candidate/context views, Validators receive native execution options and detached candidate/context views,
not a producer operation or semantic-turn loop. Return approval, or rejection not an operation executor. Return approval or rejection with separately authored
with separate stable reason and actionable `CorrectionGuidance`. Operator actionable correction guidance; operator messages are not model feedback.
`Message` is not model feedback. The detecting rule owns guidance about fields A model validator calls the shared engine once and checks native result usability
the producer controls, without internal paths/keys/opaque identities. before interpretation. The [combat validator](../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go)
Invalid rejection guidance is a contract failure. is the one-shot example. It does not own a semantic correction loop or extend
native repair budgets.
A model validator calls the shared native engine directly, checks native errors/ Deterministic modules return prepared candidates through the same core path.
validation before interpretation, and distinguishes unavailable judgment from See the [noop normalizer](../../internal/modules/generic/normalize/noop/typed.go)
semantic rejection while preserving causes. See the and the model-backed extractors with no-model branches.
[combat validator](../../internal/modules/dnd/validate/scenedescriptions/combat_semantics/validator.go).
Do not rerun a validator to extend native repair budgets.
Deterministic modules produce once through ordinary typed interfaces. The runner
assesses the value and can invoke an explicitly supported result fallback after
nonacceptance. Production errors propagate without generic retries. Model-backed
modules with legitimate no-model branches use direct `AssessProducer` on that
value; preparation-limit terminal handling uses `FinishProducerFailure` rather
than synthetic requests. The [noop normalizer](../../internal/modules/generic/normalize/noop/normalizer.go)
and registry normalizers show the distinct paths.
## Prompt And Schema Ownership ## Prompt And Schema Ownership
@@ -121,17 +124,17 @@ See [schema selection](../config.md#prompt-output-contracts-and-schemas) and the
## Semantic Reconciliation ## Semantic Reconciliation
The [shared core](../../internal/framework/semanticreconcile/preparation.go) The [shared facility](../../internal/framework/semanticreconcile/operation.go)
offers preparation, native request builders, proposal assessment, and typed prepares core operations and provides proposal assessment and typed application,
application functions, not a replacement execution service. not a replacement execution service.
[Requests](../../internal/framework/semanticreconcile/requests.go) consume one [Requests](../../internal/framework/semanticreconcile/requests.go) consume one
retained preparation. [Proposal safety](../../internal/framework/semanticreconcile/proposal.go) retained preparation. [Proposal safety](../../internal/framework/semanticreconcile/proposal.go)
resolves request-local handles; [application](../../internal/framework/semanticreconcile/application.go) resolves request-local handles; [application](../../internal/framework/semanticreconcile/application.go)
clones/preserves originals and applies domain policies. clones/preserves originals and applies domain policies.
The [item normalizer](../../internal/modules/dnd/normalize/itemregistry/normalizer.go) The [item normalizer](../../internal/modules/dnd/normalize/itemregistry/normalizer.go)
preprocesses fixed originals once, prepares bounded windows/handles once, then preprocesses fixed originals once and prepares bounded windows/handles once.
uses the same producer helper as extraction. Each complete proposal is assessed Core executes its operation like extraction. Each complete proposal is assessed
and applied afresh to originals before pipeline assessment. Domain guards, and applied afresh to originals before pipeline assessment. Domain guards,
identity, evidence, diagnostics, and supported final-only fallback remain with identity, evidence, diagnostics, and supported final-only fallback remain with
the artifact family. Do not union plans across turns, reuse prior mutated output, the artifact family. Do not union plans across turns, reuse prior mutated output,

View File

@@ -26,9 +26,9 @@ streams or roots. Standard inspection/preflight paths do not become runs.
| Executable and native CLI | [cmd/notarius](../../cmd/notarius/), [internal/cli](../../internal/cli/) | Identity, native commands/aliases/suites, invocation-local source/engine selection, registrars, run composition, publication/reporting. | | Executable and native CLI | [cmd/notarius](../../cmd/notarius/), [internal/cli](../../internal/cli/) | Identity, native commands/aliases/suites, invocation-local source/engine selection, registrars, run composition, publication/reporting. |
| Application configuration | [internal/core/config](../../internal/core/config/) | Composed ConfigKit/native settings definition, source-aware normalization, detached runtime conversion, application validation, effective domain resolution. | | Application configuration | [internal/core/config](../../internal/core/config/) | Composed ConfigKit/native settings definition, source-aware normalization, detached runtime conversion, application validation, effective domain resolution. |
| Generic source and typed contracts | [internal/core/source](../../internal/core/source/), [internal/framework/contracts](../../internal/framework/contracts/) | Documents/units/chunks, typed production/assessment, source references, codecs, native execution selections, and small cache/evidence collaborators. | | Generic source and typed contracts | [internal/core/source](../../internal/core/source/), [internal/framework/contracts](../../internal/framework/contracts/) | Documents/units/chunks, typed production/assessment, source references, codecs, native execution selections, and small cache/evidence collaborators. |
| Pipeline framework | [internal/framework/pipeline](../../internal/framework/pipeline/) | Registries, typed resolution/preparation, complete candidate assessment, native producer helper, ready-job workers, ordered handoffs, reuse eligibility, evidence/output assembly. | | Pipeline framework | [internal/framework/pipeline](../../internal/framework/pipeline/) | Registries, typed resolution, core-invoked preparation and execution, complete candidate assessment, ready-job workers, ordered handoffs, reuse eligibility, evidence/output assembly. |
| Offline dependency preflight | [internal/preflight](../../internal/preflight/) | Known native prompt/profile checks on already resolved composition and supplied engine; no synthetic request or execution input reads. | | Offline dependency preflight | [internal/preflight](../../internal/preflight/) | Known native prompt/profile checks on already resolved composition and supplied engine; no synthetic request or execution input reads. |
| Semantic reconciliation | [internal/framework/semanticreconcile](../../internal/framework/semanticreconcile/) | Fixed bounded candidate/window preparation, native request builders, request-local handle/proposal safety, and typed fresh application. | | Semantic reconciliation | [internal/framework/semanticreconcile](../../internal/framework/semanticreconcile/) | Prepared reconciliation operations, bounded candidate/window inputs, request-local proposal safety, typed fresh application, and evaluation-scoped details. |
| Embedded content | [assets](../../assets/) | Content-only native prompt/profile/schema/message files imported with filesystem contexts; no behavioral registry. | | Embedded content | [assets](../../assets/) | Content-only native prompt/profile/schema/message files imported with filesystem contexts; no behavioral registry. |
| Accepted-result cache | [internal/framework/artifactcache](../../internal/framework/artifactcache/) | Raw accepted artifact/plan bytes under native content keys, confined atomic publication, and deployment-owned creation permissions. | | Accepted-result cache | [internal/framework/artifactcache](../../internal/framework/artifactcache/) | Raw accepted artifact/plan bytes under native content keys, confined atomic publication, and deployment-owned creation permissions. |
| Capture and file placement | [internal/core/fileio](../../internal/core/fileio/), [internal/core/debugbundle](../../internal/core/debugbundle/), [internal/framework/debug](../../internal/framework/debug/) | Confined writes, run capture allocation/start-time latest link, incremental evidence, one terminalization, and retained causes. | | Capture and file placement | [internal/core/fileio](../../internal/core/fileio/), [internal/core/debugbundle](../../internal/core/debugbundle/), [internal/framework/debug](../../internal/framework/debug/) | Confined writes, run capture allocation/start-time latest link, incremental evidence, one terminalization, and retained causes. |

View File

@@ -55,13 +55,12 @@ a separate composition check, not request execution or module construction.
## Typed Operations And Assessment ## Typed Operations And Assessment
[Typed contracts](../../internal/framework/contracts/typed_pipeline.go) carry [Typed stage contracts](../../internal/framework/contracts/typed_pipeline.go)
a `ProducerOperation[T]` with resolved controls, one assessor, native execution expose preparation. The runner binds resolved controls, assessment, native
options, incoming reuse eligibility, and an optional typed cache binding. execution, reuse eligibility, and cache in a private execution context.
[Runner operation completion](../../internal/framework/pipeline/runner_operation.go) [The core executor](../../internal/framework/pipeline/operation.go) invokes
assesses deterministic production directly. Model modules use preparation and handles deterministic and model operations alike; modules do
[RunProducer](../../internal/framework/pipeline/producer.go); the runner consumes not select execution collaborators or claim acceptance.
its acceptance/fallback outcome without assessing it again.
[Candidate assessment](../../internal/framework/pipeline/candidate_assessment.go) [Candidate assessment](../../internal/framework/pipeline/candidate_assessment.go)
invokes each applicable validator once in configured order. It continues after invokes each applicable validator once in configured order. It continues after
@@ -83,13 +82,13 @@ on the shared engine and do not own another semantic loop.
## Native Continuation And Terminal Handling ## Native Continuation And Terminal Handling
For executed model work, `RunProducer` checks native errors and structural For executed model work, the [native executor](../../internal/framework/pipeline/operation_native.go) checks native errors and structural
validation status before interpretation, including a failed result with no Go validation status before interpretation, including a failed result with no Go
error. Module interpretation produces a usable typed candidate and any actionable error. Module interpretation produces a usable typed candidate and any actionable
domain guidance. The assessor runs the complete chain on every delivered usable domain guidance. The assessor runs the complete chain on every delivered usable
candidate, including unchanged revisions and the final allowed response. candidate, including unchanged revisions and the final allowed response.
When correction is possible, the helper starts native `Coordinate` from the When correction is possible, core starts native `Coordinate` from the
captured exchange. Its first callback reuses already-collected initial findings. captured exchange. Its first callback reuses already-collected initial findings.
Native coordination owns turn iteration and growing history; the module builds Native coordination owns turn iteration and growing history; the module builds
only new correction material from fixed operation inputs. Successful native only new correction material from fixed operation inputs. Successful native
@@ -105,7 +104,7 @@ recover an earlier candidate; caller cancellation and undelivered responses
produce no acceptance/fallback. Native operational timeouts retain typed causes produce no acceptance/fallback. Native operational timeouts retain typed causes
rather than becoming caller cancellation solely by error spelling. rather than becoming caller cancellation solely by error spelling.
Deterministic work produces once, then uses direct assessment and any supported Deterministic work produces once, then uses core assessment and any supported
module fallback. An operation/parse/materialization/encoding error remains an module fallback. An operation/parse/materialization/encoding error remains an
error, not a generic rerun or permissive recovery mechanism. error, not a generic rerun or permissive recovery mechanism.

View File

@@ -22,7 +22,7 @@ persisted resume ledger.
## Prepared Result Reuse ## Prepared Result Reuse
[RunProducer](../../internal/framework/pipeline/producer.go) owns native request [Core native execution](../../internal/framework/pipeline/operation_native.go) owns native request
selection and cache interaction for an eligible model operation: selection and cache interaction for an eligible model operation:
1. Prepare the initial request once with `PrepareExecution`, retain its detached 1. Prepare the initial request once with `PrepareExecution`, retain its detached

View File

@@ -828,6 +828,10 @@ and `go test -race ./internal/framework/pipeline ./internal/framework/semanticre
## Stage 22 — Provide The Working Author Example And Internal Guides ## Stage 22 — Provide The Working Author Example And Internal Guides
**Status:** Complete. The registered domain-neutral message example exercises
contextual correction and deterministic completion through core. Pipeline tests
pass, and affected internal-guide paths and API references were checked.
**Goal:** Make the new boundary usable without reading producer implementation. **Goal:** Make the new boundary usable without reading producer implementation.
**Inspect:** Stage 1's non-D&D sketches, actual finished APIs, and current **Inspect:** Stage 1's non-D&D sketches, actual finished APIs, and current

View File

@@ -0,0 +1,205 @@
package pipeline_test
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
"go.maximumdirect.net/configkit"
"go.maximumdirect.net/promptkit"
)
// This fixture is a small end-to-end authoring example for generic messages.
// Its domain interpretation uses source metadata and ordinary text chunks.
type messageTopic struct {
Topic string `json:"topic"`
}
const topicKind contracts.ArtifactKind = "example/message-topic"
type topicCodec struct{}
func (topicCodec) Kind() contracts.ArtifactKind { return topicKind }
func (topicCodec) Schema() contracts.ArtifactSchema {
return contracts.ArtifactSchema{ID: "example.message-topic", Name: "example_message_topic", Version: "v1", JSONSchema: []byte(`{"type":"object","properties":{"topic":{"type":"string"}},"required":["topic"]}`)}
}
func (topicCodec) MediaType() string { return "application/json" }
func (topicCodec) Encode(value messageTopic) ([]byte, error) { return json.Marshal(value) }
func (codec topicCodec) EncodeCandidate(value messageTopic) ([]byte, error) {
return codec.Encode(value)
}
func (topicCodec) Decode(content []byte) (messageTopic, error) {
var value messageTopic
err := json.Unmarshal(content, &value)
return value, err
}
func (codec topicCodec) DecodeCandidate(content []byte) (messageTopic, error) {
return codec.Decode(content)
}
func deterministic[T any](value T) contracts.PreparedOperation[T] {
return contracts.DeterministicOperation[T]{Evaluation: contracts.CandidateEvaluation[T]{Result: contracts.EvaluationView[T]{Candidate: &value}}}
}
type messageInput struct{ document *source.SourceDocument }
func (messageInput) Key() string { return "example/input" }
func (input messageInput) Parse(context.Context, contracts.ParseRequest) (*source.SourceDocument, error) {
return input.document, nil
}
type messageChunker struct{}
func (messageChunker) Key() string { return "example/chunk" }
func (messageChunker) ReferenceSlots() []contracts.ReferenceSlot { return nil }
func (messageChunker) PrepareChunk(_ context.Context, input contracts.ChunkInput) (contracts.PreparedOperation[source.ChunkPlan], error) {
return deterministic(source.ChunkPlan{SourceDigest: input.Source.Digest, Ranges: []source.ChunkRange{{StartUnitID: input.Source.Units[0].ID, EndUnitID: input.Source.Units[len(input.Source.Units)-1].ID}}}), nil
}
type topicExtractor struct{}
func (topicExtractor) Key() string { return "example/topic" }
func (topicExtractor) ReferenceSlots() []contracts.ReferenceSlot { return nil }
func (topicExtractor) PrepareExtraction(_ context.Context, input contracts.ExtractionInput) (contracts.PreparedOperation[messageTopic], error) {
subject, _ := input.Source.Metadata["subject"].(string)
if subject == "automatic notice" {
return deterministic(messageTopic{Topic: "notice"}), nil
}
initial := promptkit.RunRequest{PromptID: "message-topic-initial", ProfileID: input.LLMProfile, SessionID: input.SessionID, Inputs: map[string]promptkit.ArtifactRef{"message": promptkit.Inline(string(input.Chunk.Content)), "subject": promptkit.Inline(subject)}}
return contracts.NativeOperation[messageTopic]{Initial: initial,
Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[messageTopic], error) {
var value messageTopic
if err := json.Unmarshal([]byte(result.RawOutput), &value); err != nil {
return nil, err
}
if value.Topic == "unknown" {
return contracts.CandidateEvaluation[messageTopic]{Result: contracts.EvaluationView[messageTopic]{Guidance: []string{"Use the message subject: " + subject + "."}}}, nil
}
return contracts.CandidateEvaluation[messageTopic]{Result: contracts.EvaluationView[messageTopic]{Candidate: &value}}, nil
}, Correction: contracts.PromptCorrection("message-topic-correction", "assignment", func(guidance []string) promptkit.ArtifactRef { return promptkit.Inline(strings.Join(guidance, "\n")) }),
}, nil
}
type topicMerge struct{}
func (topicMerge) Key() string { return "example/merge" }
func (topicMerge) PrepareMerge(_ context.Context, input contracts.MergeInput[messageTopic]) (contracts.PreparedOperation[messageTopic], error) {
return deterministic(input.ExtractOutputs[0].Value), nil
}
type topicNormalize struct{}
func (topicNormalize) Key() string { return "example/normalize" }
func (topicNormalize) ReferenceSlots() []contracts.ReferenceSlot { return nil }
func (topicNormalize) PrepareNormalize(_ context.Context, input contracts.NormalizeInput[messageTopic]) (contracts.PreparedOperation[messageTopic], error) {
return deterministic(input.MergeOutput.Value), nil
}
type topicOutput struct{ values *[]contracts.SerializedOutput }
func (topicOutput) Key() string { return "example/output" }
func (output topicOutput) Encode(_ context.Context, input contracts.OutputRequest) (contracts.OutputResult, error) {
*output.values = input.NormalizeOutputs
return contracts.OutputResult{}, nil
}
type topicProvider struct {
calls int
correction string
}
func (provider *topicProvider) Generate(_ context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
provider.calls++
if provider.calls == 1 {
return &promptkit.GenerateResponse{Content: `{"topic":"unknown"}`}, nil
}
for _, message := range request.Prompt.Messages {
provider.correction += message.Content
}
return &promptkit.GenerateResponse{Content: `{"topic":"weather"}`}, nil
}
func TestRegisteredMessageTopicExample(t *testing.T) {
settings := `profiles:
- id: example
endpoint: https://example.invalid/v1
model: local-fake
api_key_required: false
prompts:
- id: message-topic-initial
default_profile: example
inputs: [{name: message, required: true}, {name: subject, required: true}]
messages:
- {role: user, content: '{{input "subject"}}: {{input "message"}}'}
output: {format: json, validation_mode: json, repair_attempts: 0}
- id: message-topic-correction
default_profile: example
inputs: [{name: assignment, required: true}]
messages:
- {role: user, content: '{{input "assignment"}}'}
output: {format: json, validation_mode: json, repair_attempts: 0}
`
provider := &topicProvider{}
engine, err := promptkit.NewEngine(promptkit.Config{Sources: promptkit.ConfigurationSources{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{promptkit.SettingsInput(configkit.Bytes("example", []byte(settings)))}}}}}, promptkit.WithBundledOpenRouter(false), promptkit.WithLLMClient(provider))
if err != nil {
var load *configkit.LoadError
if errors.As(err, &load) {
t.Fatalf("%v: %#v", err, load.Diagnostics())
}
t.Fatal(err)
}
for _, test := range []struct {
subject, want string
calls int
}{{"forecast discussion", "weather", 2}, {"automatic notice", "notice", 0}} {
t.Run(test.subject, func(t *testing.T) {
provider.calls, provider.correction = 0, ""
doc := &source.SourceDocument{ID: "message", Kind: "email", Format: "text/plain", Metadata: map[string]any{"subject": test.subject}, Units: []source.SourceUnit{{ID: 1, Kind: "text", Text: "Rain is expected.", Ref: source.SourceRef{SourceID: "message", StartUnitID: 1, EndUnitID: 1}}}}
doc.Digest, err = source.DigestDocument(doc)
if err != nil {
t.Fatal(err)
}
catalog := pipeline.ModuleCatalog{Inputs: pipeline.NewInputAdapterRegistry(), Chunkers: pipeline.NewChunkerRegistry(), ArtifactCodecs: pipeline.NewArtifactCodecRegistry(), Extractors: pipeline.NewExtractorRegistry(), Mergers: pipeline.NewMergerRegistry(), Normalizers: pipeline.NewNormalizerRegistry(), Validators: pipeline.NewValidatorRegistry(), ValidatorChains: pipeline.NewValidatorChainRegistry(), Outputs: pipeline.NewOutputEncoderRegistry()}
check := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
check(catalog.Inputs.RegisterWithSpec(pipeline.ModuleSpec{Key: "example/input", Stage: pipeline.StageInput, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.InputAdapter, error) { return messageInput{doc}, nil }))
check(catalog.Chunkers.RegisterWithSpec(pipeline.ModuleSpec{Key: "example/chunk", Stage: pipeline.StageChunk, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Chunker, error) { return messageChunker{}, nil }))
check(pipeline.RegisterArtifactCodec(catalog.ArtifactCodecs, topicCodec{}))
check(pipeline.RegisterExtractor(catalog.Extractors, pipeline.ModuleSpec{Key: "example/topic", Stage: pipeline.StageExtract, ArtifactKind: topicKind, ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{"message-topic-initial", "message-topic-correction"}}, func() (contracts.Extractor[messageTopic], error) { return topicExtractor{}, nil }))
check(pipeline.RegisterMerger(catalog.Mergers, pipeline.ModuleSpec{Key: "example/merge", Stage: pipeline.StageMerge, ArtifactKind: topicKind, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Merger[messageTopic], error) { return topicMerge{}, nil }))
check(pipeline.RegisterNormalizer(catalog.Normalizers, pipeline.ModuleSpec{Key: "example/normalize", Stage: pipeline.StageNormalize, ArtifactKind: topicKind, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Normalizer[messageTopic], error) { return topicNormalize{}, nil }))
var output []contracts.SerializedOutput
check(catalog.Outputs.RegisterWithSpec(pipeline.ModuleSpec{Key: "example/output", Stage: pipeline.StageOutput, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.OutputEncoder, error) { return topicOutput{&output}, nil }))
turns := 1
profile := pipeline.PipelineProfile{ID: "example", Input: pipeline.Binding("example/input"), Chunk: pipeline.Binding("example/chunk"), Output: pipeline.Binding("example/output"), LLMProfile: "example", MaxAdditionalTurns: &turns, Artifacts: map[string]pipeline.ArtifactLaneProfile{"topics": {Extract: pipeline.Binding("example/topic"), Merge: pipeline.Binding("example/merge"), Normalize: pipeline.Binding("example/normalize")}}}
resolved, err := pipeline.ResolvePipeline(profile, pipeline.ResolveOptions{}, catalog)
check(err)
resolved, _, err = pipeline.MaterializeReferences(resolved, catalog, pipeline.ReferenceMaterializationOptions{})
check(err)
prepared, err := pipeline.Prepare(resolved, pipeline.Registries{Inputs: catalog.Inputs, Chunkers: catalog.Chunkers, ArtifactCodecs: catalog.ArtifactCodecs, Extractors: catalog.Extractors, Mergers: catalog.Mergers, Normalizers: catalog.Normalizers, Validators: catalog.Validators, ValidatorChains: catalog.ValidatorChains, Outputs: catalog.Outputs}, pipeline.ModuleDependencies{Engine: engine})
check(err)
_, err = pipeline.New().Run(context.Background(), pipeline.RunInput{Prepared: prepared, RawInput: []byte("message"), Workers: 1})
check(err)
if len(output) != 1 {
t.Fatalf("outputs = %#v", output)
}
value, err := (topicCodec{}).Decode(output[0].Artifact.Content)
check(err)
if value.Topic != test.want || provider.calls != test.calls {
t.Fatalf("topic=%q calls=%d", value.Topic, provider.calls)
}
if test.calls > 0 && !strings.Contains(provider.correction, "Use the message subject") {
t.Fatal("correction assignment did not carry interpretation guidance")
}
})
}
}