gateway: /v1/decisions asks a System One decision model, and /v1/systemone a Decisions-only one (wudi_boy)
wudi_boy on Discord: a Decisions request (Python-urllib) to the Qwen
decision model, decision-model-preview, was refused, while the same
model answered on /v1/systemone. canDecide sent Decisions only to an
OpenAI key, Azure or another magpie, and nothing translated between the
two APIs.
Now a Decisions request whose model answers System One (Qwen's, Ark's,
a Jev, a Clef, a plugin's, or a decision group whose members do, none
of them a provider that serves Decisions itself) is asked there
(decisions_systemone.go): predicate -> noul, choice -> criteria map
(boolean values as "true"/"false", typed back on the answer), score ->
criteria list "label: description" least first, an unnamed question ->
question_N answered with a null name, input -> state (a string as it
is, items as {"messages":[{role, content, refusal}]}, input_json as its
JSON text). The answer comes back in the Decisions shape in the
questions' order, a missing answer as refusal, with input and output
tokens. prompt_cache_key/options and safety_identifier change no answer
and are left out. Everything with no counterpart is a 400 naming it,
before the vendor is asked: an image unless every target is a Clef or
another magpie, an http image, function/custom tool calls and outputs,
an image or refusal in a question, any other field or question type.
The reverse: /v1/systemone whose model no System One provider has but
the Decisions API serves (openai/gpt-6-luna) goes through
serveRetrieval as /v1/decisions does, and is answered as System One.
A vendor's error passes through as it was said.
Tests, against fakes with the real shapes (Ark's 2026-11-01 System One
answer, Cloudflare's result envelope, openai-python's Decision):
TestDecisionsAskSystemOne, TestDecisionsMessagesAsSystemOneState,
TestDecisionsUntranslatableRefused, TestDecisionsImagesToClef,
TestSystemOneAsksDecisions.
Run on mote (mote-run) at this change on d4712e131: go test -count=1
-timeout 45m ./internal/gateway ok (777s); go vet ./internal/gateway
for darwin, linux and windows clean; gofmt -l clean. Full suite queued
under the suite lock, not run.
Broken by hand, each red: the decide branch taken out (the qwen tests
400 "no OpenAI-style API"); the reverse call in serveSystemOne off
(404 "no Jev provider"); an image to a text-only model and a
function_call dropped silently instead of refused (200 instead of 400).
Not tried: a real Qwen or Ark key, or a real OpenAI Decisions call; a
plugin's decision model through the translation.
Reported-by: wudi_boy
This commit is contained in:
@@ -1052,6 +1052,19 @@ only `model` changed, to an OpenAI API key, to Azure OpenAI (at
|
||||
magpie. Any other provider is refused with a 400 that says so. Only input
|
||||
tokens are counted, cached ones apart.
|
||||
|
||||
A decision model that answers System One instead (Qwen's
|
||||
`decision-model-preview`, Ark's, a Jev, a Clef, a plugin's, or a decision
|
||||
group) is asked there: a predicate goes as a `noul` question, a choice's
|
||||
values as its criteria, a score's levels as its criteria least first, and
|
||||
`input` as the state (a string as it is, messages as
|
||||
`{"messages":[{role, content}]}`, JSON parts as their JSON). The answer comes
|
||||
back in the Decisions shape, in the questions' order, with the input and
|
||||
output tokens. What System One has no counterpart for (an image where the
|
||||
model isn't a Clef, a tool call or its output, another field such as
|
||||
`reasoning`) is refused with a 400 that names it, and nothing is sent. The
|
||||
other way, `/v1/systemone` with a model only the Decisions API serves
|
||||
(`openai/gpt-6-luna`) is asked there and answered as System One answers.
|
||||
|
||||
```sh
|
||||
curl localhost:3425/v1/decisions -H "Authorization: Bearer $MAGPIE_KEY" \
|
||||
-d '{"model":"gpt-6-luna","input":"The parcel arrived torn open.","questions":[{"type":"predicate","name":"damaged","instructions":"Was the parcel damaged?"}]}'
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -572,6 +572,13 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
s.serveSystemOneBody(w, r, body)
|
||||
}
|
||||
|
||||
// serveSystemOneBody answers a System One request read: from
|
||||
// /v1/systemone, or one /v1/decisions was translated to
|
||||
// (decisions_systemone.go).
|
||||
func (s *Server) serveSystemOneBody(w http.ResponseWriter, r *http.Request, body []byte) {
|
||||
var q struct {
|
||||
Model string `json:"model"`
|
||||
}
|
||||
@@ -595,6 +602,12 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
p, model, err := provider.RouteDecider(q.Model)
|
||||
if err != nil {
|
||||
// no decision model by that name, but one OpenAI's Decisions
|
||||
// API serves: asked there, the request and its answer
|
||||
// translated (decisions_systemone.go)
|
||||
if st := provider.DecideRouteStatus(err); st == http.StatusNotFound && s.systemOneByDecisions(w, r, body, q.Model) {
|
||||
return
|
||||
}
|
||||
writeError(w, provider.Chat, provider.DecideRouteStatus(err), err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -28,7 +28,8 @@ var decisionModels = []string{"gpt-6-luna"}
|
||||
// body goes as the agent sent it to a provider that can serve the API
|
||||
// (canDecide), at its OpenAI-style base + /decisions (Azure's
|
||||
// /openai/v1/decisions), and the answer comes back as it said it. The
|
||||
// API isn't streamed, and bills input tokens only.
|
||||
// API isn't streamed, and bills input tokens only. A model that answers
|
||||
// System One instead is asked there, translated (decideBySystemOne).
|
||||
func (s *Server) decide(w http.ResponseWriter, r *http.Request) {
|
||||
body, admitted := s.requestBody(w, r, provider.Chat)
|
||||
if !admitted {
|
||||
@@ -46,6 +47,15 @@ func (s *Server) decide(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, provider.Chat, 400, "name the model: \"model\" is a magpie model id, as /v1/models lists them (OpenAI's Decisions API takes gpt-6-luna)")
|
||||
return
|
||||
}
|
||||
// a decision model that answers System One, not this API (Bailian's
|
||||
// decision-model-preview, Ark's, a Jev, a Clef, a plugin's, or a
|
||||
// group of them): asked there, the request and its answer
|
||||
// translated (decisions_systemone.go). One that serves this API
|
||||
// itself (another magpie) is asked here, as it was.
|
||||
if ts, ok := systemOneTargets(asked); ok && !slices.ContainsFunc(ts, func(t systemOneTarget) bool { return canDecide(t.p) }) {
|
||||
s.decideBySystemOne(w, r, req, asked, ts)
|
||||
return
|
||||
}
|
||||
s.serveRetrieval(w, r, "/decisions", "decisions", start, asked, &decisionRequest{jsonRetrieval{req: req}})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,699 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// OpenAI's Decisions API (/v1/decisions) and System One (/v1/systemone)
|
||||
// ask the same thing in two shapes, so a request at either reaches a
|
||||
// model that answers only the other (wudi_boy on Discord): a Decisions
|
||||
// request to Bailian's decision-model-preview, Ark's, a Jev, a Clef, a
|
||||
// plugin's decision model or a group of them is asked as System One, and
|
||||
// a System One request to gpt-6-luna as Decisions; each answer comes back
|
||||
// in the shape it was asked in.
|
||||
//
|
||||
// Decisions System One
|
||||
// input: text state: the text
|
||||
// input: messages state: {"messages":[{role, content}]}
|
||||
// input_json part its data, as JSON text
|
||||
// input_image part images (a Clef's alone)
|
||||
// predicate noul (boolean at Vercel's)
|
||||
// choice, choices[].value choice, criteria {value: description}
|
||||
// score, levels[].label score, criteria [level, ...] least first
|
||||
// answers [{name, ...}] in order answers {name: {...}}
|
||||
// usage.input/output_tokens usage.input/output_tokens
|
||||
//
|
||||
// What has no counterpart is refused with a 400 that names it, never
|
||||
// dropped: a tool call or its output, an image where the model takes
|
||||
// none, an image in a question's instructions, a field the other API
|
||||
// lacks. Prompt-cache hints and safety_identifier change no answer and
|
||||
// System One has no place for them, so they alone go unsent.
|
||||
|
||||
// decisionQ is a Decisions question as it went to System One, for its
|
||||
// answer to come back as Decisions gives one.
|
||||
type decisionQ struct {
|
||||
name *string // the agent's name for it; nil when it named none
|
||||
key string // its name in System One's questions
|
||||
kind string // predicate, choice or score
|
||||
order []string
|
||||
values map[string]json.RawMessage // a choice's criteria, each its typed value
|
||||
}
|
||||
|
||||
// untranslatable is a part of a request the other API has no counterpart
|
||||
// for: the request is refused with a 400 that names it.
|
||||
type untranslatable string
|
||||
|
||||
func (e untranslatable) Error() string { return string(e) }
|
||||
|
||||
func untranslated(format string, a ...any) error { return untranslatable(fmt.Sprintf(format, a...)) }
|
||||
|
||||
// decisionsUnsent are the Decisions fields that go unsent to System One:
|
||||
// hints that change no answer.
|
||||
var decisionsUnsent = []string{"prompt_cache_key", "prompt_cache_options", "safety_identifier"}
|
||||
|
||||
// systemOneTarget is a decision model a translated request may reach.
|
||||
type systemOneTarget struct {
|
||||
p provider.Provider
|
||||
model string
|
||||
}
|
||||
|
||||
// takesImages is whether the model takes a System One request's images:
|
||||
// a Clef on Workers AI does, and another magpie passes them on.
|
||||
func (t systemOneTarget) takesImages() bool {
|
||||
if t.p.IsRemoteMagpie() {
|
||||
return true
|
||||
}
|
||||
return t.p.DecideVia() == provider.ViaCloudflare && provider.CloudflareClef(t.model)
|
||||
}
|
||||
|
||||
func (t systemOneTarget) String() string { return t.p.ID + "/" + t.model }
|
||||
|
||||
// systemOneTargets are the decision models System One would ask for the
|
||||
// model asked — a decision group's members, or the one RouteDecider
|
||||
// finds — and whether there are any.
|
||||
func systemOneTargets(asked string) ([]systemOneTarget, bool) {
|
||||
if _, ms, ok, _, err := decisionGroupOf(asked); err == nil && ok {
|
||||
var ts []systemOneTarget
|
||||
for _, m := range ms {
|
||||
ts = append(ts, systemOneTarget{m.Provider, m.Model})
|
||||
}
|
||||
return ts, len(ts) > 0
|
||||
}
|
||||
p, model, err := provider.RouteDecider(asked)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return []systemOneTarget{{p, model}}, true
|
||||
}
|
||||
|
||||
// decideBySystemOne answers a Decisions request whose model answers
|
||||
// System One: asked there, its answer in Decisions' shape.
|
||||
func (s *Server) decideBySystemOne(w http.ResponseWriter, r *http.Request, req map[string]json.RawMessage, asked string, ts []systemOneTarget) {
|
||||
body, qs, err := decisionsAsSystemOne(req, asked, ts)
|
||||
if err != nil {
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
s.serveSystemOneBody(rec, r, body)
|
||||
passTranslated(w, rec, func(b []byte) ([]byte, error) { return systemOneAsDecision(b, qs, asked) })
|
||||
}
|
||||
|
||||
// systemOneByDecisions answers a System One request whose model only
|
||||
// OpenAI's Decisions API serves: asked there, its answer in System One's
|
||||
// shape. false when no provider serves the model there, and the caller
|
||||
// says so as it would.
|
||||
func (s *Server) systemOneByDecisions(w http.ResponseWriter, r *http.Request, body []byte, asked string) bool {
|
||||
if _, _, ok := resolveRetrievalModel(asked, kindDecision); !ok {
|
||||
return false
|
||||
}
|
||||
req, keys, err := systemOneAsDecisions(body)
|
||||
if err != nil {
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, err.Error())
|
||||
return true
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
s.serveRetrieval(rec, r, "/decisions", "decisions", time.Now(), asked, &decisionRequest{jsonRetrieval{req: req}})
|
||||
passTranslated(w, rec, func(b []byte) ([]byte, error) { return decisionAsSystemOne(b, keys) })
|
||||
return true
|
||||
}
|
||||
|
||||
// passTranslated passes on the answer rec holds: a 2xx translated, an
|
||||
// error as it was said.
|
||||
func passTranslated(w http.ResponseWriter, rec *httptest.ResponseRecorder, translate func([]byte) ([]byte, error)) {
|
||||
b := rec.Body.Bytes()
|
||||
if rec.Code < 300 {
|
||||
out, err := translate(b)
|
||||
if err != nil {
|
||||
writeError(w, provider.Chat, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
b = out
|
||||
}
|
||||
h := w.Header()
|
||||
for k, vs := range rec.Header() {
|
||||
h[k] = vs
|
||||
}
|
||||
h.Del("Content-Length")
|
||||
if rec.Code < 300 {
|
||||
h.Set("Content-Type", "application/json")
|
||||
}
|
||||
w.WriteHeader(rec.Code)
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
// decisionsAsSystemOne is a Decisions request as System One asks it of
|
||||
// the model asked (ts, what it may reach), and its questions in order.
|
||||
func decisionsAsSystemOne(req map[string]json.RawMessage, asked string, ts []systemOneTarget) ([]byte, []decisionQ, error) {
|
||||
for _, k := range slices.Sorted(maps.Keys(req)) {
|
||||
if k != "model" && k != "input" && k != "questions" && !slices.Contains(decisionsUnsent, k) {
|
||||
return nil, nil, untranslated("%q has no counterpart in System One, which %s answers", k, asked)
|
||||
}
|
||||
}
|
||||
var images []string
|
||||
state, err := decisionsState(req["input"], ts, &images)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var raw []json.RawMessage
|
||||
if err := json.Unmarshal(req["questions"], &raw); err != nil || len(raw) == 0 {
|
||||
return nil, nil, untranslated("\"questions\" is a list of 1 to 400 questions")
|
||||
}
|
||||
type question struct {
|
||||
Type string `json:"type"`
|
||||
Name *string `json:"name"`
|
||||
Instructions json.RawMessage `json:"instructions"`
|
||||
Choices []struct {
|
||||
Value json.RawMessage `json:"value"`
|
||||
Description *string `json:"description"`
|
||||
} `json:"choices"`
|
||||
Levels []struct {
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
} `json:"levels"`
|
||||
}
|
||||
asks := make([]question, len(raw))
|
||||
qs := make([]decisionQ, len(raw))
|
||||
named := map[string]bool{}
|
||||
for i, b := range raw {
|
||||
q := &asks[i]
|
||||
if err := json.Unmarshal(b, q); err != nil {
|
||||
return nil, nil, untranslated("questions[%d] is not a question: %v", i, err)
|
||||
}
|
||||
if q.Name != nil {
|
||||
if named[*q.Name] {
|
||||
return nil, nil, untranslated("questions[%d]: two questions are named %q, and System One asks each by its name", i, *q.Name)
|
||||
}
|
||||
named[*q.Name] = true
|
||||
}
|
||||
qs[i] = decisionQ{name: q.Name, kind: q.Type}
|
||||
}
|
||||
sq := map[string]any{}
|
||||
for i, q := range asks {
|
||||
d := &qs[i]
|
||||
if d.name != nil {
|
||||
d.key = *d.name
|
||||
} else {
|
||||
// an unnamed question is named for System One, as no named one is
|
||||
for n := i + 1; ; n++ {
|
||||
if d.key = "question_" + strconv.Itoa(n); !named[d.key] {
|
||||
named[d.key] = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
instr, refusal, err := decisionsText(q.Instructions, fmt.Sprintf("questions[%d].instructions", i), nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if refusal != "" {
|
||||
return nil, nil, untranslated("questions[%d].instructions has a refusal part, which only an assistant's message has", i)
|
||||
}
|
||||
switch d.kind {
|
||||
case "predicate":
|
||||
sq[d.key] = map[string]any{"type": "noul", "instructions": instr}
|
||||
case "choice":
|
||||
criteria := map[string]any{}
|
||||
d.values = map[string]json.RawMessage{}
|
||||
for j, c := range q.Choices {
|
||||
var key string
|
||||
var on bool
|
||||
switch {
|
||||
case json.Unmarshal(c.Value, &key) == nil:
|
||||
case json.Unmarshal(c.Value, &on) == nil:
|
||||
key = strconv.FormatBool(on)
|
||||
default:
|
||||
return nil, nil, untranslated("questions[%d].choices[%d].value is neither a string nor a boolean", i, j)
|
||||
}
|
||||
if _, dup := d.values[key]; dup {
|
||||
return nil, nil, untranslated("questions[%d].choices[%d]: %q is there twice (as a string and as a boolean), and System One names a choice by its text alone", i, j, key)
|
||||
}
|
||||
d.values[key], d.order = c.Value, append(d.order, key)
|
||||
if c.Description != nil {
|
||||
criteria[key] = *c.Description
|
||||
} else {
|
||||
criteria[key] = nil
|
||||
}
|
||||
}
|
||||
sq[d.key] = map[string]any{"type": "choice", "instructions": instr, "criteria": criteria}
|
||||
case "score":
|
||||
levels := make([]string, len(q.Levels))
|
||||
for j, l := range q.Levels {
|
||||
d.order = append(d.order, l.Label)
|
||||
levels[j] = l.Label
|
||||
if l.Description != "" {
|
||||
levels[j] += ": " + l.Description
|
||||
}
|
||||
}
|
||||
sq[d.key] = map[string]any{"type": "score", "instructions": instr, "criteria": levels}
|
||||
default:
|
||||
return nil, nil, untranslated("questions[%d] is a %q question, which System One has no counterpart for (it asks predicate, choice and score)", i, d.kind)
|
||||
}
|
||||
}
|
||||
out := map[string]any{"model": asked, "state": state, "questions": sq}
|
||||
if len(images) > 0 {
|
||||
out["images"] = images
|
||||
}
|
||||
body, err := json.Marshal(out)
|
||||
return body, qs, err
|
||||
}
|
||||
|
||||
// decisionsState is a Decisions input as System One's state: its text,
|
||||
// or a conversation's messages, each one's parts as text. A message's
|
||||
// images are put in images, where every model ts names takes them.
|
||||
func decisionsState(input json.RawMessage, ts []systemOneTarget, images *[]string) (any, error) {
|
||||
var text string
|
||||
if json.Unmarshal(input, &text) == nil {
|
||||
return text, nil
|
||||
}
|
||||
var items []map[string]json.RawMessage
|
||||
if err := json.Unmarshal(input, &items); err != nil {
|
||||
return nil, untranslated("\"input\" is neither text nor a list of messages")
|
||||
}
|
||||
msgs := make([]map[string]any, 0, len(items))
|
||||
for i, it := range items {
|
||||
var typ, role string
|
||||
json.Unmarshal(it["type"], &typ)
|
||||
json.Unmarshal(it["role"], &role)
|
||||
if typ != "" && typ != "message" {
|
||||
return nil, untranslated("input[%d] is a %s, which System One has no counterpart for: it is asked a state, not a conversation's tool calls and their outputs", i, typ)
|
||||
}
|
||||
if role == "" {
|
||||
return nil, untranslated("input[%d] is a message with no role", i)
|
||||
}
|
||||
content, refusal, err := decisionsText(it["content"], fmt.Sprintf("input[%d].content", i), func(where, url string) error {
|
||||
for _, t := range ts {
|
||||
if !t.takesImages() {
|
||||
return untranslated("%s is an image (input_image), which %s can't take: System One takes images only for Cloudflare's Clef", where, t)
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(url, "data:") {
|
||||
return untranslated("%s is an image at a URL; System One's Clef takes an image only as a data: URL", where)
|
||||
}
|
||||
*images = append(*images, url)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m := map[string]any{"role": role, "content": content}
|
||||
if refusal != "" { // an assistant's refusal, kept as what it is
|
||||
m["refusal"] = refusal
|
||||
}
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
return map[string]any{"messages": msgs}, nil
|
||||
}
|
||||
|
||||
// decisionsText is a Decisions content (where it is: text, or a list of
|
||||
// parts) as one text: its input_text and output_text parts as written,
|
||||
// its input_json parts' data as JSON, and apart from them its refusal
|
||||
// parts' text. An image goes to image, or, where there is none (a
|
||||
// question's instructions), is refused.
|
||||
func decisionsText(raw json.RawMessage, where string, image func(where, url string) error) (text, refusal string, err error) {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return "", "", nil
|
||||
}
|
||||
if json.Unmarshal(raw, &text) == nil {
|
||||
return text, "", nil
|
||||
}
|
||||
var parts []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Refusal string `json:"refusal"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
ImageURL string `json:"image_url"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &parts); err != nil {
|
||||
return "", "", untranslated("%s is neither text nor a list of parts", where)
|
||||
}
|
||||
var out, refused []string
|
||||
for j, p := range parts {
|
||||
at := fmt.Sprintf("%s[%d]", where, j)
|
||||
switch p.Type {
|
||||
case "input_text", "output_text":
|
||||
out = append(out, p.Text)
|
||||
case "refusal":
|
||||
refused = append(refused, p.Refusal)
|
||||
case "input_json":
|
||||
var buf bytes.Buffer
|
||||
if err := json.Compact(&buf, p.Data); err != nil {
|
||||
return "", "", untranslated("%s is input_json with no JSON data", at)
|
||||
}
|
||||
out = append(out, buf.String())
|
||||
case "input_image":
|
||||
if image == nil {
|
||||
return "", "", untranslated("%s is an image (input_image), which System One has no counterpart for in a question's instructions", at)
|
||||
}
|
||||
if err := image(at, p.ImageURL); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
default:
|
||||
return "", "", untranslated("%s is a %q part, which System One has no counterpart for", at, p.Type)
|
||||
}
|
||||
}
|
||||
return strings.Join(out, "\n"), strings.Join(refused, "\n"), nil
|
||||
}
|
||||
|
||||
// systemOneUsage is a System One answer's usage.
|
||||
type systemOneUsage struct {
|
||||
Input int `json:"input_tokens"`
|
||||
Output int `json:"output_tokens"`
|
||||
}
|
||||
|
||||
// systemOneAsDecision is a System One answer as Decisions answers qs:
|
||||
// each question's answer in their order, one System One left out a
|
||||
// refusal, as Decisions says a question it didn't answer.
|
||||
func systemOneAsDecision(b []byte, qs []decisionQ, asked string) ([]byte, error) {
|
||||
var a struct {
|
||||
Model string `json:"model"`
|
||||
Answers map[string]json.RawMessage `json:"answers"`
|
||||
Usage systemOneUsage `json:"usage"`
|
||||
}
|
||||
if err := decodeJSON(b, &a); err != nil || a.Answers == nil {
|
||||
return nil, fmt.Errorf("%s's answer is not a System One answer: %.200s", asked, b)
|
||||
}
|
||||
answers := make([]map[string]any, len(qs))
|
||||
for i, q := range qs {
|
||||
var x struct {
|
||||
Choice json.RawMessage `json:"choice"`
|
||||
Score *float64 `json:"score"`
|
||||
Confidence *float64 `json:"confidence"`
|
||||
Probabilities map[string]float64 `json:"probabilities"`
|
||||
Noul *float64 `json:"noul"`
|
||||
Probability *float64 `json:"probability"`
|
||||
}
|
||||
var name any
|
||||
if q.name != nil {
|
||||
name = *q.name
|
||||
}
|
||||
refused := map[string]any{"type": "refusal", "name": name}
|
||||
raw, ok := a.Answers[q.key]
|
||||
if !ok || json.Unmarshal(raw, &x) != nil {
|
||||
answers[i] = refused
|
||||
continue
|
||||
}
|
||||
confidence := func() float64 {
|
||||
if x.Confidence != nil {
|
||||
return *x.Confidence
|
||||
}
|
||||
ps := map[string]any{}
|
||||
for k, v := range x.Probabilities {
|
||||
ps[k] = v
|
||||
}
|
||||
return provider.Confidence(ps)
|
||||
}
|
||||
switch q.kind {
|
||||
case "predicate":
|
||||
p := x.Noul
|
||||
if p == nil {
|
||||
p = x.Probability
|
||||
}
|
||||
if p == nil {
|
||||
answers[i] = refused
|
||||
continue
|
||||
}
|
||||
answers[i] = map[string]any{"type": "predicate", "name": name, "probability": *p}
|
||||
case "choice":
|
||||
var said string
|
||||
if json.Unmarshal(x.Choice, &said) != nil {
|
||||
var on bool
|
||||
if json.Unmarshal(x.Choice, &on) != nil {
|
||||
answers[i] = refused
|
||||
continue
|
||||
}
|
||||
said = strconv.FormatBool(on)
|
||||
}
|
||||
value, ok := q.values[said]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s answered %s with %q, which is none of its choices", asked, q.key, said)
|
||||
}
|
||||
ps := []map[string]any{}
|
||||
for _, k := range q.order {
|
||||
if p, ok := x.Probabilities[k]; ok {
|
||||
ps = append(ps, map[string]any{"value": q.values[k], "probability": p})
|
||||
}
|
||||
}
|
||||
answers[i] = map[string]any{"type": "choice", "name": name, "choice": value, "confidence": confidence(), "probabilities": ps}
|
||||
case "score":
|
||||
if x.Score == nil {
|
||||
answers[i] = refused
|
||||
continue
|
||||
}
|
||||
ps := []map[string]any{}
|
||||
for k, label := range q.order {
|
||||
// keyed by the level's index, its label, or the label as asked
|
||||
for _, key := range []string{strconv.Itoa(k), label} {
|
||||
if p, ok := x.Probabilities[key]; ok {
|
||||
ps = append(ps, map[string]any{"label": label, "value": k, "probability": p})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
answers[i] = map[string]any{"type": "score", "name": name, "score": *x.Score, "confidence": confidence(), "probabilities": ps}
|
||||
}
|
||||
}
|
||||
model := a.Model
|
||||
if model == "" {
|
||||
model = asked
|
||||
}
|
||||
return json.Marshal(map[string]any{"model": model, "answers": answers, "usage": map[string]any{
|
||||
"input_tokens": a.Usage.Input,
|
||||
"input_tokens_details": map[string]int{"cached_tokens": 0, "cache_write_tokens": 0},
|
||||
"output_tokens": a.Usage.Output,
|
||||
"output_tokens_details": map[string]int{"reasoning_tokens": 0},
|
||||
"total_tokens": a.Usage.Input + a.Usage.Output,
|
||||
}})
|
||||
}
|
||||
|
||||
// systemOneFields are the fields of a System One request Decisions has a
|
||||
// place for.
|
||||
var systemOneFields = []string{"model", "state", "questions", "images"}
|
||||
|
||||
// systemOneAsDecisions is a System One request as Decisions asks it, and
|
||||
// its questions' names in order (Decisions answers in that order).
|
||||
func systemOneAsDecisions(body []byte) (map[string]json.RawMessage, []string, error) {
|
||||
var req map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, nil, untranslated("not a System One request")
|
||||
}
|
||||
for _, k := range slices.Sorted(maps.Keys(req)) {
|
||||
if !slices.Contains(systemOneFields, k) {
|
||||
return nil, nil, untranslated("%q has no counterpart in OpenAI's Decisions API, which the model answers", k)
|
||||
}
|
||||
}
|
||||
var images []string
|
||||
if raw, ok := req["images"]; ok && json.Unmarshal(raw, &images) != nil {
|
||||
return nil, nil, untranslated("\"images\" is a list of image URLs")
|
||||
}
|
||||
if len(req["state"]) == 0 {
|
||||
return nil, nil, untranslated("a System One request with no state: Decisions asks its questions of an input")
|
||||
}
|
||||
var parts []map[string]any
|
||||
var text string
|
||||
var data any
|
||||
switch {
|
||||
case json.Unmarshal(req["state"], &text) == nil:
|
||||
parts = append(parts, map[string]any{"type": "input_text", "text": text})
|
||||
case json.Unmarshal(req["state"], &data) == nil && isJSONObjects(data):
|
||||
parts = append(parts, map[string]any{"type": "input_json", "data": data})
|
||||
default:
|
||||
var buf bytes.Buffer
|
||||
json.Compact(&buf, req["state"])
|
||||
parts = append(parts, map[string]any{"type": "input_text", "text": buf.String()})
|
||||
}
|
||||
for _, im := range images {
|
||||
parts = append(parts, map[string]any{"type": "input_image", "image_url": im})
|
||||
}
|
||||
var input any = []map[string]any{{"type": "message", "role": "user", "content": parts}}
|
||||
if len(images) == 0 && text != "" {
|
||||
input = text
|
||||
}
|
||||
keys, qs, err := orderedObject(req["questions"])
|
||||
if err != nil || len(keys) == 0 {
|
||||
return nil, nil, untranslated("\"questions\" is an object of questions by name")
|
||||
}
|
||||
list := make([]map[string]any, len(keys))
|
||||
for i, k := range keys {
|
||||
var q struct {
|
||||
Type string `json:"type"`
|
||||
Instructions string `json:"instructions"`
|
||||
Criteria json.RawMessage `json:"criteria"`
|
||||
Choices json.RawMessage `json:"choices"`
|
||||
}
|
||||
if err := json.Unmarshal(qs[i], &q); err != nil {
|
||||
return nil, nil, untranslated("questions.%s is not a question", k)
|
||||
}
|
||||
d := map[string]any{"name": k, "instructions": q.Instructions}
|
||||
options := q.Criteria
|
||||
if len(options) == 0 {
|
||||
options = q.Choices
|
||||
}
|
||||
switch q.Type {
|
||||
case "noul", "boolean":
|
||||
d["type"] = "predicate"
|
||||
case "choice":
|
||||
names, descs, err := criteriaOf(options)
|
||||
if err != nil {
|
||||
return nil, nil, untranslated("questions.%s: %v", k, err)
|
||||
}
|
||||
cs := make([]map[string]any, len(names))
|
||||
for j, n := range names {
|
||||
cs[j] = map[string]any{"value": n}
|
||||
if descs[j] != "" {
|
||||
cs[j]["description"] = descs[j]
|
||||
}
|
||||
}
|
||||
d["type"], d["choices"] = "choice", cs
|
||||
case "score":
|
||||
names, descs, err := criteriaOf(options)
|
||||
if err != nil {
|
||||
return nil, nil, untranslated("questions.%s: %v", k, err)
|
||||
}
|
||||
ls := make([]map[string]any, len(names))
|
||||
for j, n := range names {
|
||||
ls[j] = map[string]any{"label": n}
|
||||
if descs[j] != "" {
|
||||
ls[j]["description"] = descs[j]
|
||||
}
|
||||
}
|
||||
d["type"], d["levels"] = "score", ls
|
||||
default:
|
||||
return nil, nil, untranslated("questions.%s is a %q question, which OpenAI's Decisions API has no counterpart for (it asks predicate, choice and score)", k, q.Type)
|
||||
}
|
||||
list[i] = d
|
||||
}
|
||||
out := map[string]json.RawMessage{"model": req["model"]}
|
||||
out["input"], _ = json.Marshal(input)
|
||||
out["questions"], _ = json.Marshal(list)
|
||||
return out, keys, nil
|
||||
}
|
||||
|
||||
// isJSONObjects is whether v is what Decisions' input_json takes: an
|
||||
// object, or a list of objects.
|
||||
func isJSONObjects(v any) bool {
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
return true
|
||||
case []any:
|
||||
return len(x) > 0 && !slices.ContainsFunc(x, func(e any) bool { _, ok := e.(map[string]any); return !ok })
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// criteriaOf is a System One question's criteria: a list of names, or
|
||||
// an object of names to descriptions, in order.
|
||||
func criteriaOf(raw json.RawMessage) ([]string, []string, error) {
|
||||
var list []string
|
||||
if json.Unmarshal(raw, &list) == nil && len(list) > 0 {
|
||||
return list, make([]string, len(list)), nil
|
||||
}
|
||||
keys, vals, err := orderedObject(raw)
|
||||
if err != nil || len(keys) == 0 {
|
||||
return nil, nil, fmt.Errorf("its criteria are neither a list of names nor an object of them")
|
||||
}
|
||||
descs := make([]string, len(keys))
|
||||
for i, v := range vals {
|
||||
if json.Unmarshal(v, &descs[i]) != nil && string(v) != "null" {
|
||||
var buf bytes.Buffer
|
||||
json.Compact(&buf, v)
|
||||
descs[i] = buf.String()
|
||||
}
|
||||
}
|
||||
return keys, descs, nil
|
||||
}
|
||||
|
||||
// orderedObject is a JSON object's keys in the order written, and their
|
||||
// values.
|
||||
func orderedObject(raw json.RawMessage) ([]string, []json.RawMessage, error) {
|
||||
d := json.NewDecoder(bytes.NewReader(raw))
|
||||
if t, err := d.Token(); err != nil || t != json.Delim('{') {
|
||||
return nil, nil, fmt.Errorf("not a JSON object")
|
||||
}
|
||||
var keys []string
|
||||
var vals []json.RawMessage
|
||||
for d.More() {
|
||||
t, err := d.Token()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var v json.RawMessage
|
||||
if err := d.Decode(&v); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
keys, vals = append(keys, t.(string)), append(vals, v)
|
||||
}
|
||||
return keys, vals, nil
|
||||
}
|
||||
|
||||
// decisionAsSystemOne is a Decisions answer as System One gives it: each
|
||||
// answer under its question's name (keys, the questions in the order
|
||||
// asked), its usage's input and output tokens.
|
||||
func decisionAsSystemOne(b []byte, keys []string) ([]byte, error) {
|
||||
var a struct {
|
||||
Model string `json:"model"`
|
||||
Answers []struct {
|
||||
Type string `json:"type"`
|
||||
Name *string `json:"name"`
|
||||
Probability float64 `json:"probability"`
|
||||
Choice json.RawMessage `json:"choice"`
|
||||
Score float64 `json:"score"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
Probabilities []struct {
|
||||
Value json.RawMessage `json:"value"`
|
||||
Label string `json:"label"`
|
||||
Probability float64 `json:"probability"`
|
||||
} `json:"probabilities"`
|
||||
} `json:"answers"`
|
||||
Usage systemOneUsage `json:"usage"`
|
||||
}
|
||||
if err := decodeJSON(b, &a); err != nil || a.Answers == nil {
|
||||
return nil, fmt.Errorf("the answer is not a Decisions answer: %.200s", b)
|
||||
}
|
||||
text := func(v json.RawMessage) string {
|
||||
var s string
|
||||
if json.Unmarshal(v, &s) == nil {
|
||||
return s
|
||||
}
|
||||
return string(v) // true, false
|
||||
}
|
||||
answers := map[string]any{}
|
||||
for i, x := range a.Answers {
|
||||
name := ""
|
||||
if x.Name != nil {
|
||||
name = *x.Name
|
||||
} else if i < len(keys) {
|
||||
name = keys[i]
|
||||
}
|
||||
switch x.Type {
|
||||
case "predicate":
|
||||
answers[name] = map[string]any{"type": "noul", "noul": x.Probability}
|
||||
case "choice":
|
||||
ps := map[string]float64{}
|
||||
for _, p := range x.Probabilities {
|
||||
ps[text(p.Value)] = p.Probability
|
||||
}
|
||||
answers[name] = map[string]any{"type": "choice", "choice": text(x.Choice), "confidence": x.Confidence, "probabilities": ps}
|
||||
case "score":
|
||||
ps := map[string]float64{}
|
||||
for _, p := range x.Probabilities {
|
||||
ps[p.Label] = p.Probability
|
||||
}
|
||||
answers[name] = map[string]any{"type": "score", "score": x.Score, "confidence": x.Confidence, "probabilities": ps}
|
||||
default: // a refusal: the model declined this one
|
||||
answers[name] = map[string]any{"type": x.Type}
|
||||
}
|
||||
}
|
||||
return json.Marshal(map[string]any{"model": a.Model, "answers": answers, "usage": a.Usage})
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// systemOneUp is a vendor's System One API: it keeps each request and
|
||||
// answers with reply, as Ark answered on 2026-11-01 (a score's
|
||||
// probabilities by level index, a choice's by name, a noul a probability;
|
||||
// usage in input and output tokens).
|
||||
type systemOneUp struct {
|
||||
mu sync.Mutex
|
||||
paths []string
|
||||
got []map[string]any
|
||||
reply string
|
||||
}
|
||||
|
||||
func (u *systemOneUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var body map[string]any
|
||||
json.Unmarshal(b, &body)
|
||||
u.mu.Lock()
|
||||
u.paths, u.got = append(u.paths, r.URL.Path), append(u.got, body)
|
||||
u.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
io.WriteString(w, u.reply)
|
||||
}
|
||||
|
||||
func (u *systemOneUp) asked() []map[string]any {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return append([]map[string]any(nil), u.got...)
|
||||
}
|
||||
|
||||
const parcelSystemOneReply = `{"model":"decision-model-preview","answers":{"damaged":{"type":"noul","noul":0.91},"condition":{"type":"choice","choice":"used","probabilities":{"new":0.12,"used":0.88},"confidence":0.76},"severity":{"type":"score","score":2.05,"probabilities":{"0":0.01,"1":0.09,"2":0.73,"3":0.17},"confidence":0.43}},"usage":{"input_tokens":452,"output_tokens":0}}`
|
||||
|
||||
// qwenDecision saves wudi_boy's provider, the Qwen AI platform's decision
|
||||
// model, its System One API at up.
|
||||
func qwenDecision(t *testing.T, up http.Handler) {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(up)
|
||||
t.Cleanup(srv.Close)
|
||||
p, err := provider.FromPreset("qwen-decision")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the stand-in host isn't Bailian's, so the model is the one picked
|
||||
p.Key, p.Decide, p.Models = "sk-qwen", srv.URL+"/compatible-mode/v1", []string{"decision-model-preview"}
|
||||
if id, err := provider.Add(p); err != nil || id != "qwen-decision" {
|
||||
t.Fatalf("saved as %q: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// parcelDecision is a Decisions request (openai-python's
|
||||
// DecisionCreateParams) with a predicate, a choice and a score, and the
|
||||
// prompt-cache hints and safety_identifier that change no answer.
|
||||
const parcelDecision = `{"model":"qwen-decision/decision-model-preview","input":"The parcel arrived torn open, one corner crushed.","questions":[` +
|
||||
`{"type":"predicate","name":"damaged","instructions":"Was the parcel damaged?"},` +
|
||||
`{"type":"choice","name":"condition","instructions":"Its condition","choices":[{"value":"new"},{"value":"used","description":"opened or worn"}]},` +
|
||||
`{"type":"score","name":"severity","instructions":"How bad is the damage?","levels":[{"label":"none"},{"label":"minor"},{"label":"major","description":"the item is hurt"},{"label":"total"}]}],` +
|
||||
`"prompt_cache_key":"parcels","safety_identifier":"u-1"}`
|
||||
|
||||
// wudi_boy on Discord: /v1/decisions to a model that answers System One
|
||||
// (Python-urllib's call to qwen-decision decision-model-preview) was
|
||||
// refused. It is asked as System One — a predicate a noul, a choice's
|
||||
// values its criteria, a score's levels its criteria least first — and
|
||||
// answers as Decisions does, in the questions' order, with its usage.
|
||||
func TestDecisionsAskSystemOne(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &systemOneUp{reply: parcelSystemOneReply}
|
||||
qwenDecision(t, up)
|
||||
code, out := sendTo(New(), "/v1/decisions", parcelDecision)
|
||||
if code != 200 {
|
||||
t.Fatalf("%d %s", code, out)
|
||||
}
|
||||
got := up.asked()
|
||||
if len(got) != 1 || up.paths[0] != "/compatible-mode/v1/systemone" {
|
||||
t.Fatalf("asked %v", up.paths)
|
||||
}
|
||||
sent, _ := json.Marshal(got[0])
|
||||
for _, want := range []string{
|
||||
`"model":"decision-model-preview"`,
|
||||
`"state":"The parcel arrived torn open, one corner crushed."`,
|
||||
`"damaged":{"instructions":"Was the parcel damaged?","type":"noul"}`,
|
||||
`"condition":{"criteria":{"new":null,"used":"opened or worn"},"instructions":"Its condition","type":"choice"}`,
|
||||
`"severity":{"criteria":["none","minor","major: the item is hurt","total"],"instructions":"How bad is the damage?","type":"score"}`,
|
||||
} {
|
||||
if !strings.Contains(string(sent), want) {
|
||||
t.Fatalf("System One was asked %s\nwant %s", sent, want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(sent), "prompt_cache") || strings.Contains(string(sent), "safety") {
|
||||
t.Fatalf("a Decisions-only hint went to System One: %s", sent)
|
||||
}
|
||||
var d struct {
|
||||
Answers []map[string]any `json:"answers"`
|
||||
Usage map[string]any `json:"usage"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &d); err != nil || len(d.Answers) != 3 {
|
||||
t.Fatalf("not a Decision: %s", out)
|
||||
}
|
||||
a, _ := json.Marshal(d.Answers)
|
||||
want := `[{"name":"damaged","probability":0.91,"type":"predicate"},` +
|
||||
`{"choice":"used","confidence":0.76,"name":"condition","probabilities":[{"probability":0.12,"value":"new"},{"probability":0.88,"value":"used"}],"type":"choice"},` +
|
||||
`{"confidence":0.43,"name":"severity","probabilities":[{"label":"none","probability":0.01,"value":0},{"label":"minor","probability":0.09,"value":1},{"label":"major","probability":0.73,"value":2},{"label":"total","probability":0.17,"value":3}],"score":2.05,"type":"score"}]`
|
||||
if string(a) != want {
|
||||
t.Fatalf("answers\n%s\nwant\n%s", a, want)
|
||||
}
|
||||
if d.Usage["input_tokens"] != 452.0 || d.Usage["output_tokens"] != 0.0 || d.Usage["total_tokens"] != 452.0 {
|
||||
t.Fatalf("usage %v", d.Usage)
|
||||
}
|
||||
}
|
||||
|
||||
// A conversation goes as the state's messages, an input_json part's data
|
||||
// as its JSON and an assistant's refusal as what it is; an unnamed
|
||||
// question is named for System One and answers with no name, and a
|
||||
// boolean choice comes back a boolean.
|
||||
func TestDecisionsMessagesAsSystemOneState(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &systemOneUp{reply: `{"model":"decision-model-preview","answers":{"question_1":{"type":"choice","choice":"true","probabilities":{"true":0.7,"false":0.3},"confidence":0.4}},"usage":{"input_tokens":40,"output_tokens":2}}`}
|
||||
qwenDecision(t, up)
|
||||
code, out := sendTo(New(), "/v1/decisions", `{"model":"qwen-decision/decision-model-preview","input":[`+
|
||||
`{"role":"developer","content":"Judge the support thread."},`+
|
||||
`{"role":"user","content":[{"type":"input_text","text":"Order 7 is late."},{"type":"input_json","data":{"order":7,"days":3}}]},`+
|
||||
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Checking."},{"type":"refusal","refusal":"I can't refund."}]}],`+
|
||||
`"questions":[{"type":"choice","instructions":"Is the user upset?","choices":[{"value":true},{"value":false}]}]}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("%d %s", code, out)
|
||||
}
|
||||
sent, _ := json.Marshal(up.asked()[0]["state"])
|
||||
if want := `{"messages":[{"content":"Judge the support thread.","role":"developer"},{"content":"Order 7 is late.\n{\"order\":7,\"days\":3}","role":"user"},{"content":"Checking.","refusal":"I can't refund.","role":"assistant"}]}`; string(sent) != want {
|
||||
t.Fatalf("state %s\nwant %s", sent, want)
|
||||
}
|
||||
if want := `"answers":[{"choice":true,"confidence":0.4,"name":null,"probabilities":[{"probability":0.7,"value":true},{"probability":0.3,"value":false}],"type":"choice"}]`; !strings.Contains(out, want) {
|
||||
t.Fatalf("answer %s\nwant %s", out, want)
|
||||
}
|
||||
if !strings.Contains(out, `"input_tokens":40`) || !strings.Contains(out, `"output_tokens":2`) {
|
||||
t.Fatalf("usage %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// What System One has no counterpart for is refused with a 400 that
|
||||
// names it, and System One is never asked: an image where the model takes
|
||||
// none, a tool call or its output, an image in a question.
|
||||
func TestDecisionsUntranslatableRefused(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &systemOneUp{reply: parcelSystemOneReply}
|
||||
qwenDecision(t, up)
|
||||
s := New()
|
||||
q := `"questions":[{"type":"predicate","name":"damaged","instructions":"Was it damaged?"}]`
|
||||
for _, c := range []struct{ body, says string }{
|
||||
{decisionAsked("qwen-decision/decision-model-preview"), "input[0].content[1] is an image (input_image), which qwen-decision/decision-model-preview can't take"},
|
||||
{`{"model":"qwen-decision/decision-model-preview","input":[{"role":"user","content":"look"},{"type":"function_call","call_id":"c1","name":"read","arguments":"{}"}],` + q + `}`, "input[1] is a function_call"},
|
||||
{`{"model":"qwen-decision/decision-model-preview","input":[{"type":"custom_tool_call_output","call_id":"c1","output":"ok"}],` + q + `}`, "input[0] is a custom_tool_call_output"},
|
||||
{`{"model":"qwen-decision/decision-model-preview","input":"x","questions":[{"type":"predicate","instructions":[{"type":"input_image","image_url":"data:image/png;base64,AA=="}]}]}`, "questions[0].instructions[0] is an image"},
|
||||
{`{"model":"qwen-decision/decision-model-preview","input":"x","reasoning":{"effort":"low"},` + q + `}`, `\"reasoning\" has no counterpart in System One`},
|
||||
} {
|
||||
code, out := sendTo(s, "/v1/decisions", c.body)
|
||||
if code != 400 || !strings.Contains(out, c.says) {
|
||||
t.Fatalf("%d %s\nwant 400 saying %s", code, out, c.says)
|
||||
}
|
||||
}
|
||||
if n := len(up.asked()); n != 0 {
|
||||
t.Fatalf("System One was asked %d times", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A Clef, which takes images, gets a Decisions request's images as
|
||||
// Workers AI takes them, and its answer out of Cloudflare's envelope.
|
||||
func TestDecisionsImagesToClef(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &systemOneUp{reply: `{"result":{"model":"clef","answers":{"visible_damage":{"type":"noul","noul":0.97},"condition":{"type":"choice","choice":"new","probabilities":{"new":0.6,"used":0.4},"confidence":0.2}},"usage":{"input_tokens":900,"output_tokens":0}},"success":true,"errors":[],"messages":[]}`}
|
||||
srv := httptest.NewServer(up)
|
||||
t.Cleanup(srv.Close)
|
||||
p, err := provider.FromPreset("cloudflare-jev")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.Key, p.Decide = "k", srv.URL+"/client/v4/accounts/a/ai/run"
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, out := sendTo(New(), "/v1/decisions", decisionAsked(p.ID+"/@cf/cloudflare/clef"))
|
||||
if code != 200 || !strings.Contains(out, `{"name":"visible_damage","probability":0.97,"type":"predicate"}`) || !strings.Contains(out, `"input_tokens":900`) {
|
||||
t.Fatalf("%d %s", code, out)
|
||||
}
|
||||
got := up.asked()
|
||||
if len(got) != 1 || up.paths[0] != "/client/v4/accounts/a/ai/run/@cf/cloudflare/clef" {
|
||||
t.Fatalf("asked %v", up.paths)
|
||||
}
|
||||
if ims, _ := got[0]["images"].([]any); len(ims) != 1 || ims[0] != "data:image/png;base64,iVBORw0KGgo=" {
|
||||
t.Fatalf("the Clef got images %v", got[0]["images"])
|
||||
}
|
||||
if st, _ := json.Marshal(got[0]["state"]); string(st) != `{"messages":[{"content":"Inspect the product in this photo.","role":"user"}]}` {
|
||||
t.Fatalf("state %s", st)
|
||||
}
|
||||
}
|
||||
|
||||
// The other way: /v1/systemone to a model only OpenAI's Decisions API
|
||||
// serves is asked there — a noul a predicate, a choice's criteria its
|
||||
// choices, the state its input, the images input_image parts — and
|
||||
// answers as System One does, by name, with its usage.
|
||||
func TestSystemOneAsksDecisions(t *testing.T) {
|
||||
openai, _ := decidingProviders(t)
|
||||
s := New()
|
||||
code, out := sendTo(s, "/v1/systemone", `{"model":"openai/gpt-6-luna","state":{"photo":"product","order":7},"images":["data:image/png;base64,iVBORw0KGgo="],`+
|
||||
`"questions":{"visible_damage":{"type":"noul","instructions":"Is there visible damage?"},"condition":{"type":"choice","instructions":"Its condition","criteria":{"new":null,"used":"opened or worn"}}}}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("%d %s", code, out)
|
||||
}
|
||||
hits := openai.all()
|
||||
if len(hits) != 1 || hits[0].path != "/v1/decisions" || hits[0].auth != "Bearer sk-openai" {
|
||||
t.Fatalf("hits %+v", hits)
|
||||
}
|
||||
sent, _ := json.Marshal(hits[0].body)
|
||||
for _, want := range []string{
|
||||
`"model":"gpt-6-luna"`,
|
||||
`"input":[{"content":[{"data":{"order":7,"photo":"product"},"type":"input_json"},{"image_url":"data:image/png;base64,iVBORw0KGgo=","type":"input_image"}],"role":"user","type":"message"}]`,
|
||||
`"questions":[{"instructions":"Is there visible damage?","name":"visible_damage","type":"predicate"},{"choices":[{"value":"new"},{"description":"opened or worn","value":"used"}],"instructions":"Its condition","name":"condition","type":"choice"}]`,
|
||||
} {
|
||||
if !strings.Contains(string(sent), want) {
|
||||
t.Fatalf("Decisions was asked %s\nwant %s", sent, want)
|
||||
}
|
||||
}
|
||||
var a struct {
|
||||
Answers map[string]map[string]any `json:"answers"`
|
||||
Usage map[string]any `json:"usage"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &a); err != nil {
|
||||
t.Fatalf("not a System One answer: %s", out)
|
||||
}
|
||||
if a.Answers["visible_damage"]["noul"] != 0.92 || a.Answers["condition"]["choice"] != "used" || a.Answers["condition"]["probabilities"].(map[string]any)["used"] != 0.8 {
|
||||
t.Fatalf("answers %s", out)
|
||||
}
|
||||
if a.Usage["input_tokens"] != 1200.0 || a.Usage["output_tokens"] != 3.0 {
|
||||
t.Fatalf("usage %v", a.Usage)
|
||||
}
|
||||
if recs := decisionRecords(t, 1); recs[0].Input+recs[0].CacheRead+recs[0].CacheWrite != 1200 {
|
||||
t.Fatalf("recorded %+v", recs[0])
|
||||
}
|
||||
// a question Decisions has no counterpart for is refused, and not sent
|
||||
code, out = sendTo(s, "/v1/systemone", `{"model":"openai/gpt-6-luna","state":"x","questions":{"q":{"type":"rank","instructions":"?"}}}`)
|
||||
if code != 400 || !strings.Contains(out, `questions.q is a \"rank\" question`) || len(openai.all()) != 1 {
|
||||
t.Fatalf("%d %s", code, out)
|
||||
}
|
||||
// a model no API serves is still System One's 404
|
||||
if code, out = sendTo(s, "/v1/systemone", `{"model":"nobody/none","state":"x","questions":{"q":{"type":"noul"}}}`); code != 404 {
|
||||
t.Fatalf("%d %s", code, out)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user