A user on X wanted to spend GCP credit on Claude through Vertex AI. Claude
Code does it with CLAUDE_CODE_USE_VERTEX, ANTHROPIC_VERTEX_PROJECT_ID and
CLOUD_ML_REGION, but magpie's Vertex provider only spoke Gemini. Now a
Vertex provider with just a project and a region serves claude-* ids
(claude-sonnet-5-5, claude-sonnet-4-5@20250929, ...) on every client
protocol: Chat, Responses, Anthropic Messages and Gemini.
The request shape follows the AnthropicVertex SDK bundled in Claude Code
2.1.314 and Google's Vertex docs for Claude:
- a message goes to .../publishers/anthropic/models/{model}:streamRawPredict
when it streams and :rawPredict when it doesn't, with model taken out of
the body;
- a count goes to .../publishers/anthropic/models/count-tokens:rawPredict
with the model kept;
- the body gets anthropic_version "vertex-2023-10-16" when it has none;
- no ?beta=true query; the bearer is the existing Google OAuth token;
- the advanced-tool-use-2025-11-20 beta goes as tool-search-tool-2025-10-19,
as Claude Code sends it to Vertex (the Bedrock rename table, now for
Vertex too; Bedrock's refused betas stay Bedrock only).
How:
- provider: VertexClaude(model) and VertexClaudeRequest(path, body).
Base(Anthropic) is the Vertex project base, so a Vertex provider speaks
chat, anthropic and gemini; ListedAPIs gives a Claude id Anthropic only,
so the model id alone picks the publisher. No GUI change.
- gateway: forwardOnce, the one place every Anthropic upstream request
passes, rewrites path and body for Vertex. Gemini's effort mapping
(none -> minimal, xhigh -> high) skips Claude. countTokens takes any
provider with an Anthropic base.
- provider Test stays on Gemini (Claude needs Model Garden enablement);
TestModels asks a Claude id on rawPredict with max_tokens 16.
- preset lists claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5 and
claude-fable-5-1 at global. Docs: reference.md, providers-accounts.md,
gateway-routing.md.
Run (darwin, mote):
- gofmt -l: nothing. go build ./...: ok.
- go vet ./... ok; GOOS=linux go vet -tags nogui ./... ok;
GOOS=windows go vet ./... ok.
- go test -tags nogui -count=1 -timeout 45m before the rebase:
internal/provider ok 100s, internal/gateway ok 497s, internal/gui ok 58s,
internal/cli ok 33s, internal/tui ok 9s.
- After rebasing on origin/main (36 new commits, six in provider/gateway):
internal/provider ok 112s and internal/gateway ok 578s again, at the
rebased tree (d53336d9e before this message was written), gofmt clean.
- New tests: TestVertexClaudeModel (gateway, fake Vertex server: chat,
anthropic, responses streamed and not, two id forms, a Gemini client,
effort xhigh and none, Claude Code's ?beta=true with the tool-search
beta, count_tokens, a Gemini model still on streamGenerateContent),
TestVertexClaudeModels and TestVertexClaudeRequest (provider).
- GUI (no asset changed; files the provider list reaches):
vertex-editor and i18n-keys in Chromium on mote, 18/18. WebKit on mote
fails to launch at all (180s launch timeout under load), so WebKit ran
on the Linux box (wsl-run): vertex-editor 14/14 in four of five
runs. The first run had 13/14 with one failure whose name was lost
(log not kept, my fault); three runs with logs kept since were 0 fail,
so it isn't named or filed. No GUI asset changed here.
Broken by hand, each red, then restored:
- forwardOnce rewrite off: 502 on every Claude request.
- vertexEffort exclusion removed: xhigh reaches Vertex as high.
- beta rename off for Vertex: beta arrives unrenamed.
- countTokens back to c.p.Anthropic: the count goes to streamRawPredict.
- ListedAPIs Claude branch removed: the model is asked on gemini.
Not tried:
- No real GCP project was available: no real Vertex request, no Model
Garden enablement, no real Claude Code session against Vertex through
magpie. The shape is checked against the SDK and docs only.
- Claude is listed at global only; regional availability per model isn't
listed.
- Whether Vertex accepts a 1h cache_control TTL is unverified.
155 lines
5.6 KiB
Go
155 lines
5.6 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
)
|
|
|
|
// ---- Google Vertex AI (provider side) ----------------------------------------
|
|
//
|
|
// Vertex AI serves Gemini at streamGenerateContent, with the model in the
|
|
// path (provider.VertexPath) and Gemini's own request in the body: the one
|
|
// Code Assist carries in its envelope. Where it parts from Code Assist is in
|
|
// what it turns away. A thinking level the model doesn't have, or a level
|
|
// at all on 2.5, is a 400 (vertexEffort, vertexThinking). A call's thought
|
|
// signature goes back as Vertex AI gave it, as on every Gemini path
|
|
// (gemini_signature.go): a call made with none on a step it signed is a 400.
|
|
//
|
|
// Its partner models (provider.VertexPartner: deepseek-ai/…, zai-org/…,
|
|
// openai/gpt-oss-…) are not Gemini: Google serves them on its
|
|
// OpenAI-compatible chat completions at the project (Base(Chat)), under
|
|
// the same token, and the gateway asks them there as it asks any chat
|
|
// completions vendor. Nothing in this file is done to them.
|
|
//
|
|
// Nor to Claude (provider.VertexClaude: claude-opus-5-5,
|
|
// claude-sonnet-4-5@20250929), which Google serves on Anthropic's own
|
|
// Messages API at the project (Base(Anthropic)), under the same token.
|
|
// The gateway asks it as it asks any Anthropic vendor, relayed or built,
|
|
// and forwardOnce, last, moves the request to where Anthropic's Vertex SDK
|
|
// sends it (provider.VertexClaudeRequest): the model and whether it
|
|
// streams in the path (:streamRawPredict, :rawPredict), a count at
|
|
// count-tokens:rawPredict, anthropic_version vertex-2023-10-16 in the
|
|
// body. Tool search's beta goes under the name Claude Code gives it for
|
|
// Vertex (bedrockBetas).
|
|
|
|
// buildVertex is a streamGenerateContent body for Vertex AI, which names the
|
|
// model in its path and has none in here.
|
|
func buildVertex(r *Request, model string) ([]byte, error) {
|
|
req, err := geminiRequest(r, model, "vertex")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return json.Marshal(req)
|
|
}
|
|
|
|
// vertexThinking is the thinkingConfig a request asks Vertex AI for, which
|
|
// turns away what a model can't do. Gemini 3 is sent its level, fitted to
|
|
// the model's own by vertexEffort, with no thoughts given back when the
|
|
// client turned reasoning off: the level is then the model's lowest, as
|
|
// Gemini 3 has no way to stop thinking altogether. 2.5 takes no level
|
|
// ("thinking_level is not supported by this model"): it is sent a budget
|
|
// in its own range. Turned off, Flash and Flash-Lite are sent 0, without
|
|
// thoughts asked for ("include_thoughts is only enabled when thinking is
|
|
// enabled"), and Pro, which can't stop ("does not support setting
|
|
// thinking_budget to 0"), its least. A Gemini before 2.5 doesn't think.
|
|
func vertexThinking(r *Request, model string) map[string]any {
|
|
m := strings.ToLower(model)
|
|
if strings.HasPrefix(m, "gemini-1") || strings.HasPrefix(m, "gemini-2.0") {
|
|
return nil
|
|
}
|
|
if r.Effort == "" && !r.Thinking && !r.ThinkOff {
|
|
return nil
|
|
}
|
|
if off, least, most, ok := vertexBudgets(m); ok {
|
|
if r.ThinkOff {
|
|
return map[string]any{"thinkingBudget": off}
|
|
}
|
|
tc := map[string]any{"includeThoughts": true}
|
|
if r.Effort != "" {
|
|
tc["thinkingBudget"] = min(max(budgetOf(r.Effort), least), most)
|
|
}
|
|
return tc
|
|
}
|
|
tc := map[string]any{"includeThoughts": !r.ThinkOff}
|
|
if r.Effort != "" {
|
|
tc["thinkingLevel"] = r.Effort
|
|
}
|
|
return tc
|
|
}
|
|
|
|
// vertexBudgets are the thinking budgets a Gemini 2.5 takes, as Google's
|
|
// model reference gives them: the one that turns its thinking off, or its
|
|
// least where it can't be, and its range. Not 2.5: false.
|
|
func vertexBudgets(model string) (off, least, most int, ok bool) {
|
|
switch {
|
|
case strings.HasPrefix(model, "gemini-2.5-pro"):
|
|
return 128, 128, 32768, true
|
|
case strings.HasPrefix(model, "gemini-2.5-flash-lite"):
|
|
return 0, 512, 24576, true
|
|
case strings.HasPrefix(model, "gemini-2.5-flash"):
|
|
return 0, 1, 24576, true
|
|
}
|
|
return 0, 0, 0, false
|
|
}
|
|
|
|
// vertexEffort is req at the level it goes to Vertex AI at. Vertex AI turns
|
|
// away a level the model doesn't have (gemini-3.8-flash: 400 "Thinking
|
|
// level is unsupported: THINKING_LEVEL_MINIMAL"; every Gemini 3 for xhigh),
|
|
// so the effort is the model's nearest of its own, and reasoning turned off
|
|
// is its lowest. A model whose levels aren't known is asked for no less
|
|
// than low and no more than high, which every Gemini 3 takes there.
|
|
func vertexEffort(req *Request, levels []string) *Request {
|
|
e := req.Effort
|
|
if req.ThinkOff {
|
|
e = "minimal"
|
|
}
|
|
if e == "" {
|
|
return req
|
|
}
|
|
if len(levels) > 0 {
|
|
e = fitEffort(e, levels)
|
|
} else if at := slices.Index(effortRank, e); at < slices.Index(effortRank, "low") {
|
|
e = "low"
|
|
} else if at > slices.Index(effortRank, "high") {
|
|
e = "high"
|
|
}
|
|
if e == req.Effort {
|
|
return req
|
|
}
|
|
r := *req
|
|
r.Effort = e
|
|
return &r
|
|
}
|
|
|
|
// vertexSignatureRefused is Vertex AI turning a call's thought signature
|
|
// away as one it didn't give: "Invalid thought signature.".
|
|
var vertexSignatureRefused = regexp.MustCompile(`(?i)invalid thought signature`)
|
|
|
|
// withoutSignatures is req with no thought signature on its calls, each of
|
|
// which then goes to Vertex AI waved through (skipSignature); false when it
|
|
// had none.
|
|
func withoutSignatures(req *Request) (*Request, bool) {
|
|
had := false
|
|
msgs := slices.Clone(req.Messages)
|
|
for i, m := range msgs {
|
|
if !slices.ContainsFunc(m.Parts, func(p Part) bool { return p.Kind == ToolCall && p.Signature != "" }) {
|
|
continue
|
|
}
|
|
parts := slices.Clone(m.Parts)
|
|
for j := range parts {
|
|
if parts[j].Kind == ToolCall {
|
|
parts[j].Signature = ""
|
|
}
|
|
}
|
|
msgs[i].Parts, had = parts, true
|
|
}
|
|
if !had {
|
|
return req, false
|
|
}
|
|
r := *req
|
|
r.Messages = msgs
|
|
return &r, true
|
|
}
|