Document core operation authoring with a working example
This commit is contained in:
205
internal/framework/pipeline/author_example_test.go
Normal file
205
internal/framework/pipeline/author_example_test.go
Normal 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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user