vertex: Claude models on Anthropic's Messages API at the project
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.
This commit is contained in:
+14
-3
@@ -923,7 +923,7 @@ so magpie gives each location the models it answered with on 2026-10-06
|
||||
|
||||
| Location | Models |
|
||||
| --- | --- |
|
||||
| `global` | `gemini-3.8-flash`, `gemini-3.7-flash`, `gemini-3.6-flash`, `gemini-3.5-flash`, `gemini-3.5-flash-lite`, `gemini-4-argon`, `gemini-3.1-pro-preview`, `gemini-3.1-pro-preview-customtools`, `gemini-3.1-flash-lite`, `gemini-3-flash-preview`, `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-2.5-flash-lite`, `deepseek-ai/deepseek-v4.1-flash-maas`, `zai-org/glm-5.2-maas`, `openai/gpt-oss-120b-maas` |
|
||||
| `global` | `gemini-3.8-flash`, `gemini-3.7-flash`, `gemini-3.6-flash`, `gemini-3.5-flash`, `gemini-3.5-flash-lite`, `gemini-4-argon`, `gemini-3.1-pro-preview`, `gemini-3.1-pro-preview-customtools`, `gemini-3.1-flash-lite`, `gemini-3-flash-preview`, `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-2.5-flash-lite`, `deepseek-ai/deepseek-v4.1-flash-maas`, `zai-org/glm-5.2-maas`, `openai/gpt-oss-120b-maas`, `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-haiku-5-5`, `claude-fable-5-1` |
|
||||
| `us`, `eu` | `gemini-3.8-flash`, `gemini-3.7-flash`, `gemini-3.6-flash`, `gemini-3.5-flash`, `gemini-3.5-flash-lite`, `gemini-3.1-flash-lite` |
|
||||
| A region | `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-2.5-flash-lite` |
|
||||
|
||||
@@ -955,8 +955,19 @@ magpie provider models google-vertex gemini-3.8-flash deepseek-ai/deepseek-v4.1-
|
||||
Turn each partner model on for the project in Model Garden first: until then
|
||||
Google refuses it. `magpie provider test google-vertex` tests Gemini, and a
|
||||
partner model is tested on its own (right-click it in the app, or
|
||||
`magpie provider test google-vertex <model>`). Claude on Vertex AI isn't
|
||||
served: it takes a request of its own (`rawPredict`), not chat completions.
|
||||
`magpie provider test google-vertex <model>`).
|
||||
|
||||
Anthropic's Claude is served too, with nothing more to set: a model whose id
|
||||
starts with `claude-` is asked on Anthropic's Messages API in your project
|
||||
(`…/locations/<location>/publishers/anthropic/models/<model>:streamRawPredict`,
|
||||
`:rawPredict` for one answer whole, `count-tokens:rawPredict` for Claude
|
||||
Code's token counts), as Claude Code asks it with `CLAUDE_CODE_USE_VERTEX`.
|
||||
Every agent can use it, whatever API it speaks. `global` lists the current
|
||||
models under the ids Claude Code gives them for Vertex AI; an older one goes
|
||||
under Vertex's id with its date, such as `claude-sonnet-4-5@20250929`, typed
|
||||
in as any model is. At another location (`us-east5`, `europe-west1`), type in
|
||||
the Claude models it serves. Turn each Claude model on in Model Garden first,
|
||||
as a partner model is, and test it on its own.
|
||||
|
||||
Google's [Priority PayGo](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/priority-paygo)
|
||||
and [Flex PayGo](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/flex-paygo)
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -35,7 +35,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| A provider with no key | A provider of the user's own saves, imports and is `Ready` with no key when it is a preset with `NoKey` or its host is on this computer or the user's own network (`keyOptional`, `ownNetwork`): localhost, a loopback, private, link-local or carrier-grade NAT (Tailscale's 100.64/10) address, or a `.local` name, read from the URL alone with no lookup. A company's keyless relay at a LAN address is taken as a local server is (iSnow_999 on X: a Codex relay at http://<LAN IP>:8080 was left out of a CC Switch import as "it has no API key"); a keyless address on the internet still needs its key. With no key it is asked as one on 127.0.0.1 is: a Responses request carries no `Authorization`. | [`provider.go`](../../internal/provider/provider.go), [`importapps.go`](../../internal/provider/importapps.go), [`import_lan_test.go`](../../internal/provider/import_lan_test.go) |
|
||||
| A key a provider | One vendor's keys saved a provider each — an app that keeps an entry a key, as CC Switch does, imported (yuluo_yx on X: "NVIDIA #001" to "#600" at one address, "Mistral #0001"…) — are folded into one provider with those keys (`FoldCopies` at start-up, `foldAdded` after `ImportFromApps`): hundreds of copies listed every model hundreds of times in every agent's picker and found group, and 3,000 made `/api/state` 86 MB. At start-up only copies by name are folded: a base name and that name with a number after it (`copyBase`: " #12", or `freeName`'s " 2"), one at least numbered; an import folds what it added whatever their names. Either way they must be alike in all but their key (`foldShape`: the provider with its id, name, keys and on/off left out), what the settings say of their models (`modelPrefs`) and where they are named (`foldRefs`: Visible, the agents' picked, hidden and ordered models, the groups, the providers falling back to them), so one key shown to one agent and another to another stays apart. Not folded: a subscription's, a hidden one, one without a key, Vertex, one with a StepFun sign-in of its own. The first on, in the providers' order, takes the rest in; its name becomes the base and its key is named its old name. Each other is a key in order, named its name, off if it was off (all off: the provider is off, its keys on); its id goes in `Was`, so its calls count with the provider by their key (`ProviderKeyID` is the key's fingerprint, unchanged) and a model picked by the old id still reaches it. Group members, rules, weights and fallbacks naming them name the provider once; their per-model settings and fetched lists go; balance and window history kept by their id moves to their key's name (`foldHistories`). A providers.json that doesn't parse is left alone. It runs at every start and writes nothing when there is nothing to fold. `TestFoldCopies`, `TestFoldCopiesIntoOneOn`, `TestFoldCopiesUnreadable`, `TestImportFoldsAKeyAnEntry`. | [`fold.go`](../../internal/provider/fold.go), [`importapps.go`](../../internal/provider/importapps.go), [`main.go`](../../internal/cli/main.go) |
|
||||
| A key's plan | A vendor whose plans take keys of their own (`PresetDef.KeyPlans`: zhipu, zai, stepfun, stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud, volcengine, siliconflow) lets each key say which of the preset's Regions it is for (`KeyAccount.Plan`, `Provider.KeyPlan` for the first; yckonnnn on X: a Volcengine pay-as-you-go key and an Agent Plan key in one provider). No plan, or the provider's own, is the provider's plan, as every key was before, and is stored as none (`SetKeyPlan`, the GUI's `keys/plan`). `WithKey` moves a key's copy to its plan's endpoints (`atKeyPlan`: chat, Responses, Anthropic, decide, key page, docs and catalog; a provider at a host of its own, a mirror or a test's fake vendor, keeps that host) and marks it a key's view (`keyView`), so nothing judges plans on it again. Only when the keys in use are on more than one plan (`PlansMixed`) does anything differ: the model list is each key's plan's (`fetch` goes to `fetchPerKey`; a plan with no list of its own, `planOnly`, is its preset list without a request, so Ark's Coding and Agent Plans ask nothing while pay as you go asks `/api/v3/models` with its own key); plan media (`planMedia`) are every plan's; each key serves its plan's models alone (`PlanServing`, read by the gateway's `perKeyBarred`; a model set for the key in `AccountModels` it serves); plan windows (`PlanQuotas`), Volcengine's and Tencent Cloud's access-key windows (`planViews`) and balances (`balance.go`) are read at each key's plan. Volcengine's keys carry nothing that says their plan, so none is guessed; Xiaomi's `tp-`, Tencent's `sk-tp-`, MiniMax's `sk-cp-` and Bailian's `sk-sp-` prefixes are documented in code but not used to set a plan. The editor's key row has a plan chip (`planPicker`, the app's own menu) while the provider has several keys or the key has a plan. Not done: a gateway key held to some keys of a mixed provider's video (`videoAsker`) may pick another key's plan; a mixed provider whose own plan has no balance source while a key's plan has is not read; StepFun's plan windows are a sign-in per site, unchanged. `TestKeyPlanEndpoints`, `TestKeyPlanServing`, `TestKeyPlanOldConfigsUnchanged`, `TestSetKeyPlan`, `TestKeyPlanModelList`, `TestKeyPlanViews`, `key-plan.test.cjs`. | [`key_plans.go`](../../internal/provider/key_plans.go), [`keys.go`](../../internal/provider/keys.go), [`models.go`](../../internal/provider/models.go) |
|
||||
| Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https://<host>/v1/projects/<project>/locations/<location>`, its host following the location (`vertexHost`). It speaks chat completions and Gemini (`Speaks`, `Base`), each model one of them (`ListedAPIs`, which `ModelAPI` can't change for it): a Gemini model on generateContent at that address, and a partner model (`VertexPartner`: a `publisher/model` id, as every one models.dev lists for `google-vertex` has, such as `deepseek-ai/deepseek-v4.1-flash-maas`) on Google's OpenAI-compatible chat completions at `<address>/endpoints/openapi`. The provider's test asks Gemini alone, since a partner model answers only after the project turns it on in Model Garden. Each partner model has its own test (`TestModel`, `TestVertexPartnerModels`), and a test as Codex is refused as it is for Claude Code. It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider <id>` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) |
|
||||
| Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https://<host>/v1/projects/<project>/locations/<location>`, its host following the location (`vertexHost`). It speaks chat completions, Anthropic's Messages API and Gemini (`Speaks`, `Base`), each model one of them (`ListedAPIs`, which `ModelAPI` can't change for it): a Gemini model on generateContent at that address, a partner model (`VertexPartner`: a `publisher/model` id, as every one models.dev lists for `google-vertex` has, such as `deepseek-ai/deepseek-v4.1-flash-maas`) on Google's OpenAI-compatible chat completions at `<address>/endpoints/openapi`, and Claude (`VertexClaude`: an id starting `claude-` with no publisher, `claude-opus-5-5` or Vertex's dated `claude-sonnet-4-5@20250929`) on the Messages API at that address, each request at its model's own path (`VertexClaudeRequest`: `/publishers/anthropic/models/<model>:streamRawPredict` or `:rawPredict`, `count-tokens:rawPredict` for a count, `anthropic_version` `vertex-2023-10-16` in the body), as Anthropic's Vertex SDK in Claude Code asks it. The preset lists the current Claude models at `global` under the ids Claude Code gives them for Vertex. The provider's test asks Gemini alone, since a partner model or Claude answers only after the project turns it on in Model Garden. Each such model has its own test (`TestModel`, `TestVertexPartnerModels`, `TestVertexClaudeModels`), and a test as Codex is refused as it is for Claude Code. It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider <id>` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) |
|
||||
| Vertex AI tokens | `vertexCredentialsFile` finds the credentials as Google's libraries find Application Default Credentials: the provider's `credentials`, else the file `GOOGLE_APPLICATION_CREDENTIALS` names, else `application_default_credentials.json` in gcloud's folder (`CLOUDSDK_CONFIG`, else `~/.config/gcloud`, `%APPDATA%\gcloud` on Windows); a `~/` that starts any of them is the home. `mint` reads three kinds: `authorized_user` (a refresh-token grant), `service_account` (an RS256 JWT, RFC 7523: `signed`) and gcloud's `impersonated_service_account`, whose `source_credentials` are minted and traded at IAM Credentials, along its `delegates`, for the account its `service_account_impersonation_url` names (`impersonationURL`: the token never goes to that URL's host). With `impersonate` set, the token those give is traded at IAM Credentials' `generateAccessToken` for a `cloud-platform` token of that account's, as gcloud's `--impersonate-service-account` does (`impersonateFor`); the credentials' account needs `roles/iam.serviceAccountTokenCreator` on it, which the 403 names. `vertexTokens` keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (`mints`, `failed`). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within `vertexRefreshLead` (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets `vertexMintWait` (30 seconds). The file is only read. | [`vertex.go`](../../internal/provider/vertex.go), [`signin.go`](../../internal/provider/signin.go) |
|
||||
| Amazon Bedrock Mantle | `bedrock-mantle` ("Amazon Bedrock (Mantle)", @marktoown on X) is a vendor preset beside the runtime's `bedrock`, with the same Bedrock API key and seventeen regions of its own (`mantleRegions`: the `bedrock-mantle.{region}.api.aws` hosts that answered on 2026-10-16). Chat completions and Responses are at `/v1`, Messages at `/anthropic`; unlike the runtime it lists its models (`GET /v1/models`; `NoList` stays the runtime's alone). Its OpenAI APIs serve each model under one of two prefixes: OpenAI's closed GPTs and xAI's Grok under `/openai/v1`, the rest under `/v1` (`MantleBase`, used by the gateway and the provider test's `tinyBody`). `IsBedrockMantle` is the preset or a provider added at a Mantle host (`mantleHost`), and `IsBedrock` includes it, so every Bedrock rule holds there too: Claude on Messages alone, the key as `x-api-key` alone, `max_completion_tokens`, no metadata, no Priority. A provider added at a Mantle address is given the APIs it wasn't (`mantleEndpoints`, in `normalize`), and a chat or Responses URL given at `/openai/v1` is moved to `/v1`, where the list is. | [`presets.go`](../../internal/provider/presets.go), [`provider.go`](../../internal/provider/provider.go), [`test.go`](../../internal/provider/test.go) |
|
||||
| Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) |
|
||||
|
||||
@@ -54,8 +54,8 @@ func askedBetas(in http.Header) []string {
|
||||
func betaKey(beta string) string { return "anthropic-beta\x00" + beta }
|
||||
|
||||
// betas is the list asked (header values, each maybe comma-separated),
|
||||
// fitted to what p takes: renamed and left out as Bedrock wants, without
|
||||
// those p has refused, and without repeats.
|
||||
// fitted to what p takes: renamed as Bedrock and Vertex AI want, left out
|
||||
// as Bedrock does, without those p has refused, and without repeats.
|
||||
func (s *Server) betas(p provider.Provider, asked []string) []string {
|
||||
var out []string
|
||||
for _, v := range asked {
|
||||
@@ -64,10 +64,12 @@ func (s *Server) betas(p provider.Provider, asked []string) []string {
|
||||
if b == "" {
|
||||
continue
|
||||
}
|
||||
if p.IsBedrock() {
|
||||
if p.IsBedrock() || p.IsVertex() {
|
||||
if to, ok := bedrockBetas[b]; ok {
|
||||
b = to
|
||||
}
|
||||
}
|
||||
if p.IsBedrock() {
|
||||
if slices.Contains(bedrockRefuses, b) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1511,8 +1511,9 @@ func (s *Server) countOn(w http.ResponseWriter, r *http.Request, p provider.Prov
|
||||
// fallback model: it may use a different tokenizer.
|
||||
p.Fallback = nil
|
||||
for _, c := range s.candidates(p, model, provider.Anthropic) {
|
||||
// A relay's OpenAI-only key can't count Anthropic tokens.
|
||||
if c.p.Anthropic != "" && slices.Contains(s.usable(c.p, model), provider.Anthropic) {
|
||||
// A relay's OpenAI-only key can't count Anthropic tokens;
|
||||
// Vertex AI counts Claude's at the project (Base)
|
||||
if c.p.Base(provider.Anthropic) != "" && slices.Contains(s.usable(c.p, model), provider.Anthropic) {
|
||||
counts = append(counts, c)
|
||||
}
|
||||
}
|
||||
@@ -4511,6 +4512,17 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
|
||||
// the tier it goes at, the user's own fields in it (#1784)
|
||||
noteWireTier(ctx, to, body)
|
||||
}
|
||||
if to == provider.Anthropic && p.IsVertex() {
|
||||
// Claude at the project, as Anthropic's Vertex SDK asks it: the
|
||||
// model and whether it streams in the path, anthropic_version in
|
||||
// the body; last, as the body goes out, and every route to it
|
||||
// alike (relayed, built, counted)
|
||||
at, b, ok := provider.VertexClaudeRequest(path, body)
|
||||
if !ok {
|
||||
return nil, errors.New("a request to Claude on Vertex AI names no model")
|
||||
}
|
||||
path, body = at, b
|
||||
}
|
||||
base := p.Base(to)
|
||||
if p.IsOpenCode() && p.OpenCodeFree(gjson.GetBytes(body, "model").String()) {
|
||||
// Zen's free tier answers at the inference API's URL alone (zenfree.go)
|
||||
@@ -5720,9 +5732,10 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
|
||||
r.Effort, req = e, &r
|
||||
}
|
||||
}
|
||||
if p.IsVertex() && !provider.VertexPartner(model) {
|
||||
// Gemini's levels; a partner model on chat completions is sent
|
||||
// its effort as any OpenAI-compatible vendor is
|
||||
if p.IsVertex() && !provider.VertexPartner(model) && !provider.VertexClaude(model) {
|
||||
// Gemini's levels; a partner model on chat completions, and
|
||||
// Claude on Anthropic's Messages API, are sent their effort as
|
||||
// at any vendor of that API
|
||||
req = vertexEffort(req, p.Efforts(model))
|
||||
}
|
||||
// the names in force, read once however many endpoints the request is
|
||||
|
||||
@@ -22,6 +22,17 @@ import (
|
||||
// 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.
|
||||
|
||||
@@ -2,6 +2,7 @@ package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"net/http"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -151,6 +153,32 @@ data: [DONE]
|
||||
vertexPartnerWhole = `{"id":"chatcmpl-v41","object":"chat.completion","created":1761609600,"model":"deepseek-ai/deepseek-v4.1-flash-maas","choices":[{"index":0,"message":{"role":"assistant","content":"Hello from DeepSeek"},"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":4,"total_tokens":13}}`
|
||||
)
|
||||
|
||||
// vertexClaudeStream and vertexClaudeWhole are Claude's answer on Vertex
|
||||
// AI's streamRawPredict and rawPredict: Anthropic's Messages API events
|
||||
// and message, as Anthropic's Vertex SDK reads them.
|
||||
const (
|
||||
vertexClaudeStream = `event: message_start
|
||||
data: {"type":"message_start","message":{"id":"msg_vrtx_01","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":11,"output_tokens":1}}}
|
||||
|
||||
event: content_block_start
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
||||
|
||||
event: content_block_delta
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello from Claude"}}
|
||||
|
||||
event: content_block_stop
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":4}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
|
||||
`
|
||||
vertexClaudeWhole = `{"id":"msg_vrtx_01","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[{"type":"text","text":"Hello from Claude"}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":11,"output_tokens":4}}`
|
||||
)
|
||||
|
||||
// vertexLevels are the reasoning levels models.dev gives Gemini's models.
|
||||
const vertexLevels = `{"google":{"models":{
|
||||
"gemini-3.8-flash":{"id":"gemini-3.8-flash","reasoning_options":[{"type":"effort","values":["low","medium","high"]}]},
|
||||
@@ -172,8 +200,8 @@ type vertexUp struct {
|
||||
}
|
||||
|
||||
type vertexAsked struct {
|
||||
path, query, auth string
|
||||
body map[string]any
|
||||
path, query, auth, beta string
|
||||
body map[string]any
|
||||
}
|
||||
|
||||
func (v *vertexUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -188,7 +216,7 @@ func (v *vertexUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
case strings.HasPrefix(r.URL.Path, "/v1/projects/"):
|
||||
var m map[string]any
|
||||
json.Unmarshal(b, &m)
|
||||
v.asked = append(v.asked, vertexAsked{r.URL.Path, r.URL.RawQuery, r.Header.Get("Authorization"), m})
|
||||
v.asked = append(v.asked, vertexAsked{r.URL.Path, r.URL.RawQuery, r.Header.Get("Authorization"), r.Header.Get("anthropic-beta"), m})
|
||||
code, out, kind := http.StatusOK, vertexPong, "text/event-stream"
|
||||
if strings.HasSuffix(r.URL.Path, ":generateContent") {
|
||||
out, kind = vertexColours, "application/json; charset=UTF-8"
|
||||
@@ -200,6 +228,17 @@ func (v *vertexUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
out, kind = vertexPartnerWhole, "application/json"
|
||||
}
|
||||
}
|
||||
if strings.Contains(r.URL.Path, "/publishers/anthropic/models/") {
|
||||
// Claude, on Anthropic's Messages API
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/count-tokens:rawPredict"):
|
||||
out, kind = `{"input_tokens":21}`, "application/json"
|
||||
case strings.HasSuffix(r.URL.Path, ":streamRawPredict"):
|
||||
out = vertexClaudeStream
|
||||
default:
|
||||
out, kind = vertexClaudeWhole, "application/json"
|
||||
}
|
||||
}
|
||||
if refused := vertexSigRefused(m); refused != "" {
|
||||
code, out = http.StatusBadRequest, refused
|
||||
} else if v.reply != nil {
|
||||
@@ -917,3 +956,85 @@ func TestVertexPartnerModel(t *testing.T) {
|
||||
t.Errorf("effort xhigh sent at %s as %v", a.path, a.body["reasoning_effort"])
|
||||
}
|
||||
}
|
||||
|
||||
// Claude on Vertex AI (claude-sonnet-5-5, claude-sonnet-4-5@20250929) is
|
||||
// asked on Anthropic's Messages API at the project, as Anthropic's Vertex
|
||||
// SDK asks it, from every client magpie serves (Chat, Responses,
|
||||
// Anthropic's Messages, Gemini), streamed or not, with nothing set beyond
|
||||
// the project: at publishers/anthropic/models/<model>:streamRawPredict
|
||||
// when it streams and :rawPredict when it doesn't, signed with the same
|
||||
// minted token, the model out of the body, anthropic_version
|
||||
// vertex-2023-10-16 in it, and no Gemini body or Gemini level.
|
||||
func TestVertexClaudeModel(t *testing.T) {
|
||||
v := &vertexUp{}
|
||||
s := vertexServe(t, v, vertexLevels)
|
||||
const at = "/v1/projects/proj-1/locations/global/publishers/anthropic/models/"
|
||||
for _, upstream := range []string{"claude-sonnet-5-5", "claude-sonnet-4-5@20250929"} {
|
||||
model := "google-vertex/" + upstream
|
||||
for _, c := range []struct{ name, path, body string }{
|
||||
{"chat", "/v1/chat/completions", `{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]}`},
|
||||
{"anthropic", "/v1/messages", `{"model":"` + model + `","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`},
|
||||
{"responses", "/v1/responses", `{"model":"` + model + `","input":"hi"}`},
|
||||
} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
n := v.count()
|
||||
body := strings.TrimSuffix(c.body, "}") + `,"stream":` + strconv.FormatBool(stream) + `}`
|
||||
out := vertexAsk(t, s, c.path, body)
|
||||
a := v.last(t)
|
||||
// a translated request is always asked streamed, as
|
||||
// at any vendor; the Messages API's own as it came
|
||||
want := at + upstream + ":rawPredict"
|
||||
if stream || c.name != "anthropic" {
|
||||
want = at + upstream + ":streamRawPredict"
|
||||
}
|
||||
if v.count() != n+1 || a.path != want || a.query != "" || a.auth != "Bearer ya29.vertex-test" {
|
||||
t.Errorf("%s %s stream %v: asked %d times, at %s?%s with %q", upstream, c.name, stream, v.count()-n, a.path, a.query, a.auth)
|
||||
}
|
||||
if _, has := a.body["model"]; has || a.body["anthropic_version"] != "vertex-2023-10-16" || a.body["messages"] == nil {
|
||||
t.Errorf("%s %s stream %v: body %v", upstream, c.name, stream, a.body)
|
||||
}
|
||||
if !strings.Contains(out, "Hello from Claude") {
|
||||
t.Errorf("%s %s stream %v: client given %s", upstream, c.name, stream, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// a Gemini client's request, translated
|
||||
out := vertexAsk(t, s, "/v1beta/models/google-vertex/claude-sonnet-5-5:streamGenerateContent?alt=sse", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)
|
||||
if a := v.last(t); a.path != at+"claude-sonnet-5-5:streamRawPredict" || a.body["contents"] != nil || a.body["anthropic_version"] != "vertex-2023-10-16" {
|
||||
t.Errorf("Gemini client's request asked at %s with %v", a.path, a.body)
|
||||
}
|
||||
if !strings.Contains(out, "Hello from Claude") {
|
||||
t.Errorf("Gemini client given %s", out)
|
||||
}
|
||||
// Codex's effort goes as Claude takes it, never held to Gemini's
|
||||
// levels (vertexEffort: xhigh as high, off as minimal)
|
||||
vertexAsk(t, s, "/v1/responses", `{"model":"google-vertex/claude-sonnet-5-5","reasoning":{"effort":"xhigh"},"input":"hi"}`)
|
||||
if a := v.last(t); fmt.Sprint(a.body["output_config"]) != "map[effort:xhigh]" {
|
||||
t.Errorf("effort xhigh sent as %v", a.body)
|
||||
}
|
||||
vertexAsk(t, s, "/v1/responses", `{"model":"google-vertex/claude-sonnet-5-5","reasoning":{"effort":"none"},"input":"hi"}`)
|
||||
if a := v.last(t); strings.Contains(fmt.Sprint(a.body), "minimal") || a.body["generationConfig"] != nil {
|
||||
t.Errorf("effort none sent as %v", a.body)
|
||||
}
|
||||
// Claude Code's own request: beta=true never reaches Vertex AI, and
|
||||
// tool search's beta goes under the name it gives it for Vertex
|
||||
req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader(`{"model":"google-vertex/claude-sonnet-5-5","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hi"}]}`))
|
||||
req.Header.Set("User-Agent", "claude-cli/2.1.314 (external, cli)")
|
||||
req.Header.Set("anthropic-beta", "advanced-tool-use-2025-11-20")
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
if a := v.last(t); rec.Code != http.StatusOK || a.path != at+"claude-sonnet-5-5:streamRawPredict" || a.query != "" || a.beta != "tool-search-tool-2025-10-19" {
|
||||
t.Errorf("Claude Code's request: %d, asked at %s?%s with beta %q: %s", rec.Code, a.path, a.query, a.beta, rec.Body)
|
||||
}
|
||||
// its count, at the publisher's count-tokens with the model kept
|
||||
out = vertexAsk(t, s, "/v1/messages/count_tokens?beta=true", `{"model":"google-vertex/claude-sonnet-5-5","messages":[{"role":"user","content":"hi"}]}`)
|
||||
if a := v.last(t); a.path != at+"count-tokens:rawPredict" || a.body["model"] != "claude-sonnet-5-5" || a.body["anthropic_version"] != "vertex-2023-10-16" || !strings.Contains(out, `"input_tokens":21`) {
|
||||
t.Errorf("count asked at %s with %v, gave %s", a.path, a.body, out)
|
||||
}
|
||||
// a Gemini model beside it is still asked on generateContent
|
||||
vertexAsk(t, s, "/v1/messages", `{"model":"google-vertex/gemini-3.8-flash","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if a := v.last(t); a.path != "/v1/projects/proj-1/locations/global/publishers/google/models/gemini-3.8-flash:streamGenerateContent" || a.body["contents"] == nil {
|
||||
t.Errorf("Gemini asked at %s", a.path)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,12 +159,16 @@ func (p Provider) ListedAPIs(model string) []Protocol {
|
||||
return apis
|
||||
}
|
||||
}
|
||||
// Vertex AI serves Gemini on generateContent, and its partner models
|
||||
// (publisher/model) on chat completions alone
|
||||
// Vertex AI serves Gemini on generateContent, its partner models
|
||||
// (publisher/model) on chat completions alone, and Claude on
|
||||
// Anthropic's Messages API alone
|
||||
if p.IsVertex() {
|
||||
if VertexPartner(model) {
|
||||
return []Protocol{Chat}
|
||||
}
|
||||
if VertexClaude(model) {
|
||||
return []Protocol{Anthropic}
|
||||
}
|
||||
return []Protocol{Gemini}
|
||||
}
|
||||
// Factory serves each model on the one API droid sends it on
|
||||
|
||||
@@ -177,9 +177,11 @@ var presets = []PresetDef{
|
||||
// rather than a key; and its partner models (publisher/model ids,
|
||||
// VertexPartner) on Google's OpenAI-compatible chat completions there,
|
||||
// the live ones Google's docs list at global on 2026-10-28 (Gemma 4,
|
||||
// Experimental, is left to be typed in). It has no list to ask that
|
||||
// says which models a location serves, so they are given: these,
|
||||
// every one global serves;
|
||||
// Experimental, is left to be typed in); and Anthropic's Claude
|
||||
// (VertexClaude) on its Messages API there, the current ones under the
|
||||
// ids Claude Code asks Vertex AI for (an older one, claude-…@date, is
|
||||
// typed in). It has no list to ask that says which models a location
|
||||
// serves, so they are given: these, every one global serves;
|
||||
// vertexModels has the others'. Its Priority PayGo and Flex PayGo are
|
||||
// asked for with the two headers.
|
||||
{ID: VertexPreset, Name: "Google Vertex AI", Short: "Vertex AI", Icon: "vertexai-color", Kind: KindVendor,
|
||||
@@ -189,7 +191,8 @@ var presets = []PresetDef{
|
||||
Models: []string{"gemini-3.8-flash", "gemini-3.7-flash", "gemini-3.6-flash", "gemini-3.5-flash", "gemini-3.5-flash-lite",
|
||||
"gemini-4-argon", "gemini-3.1-pro-preview", "gemini-3.1-pro-preview-customtools", "gemini-3.1-flash-lite", "gemini-3-flash-preview",
|
||||
"gemini-2.5-pro", "gemini-2.5-flash", "gemini-2.5-flash-lite",
|
||||
"deepseek-ai/deepseek-v4.1-flash-maas", "zai-org/glm-5.2-maas", "openai/gpt-oss-120b-maas"},
|
||||
"deepseek-ai/deepseek-v4.1-flash-maas", "zai-org/glm-5.2-maas", "openai/gpt-oss-120b-maas",
|
||||
"claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-1"},
|
||||
HeaderHints: []string{"X-Vertex-AI-LLM-Request-Type", "X-Vertex-AI-LLM-Shared-Request-Type"}},
|
||||
{ID: "deepseek", Name: "DeepSeek", Icon: "deepseek-color", Kind: KindVendor, Catalog: "deepseek",
|
||||
Chat: "https://api.deepseek.com/v1", Responses: "https://api.deepseek.com/v1", Anthropic: "https://api.deepseek.com/anthropic",
|
||||
|
||||
@@ -1592,6 +1592,11 @@ func (p Provider) Base(proto Protocol) string {
|
||||
case Responses:
|
||||
return p.Responses
|
||||
case Anthropic:
|
||||
// Vertex AI's Claude models, on Anthropic's Messages API at the
|
||||
// project, each at a path of its own (VertexClaudeRequest)
|
||||
if p.IsVertex() {
|
||||
return p.vertexBase()
|
||||
}
|
||||
return p.Anthropic
|
||||
case CodeAssist:
|
||||
if p.Account != nil {
|
||||
@@ -1631,8 +1636,9 @@ func (p Provider) Speaks() []Protocol {
|
||||
// list stays on the other three (factoryAPIs); this is not one of them.
|
||||
// A custom provider's Gemini API comes after the others it has.
|
||||
// Vertex AI's Gemini models, on generateContent at its project, after
|
||||
// the chat completions its partner models are served on (ListedAPIs
|
||||
// gives each model its one).
|
||||
// the chat completions its partner models are served on and the
|
||||
// Messages API its Claude models are (ListedAPIs gives each model its
|
||||
// one).
|
||||
if p.IsVertex() {
|
||||
if p.vertexBase() != "" {
|
||||
out = append(out, Gemini)
|
||||
|
||||
@@ -71,10 +71,10 @@ func (p Provider) Test(ctx context.Context) []Result {
|
||||
}
|
||||
var out []Result
|
||||
for _, proto := range p.Speaks() {
|
||||
if p.IsVertex() && proto == Chat {
|
||||
// a partner model answers only once the project has turned it
|
||||
// on in Model Garden: the provider is tested on Gemini, and a
|
||||
// partner model by its own test (TestModel)
|
||||
if p.IsVertex() && (proto == Chat || proto == Anthropic) {
|
||||
// a partner model, and Claude, answer only once the project
|
||||
// has turned them on in Model Garden: the provider is tested
|
||||
// on Gemini, and such a model by its own test (TestModel)
|
||||
continue
|
||||
}
|
||||
q, ok := p.keyFor(proto)
|
||||
@@ -207,6 +207,12 @@ func tinyBody(q Provider, proto Protocol, model string) (url, body string) {
|
||||
case Responses:
|
||||
return q.mantleBase(q.Responses, model) + "/responses", fmt.Sprintf(`{"model":%q,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}],"max_output_tokens":16}`, model)
|
||||
case Anthropic:
|
||||
if q.IsVertex() {
|
||||
// Claude at the project, as Anthropic's Vertex SDK asks it
|
||||
// (VertexClaudeRequest)
|
||||
at, b, _ := VertexClaudeRequest("/v1/messages", fmt.Appendf(nil, `{"model":%q,"max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`, model))
|
||||
return q.Base(Anthropic) + at, string(b)
|
||||
}
|
||||
return q.Anthropic + "/v1/messages", fmt.Sprintf(`{"model":%q,"max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`, model)
|
||||
case Gemini:
|
||||
if q.IsVertex() {
|
||||
|
||||
@@ -183,6 +183,77 @@ func VertexPath(model string) string {
|
||||
// id on generateContent has one, so the slash is what tells them apart.
|
||||
func VertexPartner(model string) bool { return strings.Contains(model, "/") }
|
||||
|
||||
// VertexClaude is whether model is one of Anthropic's Claude models on
|
||||
// Vertex AI (claude-opus-5-5, claude-sonnet-4-5@20250929), which Google
|
||||
// serves on Anthropic's own Messages API at the project, under the
|
||||
// anthropic publisher (VertexClaudeRequest), not on generateContent or
|
||||
// chat completions. The id alone says so, as the slash says a partner
|
||||
// model's: no Gemini id starts so, and Claude's ids have no publisher
|
||||
// before a slash.
|
||||
func VertexClaude(model string) bool {
|
||||
return !VertexPartner(model) && strings.HasPrefix(strings.ToLower(model), "claude-")
|
||||
}
|
||||
|
||||
// vertexAnthropicVersion is the Messages API's version a Claude request
|
||||
// on Vertex AI names in its body, where Anthropic's own takes the
|
||||
// anthropic-version header; Anthropic's Vertex SDK puts it there when the
|
||||
// body has none.
|
||||
const vertexAnthropicVersion = "vertex-2023-10-16"
|
||||
|
||||
// VertexClaudeRequest is where at a Vertex AI provider (under its
|
||||
// Base(Anthropic)), and with what body, a request made for Anthropic's
|
||||
// Messages API at path (/v1/messages, its count_tokens, with or without
|
||||
// ?beta=true) goes, as Anthropic's Vertex SDK asks it: a message at
|
||||
// /publishers/anthropic/models/<model>:streamRawPredict when it streams,
|
||||
// :rawPredict when it doesn't, the model taken out of the body since the
|
||||
// path names it; a count at the publisher's count-tokens:rawPredict, the
|
||||
// model kept in the body. Either body names anthropic_version
|
||||
// (vertex-2023-10-16) unless it has one. ok is false for a body with no
|
||||
// model, which has no path.
|
||||
func VertexClaudeRequest(path string, body []byte) (string, []byte, bool) {
|
||||
var m map[string]json.RawMessage
|
||||
if json.Unmarshal(body, &m) != nil {
|
||||
return "", body, false
|
||||
}
|
||||
var model string
|
||||
if json.Unmarshal(m["model"], &model) != nil || model == "" {
|
||||
return "", body, false
|
||||
}
|
||||
if _, has := m["anthropic_version"]; !has {
|
||||
m["anthropic_version"] = json.RawMessage(`"` + vertexAnthropicVersion + `"`)
|
||||
}
|
||||
at := "/publishers/anthropic/models/"
|
||||
if p, _, _ := strings.Cut(path, "?"); strings.HasSuffix(p, "/count_tokens") {
|
||||
at += "count-tokens:rawPredict"
|
||||
} else {
|
||||
var stream bool
|
||||
_ = json.Unmarshal(m["stream"], &stream)
|
||||
verb := ":rawPredict"
|
||||
if stream {
|
||||
verb = ":streamRawPredict"
|
||||
}
|
||||
at += url.PathEscape(model) + verb
|
||||
delete(m, "model")
|
||||
}
|
||||
out, err := marshalRaw(m)
|
||||
if err != nil {
|
||||
return "", body, false
|
||||
}
|
||||
return at, out, true
|
||||
}
|
||||
|
||||
// marshalRaw is m as JSON, its values byte for byte as they came (no
|
||||
// HTML escaping of a value's <, > and &).
|
||||
func marshalRaw(m map[string]json.RawMessage) ([]byte, error) {
|
||||
var b strings.Builder
|
||||
enc := json.NewEncoder(&b)
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []byte(strings.TrimSuffix(b.String(), "\n")), nil
|
||||
}
|
||||
|
||||
// VertexWholePath is where a request for model answered as one JSON body
|
||||
// goes.
|
||||
func VertexWholePath(model string) string {
|
||||
|
||||
@@ -177,6 +177,9 @@ func (f *vertexGoogle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
case vertex && strings.Contains(r.URL.Path, "/models/gemini-9-pro:"):
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
io.WriteString(w, "{\"error\":{\"code\":404,\"message\":\"Publisher Model `projects/acme-vertex/locations/global/publishers/google/models/gemini-9-pro` was not found or your project does not have access to it. Please ensure you are using a valid model version. For more information, see: https://cloud.google.com/vertex-ai/generative-ai/docs/learn/model-versions\",\"status\":\"NOT_FOUND\"}}")
|
||||
case vertex && strings.HasSuffix(r.URL.Path, ":rawPredict") && strings.Contains(r.URL.Path, "/publishers/anthropic/models/"):
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"id":"msg_vrtx_1","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[{"type":"text","text":"Hi"}],"stop_reason":"max_tokens","usage":{"input_tokens":8,"output_tokens":1}}`)
|
||||
case vertex && strings.HasSuffix(r.URL.Path, "/endpoints/openapi/chat/completions"):
|
||||
// a partner model, on Google's OpenAI-compatible chat completions,
|
||||
// answered as its docs show
|
||||
@@ -506,7 +509,7 @@ func TestVertexProviderListed(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := "https://aiplatform.googleapis.com/v1/projects/acme-vertex/locations/global"
|
||||
if !p.Ready() || !p.On() || !slices.Equal(p.Speaks(), []Protocol{Chat, Gemini}) || p.Base(Gemini) != base || p.Base(Chat) != base+"/endpoints/openapi" {
|
||||
if !p.Ready() || !p.On() || !slices.Equal(p.Speaks(), []Protocol{Chat, Anthropic, Gemini}) || p.Base(Gemini) != base || p.Base(Chat) != base+"/endpoints/openapi" || p.Base(Anthropic) != base {
|
||||
t.Fatalf("ready %v, on %v, speaks %v at %q", p.Ready(), p.On(), p.Speaks(), p.Base(Gemini))
|
||||
}
|
||||
if !customIDs()["vertex-prod"] || PluginID("vertex-prod") != "vertex-prod-plugin" {
|
||||
@@ -1583,7 +1586,7 @@ func TestVertexPartnerModels(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := f.url + "/vertex/v1/projects/acme-vertex/locations/global"
|
||||
if !slices.Equal(p.Speaks(), []Protocol{Chat, Gemini}) || p.Base(Chat) != base+"/endpoints/openapi" || p.Base(Gemini) != base {
|
||||
if !slices.Equal(p.Speaks(), []Protocol{Chat, Anthropic, Gemini}) || p.Base(Chat) != base+"/endpoints/openapi" || p.Base(Gemini) != base {
|
||||
t.Fatalf("speaks %v, chat at %q, Gemini at %q", p.Speaks(), p.Base(Chat), p.Base(Gemini))
|
||||
}
|
||||
partners := []string{"deepseek-ai/deepseek-v4.1-flash-maas", "zai-org/glm-5.2-maas", "openai/gpt-oss-120b-maas"}
|
||||
@@ -1651,3 +1654,98 @@ func TestVertexPartnerModels(t *testing.T) {
|
||||
t.Errorf("chat completions asked %d times, want 1", chats)
|
||||
}
|
||||
}
|
||||
|
||||
// Vertex AI's Claude models are served on Anthropic's Messages API at the
|
||||
// project, under the anthropic publisher, signed with the same Google
|
||||
// token as Gemini and with nothing more set by the user: global lists the
|
||||
// current ones, the id alone puts a model on that API (one typed in with
|
||||
// Vertex's @date too), and its test is asked as Anthropic's Vertex SDK
|
||||
// asks: :rawPredict at the model's path, the model out of the body and
|
||||
// anthropic_version vertex-2023-10-16 in it. The provider's own test
|
||||
// still asks Gemini alone, as Claude answers only once the project turned
|
||||
// it on in Model Garden.
|
||||
func TestVertexClaudeModels(t *testing.T) {
|
||||
vertexHome(t)
|
||||
f := newVertexGoogle(t)
|
||||
file := filepath.Join(t.TempDir(), "application_default_credentials.json")
|
||||
writeFile(t, file, vertexUser("1//0g-test-refresh"))
|
||||
if err := Save(vertexAt("global", file)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := Find("vertex-prod")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := f.url + "/vertex/v1/projects/acme-vertex/locations/global"
|
||||
if p.Base(Anthropic) != base {
|
||||
t.Fatalf("Claude at %q, want %q", p.Base(Anthropic), base)
|
||||
}
|
||||
listed := modelIDs(p.Available())
|
||||
for _, m := range []string{"claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-1"} {
|
||||
if !slices.Contains(listed, m) {
|
||||
t.Errorf("%s not listed at global: %v", m, listed)
|
||||
}
|
||||
}
|
||||
for _, m := range []string{"claude-sonnet-5-5", "claude-sonnet-4-5@20250929", "Claude-Opus-4-1@20250805"} {
|
||||
if apis := p.APIs(m); !slices.Equal(apis, []Protocol{Anthropic}) {
|
||||
t.Errorf("%s asked on %v", m, apis)
|
||||
}
|
||||
}
|
||||
for _, m := range []string{"gemini-3.8-flash", "anthropic/claude-x"} {
|
||||
if apis := p.APIs(m); slices.Contains(apis, Anthropic) {
|
||||
t.Errorf("%s asked on %v", m, apis)
|
||||
}
|
||||
}
|
||||
rs := p.Test(context.Background())
|
||||
if len(rs) != 1 || !rs[0].OK || rs[0].Protocol != Gemini {
|
||||
t.Fatalf("provider test: %+v", rs)
|
||||
}
|
||||
rs = p.TestModels(context.Background(), []string{"claude-sonnet-4-5@20250929"})
|
||||
if len(rs) != 1 || !rs[0].OK || rs[0].Protocol != Anthropic {
|
||||
t.Fatalf("Claude's test: %+v", rs)
|
||||
}
|
||||
calls := f.vertexCalls()
|
||||
if len(calls) != 2 {
|
||||
t.Fatalf("Vertex AI was asked %d times, want 2: %+v", len(calls), calls)
|
||||
}
|
||||
c := calls[1]
|
||||
var body map[string]any
|
||||
json.Unmarshal([]byte(c.body), &body)
|
||||
if c.path != "/vertex/v1/projects/acme-vertex/locations/global/publishers/anthropic/models/claude-sonnet-4-5@20250929:rawPredict" ||
|
||||
c.header.Get("Authorization") != "Bearer ya29.minted-1" {
|
||||
t.Errorf("Claude asked at %s with %q", c.path, c.header.Get("Authorization"))
|
||||
}
|
||||
if _, has := body["model"]; has || body["anthropic_version"] != "vertex-2023-10-16" || body["max_tokens"] != float64(16) {
|
||||
t.Errorf("Claude asked with %s", c.body)
|
||||
}
|
||||
}
|
||||
|
||||
// A request made for Anthropic's Messages API goes to Vertex AI as
|
||||
// Anthropic's Vertex SDK sends it: streamed at :streamRawPredict, whole at
|
||||
// :rawPredict, beta=true dropped, the model out of the body; a count at
|
||||
// count-tokens:rawPredict with the model kept; anthropic_version added
|
||||
// unless the body has one, and the rest of the body as it came.
|
||||
func TestVertexClaudeRequest(t *testing.T) {
|
||||
for _, c := range []struct{ path, body, at, want string }{
|
||||
{"/v1/messages", `{"model":"claude-opus-5-5","max_tokens":5,"stream":true,"messages":[{"role":"user","content":"<a> & b"}]}`,
|
||||
"/publishers/anthropic/models/claude-opus-5-5:streamRawPredict",
|
||||
`{"anthropic_version":"vertex-2023-10-16","max_tokens":5,"messages":[{"role":"user","content":"<a> & b"}],"stream":true}`},
|
||||
{"/v1/messages?beta=true", `{"model":"claude-sonnet-4-5@20250929","max_tokens":5,"stream":false}`,
|
||||
"/publishers/anthropic/models/claude-sonnet-4-5@20250929:rawPredict",
|
||||
`{"anthropic_version":"vertex-2023-10-16","max_tokens":5,"stream":false}`},
|
||||
{"/v1/messages", `{"model":"claude-haiku-5-5","anthropic_version":"vertex-2099-01-01"}`,
|
||||
"/publishers/anthropic/models/claude-haiku-5-5:rawPredict",
|
||||
`{"anthropic_version":"vertex-2099-01-01"}`},
|
||||
{"/v1/messages/count_tokens?beta=true", `{"model":"claude-opus-5-5","messages":[]}`,
|
||||
"/publishers/anthropic/models/count-tokens:rawPredict",
|
||||
`{"anthropic_version":"vertex-2023-10-16","messages":[],"model":"claude-opus-5-5"}`},
|
||||
} {
|
||||
at, b, ok := VertexClaudeRequest(c.path, []byte(c.body))
|
||||
if !ok || at != c.at || string(b) != c.want {
|
||||
t.Errorf("%s %s: %v %s %s", c.path, c.body, ok, at, b)
|
||||
}
|
||||
}
|
||||
if _, _, ok := VertexClaudeRequest("/v1/messages", []byte(`{"max_tokens":5}`)); ok {
|
||||
t.Error("a body with no model was given a path")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user