Migrate combat semantics validation to native execution and unavailable assessments
This commit is contained in:
@@ -2,9 +2,10 @@ package combat_semantics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"go.maximumdirect.net/promptkit"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
@@ -14,44 +15,20 @@ import (
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/validate/scenedescriptions/shape"
|
||||
)
|
||||
|
||||
const (
|
||||
Key = "extract/dnd/scene-descriptions/combat_semantics"
|
||||
ReasonCodeActiveCombatNotClassified = "scene_active_combat_not_classified"
|
||||
ReasonCodeCombatClassificationUnsupported = "scene_combat_classification_unsupported"
|
||||
combatPolicy = "dnd.scene_descriptions.combat_semantics.v1"
|
||||
maximumExplanationRunes = 512
|
||||
)
|
||||
const Key = "extract/dnd/scene-descriptions/combat_semantics"
|
||||
const PromptID = "notarius/dnd.scene_descriptions.validate_combat"
|
||||
|
||||
type Options struct{}
|
||||
|
||||
type completionResponse struct {
|
||||
Classification string `json:"classification"`
|
||||
Explanation string `json:"explanation"`
|
||||
}
|
||||
|
||||
type Validator struct {
|
||||
llm contracts.StructuredLLMClient
|
||||
promptSHA string
|
||||
responseSchemaSHA string
|
||||
}
|
||||
type Validator struct{ engine *promptkit.Engine }
|
||||
|
||||
var _ contracts.TypedValidator[dnd.SceneDescriptionList] = (*Validator)(nil)
|
||||
var _ contracts.ManifestMetadataProvider = (*Validator)(nil)
|
||||
var _ pipeline.CheckpointFingerprintProvider = (*Validator)(nil)
|
||||
|
||||
func New(llmClient contracts.StructuredLLMClient, _ Options) (*Validator, error) {
|
||||
if llmClient == nil {
|
||||
return nil, validatorErrorf("LLM client must not be nil")
|
||||
func New(engine *promptkit.Engine, _ Options) (*Validator, error) {
|
||||
if engine == nil {
|
||||
return nil, validatorErrorf("native engine must not be nil")
|
||||
}
|
||||
promptSHA, err := promptAssetMetadata()
|
||||
if err != nil {
|
||||
return nil, validatorErrorf("load prompt metadata: %w", err)
|
||||
}
|
||||
responseSchema, err := loadResponseSchema()
|
||||
if err != nil {
|
||||
return nil, validatorErrorf("load response schema: %w", err)
|
||||
}
|
||||
return &Validator{llm: llmClient, promptSHA: promptSHA, responseSchemaSHA: responseSchema.SHA256}, nil
|
||||
return &Validator{engine: engine}, nil
|
||||
}
|
||||
|
||||
func (v *Validator) Name() string { return Key }
|
||||
@@ -60,62 +37,46 @@ func (v *Validator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassLLMBacked
|
||||
}
|
||||
|
||||
func (v *Validator) ManifestMetadata() map[string]any {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
return map[string]any{
|
||||
"prompt_id": PromptID,
|
||||
"prompt_version": SchemaVersion,
|
||||
"prompt_sha256": v.promptSHA,
|
||||
"response_schema_key": string(ResponseSchemaKey),
|
||||
"response_schema_id": ResponseSchemaID,
|
||||
"response_schema_name": ResponseSchemaName,
|
||||
"response_schema_version": SchemaVersion,
|
||||
"response_schema_sha256": v.responseSchemaSHA,
|
||||
"combat_policy": combatPolicy,
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Validator) CheckpointFingerprints() []pipeline.CheckpointFingerprint {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
return []pipeline.CheckpointFingerprint{
|
||||
{Name: "prompt", Value: v.promptSHA},
|
||||
{Name: "response_schema", Value: v.responseSchemaSHA},
|
||||
{Name: "combat_policy", Value: combatPolicy},
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Validator) Validate(ctx context.Context, req contracts.TypedValidationRequest[dnd.SceneDescriptionList]) (contracts.ValidationResult, error) {
|
||||
if v == nil {
|
||||
return contracts.ValidationResult{}, validatorErrorf("validator must not be nil")
|
||||
}
|
||||
if v.llm == nil {
|
||||
return contracts.ValidationResult{}, validatorErrorf("LLM client must not be nil")
|
||||
if v.engine == nil {
|
||||
return contracts.ValidationResult{}, validatorErrorf("native engine must not be nil")
|
||||
}
|
||||
sourceInput, scene, err := validateRequest(ctx, req)
|
||||
if err != nil {
|
||||
return contracts.ValidationResult{}, err
|
||||
}
|
||||
|
||||
var response completionResponse
|
||||
_, err = v.llm.CompleteStructured(ctx, contracts.StructuredCompletionRequest{
|
||||
StageName: Key,
|
||||
PromptID: PromptID,
|
||||
PromptVersion: SchemaVersion,
|
||||
ProfileID: req.LLMProfile,
|
||||
SessionID: req.SessionID,
|
||||
StructuredOutputRepairAttempts: req.StructuredOutputRepairAttempts,
|
||||
Inputs: contracts.LLMInputSet{
|
||||
"transcript": shared.TranscriptPromptMaterial(sourceInput),
|
||||
},
|
||||
}, &response)
|
||||
if err != nil {
|
||||
return contracts.ValidationResult{}, validatorErrorf("complete structured output: %w", err)
|
||||
material := shared.TranscriptPromptMaterial(sourceInput)
|
||||
result, err := v.engine.Run(ctx, promptkit.RunRequest{
|
||||
PromptID: PromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID,
|
||||
Inputs: map[string]promptkit.ArtifactRef{"transcript": promptkit.InlineWithURI(material.OriginURI, string(material.Content))},
|
||||
Execution: req.Execution.Execution, TransientRetries: req.Execution.TransientRetries,
|
||||
Observer: req.Execution.Observer, OnPrepared: req.Execution.OnPrepared,
|
||||
})
|
||||
if canceled := ctx.Err(); canceled != nil {
|
||||
return contracts.ValidationResult{}, canceled
|
||||
}
|
||||
return interpretResponse(response, scene.Kind)
|
||||
if err != nil {
|
||||
return contracts.ValidationResult{}, unavailable(err)
|
||||
}
|
||||
if result == nil || result.Validation.Status == promptkit.ValidationFailed || !result.Validation.IsValid {
|
||||
return contracts.ValidationResult{}, unavailable(validatorErrorf("native output contract failed: %w", promptkit.ErrValidation))
|
||||
}
|
||||
var response classificationResponse
|
||||
if err := json.Unmarshal([]byte(result.RawOutput), &response); err != nil {
|
||||
return contracts.ValidationResult{}, unavailable(validatorErrorf("decode native output: %w", err))
|
||||
}
|
||||
assessment, err := interpretResponse(response, scene.Kind)
|
||||
if canceled := ctx.Err(); canceled != nil {
|
||||
return contracts.ValidationResult{}, canceled
|
||||
}
|
||||
if err != nil {
|
||||
return contracts.ValidationResult{}, unavailable(err)
|
||||
}
|
||||
return assessment, nil
|
||||
}
|
||||
|
||||
func validateRequest(ctx context.Context, req contracts.TypedValidationRequest[dnd.SceneDescriptionList]) (contracts.LLMInputMaterial, dnd.SceneDescription, error) {
|
||||
@@ -128,7 +89,7 @@ func validateRequest(ctx context.Context, req contracts.TypedValidationRequest[d
|
||||
if req.Stage != string(pipeline.StageExtract) {
|
||||
return contracts.LLMInputMaterial{}, dnd.SceneDescription{}, validatorErrorf("validation stage must be extract, got %q", req.Stage)
|
||||
}
|
||||
sourceInput, err := shared.PrepareChunkExtraction(ctx, contracts.TypedExtractionRequest{Source: req.Source, Chunk: req.Chunk, SourceInput: req.SourceInput})
|
||||
sourceInput, err := shared.PrepareChunkExtraction(ctx, contracts.TypedExtractionRequest[dnd.SceneDescriptionList]{Source: req.Source, Chunk: req.Chunk, SourceInput: req.SourceInput})
|
||||
if err != nil {
|
||||
return contracts.LLMInputMaterial{}, dnd.SceneDescription{}, validatorErrorf("prepare chunk source input: %w", err)
|
||||
}
|
||||
@@ -154,53 +115,12 @@ func validateRequest(ctx context.Context, req contracts.TypedValidationRequest[d
|
||||
return sourceInput, scene, nil
|
||||
}
|
||||
|
||||
func interpretResponse(response completionResponse, proposedKind dnd.SceneKind) (contracts.ValidationResult, error) {
|
||||
explanation, err := validateExplanation(response.Explanation)
|
||||
if err != nil {
|
||||
return contracts.ValidationResult{}, err
|
||||
}
|
||||
switch response.Classification {
|
||||
case "combat":
|
||||
if proposedKind == dnd.SceneKindCombat {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
return contracts.ValidationResult{
|
||||
Approved: false,
|
||||
ReasonCode: ReasonCodeActiveCombatNotClassified,
|
||||
Message: "The current chunk contains substantive active combat that is not classified as combat.",
|
||||
CorrectionGuidance: "Return kind: combat for this scene. " + explanation,
|
||||
}, nil
|
||||
case "non_combat":
|
||||
if proposedKind != dnd.SceneKindCombat {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
return contracts.ValidationResult{
|
||||
Approved: false,
|
||||
ReasonCode: ReasonCodeCombatClassificationUnsupported,
|
||||
Message: "The current chunk does not support a combat classification.",
|
||||
CorrectionGuidance: "Choose the appropriate narrative, recap, or meta kind for this scene. " + explanation,
|
||||
}, nil
|
||||
default:
|
||||
return contracts.ValidationResult{}, validatorErrorf("unsupported combat-semantics classification %q", response.Classification)
|
||||
}
|
||||
}
|
||||
|
||||
func validateExplanation(value string) (string, error) {
|
||||
if !utf8.ValidString(value) {
|
||||
return "", validatorErrorf("validator explanation must be valid UTF-8")
|
||||
}
|
||||
trimmed := strings.TrimSpace(value)
|
||||
if trimmed == "" {
|
||||
return "", validatorErrorf("validator explanation must not be blank")
|
||||
}
|
||||
if utf8.RuneCountInString(trimmed) > maximumExplanationRunes {
|
||||
return "", validatorErrorf("validator explanation exceeds %d Unicode code points", maximumExplanationRunes)
|
||||
}
|
||||
return trimmed, nil
|
||||
func unavailable(cause error) error {
|
||||
return &contracts.ValidationUnavailableError{Cause: validatorErrorf("native assessment unavailable: %w", cause)}
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassLLMBacked}
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{PromptID}}
|
||||
}
|
||||
|
||||
func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
@@ -209,7 +129,7 @@ func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(request.Dependencies.LLM, options)
|
||||
return New(request.Dependencies.Engine, options)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -221,7 +141,3 @@ func DecodeOptions(options map[string]any) (Options, error) {
|
||||
}
|
||||
|
||||
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
|
||||
|
||||
func validatorErrorf(format string, args ...any) error {
|
||||
return fmt.Errorf("scene combat-semantics validator: "+format, args...)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user