Route spell extraction through core preparation with remaining extractors pending
This commit is contained in:
@@ -65,15 +65,11 @@ var _ contracts.Extractor[dnd.SpellList] = (*Extractor)(nil)
|
||||
type Options struct{}
|
||||
|
||||
type Extractor struct {
|
||||
engine *promptkit.Engine
|
||||
catalogPromptInput []byte
|
||||
npcResolver *npcregistry.Resolver
|
||||
}
|
||||
|
||||
func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
|
||||
if engine == nil {
|
||||
return nil, extractorErrorf("native engine must not be nil")
|
||||
}
|
||||
func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
|
||||
if len(references) > 1 {
|
||||
return nil, extractorErrorf("at most one reference set may be supplied")
|
||||
}
|
||||
@@ -93,7 +89,7 @@ func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceS
|
||||
if err != nil {
|
||||
return nil, extractorErrorf("prepare NPC registry prompt input: %w", err)
|
||||
}
|
||||
return &Extractor{engine: engine, catalogPromptInput: catalogPromptInput, npcResolver: npcResolver}, nil
|
||||
return &Extractor{catalogPromptInput: catalogPromptInput, npcResolver: npcResolver}, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) Key() string {
|
||||
@@ -104,22 +100,19 @@ func (e *Extractor) ReferenceSlots() []contracts.ReferenceSlot {
|
||||
return referenceSlots()
|
||||
}
|
||||
|
||||
func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRequest[dnd.SpellList]) (contracts.TypedExtractionResult[dnd.SpellList], error) {
|
||||
func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.ExtractionInput) (contracts.PreparedOperation[dnd.SpellList], error) {
|
||||
if e == nil {
|
||||
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("extractor must not be nil")
|
||||
return nil, extractorErrorf("extractor must not be nil")
|
||||
}
|
||||
if e.engine == nil {
|
||||
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("native engine must not be nil")
|
||||
}
|
||||
sourceInput, err := shared.PrepareChunkExtraction(ctx, req)
|
||||
sourceInput, err := shared.PrepareChunkInput(ctx, req)
|
||||
if err != nil {
|
||||
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("%w", err)
|
||||
return nil, extractorErrorf("%w", err)
|
||||
}
|
||||
sourceID := req.Source.ID
|
||||
order := shared.NewSourceRefOrder(req.Source)
|
||||
npcRegistry, err := e.npcResolver.Resolve(req.References)
|
||||
if err != nil {
|
||||
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("resolve NPC registry: %w", err)
|
||||
return nil, extractorErrorf("resolve NPC registry: %w", err)
|
||||
}
|
||||
|
||||
materials := shared.PromptInputs(sourceInput, req.References)
|
||||
@@ -131,29 +124,22 @@ func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRe
|
||||
registryInput := npcRegistry.PromptInput()
|
||||
inputs[NPCRegistryReferenceSlot] = promptkit.Inline(string(registryInput.Content))
|
||||
initial := promptkit.RunRequest{PromptID: PromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, Inputs: inputs}
|
||||
value, outcome, err := pipeline.RunProducer(ctx, e.engine, req.Operation, initial,
|
||||
func(_ context.Context, result *promptkit.RunResult) (*dnd.SpellList, []string, error) {
|
||||
return contracts.NativeOperation[dnd.SpellList]{Initial: initial,
|
||||
Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[dnd.SpellList], error) {
|
||||
var response extractionResponse
|
||||
if err := json.Unmarshal([]byte(result.RawOutput), &response); err != nil {
|
||||
return nil, nil, extractorErrorf("decode native output: %w", err)
|
||||
return nil, extractorErrorf("decode native output: %w", err)
|
||||
}
|
||||
canonicalizeResponse(&response, order, sourceID)
|
||||
value := canonicalSpellList(response, sourceID)
|
||||
return &value, nil, nil
|
||||
return contracts.CandidateEvaluation[dnd.SpellList]{Result: contracts.EvaluationView[dnd.SpellList]{Candidate: &value}}, nil
|
||||
},
|
||||
func(_ context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
return promptkit.RunRequest{
|
||||
PromptID: CorrectionPromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID,
|
||||
Inputs: map[string]promptkit.ArtifactRef{"guidance": promptkit.Inline(strings.Join(guidance, "\n\n"))},
|
||||
}, nil
|
||||
},
|
||||
func(context.Context, *dnd.SpellList) (dnd.SpellList, error) {
|
||||
Correction: contracts.PromptCorrection(CorrectionPromptID, "guidance", func(guidance []string) promptkit.ArtifactRef {
|
||||
return promptkit.Inline(strings.Join(guidance, "\n\n"))
|
||||
}),
|
||||
Fallback: func(context.Context, contracts.Evaluation[dnd.SpellList]) (dnd.SpellList, error) {
|
||||
return dnd.SpellList{SpellCasts: []dnd.SpellCast{}}, nil
|
||||
})
|
||||
if err != nil {
|
||||
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("produce spells: %w", err)
|
||||
}
|
||||
return contracts.TypedExtractionResult[dnd.SpellList]{Value: value, Outcome: outcome}, nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func ModuleSpec() pipeline.ModuleSpec {
|
||||
@@ -175,7 +161,7 @@ func Register(registry *pipeline.ExtractorRegistry) error {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(request.Dependencies.Engine, options, request.References)
|
||||
return New(options, request.References)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ func TestExtractReturnsCanonicalSpellListFromPrivateResponse(t *testing.T) {
|
||||
req.Operation.Execution.OnPrepared = func(_ context.Context, value promptkit.PreparedRun) { prepared = value }
|
||||
|
||||
extractor := newExtractor(t, client)
|
||||
result, err := extractor.Extract(context.Background(), req)
|
||||
result, err := runExtraction(context.Background(), extractor, req)
|
||||
if err != nil {
|
||||
t.Fatalf("Extract() error = %v, want nil", err)
|
||||
}
|
||||
@@ -88,7 +88,7 @@ func TestExtractReturnsCanonicalSpellListFromPrivateResponse(t *testing.T) {
|
||||
func TestExtractPromptProjectsCanonicalNamesAndAliasesWithoutMetadata(t *testing.T) {
|
||||
client := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}}
|
||||
extractor := newExtractor(t, client, overlaySpellCatalogReference())
|
||||
if _, err := extractor.Extract(context.Background(), extractionRequest()); err != nil {
|
||||
if _, err := runExtraction(context.Background(), extractor, extractionRequest()); err != nil {
|
||||
t.Fatalf("Extract() error = %v, want nil", err)
|
||||
}
|
||||
input := extractor.catalogPromptInput
|
||||
@@ -126,7 +126,7 @@ func TestExtractUsesAliasRecognitionToRequestCanonicalSpellNames(t *testing.T) {
|
||||
request.Chunk.Content = []byte(`{"segments":[{"id":1,"text":"Aria invokes Emberfall Aegis."}]}`)
|
||||
request.SourceInput = spellChunkInput(request.Chunk)
|
||||
|
||||
result, err := newExtractor(t, client, overlaySpellCatalogReference()).Extract(context.Background(), request)
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client, overlaySpellCatalogReference()), request)
|
||||
if err != nil {
|
||||
t.Fatalf("Extract() error = %v, want nil", err)
|
||||
}
|
||||
@@ -145,10 +145,10 @@ func TestExtractAliasOnlyCatalogChangesPromptMaterial(t *testing.T) {
|
||||
aliasClient := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}}
|
||||
baseExtractor := newExtractor(t, baseClient)
|
||||
aliasExtractor := newExtractor(t, aliasClient, aliasReference)
|
||||
if _, err := baseExtractor.Extract(context.Background(), extractionRequest()); err != nil {
|
||||
if _, err := runExtraction(context.Background(), baseExtractor, extractionRequest()); err != nil {
|
||||
t.Fatalf("base Extract() error = %v", err)
|
||||
}
|
||||
if _, err := aliasExtractor.Extract(context.Background(), extractionRequest()); err != nil {
|
||||
if _, err := runExtraction(context.Background(), aliasExtractor, extractionRequest()); err != nil {
|
||||
t.Fatalf("alias Extract() error = %v", err)
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ func TestExtractAliasOnlyCatalogChangesPromptMaterial(t *testing.T) {
|
||||
|
||||
func TestNewRejectsMalformedCatalogBeforeLLMCall(t *testing.T) {
|
||||
client := &fakeSpellsLLMClient{}
|
||||
_, err := New(newSpellEngine(t, client), Options{}, spellCatalogReference(`{"schema_version":"notarius.dnd.spell-catalog-overlay.v2","catalogs":[]}`))
|
||||
_, err := New(Options{}, spellCatalogReference(`{"schema_version":"notarius.dnd.spell-catalog-overlay.v2","catalogs":[]}`))
|
||||
if err == nil || !strings.Contains(err.Error(), "resolve effective spell catalog") {
|
||||
t.Fatalf("New() error = %v, want effective catalog error", err)
|
||||
}
|
||||
@@ -179,7 +179,7 @@ func TestExtractPassesReferencesAsPromptInputs(t *testing.T) {
|
||||
"glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Brightmantle: local temple name")}}},
|
||||
}}
|
||||
|
||||
if _, err := newExtractor(t, client).Extract(context.Background(), req); err != nil {
|
||||
if _, err := runExtraction(context.Background(), newExtractor(t, client), req); err != nil {
|
||||
t.Fatalf("Extract() error = %v, want nil", err)
|
||||
}
|
||||
text := promptText(client.requests[0])
|
||||
@@ -203,7 +203,7 @@ func TestPromptInputsMapLegacyRosterReferenceToParty(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestExtractPreservesValidEmptyCollection(t *testing.T) {
|
||||
result, err := newExtractor(t, &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[]}`)}).Extract(context.Background(), extractionRequest())
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[]}`)}), extractionRequest())
|
||||
if err != nil || result.Value.SpellCasts == nil || len(result.Value.SpellCasts) != 0 {
|
||||
t.Fatalf("empty collection: %#v %v", result, err)
|
||||
}
|
||||
@@ -220,7 +220,7 @@ func TestExtractDoesNotAssessNativeStructuralFailure(t *testing.T) {
|
||||
assessed++
|
||||
return contracts.CandidateAssessment{}, nil
|
||||
}
|
||||
result, err := newExtractor(t, client).Extract(context.Background(), request)
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), request)
|
||||
if assessed != 0 {
|
||||
t.Fatal("structurally invalid native result reached typed validation")
|
||||
}
|
||||
@@ -237,8 +237,8 @@ func TestExtractDoesNotAssessNativeStructuralFailure(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestExtractWrapsLLMClientError(t *testing.T) {
|
||||
_, err := newExtractor(t, &fakeSpellsLLMClient{err: errors.New("provider unavailable")}).Extract(context.Background(), extractionRequest())
|
||||
if err == nil || !strings.Contains(err.Error(), "dnd spells") || !strings.Contains(err.Error(), "provider unavailable") {
|
||||
_, err := runExtraction(context.Background(), newExtractor(t, &fakeSpellsLLMClient{err: errors.New("provider unavailable")}), extractionRequest())
|
||||
if err == nil || !strings.Contains(err.Error(), "provider unavailable") {
|
||||
t.Fatalf("Extract() error = %v, want wrapped provider error", err)
|
||||
}
|
||||
}
|
||||
@@ -246,21 +246,20 @@ func TestExtractWrapsLLMClientError(t *testing.T) {
|
||||
func TestExtractRejectsInvalidRequests(t *testing.T) {
|
||||
validReq := extractionRequest()
|
||||
validExtractor := newExtractor(t, &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}})
|
||||
var nilExtractor *Extractor
|
||||
nilExtractor := &extractionFixture{engine: newSpellEngine(t, &fakeSpellsLLMClient{})}
|
||||
tests := []struct {
|
||||
name string
|
||||
extractor *Extractor
|
||||
extractor *extractionFixture
|
||||
ctx context.Context
|
||||
req contracts.TypedExtractionRequest[dnd.SpellList]
|
||||
want string
|
||||
}{
|
||||
{name: "nil extractor", extractor: nilExtractor, ctx: context.Background(), req: validReq, want: "extractor"},
|
||||
{name: "nil native engine", extractor: &Extractor{}, ctx: context.Background(), req: validReq, want: "native engine"},
|
||||
{name: "wrapped preflight failure", extractor: validExtractor, ctx: context.Background(), req: mismatchedSourceInputRequest(validReq), want: "must match chunk"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, err := test.extractor.Extract(test.ctx, test.req)
|
||||
_, err := runExtraction(test.ctx, test.extractor, test.req)
|
||||
if err == nil || !strings.Contains(err.Error(), "dnd spells") || !strings.Contains(err.Error(), test.want) {
|
||||
t.Fatalf("Extract() error = %v, want %q context", err, test.want)
|
||||
}
|
||||
@@ -274,7 +273,7 @@ func TestExtractOrdersAndDeduplicatesEvidence(t *testing.T) {
|
||||
{Caster: "Aria", Spell: "Cure Wounds", SourceRefs: []spellSourceRefResponse{{StartUnitID: 1, EndUnitID: 2}, {StartUnitID: 1, EndUnitID: 2}}},
|
||||
{Caster: "Narrator", Spell: "Unknown", SourceRefs: []spellSourceRefResponse{}},
|
||||
}}}
|
||||
result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest())
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest())
|
||||
if err != nil {
|
||||
t.Fatalf("Extract() error = %v, want nil", err)
|
||||
}
|
||||
@@ -302,7 +301,7 @@ func TestExtractUsesDocumentOrderForReferencesAndSpellCasts(t *testing.T) {
|
||||
req.Chunk.Units = append([]source.SourceUnit(nil), req.Source.Units...)
|
||||
req.Chunk.Ref = source.SourceRef{SourceID: req.Source.ID, StartUnitID: 30, EndUnitID: 10}
|
||||
|
||||
result, err := newExtractor(t, client).Extract(context.Background(), req)
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), req)
|
||||
if err != nil {
|
||||
t.Fatalf("Extract() error = %v", err)
|
||||
}
|
||||
@@ -328,7 +327,7 @@ func TestExtractPreservesStableSpellOrderForEqualEvidence(t *testing.T) {
|
||||
{Caster: "First", Spell: "Cure Wounds", SourceRefs: responseSourceRefs(2, 2)},
|
||||
{Caster: "Second", Spell: "Fire Bolt", SourceRefs: responseSourceRefs(2, 2)},
|
||||
}}}
|
||||
result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest())
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest())
|
||||
if err != nil {
|
||||
t.Fatalf("Extract() error = %v", err)
|
||||
}
|
||||
@@ -342,7 +341,7 @@ func TestExtractPreservesInvalidEvidenceForValidators(t *testing.T) {
|
||||
Caster: "Aria", Spell: "Cure Wounds",
|
||||
SourceRefs: []spellSourceRefResponse{{StartUnitID: 99, EndUnitID: 0}},
|
||||
}}}}
|
||||
result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest())
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest())
|
||||
if err != nil {
|
||||
t.Fatalf("Extract() error = %v, want nil", err)
|
||||
}
|
||||
@@ -354,7 +353,7 @@ func TestExtractPreservesInvalidEvidenceForValidators(t *testing.T) {
|
||||
|
||||
func TestExtractMapsRawSemanticCandidatesWithoutRepair(t *testing.T) {
|
||||
client := &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[{"caster":"","spell":"Cure Wounds","source_refs":[{"start_unit_id":0,"end_unit_id":-1}]}]}`)}
|
||||
result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest())
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest())
|
||||
if err != nil {
|
||||
t.Fatalf("Extract() error = %v, want nil", err)
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ func TestSpellExtractorProjectsNPCNamesWithoutIdentityOrProvenance(t *testing.T)
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
client := &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[]}`)}
|
||||
if _, err := newExtractor(t, client, test.references).Extract(context.Background(), extractionRequest()); err != nil {
|
||||
if _, err := runExtraction(context.Background(), newExtractor(t, client, test.references), extractionRequest()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := promptText(client.requests[0])
|
||||
@@ -65,13 +65,13 @@ func TestSpellExtractorResolvesOperationNPCOverride(t *testing.T) {
|
||||
extractor := newExtractor(t, client)
|
||||
request := extractionRequest()
|
||||
request.References = spellNPCRegistryReference(canonical, "file:///generated.json")
|
||||
if _, err := extractor.Extract(context.Background(), request); err != nil {
|
||||
if _, err := runExtraction(context.Background(), extractor, request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(promptText(client.requests[0]), `{"npcs":[{"name":"Mira Thorn"}]}`) {
|
||||
t.Fatal("missing operation NPC projection")
|
||||
}
|
||||
if _, err := extractor.Extract(context.Background(), extractionRequest()); err != nil {
|
||||
if _, err := runExtraction(context.Background(), extractor, extractionRequest()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(promptText(client.requests[1]), `{"npcs":[]}`) {
|
||||
|
||||
117
internal/modules/dnd/extract/spells/registered_execution_test.go
Normal file
117
internal/modules/dnd/extract/spells/registered_execution_test.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package spells
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
spellcodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/spells"
|
||||
)
|
||||
|
||||
type pilotInput struct{ document *source.SourceDocument }
|
||||
|
||||
func (pilotInput) Key() string { return "pilot/input" }
|
||||
func (input pilotInput) Parse(context.Context, contracts.ParseRequest) (*source.SourceDocument, error) {
|
||||
return input.document, nil
|
||||
}
|
||||
|
||||
type pilotChunker struct{}
|
||||
|
||||
func (pilotChunker) Key() string { return "pilot/chunk" }
|
||||
func (pilotChunker) ReferenceSlots() []contracts.ReferenceSlot { return nil }
|
||||
func (pilotChunker) Plan(_ context.Context, request contracts.ChunkRequest) (contracts.ChunkPlanResult, error) {
|
||||
return contracts.ChunkPlanResult{Plan: source.ChunkPlan{SourceDigest: request.Source.Digest, Ranges: []source.ChunkRange{{StartUnitID: request.Source.Units[0].ID, EndUnitID: request.Source.Units[len(request.Source.Units)-1].ID}}}}, nil
|
||||
}
|
||||
|
||||
type pilotMerger struct{}
|
||||
|
||||
func (pilotMerger) Key() string { return "pilot/merge" }
|
||||
func (pilotMerger) Merge(_ context.Context, request contracts.TypedMergeRequest[dnd.SpellList]) (contracts.TypedMergeResult[dnd.SpellList], error) {
|
||||
return contracts.TypedMergeResult[dnd.SpellList]{Value: request.ExtractOutputs[0].Value}, nil
|
||||
}
|
||||
|
||||
type pilotNormalizer struct{}
|
||||
|
||||
func (pilotNormalizer) Key() string { return "pilot/normalize" }
|
||||
func (pilotNormalizer) ReferenceSlots() []contracts.ReferenceSlot { return nil }
|
||||
func (pilotNormalizer) Normalize(_ context.Context, request contracts.TypedNormalizeRequest[dnd.SpellList]) (contracts.TypedNormalizeResult[dnd.SpellList], error) {
|
||||
return contracts.TypedNormalizeResult[dnd.SpellList]{Value: request.MergeOutput.Value}, nil
|
||||
}
|
||||
|
||||
type pilotOutput struct{}
|
||||
|
||||
func (pilotOutput) Key() string { return "pilot/output" }
|
||||
func (pilotOutput) Encode(context.Context, contracts.OutputRequest) (contracts.OutputResult, error) {
|
||||
return contracts.OutputResult{}, nil
|
||||
}
|
||||
|
||||
type pilotValidator struct{ assessments *int }
|
||||
|
||||
func (pilotValidator) Name() string { return "pilot/check" }
|
||||
func (pilotValidator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (validator pilotValidator) Validate(_ context.Context, request contracts.TypedValidationRequest[dnd.SpellList]) (contracts.ValidationResult, error) {
|
||||
*validator.assessments++
|
||||
if len(request.Value.SpellCasts) == 0 {
|
||||
return contracts.ValidationResult{ReasonCode: "missing_spell", CorrectionGuidance: "Return the observed spell."}, nil
|
||||
}
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
|
||||
type pilotCache map[string][]byte
|
||||
|
||||
func (cache pilotCache) Lookup(_ context.Context, _ contracts.CacheMode, key string) ([]byte, error) {
|
||||
return cache[key], nil
|
||||
}
|
||||
func (cache pilotCache) Store(_ context.Context, _ contracts.CacheMode, key string, value []byte) error {
|
||||
cache[key] = append([]byte(nil), value...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestRegisteredSpellExtractionCorrectsAndReusesAcceptedOutput(t *testing.T) {
|
||||
doc := promptSourceDocument()
|
||||
var err error
|
||||
doc.Digest, err = source.DigestDocument(doc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &fakeSpellsLLMClient{outputs: []string{`{"spell_casts":[]}`, `{"spell_casts":[{"caster":"Aria","spell":"Cure Wounds","source_refs":[{"start_unit_id":1,"end_unit_id":1}]}]}`}}
|
||||
engine := newSpellEngine(t, client)
|
||||
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: "pilot/input", Stage: pipeline.StageInput, ExecutionClass: contracts.ExecutionClassDeterministic, Provides: []string{"source.transcript"}}, func() (contracts.InputAdapter, error) { return pilotInput{doc}, nil }))
|
||||
check(catalog.Chunkers.RegisterWithSpec(pipeline.ModuleSpec{Key: "pilot/chunk", Stage: pipeline.StageChunk, ExecutionClass: contracts.ExecutionClassDeterministic, Provides: []string{"chunks"}}, func() (contracts.Chunker, error) { return pilotChunker{}, nil }))
|
||||
check(pipeline.RegisterArtifactCodec(catalog.ArtifactCodecs, spellcodec.New()))
|
||||
check(Register(catalog.Extractors))
|
||||
check(pipeline.RegisterMerger(catalog.Mergers, pipeline.ModuleSpec{Key: "pilot/merge", Stage: pipeline.StageMerge, ArtifactKind: dnd.SpellListKind, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Merger[dnd.SpellList], error) { return pilotMerger{}, nil }))
|
||||
check(pipeline.RegisterNormalizer(catalog.Normalizers, pipeline.ModuleSpec{Key: "pilot/normalize", Stage: pipeline.StageNormalize, ArtifactKind: dnd.SpellListKind, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Normalizer[dnd.SpellList], error) { return pilotNormalizer{}, nil }))
|
||||
check(catalog.Outputs.RegisterWithSpec(pipeline.ModuleSpec{Key: "pilot/output", Stage: pipeline.StageOutput, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.OutputEncoder, error) { return pilotOutput{}, nil }))
|
||||
assessments := 0
|
||||
check(pipeline.RegisterTypedValidator(catalog.Validators, dnd.SpellListKind, pipeline.ValidatorSpec{Key: "pilot/check", ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.TypedValidator[dnd.SpellList], error) { return pilotValidator{&assessments}, nil }))
|
||||
turns := 1
|
||||
profile := pipeline.PipelineProfile{ID: "pilot", Input: pipeline.Binding("pilot/input"), Chunk: pipeline.Binding("pilot/chunk"), Output: pipeline.Binding("pilot/output"), LLMProfile: "profile-spells", MaxAdditionalTurns: &turns,
|
||||
Artifacts: map[string]pipeline.ArtifactLaneProfile{"spells": {Extract: pipeline.ModuleBinding{Module: Key, Validators: pipeline.ValidatorOverride{Set: true, Validators: []pipeline.ModuleBinding{pipeline.Binding("pilot/check")}}}, Merge: pipeline.Binding("pilot/merge"), Normalize: pipeline.Binding("pilot/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)
|
||||
cache := pilotCache{}
|
||||
for range 2 {
|
||||
_, err := pipeline.New().Run(context.Background(), pipeline.RunInput{Prepared: prepared, RawInput: []byte("input"), Cache: cache, Workers: 1})
|
||||
check(err)
|
||||
}
|
||||
if len(client.requests) != 2 || assessments != 2 || len(cache) != 1 {
|
||||
t.Fatalf("native calls=%d assessments=%d cache entries=%d", len(client.requests), assessments, len(cache))
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,7 @@ import (
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
)
|
||||
|
||||
func TestNewRequiresNativeEngineAndReturnsExtractor(t *testing.T) {
|
||||
if _, err := New(nil, Options{}); err == nil || !strings.Contains(err.Error(), "native engine") {
|
||||
t.Fatalf("New(nil) error = %v, want native engine error", err)
|
||||
}
|
||||
func TestNewReturnsExtractor(t *testing.T) {
|
||||
extractor := newExtractor(t, &fakeSpellsLLMClient{})
|
||||
if extractor.Key() != Key {
|
||||
t.Fatalf("extractor.Key() = %q, want %q", extractor.Key(), Key)
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
spellcatalog "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/spells/catalog"
|
||||
)
|
||||
|
||||
@@ -112,13 +113,27 @@ func mismatchedSourceInputRequest(req contracts.TypedExtractionRequest[dnd.Spell
|
||||
return req
|
||||
}
|
||||
|
||||
func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *Extractor {
|
||||
type extractionFixture struct {
|
||||
*Extractor
|
||||
engine *promptkit.Engine
|
||||
}
|
||||
|
||||
func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *extractionFixture {
|
||||
t.Helper()
|
||||
extractor, err := New(newSpellEngine(t, client), Options{}, references...)
|
||||
extractor, err := New(Options{}, references...)
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v, want nil", err)
|
||||
}
|
||||
return extractor
|
||||
return &extractionFixture{Extractor: extractor, engine: newSpellEngine(t, client)}
|
||||
}
|
||||
|
||||
func runExtraction(ctx context.Context, fixture *extractionFixture, req contracts.TypedExtractionRequest[dnd.SpellList]) (pipeline.OperationResult[dnd.SpellList], error) {
|
||||
operation := req.Operation
|
||||
execution := pipeline.ExecutionContext[dnd.SpellList]{Engine: fixture.engine, Controls: operation.Controls, Assess: operation.Assess, Execution: operation.Execution, ReuseEligible: operation.ReuseEligible, Cache: operation.Cache}
|
||||
input := contracts.ExtractionInput{Source: req.Source, Chunk: req.Chunk, SourceInput: req.SourceInput, SessionID: req.SessionID, References: req.References, LLMProfile: req.LLMProfile, Metadata: req.Metadata, AmbientContext: req.AmbientContext}
|
||||
return pipeline.ExecuteOperation(ctx, execution, func(ctx context.Context) (contracts.PreparedOperation[dnd.SpellList], error) {
|
||||
return fixture.Extractor.PrepareExtraction(ctx, input)
|
||||
})
|
||||
}
|
||||
|
||||
func spellCatalogReference(content string) contracts.ReferenceSet {
|
||||
|
||||
@@ -11,6 +11,11 @@ import (
|
||||
// PrepareChunkExtraction validates common D&D extraction prerequisites and
|
||||
// prepares owned chunk-scoped source material for prompt inputs.
|
||||
func PrepareChunkExtraction[T any](ctx context.Context, req contracts.TypedExtractionRequest[T]) (contracts.LLMInputMaterial, error) {
|
||||
return PrepareChunkInput(ctx, contracts.ExtractionInput{Source: req.Source, Chunk: req.Chunk, SourceInput: req.SourceInput})
|
||||
}
|
||||
|
||||
// PrepareChunkInput validates the chunk-scoped inputs used during preparation.
|
||||
func PrepareChunkInput(ctx context.Context, req contracts.ExtractionInput) (contracts.LLMInputMaterial, error) {
|
||||
if ctx == nil {
|
||||
return contracts.LLMInputMaterial{}, fmt.Errorf("context must not be nil")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user