gateway: POST /v1/decisions goes to OpenAI, Azure OpenAI or another magpie

A Discord user's POST /v1/decisions was answered 404 ("magpie serves
/v1/chat/completions, ..."). It is OpenAI's Decisions API (gpt-6-luna):
one input, up to 400 questions, typed answers, input tokens billed only.

The shape was taken from openai-python (resources/decisions.py,
types/decision_create_params.py, types/decision.py, added in #4033 on
10-06) and the Decisions guide, not guessed: POST /v1/decisions, a JSON
body of model, input (a string or messages/items with input_text,
input_image as a data or http(s) URL, JSON parts; function and custom
tool calls and their outputs), questions (predicate / choice / score),
and optional prompt_cache_key, prompt_cache_options, safety_identifier.
The answer is {answers, model, usage}, not streamed; usage.input_tokens
includes input_tokens_details.cached_tokens and cache_write_tokens. The
Azure client sends it on the v1 API (/openai/v1/decisions), the model in
the body.

- decide (decisions.go) goes through serveRetrieval as embeddings and
  rerank do, body as sent with only model changed. So a disabled model,
  a key's models, accounts and spent limits, pause rules, keys/accounts
  of the provider, masking and the Routing page hold here as on every
  route.
- Only a provider canDecide takes is sent it: an OpenAI API key on
  api.openai.com, Azure OpenAI (IsAzure, at its OpenAIBase, so
  /openai/v1/decisions with api-key), or another magpie. Anyone else (a
  relay, a plugin, a ChatGPT sign-in) gets a 400 that says who serves
  it, checked in serveRetrieval's try loop beside the no-OpenAI-API
  check (refusingRetrieval), never the vendor's 404; a group moves on.
- A bare gpt-6-luna is a kind group "decision" (servesDecision), so a
  relay that lists the same id is never its member.
- Usage is recorded as "decisions" (countedRetrieval): input less the
  cached and cache-written tokens, those as CacheRead/CacheWrite, and
  no output, so gpt-6-luna's own models.dev rates price it as OpenAI
  bills ($0.10/1M input, cache read/write at their rates).
- /decisions joins the one-port client prefixes, another magpie's URL
  suffixes, the 404's route list and info's apis. The readonly, LAN
  and CORS guard tests list the route.
- native_endpoints is left alone: it names the chat APIs a model is
  relayed on (Cursor's names, a remote's API choice).
- docs: gateway-routing.md has a Decisions row; reference.md a section.

Run on mote at this tree (mote-run): gofmt -l clean; go vet of gateway
and provider; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet
./...; go build ./..., linux nogui and windows builds ok;
go test -count=1 -timeout 45m ./internal/gateway ./internal/provider
./internal/usage: ok (gateway 413s, provider 88s, usage 18s).

Red on the old code (e0930b1de, the new tests copied in): every
TestDecisions* is red with magpie's 404.
Broken by hand, each red: refuses always "" (the relay is sent it:
TestDecisionsRefusedWhereNotServed); the cache split not read
(Input 1200, CacheRead 0: TestDecisionsReachOpenAIAndAzure); canDecide
without the api.openai.com check (TestCanDecide, the relay sent it);
/v1/decisions out of the remote suffixes (TestRemoteMagpie).

Not tried: a real OpenAI Decisions request, or a real Azure resource.
Tests reach only httptest servers (OpenAI's host through the provider's
proxy).
This commit is contained in:
yetone
2026-11-07 16:05:37 +08:00
parent e0930b1dee
commit 191f3c0af1
13 changed files with 468 additions and 10 deletions
+16
View File
@@ -1040,6 +1040,22 @@ curl localhost:3425/v1/rerank -H "Authorization: Bearer $MAGPIE_KEY" \
-d '{"model":"voyage/rerank-3","query":"what eats seeds","documents":["a magpie","a stone"],"top_k":1}'
```
### Decisions
`/v1/decisions` (also without `/v1`) is OpenAI's Decisions API: a model
(`gpt-6-luna`), an `input` every question shares (text, images, a
conversation), and `questions`, each answered with a probability, a choice
or a score. It takes the gateway's key, as chat does, and is sent as given,
only `model` changed, to an OpenAI API key, to Azure OpenAI (at
`/openai/v1/decisions`, the model your deployment's name) or to another
magpie. Any other provider is refused with a 400 that says so. Only input
tokens are counted, cached ones apart.
```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?"}]}'
```
### Google Vertex AI
Google Vertex AI (`google-vertex`), which Google's documentation now calls
File diff suppressed because one or more lines are too long
+2
View File
@@ -238,6 +238,7 @@ func TestForeignPagesRefused(t *testing.T) {
{"POST", "/v1beta/models/plan/m1:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`},
{"POST", "/v1/embeddings", `{"model":"plan/m1","input":"hi"}`},
{"POST", "/v1/rerank", `{"model":"plan/m1","query":"hi","documents":["a"]}`},
{"POST", "/v1/decisions", `{"model":"plan/m1","input":"hi","questions":[{"type":"predicate","instructions":"is it?"}]}`},
{"POST", "/v1/audio/transcriptions", "--b\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nplan/m1\r\n--b--\r\n"},
{"POST", "/v1/audio/speech", `{"model":"plan/m1","input":"hi","voice":"coral"}`},
{"POST", "/v1/images/generations", `{"model":"plan/m1","prompt":"hi"}`},
@@ -355,6 +356,7 @@ func TestOpaqueOriginNeedsAKey(t *testing.T) {
{"POST", "/v1/messages"},
{"POST", "/v1/images/generations"},
{"POST", "/v1/embeddings"},
{"POST", "/v1/decisions"},
{"GET", "/v1/models"},
} {
if w := do(p.method, p.path, "null", ""); w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "gateway key") || w.Header().Get("Access-Control-Allow-Origin") != "" {
+111
View File
@@ -0,0 +1,111 @@
package gateway
import (
"encoding/json"
"fmt"
"net/http"
"slices"
"time"
"github.com/yetone/magpie/internal/provider"
)
// kindDecision is the kind of model OpenAI's Decisions API is asked of
// (serveRetrieval's "decisions"): a group of it is the providers that
// can serve the API and list the model (servesKind).
const kindDecision = "decision"
// decisionModels are the models OpenAI's Decisions API takes
// (openai-python's DecisionCreateParams.model: gpt-6-luna alone), served
// by a provider that can serve the API even when its list of models to
// chat with leaves them out.
var decisionModels = []string{"gpt-6-luna"}
// decide serves POST /v1/decisions, OpenAI's Decisions API: a model, an
// input shared by every question (text, images, a conversation's items)
// and up to 400 questions, each answered with a probability, a choice or
// a score. Like embeddings it is no chat, so it is not translated: the
// 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.
func (s *Server) decide(w http.ResponseWriter, r *http.Request) {
body, admitted := s.requestBody(w, r, provider.Chat)
if !admitted {
return
}
start := time.Now()
var req map[string]json.RawMessage
if json.Unmarshal(body, &req) != nil || req == nil {
writeError(w, provider.Chat, 400, "the body isn't a JSON object")
return
}
var asked string
json.Unmarshal(req["model"], &asked)
if asked == "" {
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
}
s.serveRetrieval(w, r, "/decisions", "decisions", start, asked, &decisionRequest{jsonRetrieval{req: req}})
}
// decisionRequest is a Decisions API body: a JSON object, sent only to
// a provider that can serve the API, and counted by its own usage.
type decisionRequest struct{ jsonRetrieval }
// refuses is why p can't be sent the request, "" when it can.
func (d *decisionRequest) refuses(p provider.Provider) string {
if canDecide(p) {
return ""
}
return fmt.Sprintf("%s can't serve OpenAI's Decisions API (/v1/decisions): only an OpenAI API key, Azure OpenAI and another magpie serve it", p.Name)
}
// counted is what the answer's usage says: input_tokens has the cached
// and cache-written tokens in it (input_tokens_details), told apart so
// each is priced at its rate; no output is billed.
func (d *decisionRequest) counted(b []byte) Usage {
var a struct {
Usage struct {
Input int `json:"input_tokens"`
Details struct {
Cached int `json:"cached_tokens"`
Write int `json:"cache_write_tokens"`
} `json:"input_tokens_details"`
} `json:"usage"`
}
if json.Unmarshal(b, &a) != nil {
return Usage{}
}
u := a.Usage
read, write := max(u.Details.Cached, 0), max(u.Details.Write, 0)
return Usage{Input: max(u.Input-read-write, 0), CacheRead: read, CacheWrite: write}
}
// canDecide is whether p can serve OpenAI's Decisions API: OpenAI's own
// API with a key (a ChatGPT sign-in's backend has no such route), Azure
// OpenAI, which serves it on its v1 API, or another magpie, which routes
// it on. A relay or a plugin, whatever models it lists, is none.
func canDecide(p provider.Provider) bool {
if p.IsPlugin() {
return false
}
if p.IsRemoteMagpie() || p.IsAzure() {
return true
}
return p.Account == nil && p.Key != "" && provider.HostOf(p.Base(provider.Chat)) == "api.openai.com"
}
// servesDecision is servesKind's for the Decisions API: a provider that
// can serve it with the model on its list, or an OpenAI key asked for a
// model the API takes. Azure's ids are its deployments' and another
// magpie's are its own, so each has the model when its list says so.
func servesDecision(p provider.Provider, model string) bool {
if !canDecide(p) {
return false
}
if !offChatList(p, model) {
return true
}
return slices.Contains(decisionModels, model) && !p.IsAzure() && !p.IsRemoteMagpie()
}
+293
View File
@@ -0,0 +1,293 @@
package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// decisionAsked is the Decisions guide's request
// (developers.openai.com/api/docs/guides/decisions), as openai-python's
// client.decisions.create sends it: a model, the input every question
// shares (a user message of text and an image) and the questions.
func decisionAsked(model string) string {
return `{"model":"` + model + `","input":[{"role":"user","content":[{"type":"input_text","text":"Inspect the product in this photo."},{"type":"input_image","image_url":"data:image/png;base64,iVBORw0KGgo="}]}],"questions":[{"type":"predicate","name":"visible_damage","instructions":"Is there visible damage?"},{"type":"choice","name":"condition","instructions":"Its condition","choices":[{"value":"new"},{"value":"used"}]}]}`
}
// decisionAnswer is a Decisions answer, the shape openai-python's
// Decision reads: typed answers and a usage whose input_tokens has its
// cached and cache-written tokens in it.
const decisionAnswer = `{"answers":[{"type":"predicate","name":"visible_damage","probability":0.92},{"type":"choice","name":"condition","choice":"used","confidence":0.8,"probabilities":[{"value":"new","probability":0.2},{"value":"used","probability":0.8}]}],"model":"gpt-6-luna","usage":{"input_tokens":1200,"input_tokens_details":{"cached_tokens":1000,"cache_write_tokens":50},"output_tokens":3,"output_tokens_details":{"reasoning_tokens":0},"total_tokens":1203}}`
type decisionHit struct {
host, path, auth, apiKey string
body map[string]any
}
// decider is a vendor that serves the Decisions API at /v1/decisions and
// Azure's /openai/v1/decisions, and keeps each request.
type decider struct {
mu sync.Mutex
hits []decisionHit
}
func (d *decider) ServeHTTP(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var body map[string]any
json.Unmarshal(raw, &body)
d.mu.Lock()
d.hits = append(d.hits, decisionHit{host: r.Host, path: r.URL.Path, auth: r.Header.Get("Authorization"), apiKey: r.Header.Get("api-key"), body: body})
d.mu.Unlock()
if r.URL.Path != "/v1/decisions" && r.URL.Path != "/openai/v1/decisions" {
w.WriteHeader(404)
return
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, decisionAnswer)
}
func (d *decider) all() []decisionHit {
d.mu.Lock()
defer d.mu.Unlock()
return append([]decisionHit(nil), d.hits...)
}
// decidingProviders saves an OpenAI API key (reached through the
// provider's proxy, so its host is OpenAI's own), an Azure OpenAI
// resource and a relay that lists gpt-6-luna among its chat models.
func decidingProviders(t *testing.T) (*decider, *decider) {
t.Helper()
fresh(t)
for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} {
t.Setenv(k, "")
}
openai := &decider{}
ou := httptest.NewServer(openai)
t.Cleanup(ou.Close)
if err := provider.Save(provider.Provider{ID: "openai", Name: "OpenAI", Key: "sk-openai", Chat: "http://api.openai.com/v1", Proxy: ou.URL, Models: []string{"gpt-6-sol"}}); err != nil {
t.Fatal(err)
}
other := &decider{}
au := httptest.NewServer(other)
t.Cleanup(au.Close)
az, err := provider.FromPreset(provider.AzurePreset)
if err != nil {
t.Fatal(err)
}
az.Key, az.Chat, az.Models = "azure-key", au.URL+"/openai/v1", []string{"luna-deploy"}
az.Responses = az.Chat
if err := provider.Save(az); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "relay-key", Chat: au.URL + "/v1", Models: []string{"gpt-6-luna"}}); err != nil {
t.Fatal(err)
}
return openai, other
}
func decisionRecords(t *testing.T, n int) []usage.Record {
t.Helper()
var recs []usage.Record
for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
recs = nil
for _, r := range usage.Load(time.Time{}) {
if r.Operation == "decisions" {
recs = append(recs, r)
}
}
if len(recs) >= n {
return recs
}
}
t.Fatalf("%d decisions recorded, want %d: %+v", len(recs), n, recs)
return nil
}
// POST /v1/decisions (a Discord user had a 404) goes as the agent sent it
// to OpenAI with its key, to Azure OpenAI at its v1 API's
// /openai/v1/decisions with the key in api-key, and on the bare
// /decisions an SDK given magpie's root posts to. The answer comes back
// as OpenAI said it, and the call is recorded as decisions: its input
// apart from the cached and cache-written tokens, each priced at its
// rate, and no output.
func TestDecisionsReachOpenAIAndAzure(t *testing.T) {
openai, other := decidingProviders(t)
s := New()
for _, tc := range []struct {
name, path, model, sentModel, host, upPath string
up *decider
}{
{"openai by its ref", "/v1/decisions", "openai/gpt-6-luna", "gpt-6-luna", "api.openai.com", "/v1/decisions", openai},
// a relay lists the same id, but only OpenAI can serve the API
{"the bare id", "/v1/decisions", "gpt-6-luna", "gpt-6-luna", "api.openai.com", "/v1/decisions", openai},
{"the bare path", "/decisions", "openai/gpt-6-luna", "gpt-6-luna", "api.openai.com", "/v1/decisions", openai},
{"azure", "/v1/decisions", "azure/luna-deploy", "luna-deploy", "", "/openai/v1/decisions", other},
} {
t.Run(tc.name, func(t *testing.T) {
before := len(tc.up.all())
code, raw := postJSON(t, s, tc.path, decisionAsked(tc.model))
if code != 200 || raw != decisionAnswer {
t.Fatalf("%d %s", code, raw)
}
hits := tc.up.all()
if len(hits) != before+1 {
t.Fatalf("vendor asked %d times", len(hits)-before)
}
h := hits[len(hits)-1]
if h.path != tc.upPath || tc.host != "" && h.host != tc.host || h.body["model"] != tc.sentModel {
t.Fatalf("sent to %s%s as %v", h.host, h.path, h.body["model"])
}
if qs, _ := h.body["questions"].([]any); len(qs) != 2 {
t.Fatalf("questions sent: %v", h.body["questions"])
}
in, _ := h.body["input"].([]any)
if b, _ := json.Marshal(in); !strings.Contains(string(b), `"image_url":"data:image/png;base64,iVBORw0KGgo="`) {
t.Fatalf("input sent: %s", b)
}
if tc.up == other {
if h.apiKey != "azure-key" || h.auth != "" {
t.Fatalf("azure signed with %q %q", h.apiKey, h.auth)
}
} else if h.auth != "Bearer sk-openai" {
t.Fatalf("openai signed with %q", h.auth)
}
})
}
for _, h := range other.all() {
if h.path == "/v1/decisions" {
t.Fatal("the relay was sent a decision")
}
}
recs := decisionRecords(t, 4)
for _, r := range recs {
if r.Status != 200 || r.Input != 150 || r.CacheRead != 1000 || r.CacheWrite != 50 || r.Output != 0 {
t.Fatalf("recorded %+v", r)
}
}
if r := recs[0]; r.Provider != "openai" || r.Model != "gpt-6-luna" || r.Requested != "openai/gpt-6-luna" {
t.Fatalf("recorded %+v", r)
}
}
// A provider that can't serve the Decisions API is never sent the
// request: a relay, whatever its list says, gets a 400 that says who
// can, not the vendor's 404.
func TestDecisionsRefusedWhereNotServed(t *testing.T) {
_, other := decidingProviders(t)
code, raw := postJSON(t, New(), "/v1/decisions", decisionAsked("relay/gpt-6-luna"))
if code != 400 || !strings.Contains(raw, "Relay can't serve OpenAI's Decisions API") || !strings.Contains(raw, "Azure OpenAI") {
t.Fatalf("%d %s", code, raw)
}
if hits := other.all(); len(hits) != 0 {
t.Fatalf("the relay was asked: %+v", hits)
}
// no model, no JSON
if code, raw := postJSON(t, New(), "/v1/decisions", `{"input":"hi","questions":[]}`); code != 400 || !strings.Contains(raw, "name the model") {
t.Fatalf("no model: %d %s", code, raw)
}
}
// canDecide: OpenAI's API with a key, Azure OpenAI and another magpie;
// never a ChatGPT sign-in on OpenAI's host, a plugin, or a relay.
func TestCanDecide(t *testing.T) {
for _, tc := range []struct {
name string
p provider.Provider
want bool
}{
{"openai key", provider.Provider{ID: "openai", Key: "sk", Chat: "https://api.openai.com/v1"}, true},
{"azure", provider.Provider{ID: "az", Preset: provider.AzurePreset, Key: "k", Chat: "https://res.openai.azure.com/openai/v1"}, true},
{"azure by its host", provider.Provider{ID: "az2", Key: "k", Chat: "https://res.openai.azure.com/openai/v1"}, true},
{"another magpie", provider.Provider{ID: "office", Preset: provider.RemoteMagpiePreset, Key: "k", Chat: "http://192.168.1.20:3425/v1"}, true},
{"a chatgpt sign-in", provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "me@example.com"}, Chat: "https://api.openai.com/v1"}, false},
{"a plugin", provider.PluginForTest("grok", "grok"), false},
{"a relay", provider.Provider{ID: "relay", Key: "k", Chat: "https://relay.example/v1"}, false},
{"openai with no key", provider.Provider{ID: "openai", Chat: "https://api.openai.com/v1"}, false},
} {
if got := canDecide(tc.p); got != tc.want {
t.Errorf("%s: %v", tc.name, got)
}
}
}
// Another magpie serves the Decisions API by routing it on: the request
// reaches its /v1/decisions and, through it, OpenAI.
func TestDecisionsThroughAnotherMagpie(t *testing.T) {
openai, _ := decidingProviders(t)
remote := httptest.NewServer(New().Handler())
t.Cleanup(remote.Close)
if err := provider.Save(provider.Provider{ID: "office", Preset: provider.RemoteMagpiePreset, Chat: remote.URL, Key: "remote-key", Models: []string{"openai/gpt-6-luna"}}); err != nil {
t.Fatal(err)
}
p, _ := provider.Find("office")
if _, err := p.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
code, raw := postJSON(t, New(), "/v1/decisions", decisionAsked("office/openai/gpt-6-luna"))
if code != 200 || raw != decisionAnswer {
t.Fatalf("%d %s", code, raw)
}
if hits := openai.all(); len(hits) != 1 || hits[0].body["model"] != "gpt-6-luna" {
t.Fatalf("openai asked %+v", hits)
}
recs := decisionRecords(t, 2)
seen := map[string]bool{}
for _, r := range recs {
seen[r.Provider] = true
}
if !seen["office"] || !seen["openai"] {
t.Fatalf("recorded %+v", recs)
}
}
// A gateway key's rules hold on /v1/decisions as on every route: a key
// held to other models is refused before any vendor is asked, a disabled
// model is refused, and a key's spent limit of the model refuses it.
func TestDecisionsHeldByKeysAndRules(t *testing.T) {
openai, _ := decidingProviders(t)
budget.Forget()
pinLimitClock(t)
keys, secrets := newCaller(t, "Held", "Capped")
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"relay/*"}}); err != nil {
t.Fatal(err)
}
setLimit(t, keys[1].ID, &access.Limit{Period: "day", Tokens: 100, Models: []string{"openai/*"}})
h := New().Handler()
if w := keyCall(h, secrets[0], "/v1/decisions", decisionAsked("openai/gpt-6-luna")); w.Code != http.StatusForbidden {
t.Fatalf("a key held to other models: %d %s", w.Code, w.Body.String())
}
if w := keyCall(h, "sk-magpie-not-a-key", "/v1/decisions", decisionAsked("openai/gpt-6-luna")); w.Code != http.StatusUnauthorized && w.Code != http.StatusForbidden {
t.Fatalf("a wrong key: %d %s", w.Code, w.Body.String())
}
if n := len(openai.all()); n != 0 {
t.Fatalf("openai asked %d times", n)
}
if w := keyCall(h, secrets[1], "/v1/decisions", decisionAsked("openai/gpt-6-luna")); w.Code != 200 {
t.Fatalf("the capped key's first call: %d %s", w.Code, w.Body.String())
}
decisionRecords(t, 1)
spentSaid(t, keyCall(h, secrets[1], "/v1/decisions", decisionAsked("openai/gpt-6-luna")), "openai/*")
if n := len(openai.all()); n != 1 {
t.Fatalf("openai asked %d times", n)
}
if err := provider.DisableModels("openai/gpt-6-luna"); err != nil {
t.Fatal(err)
}
if code, raw := postJSON(t, New(), "/v1/decisions", decisionAsked("openai/gpt-6-luna")); code != http.StatusForbidden {
t.Fatalf("a disabled model: %d %s", code, raw)
}
if n := len(openai.all()); n != 1 {
t.Fatalf("openai asked %d times", n)
}
}
+28 -3
View File
@@ -63,6 +63,18 @@ type retrieval interface {
answerType(got string) string
}
// refusingRetrieval is a retrieval request only some providers can be
// sent: refuses is why p can't, "" when it can (decisionRequest).
type refusingRetrieval interface {
refuses(p provider.Provider) string
}
// countedRetrieval is a retrieval request whose answer's usage is read
// its own way, cached tokens apart (decisionRequest).
type countedRetrieval interface {
counted(b []byte) Usage
}
// jsonRetrieval is an embeddings or rerank body: a JSON object.
type jsonRetrieval struct{ req map[string]json.RawMessage }
@@ -228,6 +240,8 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
switch req.(type) {
case *audioForm, *speechRequest:
what = "audio"
case *decisionRequest:
what = "decisions"
}
// the record names the try that had it last, not the first
// planned (noteMaskedUntil)
@@ -240,8 +254,13 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
call.Provider, went = c.p.ID, c.model
base := strings.TrimRight(c.p.OpenAIBase(), "/")
tried := side.try(c)
msg := ""
if base == "" {
msg := fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path)
msg = fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path)
} else if rr, ok := req.(refusingRetrieval); ok {
msg = rr.refuses(c.p) // never sent, so never a 404 of the vendor's
}
if msg != "" {
tried(400, errors.New(msg))
if !last {
skipped = append(skipped, c.label()+": "+msg)
@@ -289,6 +308,11 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
}
call.Status = code
in, outTokens := retrievedTokens(b), answeredTokens(b)
var cached Usage // the cache's share, when the answer tells it
if cr, ok := req.(countedRetrieval); ok && res == nil && err == nil {
cached = cr.counted(b)
in, outTokens = cached.Input, cached.Output
}
if res != nil {
// passed on as it comes: audio, or SSE, is never held whole
heard.into(w.Header())
@@ -303,14 +327,15 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
}
}
call.Usage.Input, call.Usage.Output = in, outTokens
call.Usage.CacheRead, call.Usage.CacheWrite = cached.CacheRead, cached.CacheWrite
call.Fallback = strings.Join(skipped, "; ")
providerKeyID, providerKeyName := "", ""
if c.p.Account == nil && c.p.Key != "" {
providerKeyID, providerKeyName = provider.KeyID(c.p.Key), c.p.KeyName
}
side.end(c.p, c.model, code, err, Usage{Input: in, Output: outTokens})
side.end(c.p, c.model, code, err, Usage{Input: in, Output: outTokens, CacheRead: cached.CacheRead, CacheWrite: cached.CacheWrite})
appendUsage(r, usage.Record{RouteID: side.id(), Operation: operation, Time: start, Agent: call.Agent, Via: call.Via, Provider: c.p.ID, Host: c.p.Where(), Model: c.model, Requested: asked, ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: accountOf(c.p),
Input: in, Output: outTokens, Millis: call.Millis, Status: code, Session: sessionOf(r.Header)})
Input: in, Output: outTokens, CacheRead: cached.CacheRead, CacheWrite: cached.CacheWrite, Millis: call.Millis, Status: code, Session: sessionOf(r.Header)})
if err != nil {
call.Error = err.Error()
s.record(call)
+5 -2
View File
@@ -1034,6 +1034,9 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("POST /embeddings", s.retrieve("/embeddings", "embeddings"))
mux.HandleFunc("POST /v1/rerank", s.retrieve("/rerank", "rerank"))
mux.HandleFunc("POST /rerank", s.retrieve("/rerank", "rerank"))
// OpenAI's Decisions API, typed answers to questions on one input
mux.HandleFunc("POST /v1/decisions", s.decide)
mux.HandleFunc("POST /decisions", s.decide)
// speech to text, for a client's voice input (#2053)
mux.HandleFunc("POST /v1/audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions"))
mux.HandleFunc("POST /audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions"))
@@ -1070,7 +1073,7 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("GET /v1beta/models", s.geminiModels)
mux.HandleFunc("POST /v1beta/models/{call...}", s.gemini)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech and /v1beta/models/*")
writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/decisions, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech and /v1beta/models/*")
})
return mux
}
@@ -1099,7 +1102,7 @@ var catalogSize stamped[struct{}, int]
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return len(provider.Catalog()) }), "window": Window,
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
// which process serves, for another magpie on this computer to name it
// on its Routing page (#2606); not told to another machine
if local(r) {
+1 -1
View File
@@ -372,7 +372,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) {
{"POST", "/v1/messages"}, {"POST", "/messages"}, {"POST", "/v1/messages/count_tokens"},
{"POST", "/v1/systemone"},
{"POST", "/v1/images/generations"}, {"POST", "/v1/images/edits"},
{"POST", "/v1/embeddings"}, {"POST", "/v1/rerank"},
{"POST", "/v1/embeddings"}, {"POST", "/v1/rerank"}, {"POST", "/v1/decisions"},
{"POST", "/v1/audio/transcriptions"}, {"POST", "/v1/audio/translations"}, {"POST", "/v1/audio/speech"},
{"POST", "/v1/videos"}, {"GET", "/v1/videos/v1"}, {"GET", "/v1/videos/v1/content"},
{"POST", "/_magpie/claude-mcp/tok"}, {"POST", "/mcp/neon"},
+6 -1
View File
@@ -10,7 +10,7 @@ import (
// mediaMembers is the routing group ref with its members ready now for
// an API that is no chat, kind's (catalog.Serves*, provider.KindVideo):
// embeddings, rerank, speech, transcriptions and videos.
// embeddings, rerank, speech, transcriptions, videos and decisions.
//
// A group the user made: a provider's picks are of its chat models, and
// these models are in no chat list (a fetched list keeps them apart,
@@ -61,6 +61,9 @@ func bareRef(ref string) bool {
// preset names it (PlanRetrieval).
func servesKind(kind string) func(p provider.Provider, model string) bool {
is := func(m catalog.Model, model string) bool { return m.ID == model }
if kind == kindDecision {
return servesDecision
}
if kind == provider.KindVideo {
return func(p provider.Provider, model string) bool {
return slices.ContainsFunc(Videomakers(p), func(m catalog.Model) bool { return is(m, model) })
@@ -87,6 +90,8 @@ func retrievalKind(operation string) string {
return catalog.ServesSpeech
case "transcriptions", "translations":
return catalog.ServesTranscription
case "decisions":
return kindDecision
}
return catalog.ServesEmbedding
}
+1 -1
View File
@@ -26,7 +26,7 @@ func (s *Server) Front() http.Handler {
var clientPrefixes = []string{
"/v1", "/v1beta",
"/models", "/chat/completions", "/responses", "/messages",
"/images", "/embeddings", "/rerank", "/audio", "/videos",
"/images", "/embeddings", "/rerank", "/decisions", "/audio", "/videos",
"/muse-code/models", CodexPath, AlphaSearchPath, "/mcp",
// the key page (KeyPagePath): a key's holder opens it at the address
// they give their agents
+1
View File
@@ -39,6 +39,7 @@ var readOnlyRefused = []string{
"POST /v1" + AlphaSearchPath, "POST " + AlphaSearchPath, "POST /v1/messages/count_tokens",
"POST /v1/images/generations", "POST /images/generations", "POST /v1/images/edits", "POST /images/edits",
"POST /v1/embeddings", "POST /embeddings", "POST /v1/rerank", "POST /rerank",
"POST /v1/decisions", "POST /decisions",
"POST /v1/audio/transcriptions", "POST /audio/transcriptions",
"POST /v1/audio/translations", "POST /audio/translations",
"POST /v1/audio/speech", "POST /audio/speech",
+1 -1
View File
@@ -94,7 +94,7 @@ func (p *Provider) remoteMagpieEndpoints() {
for _, suf := range []string{
"/v1/messages/count_tokens", "/v1/messages",
"/v1/chat/completions", "/v1/responses", "/v1/systemone",
"/v1/embeddings", "/v1/rerank",
"/v1/embeddings", "/v1/rerank", "/v1/decisions",
"/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech",
"/v1/images/generations", "/v1/images/edits",
"/v1/videos", "/v1",
+1
View File
@@ -20,6 +20,7 @@ func TestRemoteMagpie(t *testing.T) {
"http://192.168.1.20:3425/v1/systemone",
"http://192.168.1.20:3425/v1/embeddings",
"http://192.168.1.20:3425/v1/rerank",
"http://192.168.1.20:3425/v1/decisions",
"http://192.168.1.20:3425/v1/images/generations",
"http://192.168.1.20:3425/v1/images/edits",
"http://192.168.1.20:3425/v1/videos",