feat(guards): judge calls record their payload and response, and the OpenAI Decisions API is a judge backend
publish / publish (push) Successful in 1m18s
publish / publish (push) Successful in 1m18s
This commit is contained in:
27 files changed
+2230
-99
No files matched your search
@@ -0,0 +1,456 @@
|
||||
// Package decisions speaks the OpenAI Decisions API: one input, typed
|
||||
// questions, and answers carrying choices, scores or predicate probabilities.
|
||||
//
|
||||
// It maps the same question set the guards already ask a System One endpoint
|
||||
// onto the Decisions API: a choice becomes a choice, a score becomes a score
|
||||
// with its levels, and a bool becomes a predicate. The result is the System One
|
||||
// result shape, so a guard reads both backends the same way.
|
||||
package decisions
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archipelago/sdk/systemone"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultBaseURL is the OpenAI API root.
|
||||
DefaultBaseURL = "https://api.openai.com/v1"
|
||||
// DefaultModel is the model asked when the operator names none.
|
||||
DefaultModel = "gpt-6-luna"
|
||||
)
|
||||
|
||||
// Client is an OpenAI Decisions endpoint.
|
||||
type Client struct {
|
||||
// BaseURL is the API root including its version segment.
|
||||
BaseURL string
|
||||
Model string
|
||||
// APIKey is sent as a bearer token when set. It is never recorded.
|
||||
APIKey string
|
||||
// Label names the deployment in reports.
|
||||
Label string
|
||||
// HTTP is optional; a 30s-timeout client is used when nil.
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
// ModelID is the model this client asks.
|
||||
func (c Client) ModelID() string { return c.Model }
|
||||
|
||||
// Deployment names the endpoint in reports.
|
||||
func (c Client) Deployment() string { return c.Label }
|
||||
|
||||
// Endpoint resolves the decision URL: "decisions" is appended to the base URL,
|
||||
// so .../v1 becomes .../v1/decisions.
|
||||
func (c Client) Endpoint() string {
|
||||
base := c.BaseURL
|
||||
if base == "" {
|
||||
base = DefaultBaseURL
|
||||
}
|
||||
return strings.TrimRight(base, "/") + "/decisions"
|
||||
}
|
||||
|
||||
// Classify asks every question about state in one request.
|
||||
//
|
||||
// The raw request and response are returned with every result, including on a
|
||||
// failed call, so the caller can record what was asked and whatever came back.
|
||||
// A refusal is an error: the model declined to answer, so the call failed.
|
||||
func (c Client) Classify(ctx context.Context, state any, questions map[string]systemone.Question) (systemone.Result, error) {
|
||||
if c.Model == "" {
|
||||
return systemone.Result{}, errors.New("decisions: model is required")
|
||||
}
|
||||
if len(questions) == 0 {
|
||||
return systemone.Result{}, errors.New("decisions: at least one question is required")
|
||||
}
|
||||
wire, err := questionWires(questions)
|
||||
if err != nil {
|
||||
return systemone.Result{}, err
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{
|
||||
"model": c.Model,
|
||||
"input": RenderInput(state),
|
||||
"questions": wire,
|
||||
})
|
||||
if err != nil {
|
||||
return systemone.Result{}, fmt.Errorf("decisions: encode request: %w", err)
|
||||
}
|
||||
|
||||
endpoint := c.Endpoint()
|
||||
result := systemone.Result{
|
||||
Request: body, EndpointPath: endpointPath(endpoint), Model: c.Model, Provider: c.Label,
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("decisions: build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if c.APIKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.APIKey)
|
||||
}
|
||||
|
||||
httpClient := c.HTTP
|
||||
if httpClient == nil {
|
||||
httpClient = &http.Client{Timeout: 30 * time.Second}
|
||||
}
|
||||
start := time.Now()
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
result.Latency = time.Since(start)
|
||||
return result, fmt.Errorf("decisions: %s: %w", c.Label, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
result.Latency = time.Since(start)
|
||||
result.HTTPStatus = resp.StatusCode
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
result.Response = payload
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("decisions: read response: %w", err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return result, fmt.Errorf("decisions: %s returned HTTP %d: %s",
|
||||
c.Label, resp.StatusCode, truncate(string(payload), 300))
|
||||
}
|
||||
|
||||
var decoded response
|
||||
if err := json.Unmarshal(payload, &decoded); err != nil {
|
||||
return result, fmt.Errorf("decisions: decode response: %w", err)
|
||||
}
|
||||
result.ID = decoded.ID
|
||||
if decoded.Model != "" {
|
||||
result.Model = decoded.Model
|
||||
}
|
||||
result.Usage = decoded.Usage
|
||||
|
||||
answers, answerErr := answersOf(decoded.Answers)
|
||||
result.Answers = answers
|
||||
if answerErr != nil {
|
||||
return result, answerErr
|
||||
}
|
||||
if err := checkAnswers(answers, questions); err != nil {
|
||||
return result, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// response is the Decisions API response body.
|
||||
type response struct {
|
||||
ID string `json:"id"`
|
||||
Model string `json:"model"`
|
||||
Answers []answer `json:"answers"`
|
||||
Usage *systemone.Usage `json:"usage"`
|
||||
}
|
||||
|
||||
type answer struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Choice string `json:"choice"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
Score *float64 `json:"score"`
|
||||
Probability *float64 `json:"probability"`
|
||||
Probabilities json.RawMessage `json:"probabilities"`
|
||||
}
|
||||
|
||||
// answersOf converts the Decisions answers into the shared answer shape. A
|
||||
// refusal stops the conversion: the call failed, and the response that says so
|
||||
// is kept by the caller.
|
||||
func answersOf(list []answer) (map[string]systemone.Answer, error) {
|
||||
out := make(map[string]systemone.Answer, len(list))
|
||||
for _, a := range list {
|
||||
if a.Type == "refusal" {
|
||||
return out, fmt.Errorf("decisions: the model refused question %q", a.Name)
|
||||
}
|
||||
converted, err := answerOf(a)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out[a.Name] = converted
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// answerOf maps one answer into the shared shape, using the wire names System
|
||||
// One uses so the guards read both backends identically.
|
||||
func answerOf(a answer) (systemone.Answer, error) {
|
||||
out := systemone.Answer{
|
||||
Choice: a.Choice, Confidence: a.Confidence, Score: a.Score, Probability: a.Probability,
|
||||
}
|
||||
if len(a.Probabilities) > 0 {
|
||||
if p, ok := probabilities(a.Probabilities); ok {
|
||||
out.Probabilities = p
|
||||
}
|
||||
}
|
||||
switch a.Type {
|
||||
case "choice":
|
||||
if a.Choice == "" {
|
||||
return out, fmt.Errorf("decisions: answer for %q has no choice", a.Name)
|
||||
}
|
||||
out.Type = systemone.QuestionChoice
|
||||
case "score":
|
||||
if a.Score == nil {
|
||||
return out, fmt.Errorf("decisions: answer for %q has no score", a.Name)
|
||||
}
|
||||
out.Type = systemone.QuestionScore
|
||||
case "predicate":
|
||||
if a.Probability == nil {
|
||||
return out, fmt.Errorf("decisions: answer for %q has no probability", a.Name)
|
||||
}
|
||||
// "noul" is the shared wire name for a boolean answer.
|
||||
out.Type = systemone.WireType(systemone.QuestionBool)
|
||||
default:
|
||||
return out, fmt.Errorf("decisions: unknown answer type %q for %q", a.Type, a.Name)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// probabilities accepts either a label-to-probability object or the service's
|
||||
// list of value, label and probability, whichever the deployment returns.
|
||||
func probabilities(raw json.RawMessage) (map[string]float64, bool) {
|
||||
var object map[string]float64
|
||||
if err := json.Unmarshal(raw, &object); err == nil {
|
||||
return object, true
|
||||
}
|
||||
var list []struct {
|
||||
Value any `json:"value"`
|
||||
Label string `json:"label"`
|
||||
Probability float64 `json:"probability"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &list); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
out := make(map[string]float64, len(list))
|
||||
for _, p := range list {
|
||||
key := p.Label
|
||||
if key == "" {
|
||||
key = fmt.Sprint(p.Value)
|
||||
}
|
||||
out[key] = p.Probability
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// checkAnswers fails closed on an incomplete answer set, so a partial response
|
||||
// is never read as an approval.
|
||||
func checkAnswers(answers map[string]systemone.Answer, questions map[string]systemone.Question) error {
|
||||
if len(answers) == 0 {
|
||||
return errors.New("decisions: the model returned no answers")
|
||||
}
|
||||
for id, q := range questions {
|
||||
answer, ok := answers[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("decisions: no answer for question %q", id)
|
||||
}
|
||||
if want := systemone.WireType(q.Type); answer.Type != want {
|
||||
return fmt.Errorf("decisions: answer for %q has type %q, want %q", id, answer.Type, want)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type wireQuestion struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Instructions string `json:"instructions"`
|
||||
Choices []wireChoice `json:"choices,omitempty"`
|
||||
Levels []wireLevel `json:"levels,omitempty"`
|
||||
}
|
||||
|
||||
type wireChoice struct {
|
||||
Value string `json:"value"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type wireLevel struct {
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// questionWires renders the questions in a stable order.
|
||||
func questionWires(questions map[string]systemone.Question) ([]wireQuestion, error) {
|
||||
ids := make([]string, 0, len(questions))
|
||||
for id := range questions {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
out := make([]wireQuestion, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
q := questions[id]
|
||||
if strings.TrimSpace(q.Instructions) == "" {
|
||||
return nil, fmt.Errorf("decisions: question %q needs instructions", id)
|
||||
}
|
||||
wire := wireQuestion{Name: id, Instructions: q.Instructions}
|
||||
switch q.Type {
|
||||
case systemone.QuestionChoice:
|
||||
criteria, ok := q.Criteria.(map[string]string)
|
||||
if !ok || len(criteria) < 2 {
|
||||
return nil, fmt.Errorf("decisions: question %q needs at least two choices", id)
|
||||
}
|
||||
wire.Type = "choice"
|
||||
wire.Choices = choiceWires(criteria)
|
||||
case systemone.QuestionScore:
|
||||
levels, ok := q.Criteria.([]string)
|
||||
if !ok || len(levels) < 2 {
|
||||
return nil, fmt.Errorf("decisions: question %q needs at least two levels", id)
|
||||
}
|
||||
wire.Type = "score"
|
||||
wire.Levels = levelWires(levels)
|
||||
case systemone.QuestionBool:
|
||||
criteria, ok := q.Criteria.(map[string]string)
|
||||
if !ok || criteria["true"] == "" || criteria["false"] == "" {
|
||||
return nil, fmt.Errorf("decisions: question %q needs both criteria", id)
|
||||
}
|
||||
wire.Type = "predicate"
|
||||
wire.Instructions = predicateInstructions(q.Instructions, criteria)
|
||||
default:
|
||||
return nil, fmt.Errorf("decisions: question %q has unknown type %q", id, q.Type)
|
||||
}
|
||||
out = append(out, wire)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func choiceWires(criteria map[string]string) []wireChoice {
|
||||
keys := make([]string, 0, len(criteria))
|
||||
for key := range criteria {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
out := make([]wireChoice, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
out = append(out, wireChoice{Value: key, Description: criteria[key]})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func levelWires(levels []string) []wireLevel {
|
||||
out := make([]wireLevel, 0, len(levels))
|
||||
for _, level := range levels {
|
||||
out = append(out, wireLevel{Label: level, Description: level})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// predicateInstructions folds a bool question's two criteria into the one
|
||||
// instruction a predicate carries.
|
||||
func predicateInstructions(instructions string, criteria map[string]string) string {
|
||||
return instructions + "\n\nThe predicate is true when: " + criteria["true"] +
|
||||
"\nThe predicate is false when: " + criteria["false"]
|
||||
}
|
||||
|
||||
// RenderInput renders the state as labelled sections for the decision input.
|
||||
//
|
||||
// Sections keep a model's attention on one part at a time, and a nested value
|
||||
// that sections cannot make clearer is shown as indented JSON. The guards send
|
||||
// structured state, so the same input is rendered the same way every run.
|
||||
func RenderInput(state any) string {
|
||||
raw, err := json.Marshal(state)
|
||||
if err != nil {
|
||||
return fmt.Sprint(state)
|
||||
}
|
||||
var value any
|
||||
if err := json.Unmarshal(raw, &value); err != nil {
|
||||
return string(raw)
|
||||
}
|
||||
var b strings.Builder
|
||||
writeValue(&b, value, 0)
|
||||
return strings.TrimSpace(b.String())
|
||||
}
|
||||
|
||||
func writeValue(b *strings.Builder, value any, depth int) {
|
||||
switch v := value.(type) {
|
||||
case map[string]any:
|
||||
writeMap(b, v, depth)
|
||||
case []any:
|
||||
for _, item := range v {
|
||||
if isSimple(item) {
|
||||
fmt.Fprintf(b, "%s- %s\n", indent(depth), scalar(item))
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(b, "%s-\n", indent(depth))
|
||||
writeValue(b, item, depth+1)
|
||||
}
|
||||
default:
|
||||
if value != nil {
|
||||
fmt.Fprintf(b, "%s%s\n", indent(depth), scalar(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeMap(b *strings.Builder, m map[string]any, depth int) {
|
||||
keys := make([]string, 0, len(m))
|
||||
for key := range m {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
value := m[key]
|
||||
if isSimple(value) {
|
||||
fmt.Fprintf(b, "%s%s: %s\n", indent(depth), strings.ReplaceAll(key, "_", " "), scalar(value))
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(b, "\n%s %s\n", heading(depth), strings.ToUpper(strings.ReplaceAll(key, "_", " ")))
|
||||
writeValue(b, value, depth)
|
||||
}
|
||||
}
|
||||
|
||||
func isSimple(value any) bool {
|
||||
switch value.(type) {
|
||||
case nil, string, float64, bool:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// scalar renders a leaf value, pretty-printing a string that is itself JSON so
|
||||
// an action's input reads as structure rather than one long line.
|
||||
func scalar(value any) string {
|
||||
if value == nil {
|
||||
return "none"
|
||||
}
|
||||
s, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Sprint(value)
|
||||
}
|
||||
trimmed := strings.TrimSpace(s)
|
||||
if strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") {
|
||||
var out bytes.Buffer
|
||||
if json.Indent(&out, []byte(trimmed), "", " ") == nil {
|
||||
return "\n" + out.String()
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func indent(depth int) string { return strings.Repeat(" ", depth) }
|
||||
|
||||
func heading(depth int) string { return strings.Repeat("#", min(depth+2, 6)) }
|
||||
|
||||
// endpointPath is the request path without its host, which is what a stored
|
||||
// record keeps.
|
||||
func endpointPath(endpoint string) string {
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Path == "" {
|
||||
return endpoint
|
||||
}
|
||||
return u.Path
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "..."
|
||||
}
|
||||
@@ -135,6 +135,13 @@ type JudgeRecord struct {
|
||||
AdvisoryReason string
|
||||
// EvalDate is the day of the eval the judge's standing comes from.
|
||||
EvalDate string
|
||||
// Request and Response are the exact bodies the judge endpoint was sent
|
||||
// and returned, kept even when the call failed.
|
||||
Request []byte
|
||||
Response []byte
|
||||
EndpointPath string
|
||||
HTTPStatus int
|
||||
LatencyMS int64
|
||||
}
|
||||
|
||||
// Guard judges one concrete action.
|
||||
|
||||
@@ -66,6 +66,8 @@ func (s *server) Judge(ctx context.Context, req *guardv1.JudgeRequest) (*guardv1
|
||||
Model: j.Model, ResultId: j.ResultID, Answer: j.Answer, Confidence: j.Confidence, Reason: j.Reason,
|
||||
Basis: j.Basis, BasisDigest: j.BasisDigest, Answers: j.Answers,
|
||||
Trusted: j.Trusted, AdvisoryReason: j.AdvisoryReason, EvalDate: j.EvalDate,
|
||||
Request: j.Request, Response: j.Response,
|
||||
EndpointPath: j.EndpointPath, HttpStatus: int32(j.HTTPStatus), LatencyMs: j.LatencyMS,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
|
||||
@@ -905,7 +905,18 @@ type JudgeRecord struct {
|
||||
Trusted bool `protobuf:"varint,9,opt,name=trusted,proto3" json:"trusted,omitempty"`
|
||||
AdvisoryReason string `protobuf:"bytes,10,opt,name=advisory_reason,json=advisoryReason,proto3" json:"advisory_reason,omitempty"`
|
||||
// eval_date is the date of the eval the judge's standing comes from.
|
||||
EvalDate string `protobuf:"bytes,11,opt,name=eval_date,json=evalDate,proto3" json:"eval_date,omitempty"`
|
||||
EvalDate string `protobuf:"bytes,11,opt,name=eval_date,json=evalDate,proto3" json:"eval_date,omitempty"`
|
||||
// request is the exact body sent to the judge endpoint, and response the
|
||||
// exact body it returned, both kept for audit. A failed call records what
|
||||
// was sent and whatever came back.
|
||||
Request []byte `protobuf:"bytes,12,opt,name=request,proto3" json:"request,omitempty"`
|
||||
Response []byte `protobuf:"bytes,13,opt,name=response,proto3" json:"response,omitempty"`
|
||||
// endpoint_path is the path the request was sent to, without the host.
|
||||
EndpointPath string `protobuf:"bytes,14,opt,name=endpoint_path,json=endpointPath,proto3" json:"endpoint_path,omitempty"`
|
||||
// http_status is the response status, or 0 when no response arrived.
|
||||
HttpStatus int32 `protobuf:"varint,15,opt,name=http_status,json=httpStatus,proto3" json:"http_status,omitempty"`
|
||||
// latency_ms is how long the call took, measured by the caller.
|
||||
LatencyMs int64 `protobuf:"varint,16,opt,name=latency_ms,json=latencyMs,proto3" json:"latency_ms,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -1017,6 +1028,41 @@ func (x *JudgeRecord) GetEvalDate() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *JudgeRecord) GetRequest() []byte {
|
||||
if x != nil {
|
||||
return x.Request
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *JudgeRecord) GetResponse() []byte {
|
||||
if x != nil {
|
||||
return x.Response
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *JudgeRecord) GetEndpointPath() string {
|
||||
if x != nil {
|
||||
return x.EndpointPath
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *JudgeRecord) GetHttpStatus() int32 {
|
||||
if x != nil {
|
||||
return x.HttpStatus
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *JudgeRecord) GetLatencyMs() int64 {
|
||||
if x != nil {
|
||||
return x.LatencyMs
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
var File_guard_v1_guard_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_guard_v1_guard_proto_rawDesc = "" +
|
||||
@@ -1078,7 +1124,7 @@ const file_guard_v1_guard_proto_rawDesc = "" +
|
||||
"\bfindings\x18\x02 \x03(\v2\x11.guard.v1.FindingR\bfindings\x12\x1f\n" +
|
||||
"\vblind_spots\x18\x03 \x03(\tR\n" +
|
||||
"blindSpots\x12-\n" +
|
||||
"\x06judges\x18\x04 \x03(\v2\x15.guard.v1.JudgeRecordR\x06judges\"\xc3\x02\n" +
|
||||
"\x06judges\x18\x04 \x03(\v2\x15.guard.v1.JudgeRecordR\x06judges\"\xde\x03\n" +
|
||||
"\vJudgeRecord\x12\x14\n" +
|
||||
"\x05model\x18\x01 \x01(\tR\x05model\x12\x1b\n" +
|
||||
"\tresult_id\x18\x02 \x01(\tR\bresultId\x12\x16\n" +
|
||||
@@ -1093,7 +1139,14 @@ const file_guard_v1_guard_proto_rawDesc = "" +
|
||||
"\atrusted\x18\t \x01(\bR\atrusted\x12'\n" +
|
||||
"\x0fadvisory_reason\x18\n" +
|
||||
" \x01(\tR\x0eadvisoryReason\x12\x1b\n" +
|
||||
"\teval_date\x18\v \x01(\tR\bevalDate*\x95\x01\n" +
|
||||
"\teval_date\x18\v \x01(\tR\bevalDate\x12\x18\n" +
|
||||
"\arequest\x18\f \x01(\fR\arequest\x12\x1a\n" +
|
||||
"\bresponse\x18\r \x01(\fR\bresponse\x12#\n" +
|
||||
"\rendpoint_path\x18\x0e \x01(\tR\fendpointPath\x12\x1f\n" +
|
||||
"\vhttp_status\x18\x0f \x01(\x05R\n" +
|
||||
"httpStatus\x12\x1d\n" +
|
||||
"\n" +
|
||||
"latency_ms\x18\x10 \x01(\x03R\tlatencyMs*\x95\x01\n" +
|
||||
"\rReversibility\x12\x1d\n" +
|
||||
"\x19REVERSIBILITY_UNSPECIFIED\x10\x00\x12&\n" +
|
||||
"\"REVERSIBILITY_UNDONE_AUTOMATICALLY\x10\x01\x12\x1d\n" +
|
||||
|
||||
+11
-9
@@ -4,13 +4,10 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archipelago/sdk/systemone"
|
||||
)
|
||||
|
||||
// EvalSpec is what a guard supplies to measure its judge.
|
||||
@@ -25,26 +22,31 @@ type EvalSpec[T any] struct {
|
||||
Load func(path string) ([]T, error)
|
||||
// Judge asks the judge about one case and grades its answer against the
|
||||
// case's label. On an error it still returns the case's id and label.
|
||||
Judge func(ctx context.Context, c systemone.Client, tc T) (Graded, error)
|
||||
Judge func(ctx context.Context, c Client, tc T) (Graded, error)
|
||||
}
|
||||
|
||||
// RunEval is a guard's cmd/eval: it measures the judge named on the command
|
||||
// line against the labelled cases and writes the record the guard reads at start.
|
||||
func RunEval[T any](spec EvalSpec[T]) error {
|
||||
base := flag.String("base", "", "System One base URL including its version segment")
|
||||
model := flag.String("model", "", "judge model id")
|
||||
api := flag.String("api", APISystemOne, "judge backend: systemone or openai-decisions")
|
||||
base := flag.String("base", "", "judge base URL; required for systemone, defaults for openai-decisions")
|
||||
model := flag.String("model", "", "judge model id; defaults for openai-decisions")
|
||||
cases := flag.String("cases", "eval/cases.json", "labelled cases")
|
||||
out := flag.String("out", "eval_result.json", "where to write the result")
|
||||
answers := flag.String("answers", "eval/answers.json", "where to write every case's answer for review")
|
||||
flag.Parse()
|
||||
if *base == "" || *model == "" {
|
||||
return errors.New("-base and -model are required")
|
||||
key := os.Getenv(spec.KeyEnv)
|
||||
if *api == APIOpenAIDecisions {
|
||||
key = os.Getenv("OPENAI_API_KEY")
|
||||
}
|
||||
client, err := EvalClient(*api, *base, *model, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
loaded, err := spec.Load(*cases)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client := systemone.Client{BaseURL: *base, Model: *model, APIKey: os.Getenv(spec.KeyEnv), Label: "judge"}
|
||||
measured := Measure(context.Background(), loaded, func(ctx context.Context, tc T) (Graded, error) {
|
||||
return spec.Judge(ctx, client, tc)
|
||||
})
|
||||
|
||||
@@ -13,10 +13,12 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archipelago/sdk/decisions"
|
||||
"github.com/samcharles93/archipelago/sdk/guard"
|
||||
"github.com/samcharles93/archipelago/sdk/systemone"
|
||||
)
|
||||
@@ -24,15 +26,73 @@ import (
|
||||
// DefaultMaxAgeDays is how long a passing evaluation stays trusted.
|
||||
const DefaultMaxAgeDays = 90
|
||||
|
||||
// Client builds the System One client the settings name: judge_base_url and
|
||||
// judge_model, and the optional secret judge_api_key. ok is false when either
|
||||
// setting is empty.
|
||||
func Client(cfg guard.Config) (c systemone.Client, ok bool) {
|
||||
base, model := cfg.Settings["judge_base_url"], cfg.Settings["judge_model"]
|
||||
if base == "" || model == "" {
|
||||
return systemone.Client{}, false
|
||||
// Client is a judge endpoint a guard asks. System One and the OpenAI
|
||||
// Decisions API answer the same typed questions through it.
|
||||
type Client interface {
|
||||
// ModelID is the model this client asks.
|
||||
ModelID() string
|
||||
// Deployment names the endpoint in reports, such as "judge" or
|
||||
// "openai-decisions".
|
||||
Deployment() string
|
||||
Classify(ctx context.Context, state any, questions map[string]systemone.Question) (systemone.Result, error)
|
||||
}
|
||||
|
||||
// The judge backends judge_api selects.
|
||||
const (
|
||||
APISystemOne = "systemone"
|
||||
APIOpenAIDecisions = "openai-decisions"
|
||||
)
|
||||
|
||||
// NewClient builds the judge the settings name. judge_api selects systemone
|
||||
// (the default) or openai-decisions. System One needs judge_base_url and
|
||||
// judge_model; the Decisions API defaults its base URL and model. ok is false
|
||||
// when a required setting is empty.
|
||||
func NewClient(cfg guard.Config) (Client, bool, error) {
|
||||
switch api := strings.TrimSpace(cfg.Settings["judge_api"]); api {
|
||||
case "", APISystemOne:
|
||||
base, model := cfg.Settings["judge_base_url"], cfg.Settings["judge_model"]
|
||||
if base == "" || model == "" {
|
||||
return nil, false, nil
|
||||
}
|
||||
return systemone.Client{BaseURL: base, Model: model, APIKey: cfg.Secrets["judge_api_key"], Label: "judge"}, true, nil
|
||||
case APIOpenAIDecisions:
|
||||
base := cfg.Settings["judge_base_url"]
|
||||
if base == "" {
|
||||
base = decisions.DefaultBaseURL
|
||||
}
|
||||
model := cfg.Settings["judge_model"]
|
||||
if model == "" {
|
||||
model = decisions.DefaultModel
|
||||
}
|
||||
key := cfg.Secrets["judge_api_key"]
|
||||
if key == "" {
|
||||
key = os.Getenv("OPENAI_API_KEY")
|
||||
}
|
||||
return decisions.Client{BaseURL: base, Model: model, APIKey: key, Label: APIOpenAIDecisions}, true, nil
|
||||
default:
|
||||
return nil, false, fmt.Errorf("judge_api %q must be %s or %s", api, APISystemOne, APIOpenAIDecisions)
|
||||
}
|
||||
}
|
||||
|
||||
// EvalClient builds the judge named on an eval command line.
|
||||
func EvalClient(api, base, model, key string) (Client, error) {
|
||||
switch api {
|
||||
case "", APISystemOne:
|
||||
if base == "" || model == "" {
|
||||
return nil, errors.New("-base and -model are required for systemone")
|
||||
}
|
||||
return systemone.Client{BaseURL: base, Model: model, APIKey: key, Label: "judge"}, nil
|
||||
case APIOpenAIDecisions:
|
||||
if base == "" {
|
||||
base = decisions.DefaultBaseURL
|
||||
}
|
||||
if model == "" {
|
||||
model = decisions.DefaultModel
|
||||
}
|
||||
return decisions.Client{BaseURL: base, Model: model, APIKey: key, Label: APIOpenAIDecisions}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("-api %q must be %s or %s", api, APISystemOne, APIOpenAIDecisions)
|
||||
}
|
||||
return systemone.Client{BaseURL: base, Model: model, APIKey: cfg.Secrets["judge_api_key"], Label: "judge"}, true
|
||||
}
|
||||
|
||||
// MaxAge is how long a passing evaluation stays trusted, from eval_max_age_days.
|
||||
@@ -189,6 +249,13 @@ type Graded struct {
|
||||
// Reason is what the answer rests on: the rule cited or the gap found.
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
// Request and Response are the exact bodies the judge endpoint was sent
|
||||
// and returned, kept for review even when the call failed.
|
||||
Request string `json:"request,omitempty"`
|
||||
Response string `json:"response,omitempty"`
|
||||
EndpointPath string `json:"endpoint_path,omitempty"`
|
||||
HTTPStatus int `json:"http_status,omitempty"`
|
||||
LatencyMS int64 `json:"latency_ms,omitempty"`
|
||||
}
|
||||
|
||||
// Measure runs every case through judge and scores the answers against the
|
||||
|
||||
+25
-2
@@ -37,12 +37,25 @@ type Call struct {
|
||||
Answers []byte
|
||||
// Basis is the text the judge was given beyond the action.
|
||||
Basis string
|
||||
// Request and Response are the exact bodies sent and received, and the
|
||||
// path, status and latency that describe the call. They are set even when
|
||||
// the call failed.
|
||||
Request []byte
|
||||
Response []byte
|
||||
EndpointPath string
|
||||
HTTPStatus int
|
||||
LatencyMS int64
|
||||
}
|
||||
|
||||
// CallOf describes a call made to model that returned res, whether or not it
|
||||
// succeeded: a failed call still names the model and the basis it was given.
|
||||
// succeeded: a failed call still names the model, the basis it was given, and
|
||||
// what was sent and received.
|
||||
func CallOf(model, basis string, res systemone.Result) Call {
|
||||
c := Call{Model: model, ResultID: res.ID, Basis: basis}
|
||||
c := Call{
|
||||
Model: model, ResultID: res.ID, Basis: basis,
|
||||
Request: res.Request, Response: res.Response,
|
||||
EndpointPath: res.EndpointPath, HTTPStatus: res.HTTPStatus, LatencyMS: res.Latency.Milliseconds(),
|
||||
}
|
||||
if res.Model != "" {
|
||||
c.Model = res.Model
|
||||
}
|
||||
@@ -52,6 +65,14 @@ func CallOf(model, basis string, res systemone.Result) Call {
|
||||
return c
|
||||
}
|
||||
|
||||
// Attach copies what the call sent and received into a review record, so a
|
||||
// case's answer keeps its payload even when the judge failed.
|
||||
func (c Call) Attach(g Graded) Graded {
|
||||
g.Request, g.Response = string(c.Request), string(c.Response)
|
||||
g.EndpointPath, g.HTTPStatus, g.LatencyMS = c.EndpointPath, c.HTTPStatus, c.LatencyMS
|
||||
return g
|
||||
}
|
||||
|
||||
// Record is what the call answered, kept whole so the verdict can be audited
|
||||
// without asking the model again.
|
||||
func (c Call) Record(answer string, confidence float64, reason string, st Standing) guard.JudgeRecord {
|
||||
@@ -59,6 +80,8 @@ func (c Call) Record(answer string, confidence float64, reason string, st Standi
|
||||
Model: c.Model, ResultID: c.ResultID, Answer: answer, Confidence: confidence, Reason: reason,
|
||||
Basis: c.Basis, Answers: c.Answers,
|
||||
Trusted: st.Trusted, AdvisoryReason: st.Reason, EvalDate: st.EvalDate,
|
||||
Request: c.Request, Response: c.Response,
|
||||
EndpointPath: c.EndpointPath, HTTPStatus: c.HTTPStatus, LatencyMS: c.LatencyMS,
|
||||
}
|
||||
if c.Basis != "" {
|
||||
sum := sha256.Sum256([]byte(c.Basis))
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -226,6 +227,13 @@ type Result struct {
|
||||
Usage *Usage `json:"usage,omitempty"`
|
||||
StopReason string `json:"stopReason,omitempty"`
|
||||
ErrorMessage string `json:"errorMessage,omitempty"`
|
||||
// Request is the exact body sent to the endpoint, and Response the exact
|
||||
// body it returned. Both are kept even when the call fails, so a failed
|
||||
// judge call still records what was asked and whatever came back.
|
||||
Request []byte `json:"-"`
|
||||
Response []byte `json:"-"`
|
||||
EndpointPath string `json:"-"`
|
||||
HTTPStatus int `json:"-"`
|
||||
// Latency is measured by this client, not reported by the service.
|
||||
Latency time.Duration `json:"-"`
|
||||
}
|
||||
@@ -289,6 +297,12 @@ func (c Client) Endpoint() string {
|
||||
return strings.TrimRight(c.BaseURL, "/") + "/systemone"
|
||||
}
|
||||
|
||||
// ModelID is the model this client asks.
|
||||
func (c Client) ModelID() string { return c.Model }
|
||||
|
||||
// Deployment names the endpoint in reports.
|
||||
func (c Client) Deployment() string { return c.Label }
|
||||
|
||||
// Classify asks every question about state in one request.
|
||||
//
|
||||
// State is any JSON value: the API accepts an object of named fields, and the
|
||||
@@ -322,11 +336,14 @@ func (c Client) Classify(ctx context.Context, state any, questions map[string]Qu
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
endpoint := c.Endpoint()
|
||||
result := Result{Request: body, EndpointPath: endpointPath(endpoint), Model: c.Model, Provider: c.Label}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.Endpoint(), bytes.NewReader(body))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("systemone: build request: %w", err)
|
||||
return result, fmt.Errorf("systemone: build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if c.APIKey != "" {
|
||||
@@ -340,25 +357,26 @@ func (c Client) Classify(ctx context.Context, state any, questions map[string]Qu
|
||||
start := time.Now()
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("systemone: %s: %w", c.Label, err)
|
||||
result.Latency = time.Since(start)
|
||||
return result, fmt.Errorf("systemone: %s: %w", c.Label, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
latency := time.Since(start)
|
||||
|
||||
result.Latency = time.Since(start)
|
||||
result.HTTPStatus = resp.StatusCode
|
||||
payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
result.Response = payload
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("systemone: read response: %w", err)
|
||||
return result, fmt.Errorf("systemone: read response: %w", err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return Result{}, fmt.Errorf("systemone: %s returned HTTP %d%s: %s",
|
||||
return result, fmt.Errorf("systemone: %s returned HTTP %d%s: %s",
|
||||
c.Label, resp.StatusCode, statusHint(resp.StatusCode), truncate(string(payload), 300))
|
||||
}
|
||||
|
||||
var result Result
|
||||
if err := json.Unmarshal(payload, &result); err != nil {
|
||||
return Result{}, fmt.Errorf("systemone: decode response: %w", err)
|
||||
return result, fmt.Errorf("systemone: decode response: %w", err)
|
||||
}
|
||||
result.Latency = latency
|
||||
if result.Provider == "" {
|
||||
result.Provider = c.Label
|
||||
}
|
||||
@@ -439,6 +457,16 @@ func statusHint(status int) string {
|
||||
}
|
||||
}
|
||||
|
||||
// endpointPath is the request path without its host, which is what a stored
|
||||
// record keeps.
|
||||
func endpointPath(endpoint string) string {
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Path == "" {
|
||||
return endpoint
|
||||
}
|
||||
return u.Path
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) <= n {
|
||||
|
||||
Reference in new issue
Block a user