Prepare NPC item and location registry extraction in core
This commit is contained in:
@@ -37,32 +37,26 @@ var _ contracts.Extractor[dnd.LocationRegistry] = (*Extractor)(nil)
|
||||
|
||||
type Options struct{}
|
||||
|
||||
type Extractor struct{ engine *promptkit.Engine }
|
||||
type Extractor struct{}
|
||||
|
||||
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")
|
||||
}
|
||||
return &Extractor{engine: engine}, nil
|
||||
return &Extractor{}, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) Key() string { return Key }
|
||||
|
||||
func (e *Extractor) ReferenceSlots() []contracts.ReferenceSlot { return referenceSlots() }
|
||||
|
||||
func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRequest[dnd.LocationRegistry]) (contracts.TypedExtractionResult[dnd.LocationRegistry], error) {
|
||||
func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.ExtractionInput) (contracts.PreparedOperation[dnd.LocationRegistry], error) {
|
||||
if e == nil {
|
||||
return contracts.TypedExtractionResult[dnd.LocationRegistry]{}, extractorErrorf("extractor must not be nil")
|
||||
return nil, extractorErrorf("extractor must not be nil")
|
||||
}
|
||||
if e.engine == nil {
|
||||
return contracts.TypedExtractionResult[dnd.LocationRegistry]{}, 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.LocationRegistry]{}, extractorErrorf("%w", err)
|
||||
return nil, extractorErrorf("%w", err)
|
||||
}
|
||||
order := shared.NewSourceRefOrder(req.Source)
|
||||
|
||||
@@ -73,27 +67,20 @@ func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRe
|
||||
inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.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.LocationRegistry, []string, error) {
|
||||
return contracts.NativeOperation[dnd.LocationRegistry]{Initial: initial,
|
||||
Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[dnd.LocationRegistry], 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 := canonicalLocationRegistry(response, sourceID)
|
||||
return &value, nil, nil
|
||||
return contracts.CandidateEvaluation[dnd.LocationRegistry]{Result: contracts.EvaluationView[dnd.LocationRegistry]{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.LocationRegistry) (dnd.LocationRegistry, 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.LocationRegistry]) (dnd.LocationRegistry, error) {
|
||||
return dnd.LocationRegistry{Locations: []dnd.Location{}}, nil
|
||||
})
|
||||
if err != nil {
|
||||
return contracts.TypedExtractionResult[dnd.LocationRegistry]{}, extractorErrorf("produce registry: %w", err)
|
||||
}
|
||||
return contracts.TypedExtractionResult[dnd.LocationRegistry]{Value: value, Outcome: outcome}, nil
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func ModuleSpec() pipeline.ModuleSpec {
|
||||
@@ -111,7 +98,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)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestExtractMapsLocationsWithOwnedEvidenceAndDeterministicOrder(t *testing.T
|
||||
{Name: "The Tavern", SourceRefs: responseSourceRefs(3, 2)},
|
||||
{Name: "Old Mill", SourceRefs: []locationSourceRefResponse{{StartUnitID: 2, EndUnitID: 2}, {StartUnitID: 1, EndUnitID: 1}, {StartUnitID: 1, EndUnitID: 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)
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func TestExtractRetainsSameNameLocationsAtDifferentAnchors(t *testing.T) {
|
||||
{Name: "the tavern", SourceRefs: responseSourceRefs(1, 1)},
|
||||
{Name: "the tavern", SourceRefs: responseSourceRefs(3, 3)},
|
||||
}}}
|
||||
result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest())
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest())
|
||||
if err != nil || len(result.Value.Locations) != 2 {
|
||||
t.Fatalf("Extract() = %#v, %v; want both same-name candidates", result, err)
|
||||
}
|
||||
@@ -56,7 +56,7 @@ func TestExtractRetainsSameNameLocationsAtDifferentAnchors(t *testing.T) {
|
||||
|
||||
func TestExtractPreservesInvalidCandidatesForValidators(t *testing.T) {
|
||||
client := &fakeLocationsLLMClient{content: []byte(`{"locations":[{"name":"","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)
|
||||
}
|
||||
@@ -72,7 +72,7 @@ func TestExtractPassesReferencesWithoutTreatingThemAsEvidence(t *testing.T) {
|
||||
req.References = contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Old Mill: abandoned granary")}}},
|
||||
}}
|
||||
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", err)
|
||||
}
|
||||
messageContaining(t, client.requests[0], "Old Mill: abandoned granary")
|
||||
@@ -88,7 +88,7 @@ func TestExtractDoesNotMutateRequestMaterials(t *testing.T) {
|
||||
beforeUnits := append([]source.SourceUnit(nil), req.Source.Units...)
|
||||
beforeChunkUnits := append([]source.SourceUnit(nil), req.Chunk.Units...)
|
||||
beforeContent := append([]byte(nil), req.Chunk.Content...)
|
||||
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", err)
|
||||
}
|
||||
if !reflect.DeepEqual(req.Source.Units, beforeUnits) || !reflect.DeepEqual(req.Chunk.Units, beforeChunkUnits) || !reflect.DeepEqual(req.Chunk.Content, beforeContent) {
|
||||
@@ -97,30 +97,29 @@ func TestExtractDoesNotMutateRequestMaterials(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestExtractHandlesEmptyOutputAndLocalFailures(t *testing.T) {
|
||||
empty, err := newExtractor(t, &fakeLocationsLLMClient{response: extractionResponse{Locations: []locationResponse{}}}).Extract(context.Background(), extractionRequest())
|
||||
empty, err := runExtraction(context.Background(), newExtractor(t, &fakeLocationsLLMClient{response: extractionResponse{Locations: []locationResponse{}}}), extractionRequest())
|
||||
if err != nil || empty.Value.Locations == nil || len(empty.Value.Locations) != 0 {
|
||||
t.Fatalf("empty Extract() = %#v, %v; want empty list", empty, err)
|
||||
}
|
||||
request := extractionRequest()
|
||||
var nilExtractor *Extractor
|
||||
var nilExtractor *extractionFixture
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
extractor *Extractor
|
||||
extractor *extractionFixture
|
||||
req contracts.TypedExtractionRequest[dnd.LocationRegistry]
|
||||
want string
|
||||
}{
|
||||
{name: "nil extractor", extractor: nilExtractor, req: request, want: "extractor"},
|
||||
{name: "nil client", extractor: &Extractor{}, req: request, want: "native engine"},
|
||||
{name: "preflight", extractor: newExtractor(t, &fakeLocationsLLMClient{}), req: mismatchedSourceInputRequest(request), want: "must match chunk"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := test.extractor.Extract(context.Background(), test.req); err == nil || !strings.Contains(err.Error(), "dnd location registry") || !strings.Contains(err.Error(), test.want) {
|
||||
if _, err := runExtraction(context.Background(), test.extractor, test.req); err == nil || !strings.Contains(err.Error(), "dnd location registry") || !strings.Contains(err.Error(), test.want) {
|
||||
t.Fatalf("Extract() error = %v, want local context", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
_, err = newExtractor(t, &fakeLocationsLLMClient{err: errors.New("provider unavailable")}).Extract(context.Background(), request)
|
||||
if err == nil || !strings.Contains(err.Error(), "dnd location registry") || !strings.Contains(err.Error(), "provider unavailable") {
|
||||
_, err = runExtraction(context.Background(), newExtractor(t, &fakeLocationsLLMClient{err: errors.New("provider unavailable")}), request)
|
||||
if err == nil || !strings.Contains(err.Error(), "provider unavailable") {
|
||||
t.Fatalf("provider error = %v, want contextual provider error", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ func TestNativeExtractionCorrectsGroundingWithFixedInputs(t *testing.T) {
|
||||
}
|
||||
return assessment, err
|
||||
}
|
||||
result, err := newExtractor(t, client).Extract(context.Background(), request)
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), request)
|
||||
if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || !result.Outcome.ReuseEligible ||
|
||||
assessments != 2 || len(client.requests) != 2 || len(prepared) != 2 || len(result.Value.Locations) != 1 {
|
||||
t.Fatalf("corrected registry=%#v %v, assessments/provider/prepared=%d/%d/%d", result, err, assessments, len(client.requests), len(prepared))
|
||||
@@ -122,7 +122,7 @@ func TestNativeExtractionDistinguishesEmptyAcceptanceFromFallback(t *testing.T)
|
||||
assessments++
|
||||
return assessRegistry(ctx, request, value)
|
||||
}
|
||||
result, err := newExtractor(t, client).Extract(context.Background(), request)
|
||||
result, err := runExtraction(context.Background(), newExtractor(t, client), request)
|
||||
if (err != nil) != test.wantError || assessments != test.wantAssessments || prepared != test.wantRuns {
|
||||
t.Fatalf("registry=%#v %v, assessments=%d runs=%d", result, err, assessments, prepared)
|
||||
}
|
||||
@@ -149,7 +149,7 @@ func TestCanceledNativeExtractionCannotDeliverFallback(t *testing.T) {
|
||||
client := &fakeLocationsLLMClient{content: []byte(groundedRegistry), onGenerate: func(context.Context, promptkit.GenerateRequest) { cancel() }}
|
||||
request := extractionRequest()
|
||||
request.Operation.Controls.Mode = contracts.ModePermissive
|
||||
result, err := newExtractor(t, client).Extract(ctx, request)
|
||||
result, err := runExtraction(ctx, newExtractor(t, client), request)
|
||||
if !errors.Is(err, context.Canceled) || result.Outcome.Disposition != "" || len(client.requests) != 1 {
|
||||
t.Fatalf("cancellation=%#v %v", result, err)
|
||||
}
|
||||
|
||||
@@ -11,10 +11,7 @@ import (
|
||||
)
|
||||
|
||||
func TestModuleRegistrationAndNativeDependencies(t *testing.T) {
|
||||
if _, err := New(nil, Options{}); err == nil || !strings.Contains(err.Error(), "native engine") {
|
||||
t.Fatalf("New(nil) error = %v, want client rejection", err)
|
||||
}
|
||||
if _, err := New(newExtractor(t, &fakeLocationsLLMClient{}).engine, Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one") {
|
||||
if _, err := New(Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one") {
|
||||
t.Fatalf("New() error = %v, want reference-set rejection", err)
|
||||
}
|
||||
want := pipeline.ModuleSpec{Key: Key, Stage: pipeline.StageExtract, ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{PromptID, CorrectionPromptID}, Requires: []string{"chunks", "source.transcript"}, Provides: []string{"dnd.location_registry"}, ArtifactKind: dnd.LocationRegistryKind, ReferenceSlots: referenceSlots()}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"gitea.maximumdirect.net/eric/notarius/assets"
|
||||
"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"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
@@ -51,7 +52,12 @@ func registryOperation() contracts.ProducerOperation[dnd.LocationRegistry] {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
type settings struct {
|
||||
PromptKit promptkit.Settings `yaml:"promptkit"`
|
||||
@@ -75,11 +81,25 @@ func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contra
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
extractor, err := New(engine, Options{}, references...)
|
||||
extractor, err := New(Options{}, references...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return extractor
|
||||
return &extractionFixture{Extractor: extractor, engine: engine}
|
||||
}
|
||||
|
||||
func runExtraction(ctx context.Context, fixture *extractionFixture, req contracts.TypedExtractionRequest[dnd.LocationRegistry]) (pipeline.OperationResult[dnd.LocationRegistry], error) {
|
||||
var extractor *Extractor
|
||||
var engine *promptkit.Engine
|
||||
if fixture != nil {
|
||||
extractor, engine = fixture.Extractor, fixture.engine
|
||||
}
|
||||
op := req.Operation
|
||||
execution := pipeline.ExecutionContext[dnd.LocationRegistry]{Engine: engine, Controls: op.Controls, Assess: op.Assess, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Cache: op.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.LocationRegistry], error) {
|
||||
return extractor.PrepareExtraction(ctx, input)
|
||||
})
|
||||
}
|
||||
|
||||
func messageContaining(t *testing.T, request promptkit.GenerateRequest, text string) promptkit.RenderedMessage {
|
||||
|
||||
Reference in New Issue
Block a user