Preserve native diagnostic evidence
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -54,6 +55,39 @@ type pendingCall struct {
|
||||
err error
|
||||
}
|
||||
|
||||
// preparedEvidence keeps the native prepared run while allowing repair
|
||||
// histories to retain a shared prefix of their append-only messages.
|
||||
type preparedEvidence struct {
|
||||
run pk.PreparedRun
|
||||
history *preparedMessageHistory
|
||||
}
|
||||
|
||||
type preparedMessageHistory struct{ messages []pk.RenderedMessage }
|
||||
|
||||
func (e preparedEvidence) MarshalJSON() ([]byte, error) { return json.Marshal(e.run) }
|
||||
|
||||
func (e preparedEvidence) ShareMessages(previous any) any {
|
||||
prior, ok := previous.(preparedEvidence)
|
||||
if !ok || prior.history == nil || len(prior.history.messages) > len(e.run.Messages) || !slices.EqualFunc(prior.history.messages, e.run.Messages[:len(prior.history.messages)], sameRenderedMessage) {
|
||||
e.history = &preparedMessageHistory{messages: e.run.Messages}
|
||||
} else {
|
||||
e.history = prior.history
|
||||
e.history.messages = append(e.history.messages, e.run.Messages[len(e.history.messages):]...)
|
||||
}
|
||||
e.run.Messages = slices.Clip(e.history.messages)
|
||||
return e
|
||||
}
|
||||
|
||||
func sameRenderedMessage(a, b pk.RenderedMessage) bool {
|
||||
if a.Role != b.Role || a.Content != b.Content {
|
||||
return false
|
||||
}
|
||||
if a.CacheControl == nil || b.CacheControl == nil {
|
||||
return a.CacheControl == b.CacheControl
|
||||
}
|
||||
return *a.CacheControl == *b.CacheControl
|
||||
}
|
||||
|
||||
func (p *pendingCall) finish(result *pk.RunResult, err error) (structuredoutput.Response, error) {
|
||||
p.once.Do(func() {
|
||||
p.response, p.err = p.complete(result, err)
|
||||
@@ -159,7 +193,7 @@ func (c *RoleClient) prepareCall(parent context.Context, req structuredoutput.Re
|
||||
metadata := promptMetadata(details)
|
||||
var snapshot *structuredoutput.PreparedSnapshot
|
||||
if req.CaptureDiagnostics {
|
||||
snapshot = &structuredoutput.PreparedSnapshot{Messages: convertMessages(details.Messages), Prompt: metadata}
|
||||
snapshot = &structuredoutput.PreparedSnapshot{Messages: convertMessages(details.Messages), Prompt: metadata, PromptKit: preparedEvidence{run: details}}
|
||||
}
|
||||
mu.Lock()
|
||||
prepared, prompt = snapshot, metadata
|
||||
|
||||
Reference in New Issue
Block a user