288 lines
10 KiB
Go
288 lines
10 KiB
Go
package pipeline
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
|
"go.maximumdirect.net/promptkit"
|
|
)
|
|
|
|
type nativeEvaluation[T any] struct {
|
|
evaluation contracts.Evaluation[T]
|
|
assessment contracts.CandidateAssessment
|
|
guidance []string
|
|
failure error
|
|
accepted bool
|
|
}
|
|
|
|
func executeNative[T any](ctx context.Context, execution ExecutionContext[T], operation contracts.NativeOperation[T]) (OperationResult[T], error) {
|
|
var empty OperationResult[T]
|
|
if execution.Engine == nil || execution.Assess == nil || operation.Interpret == nil {
|
|
return empty, errors.New("native engine, interpretation, and assessment must be supplied")
|
|
}
|
|
if execution.Controls.MaxAdditionalTurns < 0 {
|
|
return empty, fmt.Errorf("%w: additional turns must not be negative", promptkit.ErrInvalidRequest)
|
|
}
|
|
if err := recordDomainEvidence(execution.Execution, "preparation-domain.json", operation.Evidence); err != nil {
|
|
return empty, err
|
|
}
|
|
var current nativeEvaluation[T]
|
|
var fatal error
|
|
evaluate := func(result *promptkit.RunResult) {
|
|
current = nativeEvaluation[T]{}
|
|
if execution.Execution.Capture != nil && result != nil {
|
|
defer func() {
|
|
if err := captureEvaluation(execution.Execution, result.RunID, current.evaluation, current.assessment, current.guidance, current.accepted, errors.Join(current.failure, fatal)); err != nil {
|
|
fatal = errors.Join(fatal, err)
|
|
}
|
|
}()
|
|
}
|
|
if err := CheckNativeResult(result, nil); err != nil {
|
|
current.failure = err
|
|
return
|
|
}
|
|
evaluation, err := operation.Interpret(ctx, result)
|
|
if canceled := ctx.Err(); canceled != nil {
|
|
fatal = canceled
|
|
return
|
|
}
|
|
if err != nil {
|
|
var captureErr *contracts.CaptureError
|
|
if errors.As(err, &captureErr) {
|
|
fatal = err
|
|
} else {
|
|
current.failure = err
|
|
}
|
|
return
|
|
}
|
|
if evaluation == nil {
|
|
current.failure = errors.New("native response has no evaluation")
|
|
return
|
|
}
|
|
current.evaluation = evaluation
|
|
view := evaluation.View()
|
|
current.guidance = append([]string(nil), view.Guidance...)
|
|
if view.Candidate == nil {
|
|
current.failure = errors.New("native response could not be interpreted as a usable candidate")
|
|
return
|
|
}
|
|
current.assessment, err = execution.Assess(ctx, *view.Candidate)
|
|
if canceled := ctx.Err(); canceled != nil {
|
|
fatal = canceled
|
|
return
|
|
}
|
|
if err != nil {
|
|
fatal = err
|
|
return
|
|
}
|
|
validatorGuidance, err := current.assessment.Guidance()
|
|
if err != nil {
|
|
fatal = err
|
|
return
|
|
}
|
|
current.guidance = append(current.guidance, validatorGuidance...)
|
|
current.accepted = current.assessment.Accepted() && len(current.guidance) == 0
|
|
current.failure = current.assessment.Err()
|
|
if !current.accepted && current.failure == nil {
|
|
current.failure = errors.New("native candidate requires correction")
|
|
}
|
|
}
|
|
|
|
request := producerRequest(operation.Initial, execution.Execution)
|
|
request.CaptureExchange = request.CaptureExchange || (operation.Correction != nil && execution.Controls.MaxAdditionalTurns > 0)
|
|
request, capture := CaptureNativeRequest(request, scopeEvidence(execution.Execution.Capture, "initial"))
|
|
if err := capture.Err(); err != nil {
|
|
return empty, err
|
|
}
|
|
var result *promptkit.RunResult
|
|
var err error
|
|
var cacheKey string
|
|
cache := execution.Cache
|
|
if cache != nil && cache.Decode != nil && operation.Reuse != nil {
|
|
copy := *cache
|
|
decode := cache.Decode
|
|
copy.Decode = func(content []byte) (T, error) {
|
|
value, err := decode(content)
|
|
if err != nil {
|
|
return value, err
|
|
}
|
|
return operation.Reuse(value)
|
|
}
|
|
cache = ©
|
|
}
|
|
if execution.Execution.Capture != nil {
|
|
if err := execution.Execution.RecordEvidence("cache/selection.json", map[string]any{"mode": execution.Controls.Cache, "reuse_eligible": execution.ReuseEligible, "store_available": cache != nil && cache.Store != nil}); err != nil {
|
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
|
}
|
|
if cache != nil {
|
|
copy := *cache
|
|
existing := copy.Observe
|
|
copy.Observe = func(ctx context.Context, observation contracts.CacheObservation) error {
|
|
if err := captureCacheObservation(execution.Execution.Capture, observation); err != nil {
|
|
return err
|
|
}
|
|
if existing != nil {
|
|
return existing(ctx, observation)
|
|
}
|
|
return nil
|
|
}
|
|
cache = ©
|
|
}
|
|
}
|
|
if cache != nil && cache.Store != nil && execution.ReuseEligible && execution.Controls.Cache != contracts.CacheBypass {
|
|
if cache.Encode == nil || cache.Decode == nil {
|
|
err := errors.New("producer cache codec must be supplied")
|
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
|
}
|
|
if mode := execution.Controls.Cache; mode != "" && mode != contracts.CacheAuto && mode != contracts.CacheRefresh {
|
|
err := fmt.Errorf("%w: unknown cache mode %q", promptkit.ErrInvalidRequest, mode)
|
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
|
}
|
|
var prepared *promptkit.PreparedExecution
|
|
prepared, err = execution.Engine.PrepareExecution(ctx, request)
|
|
if err == nil {
|
|
defer prepared.Discard()
|
|
details := prepared.Details()
|
|
cacheKey = details.MessageContentHash
|
|
if capture != nil {
|
|
capture.RetainPrepared(copyPreparedEvidence(details))
|
|
}
|
|
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "prepared", MessageContentHash: cacheKey, Prepared: &details}); err != nil {
|
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
|
}
|
|
reused, lookupErr := lookupProducerCache(ctx, cache, execution.Controls.Cache, cacheKey)
|
|
if lookupErr != nil {
|
|
return empty, captureFailure(lookupErr, capture.Finish(nil, lookupErr, false, false))
|
|
}
|
|
if reused != nil {
|
|
if err := capture.Finish(nil, nil, false, true); err != nil {
|
|
return empty, err
|
|
}
|
|
return OperationResult[T]{Value: *reused, Outcome: contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: true}}, nil
|
|
}
|
|
result, err = execution.Engine.RunPrepared(ctx, prepared)
|
|
}
|
|
} else {
|
|
if cache != nil {
|
|
decision := "bypass"
|
|
if !execution.ReuseEligible {
|
|
decision = "ineligible"
|
|
}
|
|
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: decision}); err != nil {
|
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
|
}
|
|
}
|
|
result, err = execution.Engine.Run(ctx, request)
|
|
}
|
|
if captureErr := capture.Finish(result, err, ctx.Err() != nil, false); captureErr != nil {
|
|
return empty, captureFailure(errors.Join(ctx.Err(), err), captureErr)
|
|
}
|
|
if canceled := ctx.Err(); canceled != nil {
|
|
return empty, canceled
|
|
}
|
|
if err != nil {
|
|
var captureErr *contracts.CaptureError
|
|
if errors.As(err, &captureErr) {
|
|
return empty, err
|
|
}
|
|
current.failure = CheckNativeResult(result, err)
|
|
} else {
|
|
evaluate(result)
|
|
}
|
|
if fatal != nil {
|
|
return empty, fatal
|
|
}
|
|
if !current.accepted && err == nil && len(current.guidance) > 0 && operation.Correction != nil && execution.Controls.MaxAdditionalTurns > 0 {
|
|
var pendingCapture *NativeCapture
|
|
var recordingErr error
|
|
coordination, coordinateErr := execution.Engine.Coordinate(ctx, promptkit.CoordinateRequest{
|
|
Start: result.Exchange, AdditionalTurns: execution.Controls.MaxAdditionalTurns,
|
|
Next: func(_ context.Context, turn promptkit.ConversationTurn) (*promptkit.RunRequest, error) {
|
|
if turn.Result != nil {
|
|
recordingErr = pendingCapture.Finish(turn.Result, nil, false, false)
|
|
pendingCapture = nil
|
|
if recordingErr != nil {
|
|
return nil, recordingErr
|
|
}
|
|
evaluate(turn.Result)
|
|
}
|
|
if fatal != nil {
|
|
return nil, fatal
|
|
}
|
|
if current.accepted || len(current.guidance) == 0 || turn.RemainingTurns == 0 {
|
|
return nil, nil
|
|
}
|
|
guidance := current.guidance
|
|
// Selecting another execution invalidates the entire previous
|
|
// evaluation before even attempting to construct its request.
|
|
current = nativeEvaluation[T]{}
|
|
correctionPath := ""
|
|
if execution.Execution.Capture != nil {
|
|
correctionPath = "corrections/" + turn.Exchange.Details().RunID
|
|
if recordingErr = execution.Execution.RecordEvidence(correctionPath+"/assignment.json", map[string]any{"guidance": guidance}); recordingErr != nil {
|
|
return nil, recordingErr
|
|
}
|
|
}
|
|
next, err := operation.Correction(ctx, guidance)
|
|
if err != nil {
|
|
if correctionPath != "" {
|
|
recordingErr = execution.Execution.RecordEvidence(correctionPath+"/construction-failure.json", map[string]any{"error": err.Error()})
|
|
}
|
|
return nil, err
|
|
}
|
|
if operation.Initial.ProfileID != "" {
|
|
next.ProfileID = operation.Initial.ProfileID
|
|
}
|
|
if operation.Initial.SessionID != "" {
|
|
next.SessionID = operation.Initial.SessionID
|
|
}
|
|
next = producerRequest(next, execution.Execution)
|
|
if correctionPath != "" {
|
|
next, pendingCapture = CaptureNativeRequest(next, scopeEvidence(execution.Execution.Capture, correctionPath))
|
|
if recordingErr = pendingCapture.Err(); recordingErr != nil {
|
|
return nil, recordingErr
|
|
}
|
|
}
|
|
return &next, nil
|
|
},
|
|
})
|
|
if pendingCapture != nil {
|
|
recordingErr = errors.Join(recordingErr, pendingCapture.Finish(coordination.Undelivered, coordinateErr, coordination.Undelivered != nil, false))
|
|
}
|
|
if recordingErr != nil {
|
|
return empty, captureFailure(errors.Join(ctx.Err(), coordinateErr), recordingErr)
|
|
}
|
|
if canceled := ctx.Err(); canceled != nil {
|
|
return empty, canceled
|
|
}
|
|
if coordination.Undelivered != nil {
|
|
if coordinateErr == nil {
|
|
coordinateErr = errors.New("native continuation response was not delivered")
|
|
}
|
|
return empty, coordinateErr
|
|
}
|
|
if fatal != nil {
|
|
return empty, fatal
|
|
}
|
|
if coordinateErr != nil {
|
|
var captureErr *contracts.CaptureError
|
|
if errors.As(coordinateErr, &captureErr) {
|
|
return empty, coordinateErr
|
|
}
|
|
current = nativeEvaluation[T]{failure: coordinateErr}
|
|
}
|
|
}
|
|
if current.accepted {
|
|
if cacheKey != "" {
|
|
if err := storeProducerCache(ctx, cache, execution.Controls.Cache, cacheKey, *current.evaluation.View().Candidate); err != nil {
|
|
return empty, err
|
|
}
|
|
}
|
|
outcome := contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: execution.ReuseEligible}
|
|
return completeOperation(*current.evaluation.View().Candidate, current.evaluation, current.assessment, outcome, operation.Diagnostics)
|
|
}
|
|
return finishOperation(ctx, execution.Controls.Mode, current.failure, current.evaluation, current.assessment, operation.Fallback, operation.Diagnostics)
|
|
}
|