provider: an AI Studio key decides with Google's gemini-decision-1 (WangYeruo on X)

WangYeruo (v0.1.4401) has a Google AI Studio key's provider, the google
preset. magpie's System One asked for google/gemini-decision-1 fell to
OpenRouter's decision list, because the google provider had no decision
API, and the user's own attempt got Google's 400 "type parameter is
required at input[0]" for an object input.

Google's Decisions API (launched 11-11, aistudio.google.com/docs/
decisions-api, api-reference/decisions/create-decision) serves
gemini-decision-1 at POST generativelanguage.googleapis.com/v1beta/
decisions on any AI Studio key, free tier included, with the key as
x-goog-api-key. It takes System One's questions (noul, choice, score),
an input of text or content blocks, and answers by name with usage
total_input_tokens / total_output_tokens.

- normalize gives a provider asked at the Gemini Developer API (the
  google preset's OpenAI-compatible base or a native Gemini base) its
  System One at AIStudioGemini (googleDecisions). Not Vertex, not a
  signed-in account, not another magpie, and a URL the user gave is kept.
- ViaGoogle: /decisions, signed as Gemini (x-goog-api-key, never Bearer;
  DecideProtocol), in AskSystemOne, the list and key checks, and the
  gateway's postDecideSent.
- googleAsk: the state goes as input (a string as it is, an object as
  its JSON text, never an object, which Google reads as a block), images
  as image blocks after it, a choice's null description as "".
- DecideResult: the usage comes back as System One's input_tokens /
  output_tokens; prompt_feedback.block_reason with no answers is a 400
  that says why. Every other way of asking is unchanged (tested).
- gemini-decision-1: 262,144 context, takes images, so the gateway lets
  images through to it as it does for the Clef.
- docs/subsystems/providers-accounts.md says so.

Tests, from Google's documented request and answer bytes, no network:
TestGoogleDecideWire, TestGoogleKeyDecides (with OpenRouter's live list
holding google/gemini-decision-1 seeded: it now routes to google),
TestGoogleSystemOne, TestGoogleDecisionsTakesImages.

Broken by hand, each red: the normalize fill dropped (KeyDecides,
SystemOne, TakesImages red); googleAsk skipped (Wire, KeyDecides,
SystemOne, TakesImages red); signed as Chat/Bearer (KeyDecides,
SystemOne, TakesImages red).

Run at this head:
- gofmt -l internal/: clean. go vet (provider, gateway), GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./... on mote: ok.
- Full suite on mote at 6317fd789 (this change on 7707ba9ad+f4b202030):
  go test -count=1 -timeout 45m ./...: 103 packages ok, exit 0, no FAIL.
- Rebased onto bf1b2893d (GUI and docs only since: app.js, two GUI
  tests, skill-router.md; nothing this change reads), then at this head
  on mote: go test -run 'Google|Decide|Decision|SystemOne|Ark'
  ./internal/provider ./internal/gateway: ok. The whole internal/provider
  package was also ok at 6317fd789 (155s).
- No GUI file changed, so no GUI suite.

Not tried: a real call. No AI Studio key is in magpie's accounts here.
This commit is contained in:
yetone
2026-11-18 12:08:46 +08:00
parent bf1b2893d4
commit 32a1818681
9 changed files with 599 additions and 19 deletions
+16
View File
@@ -160,6 +160,22 @@ Coding and Agent Plans answer System One nothing (404) and get none; a
key of another plan is never asked it (`decideKeys`). A URL the user gave
is kept. `TestArkPayAsYouGoDecides`, `TestArkDecisionSkipsPlanKeys`,
`custom-systemone-url.test.cjs`.
A provider asked at the Gemini Developer API with an AI Studio key
(`generativelanguage.googleapis.com`, the `google` preset's OpenAI-compatible
base or a native Gemini base; not Vertex, a signed-in account or another
magpie) gets its System One at `AIStudioGemini` too (`googleDecisions`):
Google's Decisions API (`POST /v1beta/decisions`, `ViaGoogle`) serves
`gemini-decision-1` on the same key, which goes as `x-goog-api-key`
(`DecideProtocol`), never as a Bearer token. Google takes System One's
questions as they are, with a choice's undescribed option as `""`; the
state goes as `input`, a string as it is and an object as its JSON text
(an object would be read as a content block), and the images as image
blocks after it (`googleAsk`). The answer's usage
(`total_input_tokens`/`total_output_tokens`) comes back as System One's,
and a `prompt_feedback.block_reason` with no answers is a 400 saying why
(`DecideResult`). Before, `google/gemini-decision-1` fell to OpenRouter's
decision list. `TestGoogleDecideWire`, `TestGoogleKeyDecides`,
`TestGoogleSystemOne`, `TestGoogleDecisionsTakesImages`.
Refresh replaces the list: removed decisions stop routing, and an empty
remote list never gains a fabricated Jev alias.
An older peer without the decision-list extension continues serving its
+3 -5
View File
@@ -544,7 +544,7 @@ func (s *Server) postDecideSent(ctx context.Context, p provider.Provider, model
req.Header.Set("ai-model-id", model)
req.Header.Set("ai-evaluation-model-specification-version", "4")
}
if err := p.Sign(ctx, req, provider.Chat, body); err != nil {
if err := p.Sign(ctx, req, p.DecideProtocol(), body); err != nil {
return decided{}, err
}
res, err := p.Do(s.client, req)
@@ -553,10 +553,8 @@ func (s *Server) postDecideSent(ctx context.Context, p provider.Provider, model
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if res.StatusCode < 300 {
b = provider.DecideAnswer(via, b)
}
return decided{sent: req, body: body, status: res.StatusCode, answer: b, header: res.Header}, nil
status, b := provider.DecideResult(via, res.StatusCode, b)
return decided{sent: req, body: body, status: status, answer: b, header: res.Header}, nil
}
// maxSystemOneBody is the most a System One request may be; larger is 413
+141
View File
@@ -0,0 +1,141 @@
package gateway
import (
"encoding/json"
"errors"
"io"
"net/http"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// Google's Decisions API's choice answer, as its reference gives it
// (aistudio.google.com/api-reference/decisions/create-decision), with
// the usage its yes-or-no example answers with.
const googleChoiceReply = `{"answers":{"ticket_route":{"type":"choice","choice":"technical_support","confidence":0.95,"probabilities":{"account_access":0.02,"billing":0.03,"technical_support":0.95}}},"usage":{"input_tokens_by_modality":[{"modality":"text","tokens":152}],"total_input_tokens":152,"total_output_tokens":0,"total_tokens":152}}`
// googleDecisionsUp stands in for generativelanguage.googleapis.com, in
// process: POST /v1beta/decisions answers reply to the key as
// x-goog-api-key and an input that is not an object (Google reads an
// object as a content block, and refuses one without its type); anything
// else is refused as Google refuses it. No other host is reached.
type googleDecisionsUp struct {
mu sync.Mutex
reply string
asked []string
bodies []map[string]any
}
func (u *googleDecisionsUp) RoundTrip(r *http.Request) (*http.Response, error) {
if r.URL.Hostname() != "generativelanguage.googleapis.com" {
return nil, errors.New("test reached " + r.URL.Host)
}
b, _ := io.ReadAll(r.Body)
var q map[string]any
json.Unmarshal(b, &q)
u.mu.Lock()
u.asked = append(u.asked, r.URL.Path+" key="+r.Header.Get("x-goog-api-key")+" auth="+r.Header.Get("Authorization"))
u.bodies = append(u.bodies, q)
u.mu.Unlock()
reply := func(code int, s string) (*http.Response, error) {
return &http.Response{StatusCode: code, Header: http.Header{"Content-Type": {"application/json; charset=UTF-8"}},
Body: io.NopCloser(strings.NewReader(s)), Request: r}, nil
}
if r.URL.Path != "/v1beta/decisions" {
return reply(404, `{"error":{"code":404,"message":"Not found","status":"NOT_FOUND"}}`)
}
if r.Header.Get("x-goog-api-key") != "AIza-test" {
return reply(401, `{"error":{"code":401,"message":"Expected OAuth 2 access token","status":"UNAUTHENTICATED"}}`)
}
if _, isObject := q["input"].(map[string]any); isObject || q["input"] == nil {
return reply(400, `{"error":{"code":400,"message":"type parameter is required at input[0]","status":"INVALID_ARGUMENT"}}`)
}
return reply(200, u.reply)
}
func (u *googleDecisionsUp) got() ([]string, []map[string]any) {
u.mu.Lock()
defer u.mu.Unlock()
return slices.Clone(u.asked), slices.Clone(u.bodies)
}
// googleKey saves WangYeruo's provider, the google preset with an AI
// Studio key, and has the gateway's Google be up.
func googleKey(t *testing.T, up *googleDecisionsUp) *Server {
t.Helper()
p, err := provider.FromPreset("google")
if err != nil {
t.Fatal(err)
}
p.Key = "AIza-test"
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
old := http.DefaultClient.Transport
http.DefaultClient.Transport = up
t.Cleanup(func() { http.DefaultClient.Transport = old })
s := New()
s.client = &http.Client{Transport: up}
return s
}
// WangYeruo on X: magpie's System One API, asked for
// google/gemini-decision-1 with a Google AI Studio key's provider, went to
// OpenRouter. It reaches Google's Decisions API on that key, as Google
// takes it — the state an input of text, the key as x-goog-api-key — and
// Google's answer comes back as System One's, its usage as System One
// names it.
func TestGoogleSystemOne(t *testing.T) {
fresh(t)
up := &googleDecisionsUp{reply: googleChoiceReply}
s := googleKey(t, up)
code, out := sendTo(s, "/v1/systemone", `{"model":"google/`+provider.GoogleDecision+`","state":{"message":"Every time I click Export to PDF, the app freezes and crashes with error code 504."},`+
`"questions":{"ticket_route":{"type":"choice","instructions":"Route the support ticket to the most appropriate team.","criteria":{"billing":"Invoices, charges, refunds, or subscription plan changes.","technical_support":"Bugs, crashes, errors, or product functionality issues.","account_access":null}}}}`)
if code != 200 || !strings.Contains(out, `"choice":"technical_support"`) || !strings.Contains(out, `"input_tokens":152`) {
t.Fatalf("System One: %d %s", code, out)
}
asked, bodies := up.got()
if !slices.Equal(asked, []string{"/v1beta/decisions key=AIza-test auth="}) {
t.Fatalf("Google asked: %q", asked)
}
if in := bodies[0]["input"]; in != `{"message":"Every time I click Export to PDF, the app freezes and crashes with error code 504."}` {
t.Fatalf("input %v", in)
}
if _, ok := bodies[0]["state"]; ok || bodies[0]["model"] != provider.GoogleDecision {
t.Fatalf("sent %v", bodies[0])
}
c := bodies[0]["questions"].(map[string]any)["ticket_route"].(map[string]any)["criteria"].(map[string]any)
if c["account_access"] != "" || c["billing"] != "Invoices, charges, refunds, or subscription plan changes." {
t.Fatalf("criteria %v", c)
}
if recs := usage.Load(time.Time{}); len(recs) != 1 || recs[0].Provider != "google" || recs[0].Model != provider.GoogleDecision || recs[0].Input+recs[0].CacheRead+recs[0].CacheWrite != 152 {
t.Fatalf("recorded %+v", recs)
}
}
// OpenAI's Decisions API asked for Google's decision model is asked as
// System One there, its message's image an image block of the input,
// which gemini-decision-1 reads.
func TestGoogleDecisionsTakesImages(t *testing.T) {
fresh(t)
up := &googleDecisionsUp{reply: `{"answers":{"visible_damage":{"type":"noul","noul":0.92,"confidence":0.84},"condition":{"type":"choice","choice":"used","confidence":0.6,"probabilities":{"new":0.2,"used":0.8}}},"usage":{"total_input_tokens":1290,"total_output_tokens":0,"total_tokens":1290}}`}
s := googleKey(t, up)
code, out := sendTo(s, "/v1/decisions", decisionAsked("google/"+provider.GoogleDecision))
if code != 200 || !strings.Contains(out, `"choice":"used"`) {
t.Fatalf("Decisions: %d %s", code, out)
}
_, bodies := up.got()
if len(bodies) != 1 {
t.Fatalf("Google asked %d times", len(bodies))
}
in, _ := json.Marshal(bodies[0]["input"])
if want := `[{"text":"{\"messages\":[{\"content\":\"Inspect the product in this photo.\",\"role\":\"user\"}]}","type":"text"},{"data":"iVBORw0KGgo=","mime_type":"image/png","type":"image"}]`; string(in) != want {
t.Fatalf("input %s\nwant %s", in, want)
}
}
+4 -3
View File
@@ -69,9 +69,10 @@ type systemOneTarget struct {
}
// takesImages is whether the model takes a System One request's images:
// a Clef on Workers AI does, and another magpie passes them on.
// a Clef on Workers AI does, Google's gemini-decision-1 does (as image
// blocks of its input), and another magpie passes them on.
func (t systemOneTarget) takesImages() bool {
if t.p.IsRemoteMagpie() {
if t.p.IsRemoteMagpie() || t.p.DecideVia() == provider.ViaGoogle {
return true
}
return t.p.DecideVia() == provider.ViaCloudflare && provider.CloudflareClef(t.model)
@@ -295,7 +296,7 @@ func decisionsState(input json.RawMessage, ts []systemOneTarget, images *[]strin
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)
return untranslated("%s is an image (input_image), which %s can't take: System One takes images only for Cloudflare's Clef and Google's gemini-decision-1", where, t)
}
}
if !strings.HasPrefix(url, "data:") {
+64 -8
View File
@@ -90,10 +90,45 @@ func (p Provider) arkSystemOne() string {
return ""
}
// GoogleDecision is Google's decision model, gemini-decision-1, which the
// Gemini Developer API answers at its Decisions API (POST
// /v1beta/decisions) on an AI Studio key: typed noul, choice and score
// questions, as System One asks them, over an input (Google's docs,
// aistudio.google.com/docs/decisions-api, 2026-11-11).
const GoogleDecision = "gemini-decision-1"
// googleDecides reports whether base is the Gemini Developer API's,
// generativelanguage.googleapis.com, AI Studio keys' host: the one host
// Google serves its Decisions API at ("Available on the Gemini Developer
// API (v1beta) … only"; Vertex AI has none).
func googleDecides(base string) bool {
return HostOf(base) == "generativelanguage.googleapis.com"
}
// googleDecisions is the decision base of a key's provider asked at the
// Gemini Developer API (the google preset, AI Studio's OpenAI-compatible
// …/v1beta/openai or its own …/v1beta): AIStudioGemini, whose
// /decisions answers gemini-decision-1 on the same key (WangYeruo on X:
// google/gemini-decision-1 was asked at OpenRouter, the google provider
// having no decision API); "" for any other. A signed-in account, a
// plugin, a remote magpie and Vertex say their own.
func (p Provider) googleDecisions() string {
if p.Account != nil || p.IsRemoteMagpie() || p.IsVertex() {
return ""
}
if googleDecides(p.Chat) || googleDecides(p.Gemini) {
return AIStudioGemini
}
return ""
}
// vendorDecision is the decision model of the vendor whose System One
// API base is, Bailian's or Ark's, which its model list never names.
// API base is, Bailian's, Ark's or Google's, which its model list never
// names (Google's: its chat list is the chat models').
func vendorDecision(base string) (catalog.Model, bool) {
switch {
case googleDecides(base):
return catalog.Model{ID: GoogleDecision, Name: "Gemini Decision 1"}, true
case bailianDecides(base):
return catalog.Model{ID: BailianDecision, Name: "Decision model (preview)"}, true
case arkDecides(base):
@@ -342,12 +377,14 @@ var cloudflareDecideModels = []catalog.Model{
// setup points, at the AI SDK's evaluation models (a boolean for a noul
// and probabilities for a confidence); or Workers AI (System One's
// questions and answers, in Cloudflare's envelope and at an account's
// address).
// address); or Google's Decisions API (System One's questions over an
// input, at the Gemini API's /decisions, its key as x-goog-api-key).
const (
ViaSystemOne = "systemone"
ViaVercel = "vercel"
ViaVercelEval = "vercel-eval"
ViaCloudflare = "cloudflare"
ViaGoogle = "google"
)
// DecideVia is the way p's decision API is asked, known by its host or by
@@ -359,6 +396,8 @@ func (p Provider) DecideVia() string {
}
base := strings.TrimRight(p.Decide, "/")
switch h := HostOf(base); {
case googleDecides(base):
return ViaGoogle
case strings.HasSuffix(base, "/v4/ai"):
return ViaVercelEval
case h == "ai-gateway.vercel.sh" || strings.HasSuffix(base, "/typesafe") || strings.Contains(base, "/typesafe/v1"):
@@ -464,6 +503,10 @@ func decideFactOf(id string) (decideFact, bool) {
return decideFact{context: 65_536, images: true}, true
case last == BailianDecision:
return decideFact{context: 65_536}, true
case last == GoogleDecision:
// "up to 262,144 tokens" of text, images, video, audio and PDFs
// (its model page)
return decideFact{context: 262_144, images: true}, true
case last == ArkDecision:
// its window on System One is not documented; an image in the
// request was left unread on 11-01 (a red square asked "is it
@@ -572,10 +615,23 @@ func (p Provider) DecideURL(ctx context.Context) (string, error) {
}
}
return api + "/accounts/" + acct + "/ai/run", nil
case ViaGoogle:
return strings.TrimSuffix(strings.TrimRight(p.Decide, "/"), "/decisions") + "/decisions", nil
}
return p.Decide + "/systemone", nil
}
// DecideProtocol is the protocol p's decision API is signed as: Google's
// as its Gemini API (x-goog-api-key, where a key as a Bearer token is
// turned away, "Expected OAuth 2 access token"), every other as chat
// completions.
func (p Provider) DecideProtocol() Protocol {
if p.DecideVia() == ViaGoogle {
return Gemini
}
return Chat
}
// DecideModelURL is where a question for model is posted: DecideURL, or,
// for a Clef on Workers AI, its own run under it.
func (p Provider) DecideModelURL(ctx context.Context, model string) (string, error) {
@@ -955,7 +1011,7 @@ func (p Provider) fetchDecide(ctx context.Context) ([]catalog.Model, error) {
if err != nil {
return nil, err
}
if err := p.Sign(ctx, req, Chat, nil); err != nil {
if err := p.Sign(ctx, req, p.DecideProtocol(), nil); err != nil {
return nil, err
}
res, err := Keyed(http.DefaultClient).Do(req)
@@ -1056,7 +1112,7 @@ func (p Provider) AskSystemOne(ctx context.Context, model string) error {
}
req.Header.Set("Content-Type", "application/json")
p.DecideHeaders(req.Header)
if err := p.Sign(ctx, req, Chat, nil); err != nil {
if err := p.Sign(ctx, req, p.DecideProtocol(), nil); err != nil {
return err
}
// a plugin's goes through its fetch (Do), at plugin://<id>/v1/systemone
@@ -1066,10 +1122,10 @@ func (p Provider) AskSystemOne(ctx context.Context, model string) error {
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if res.StatusCode != http.StatusOK {
return fmt.Errorf("%s: %s", p.Name, APIError(b, res.Status))
status, b := DecideResult(via, res.StatusCode, b)
if status != http.StatusOK {
return fmt.Errorf("%s: %s", p.Name, APIError(b, fmt.Sprintf("%d %s", status, http.StatusText(status))))
}
b = DecideAnswer(via, b)
var out struct {
Answers map[string]json.RawMessage `json:"answers"`
}
@@ -1169,7 +1225,7 @@ func (p Provider) checkKey(ctx context.Context, u string) error {
if err != nil {
return err
}
if err := p.Sign(ctx, req, Chat, nil); err != nil {
if err := p.Sign(ctx, req, p.DecideProtocol(), nil); err != nil {
return err
}
res, err := Keyed(http.DefaultClient).Do(req)
+246
View File
@@ -0,0 +1,246 @@
package provider
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"reflect"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
)
// Google's Decisions API, as its reference gives it
// (aistudio.google.com/api-reference/decisions/create-decision, 11-11):
// the yes-or-no example's request and its answer.
const (
googleNoulAsk = `{"model": "gemini-decision-1","input": "Customer message: Hi, I was charged twice for my monthly subscription this morning. Can you refund the duplicate charge?","questions": {"needs_billing_refund": {"type": "noul","instructions": "Determine whether the customer is requesting a billing refund.","criteria": {"true_description": "The customer explicitly asks for a refund or reversal of a charge.","false_description": "The customer is asking a general question or reporting a non-billing issue."}}}}`
googleNoulAnswer = `{
"answers": {
"needs_billing_refund": {
"type": "noul",
"confidence": 0.97,
"noul": 0.97
}
},
"usage": {
"input_tokens_by_modality": [
{
"modality": "text",
"tokens": 152
}
],
"total_input_tokens": 152,
"total_output_tokens": 0,
"total_tokens": 152
}
}`
// what an object as the input was answered with (WangYeruo on X)
googleNoType = `{"error":{"code":400,"message":"type parameter is required at input[0]","status":"INVALID_ARGUMENT"}}`
)
func sameJSON(t *testing.T, what string, got []byte, want string) {
t.Helper()
var g, w any
if err := json.Unmarshal(got, &g); err != nil {
t.Fatalf("%s: %v in %s", what, err, got)
}
if err := json.Unmarshal([]byte(want), &w); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(g, w) {
t.Fatalf("%s:\n got %s\nwant %s", what, got, want)
}
}
// A System One request goes to Google as its Decisions API takes it: the
// state as the input, text as it is and an object as its JSON text, a
// choice's undescribed option with an empty description, images as image
// blocks after the text; and its answer comes back as System One's, with
// its usage named as System One names it.
func TestGoogleDecideWire(t *testing.T) {
ask := strings.Replace(googleNoulAsk, `"input"`, `"state"`, 1)
sameJSON(t, "text state", DecideAsk(ViaGoogle, GoogleDecision, []byte(ask)), googleNoulAsk)
obj := `{"model":"gemini-decision-1","state":{"message":"fix the build","previous_message_kind":"coding"},"questions":{"intent":{"type":"choice","instructions":"Which?","criteria":{"coding":null,"chat":"small talk"}}},"images":["data:image/png;base64,iVBORw0KGgo=","https://example.com/a.jpg"]}`
sameJSON(t, "object state", DecideAsk(ViaGoogle, GoogleDecision, []byte(obj)),
`{"model":"gemini-decision-1","input":[{"type":"text","text":"{\"message\":\"fix the build\",\"previous_message_kind\":\"coding\"}"},{"type":"image","data":"iVBORw0KGgo=","mime_type":"image/png"},{"type":"image","uri":"https://example.com/a.jpg"}],"questions":{"intent":{"type":"choice","instructions":"Which?","criteria":{"coding":"","chat":"small talk"}}}}`)
status, b := DecideResult(ViaGoogle, 200, []byte(googleNoulAnswer))
if status != 200 {
t.Fatalf("status %d", status)
}
sameJSON(t, "answer", b, `{"answers":{"needs_billing_refund":{"type":"noul","confidence":0.97,"noul":0.97}},"usage":{"input_tokens":152,"output_tokens":0}}`)
// an input its filters blocked answers nothing: a 400 that says why
status, b = DecideResult(ViaGoogle, 200, []byte(`{"answers":{},"prompt_feedback":{"block_reason":"safety","block_reason_message":"Harmful content."}}`))
if status != 400 || APIError(b, "") != "Google blocked the input (safety): Harmful content." {
t.Fatalf("blocked: %d %s", status, b)
}
// a refusal is passed on as Google gave it
if status, b = DecideResult(ViaGoogle, 400, []byte(googleNoType)); status != 400 || string(b) != googleNoType {
t.Fatalf("refusal: %d %s", status, b)
}
// and nothing changes for any other way of asking
for _, via := range []string{ViaSystemOne, ViaVercel} {
if got := DecideAsk(via, "jev-latest", []byte(obj)); string(got) != obj {
t.Fatalf("%s: %s", via, got)
}
if status, got := DecideResult(via, 200, []byte(googleNoulAnswer)); status != 200 || string(got) != googleNoulAnswer {
t.Fatalf("%s answer: %d %s", via, status, got)
}
}
}
// googleUp stands in for generativelanguage.googleapis.com, in process:
// POST /v1beta/decisions with the key as x-goog-api-key, the input not
// an object (an object is a content block, refused without its type), is
// answered with Google's documented answer; a key as a Bearer token is
// refused as Google refuses it. Any other host is never reached.
type googleUp struct {
mu sync.Mutex
asked []string
body []byte
}
func (u *googleUp) RoundTrip(r *http.Request) (*http.Response, error) {
if r.URL.Hostname() != "generativelanguage.googleapis.com" {
return nil, errors.New("test reached " + r.URL.Host)
}
b, _ := io.ReadAll(r.Body)
u.mu.Lock()
u.asked = append(u.asked, r.Method+" "+r.URL.Path+" key="+r.Header.Get("x-goog-api-key")+" auth="+r.Header.Get("Authorization"))
u.body = b
u.mu.Unlock()
reply := func(code int, s string) (*http.Response, error) {
return &http.Response{StatusCode: code, Header: http.Header{"Content-Type": {"application/json; charset=UTF-8"}},
Body: io.NopCloser(strings.NewReader(s)), Request: r}, nil
}
if r.Method != http.MethodPost || r.URL.Path != "/v1beta/decisions" {
return reply(404, `{"error":{"code":404,"message":"Not found","status":"NOT_FOUND"}}`)
}
if r.Header.Get("x-goog-api-key") != "AIza-test" {
return reply(401, `{"error":{"code":401,"message":"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential.","status":"UNAUTHENTICATED"}}`)
}
var q struct {
Input json.RawMessage `json:"input"`
}
if json.Unmarshal(b, &q) != nil || len(q.Input) == 0 || q.Input[0] == '{' {
return reply(400, googleNoType)
}
return reply(200, googleNoulAnswer)
}
func (u *googleUp) got() []string {
u.mu.Lock()
defer u.mu.Unlock()
return slices.Clone(u.asked)
}
func fakeGoogleDecisions(t *testing.T) *googleUp {
up := &googleUp{}
old := http.DefaultClient.Transport
http.DefaultClient.Transport = up
t.Cleanup(func() { http.DefaultClient.Transport = old })
return up
}
// WangYeruo on X: with a Google AI Studio key's provider (the google
// preset), google/gemini-decision-1 went to OpenRouter, the google
// provider having no decision API. Google answers it at the Gemini API's
// /v1beta/decisions on the same key: a provider asked at the Gemini
// Developer API, the preset's or a custom one, offers it with no URL
// typed, keeps it out of its chat models, and is the one asked for it;
// Vertex and other hosts are as they were.
func TestGoogleKeyDecides(t *testing.T) {
arkHome(t)
up := fakeGoogleDecisions(t)
g, err := FromPreset("google")
if err != nil {
t.Fatal(err)
}
g.Key, g.Models = "AIza-test", []string{"gemini-3.5-flash"}
or, err := FromPreset("openrouter")
if err != nil {
t.Fatal(err)
}
or.Key = "sk-or-1"
for _, p := range []Provider{g,
{ID: "gem-native", Name: "Gemini native", Gemini: AIStudioGemini, Key: "AIza-test"},
{ID: "other", Name: "Other", Chat: "https://api.example.com/v1beta/openai", Key: "k"},
{ID: "own", Name: "Own", Chat: AIStudioChat, Decide: "https://api.typesafe.ai/v1", Key: "AIza-test"},
or,
} {
if err := Save(p); err != nil {
t.Fatal(err)
}
}
// OpenRouter lists Google's decision model as its own, as it does
if err := catalog.SaveLive(decisionsID("openrouter"), "https://openrouter.ai/api/v1", []catalog.Model{{ID: "google/gemini-decision-1"}, {ID: OpenRouterJev}}); err != nil {
t.Fatal(err)
}
for id, want := range map[string]string{"google": AIStudioGemini, "gem-native": AIStudioGemini, "other": "", "own": "https://api.typesafe.ai/v1"} {
p, err := Find(id)
if err != nil {
t.Fatal(err)
}
if p.Decide != want {
t.Errorf("%s: decisions at %q, want %q", id, p.Decide, want)
}
}
p, err := Find("google")
if err != nil {
t.Fatal(err)
}
if p.DecideVia() != ViaGoogle || p.Jev() != GoogleDecision || !p.DecidesModel(GoogleDecision) || p.DecidesModel("gemini-3.5-flash") {
t.Fatalf("google: via %s, asked with %s", p.DecideVia(), p.Jev())
}
if ms := p.decideModels(); len(ms) != 1 || ms[0].Context != 262_144 || ms[0].ImageInput == nil || !*ms[0].ImageInput {
t.Fatalf("decision models: %+v", ms)
}
if u, _ := p.DecideURL(context.Background()); u != "https://generativelanguage.googleapis.com/v1beta/decisions" {
t.Fatalf("asked at %s", u)
}
// the user's model reaches Google, on the provider it names; Google's
// name alone, served by both here, asks which, and is never OpenRouter's
for _, id := range []string{"google", "gem-native"} {
got, m, err := RouteDecider(id + "/" + GoogleDecision)
if err != nil || got.ID != id || m != GoogleDecision {
t.Fatalf("%s routed to %s %s %v", id, got.ID, m, err)
}
}
if _, _, err := RouteDecider(GoogleDecision); err == nil || !strings.Contains(err.Error(), "name it gem-native/gemini-decision-1 or google/gemini-decision-1") {
t.Fatalf("Google's name alone: %v", err)
}
// OpenRouter's own is still OpenRouter's
if got, m, err := RouteDecider("openrouter/google/gemini-decision-1"); err != nil || got.ID != "openrouter" || m != "google/gemini-decision-1" {
t.Fatalf("openrouter's routed to %s %s %v", got.ID, m, err)
}
for _, e := range providerEntries() {
if e.ID == "google/"+GoogleDecision {
t.Fatalf("an agent is offered %s", e.ID)
}
}
// the provider's test asks it the smallest question, with the key as
// Google takes it
if err := p.AskSystemOne(context.Background(), GoogleDecision); err != nil {
t.Fatal(err)
}
if got := up.got(); !slices.Equal(got, []string{"POST /v1beta/decisions key=AIza-test auth="}) {
t.Fatalf("Google asked: %q", got)
}
sameJSON(t, "smallest question", up.body, `{"model":"gemini-decision-1","input":"{\"text\":\"ping\"}","questions":{"ok":{"type":"noul","instructions":"Is this a test?"}}}`)
// a signed-in account and Vertex say their own
if d := (Provider{Chat: AIStudioChat, Account: &Account{}}).googleDecisions(); d != "" {
t.Fatalf("an account: %q", d)
}
if d := (Provider{Preset: VertexPreset, Gemini: AIStudioGemini}).googleDecisions(); d != "" {
t.Fatalf("vertex: %q", d)
}
}
+115 -1
View File
@@ -3,6 +3,7 @@ package provider
import (
"encoding/json"
"math"
"net/http"
"strings"
)
@@ -10,12 +11,16 @@ import (
// TypeSafe API takes it as it is; its evaluation models name the model in
// a header and ask a noul as a boolean; Workers AI takes the state and
// questions as the input of a run of the model, and a Clef there takes
// the request as it is, its model named as Clef names itself.
// the request as it is, its model named as Clef names itself; Google's
// Decisions API takes it as googleAsk makes it.
func DecideAsk(via, model string, body []byte) []byte {
var q map[string]any
if via == ViaSystemOne || via == ViaVercel || json.Unmarshal(body, &q) != nil {
return body
}
if via == ViaGoogle {
return googleAsk(q, body)
}
delete(q, "model")
switch via {
case ViaVercelEval:
@@ -53,6 +58,28 @@ func DecideAnswer(via string, b []byte) []byte {
if json.Unmarshal(b, &env) == nil && len(env.Result) > 0 && env.Result[0] == '{' {
return env.Result
}
case ViaGoogle:
// Google's usage is total_input_tokens and total_output_tokens
// (always 0: "Only input tokens are billed"); its answers are
// System One's, noul, choice and score alike
var g struct {
Model string `json:"model"`
Answers json.RawMessage `json:"answers"`
Usage struct {
Input int `json:"total_input_tokens"`
Output int `json:"total_output_tokens"`
} `json:"usage"`
}
if json.Unmarshal(b, &g) != nil || len(g.Answers) == 0 || g.Answers[0] != '{' {
return b
}
out := map[string]any{"answers": g.Answers,
"usage": map[string]int{"input_tokens": g.Usage.Input, "output_tokens": g.Usage.Output}}
if g.Model != "" {
out["model"] = g.Model
}
b, _ := json.Marshal(out)
return b
case ViaVercelEval:
var v struct {
Model string `json:"model"`
@@ -83,6 +110,93 @@ func DecideAnswer(via string, b []byte) []byte {
return b
}
// googleAsk is a System One request (q, as body) as Google's Decisions
// API takes it (aistudio.google.com/docs/decisions-api): its state is the
// input, text as it is and an object or list as its JSON text ("Serialize
// JSON objects and arrays to a string and pass them as text"), where an
// object would be read as a content block and refused (400 "type
// parameter is required at input[0]"); its images, data: URLs, are image
// blocks after it, and any other URL a block at that uri. Its questions
// are System One's, noul, choice and score, but a choice's option with no
// description (null, as magpie's "none of these" goes) has an empty one,
// which Google takes. Everything else goes as it is, for Google to refuse
// what it has no place for with a 400 naming it.
func googleAsk(q map[string]any, body []byte) []byte {
state, ok := q["state"]
if !ok {
return body
}
delete(q, "state")
text, isText := state.(string)
if !isText {
b, _ := json.Marshal(state)
text = string(b)
}
var input any = text
if ims, ok := q["images"].([]any); ok {
delete(q, "images")
blocks := []any{map[string]any{"type": "text", "text": text}}
for _, im := range ims {
u, _ := im.(string)
if u == "" {
continue
}
block := map[string]any{"type": "image", "uri": u}
if meta, data, ok := strings.Cut(strings.TrimPrefix(u, "data:"), ","); ok && strings.HasPrefix(u, "data:") && strings.HasSuffix(meta, ";base64") {
block = map[string]any{"type": "image", "data": data, "mime_type": strings.TrimSuffix(meta, ";base64")}
}
blocks = append(blocks, block)
}
if len(blocks) > 1 {
input = blocks
}
}
q["input"] = input
if qs, ok := q["questions"].(map[string]any); ok {
for _, v := range qs {
x, _ := v.(map[string]any)
if c, ok := x["criteria"].(map[string]any); ok && x["type"] == "choice" {
for k, d := range c {
if d == nil {
c[k] = ""
}
}
}
}
}
b, _ := json.Marshal(q)
return b
}
// DecideResult is a decision API's answer, status and body, as System
// One gives it: DecideAnswer's translation of one that answered, and,
// from Google, an input its filters blocked (prompt_feedback.block_reason,
// "no decisions were evaluated, and answers is empty") as the 400 Google
// answers a blocked input with otherwise, its reason in the message.
func DecideResult(via string, status int, b []byte) (int, []byte) {
if status >= 300 {
return status, b
}
if via == ViaGoogle {
var g struct {
Answers map[string]json.RawMessage `json:"answers"`
Feedback struct {
Reason string `json:"block_reason"`
Message string `json:"block_reason_message"`
} `json:"prompt_feedback"`
}
if json.Unmarshal(b, &g) == nil && g.Feedback.Reason != "" && len(g.Answers) == 0 {
msg := "Google blocked the input (" + g.Feedback.Reason + ")"
if g.Feedback.Message != "" {
msg += ": " + g.Feedback.Message
}
out, _ := json.Marshal(map[string]any{"error": map[string]any{"code": g.Feedback.Reason, "message": msg}})
return http.StatusBadRequest, out
}
}
return status, DecideAnswer(via, b)
}
// Confidence is how sure a set of probabilities is of its likeliest, as
// System One gives it: 0 with every option as likely, 1 with one certain
// (its 0.87 of three options is 0.8).
+7
View File
@@ -1981,6 +1981,13 @@ func normalize(p Provider) Provider {
if p.Decide == "" {
p.Decide = p.arkSystemOne()
}
// one asked at the Gemini Developer API on an AI Studio key, the
// google preset's or a custom one, answers gemini-decision-1 at its
// Decisions API on the same key (WangYeruo on X: it was asked at
// OpenRouter instead, this provider having no decision API)
if p.Decide == "" {
p.Decide = p.googleDecisions()
}
if p.Routing != Ordered && p.Routing != Rotate && p.Routing != LeastUsed && p.Routing != Pace && p.Routing != Weighted && p.Routing != FreeFirst && p.Routing != Fastest && p.Routing != Drain && !PluginRouting(p.Routing) {
p.Routing = ""
}
+3 -2
View File
@@ -220,10 +220,11 @@ func (p Provider) ModelTest() string {
// (Vercel's TypeSafe API, OpenRouter's), or Workers AI's, which DecideAsk
// wraps it for (ARNO on Discord: cloudflare-jev's models couldn't be
// tested from their right-click); not Vercel's evaluation models, which
// name the model in headers of their own.
// name the model in headers of their own. Google's Decisions API, which
// DecideAsk asks as it takes it, can be too.
func (p Provider) AsksDecideModels() bool {
v := p.DecideVia()
return p.Decides() && (v == ViaSystemOne || v == ViaVercel || v == ViaCloudflare)
return p.Decides() && (v == ViaSystemOne || v == ViaVercel || v == ViaCloudflare || v == ViaGoogle)
}
// mantleBase is base for model at the prefix Mantle serves it under