plugins: a model served on more APIs keeps the client's (gaubeebangeel on X)
gaubeebangeel on X: OpenDesign's Anthropic requests to an Open Design Cloud account were all sent upstream as chat completions. The Open Design plugin declares each model on one AI SDK package (chat completions for most, Responses for deepseek-v4-pro and claude-haiku-5.5, plugins#141), and pluginAPIs gave a plugin model that one API alone, so attempt never relayed a /v1/messages request and translated it, though amr-link serves every model on all three (plugins#888). A DeepSeek API-key provider, the case first suspected, relays to /anthropic/v1/messages as sent: tried with OpenCode's, node's and no User-Agent, bare and prefixed ids, and web search. A plugin model can now list the other APIs its vendor serves it on, as their AI SDK packages (m.also; plugin.Model.Also through host.js, config model and models hook). pluginProtocols gives the model's own API first, then those; ListedAPIs, the catalog's APIs and the provider's bases come from it, so a client's request on any of them is relayed as sent. usable puts a plugin model's own API first, so a request on an API it isn't served on is still translated to the declared one. A model with no also is unchanged. opendesign 0.1.13 (plugins 397da020) sets also on every model. Test: TestPluginModelServedOnMoreAPIsKeepsTheClientAPI (fake plugin, FAKE_ALSO): Anthropic, Responses and Chat requests to the also model reach the upstream on their own path; fake-1 (no also) is still translated to /chat/completions. Red on HEAD's plugins.go: Anthropic and Responses reached /v1/chat/completions, ListedAPIs and usable were [chat]. Run (mote unless said): go test ./internal/provider ./internal/plugin ./internal/catalog ok; go test ./internal/gateway ok (972s); GOOS=linux/windows go vet of the three packages ok; gofmt clean. Not run: the full ./... suite (mote and mica each had full suites queued under suite.lock); not tried against a real amr-link account (keyblues's plugins#888 measurements are the evidence it serves /v1/messages for every model).
This commit is contained in:
@@ -118,6 +118,8 @@ A plugin's model on Gemini's API (`@ai-sdk/google`, so `Provider.APIs` is Code A
|
||||
|
||||
A request `pluginFetch` sends goes under the loader's `baseURL`, else the model's own `api.url`, the provider's `api`, its npm's default (`pluginRequestBase` in [`plugins.go`](../../internal/provider/plugins.go)); magpie's `/v1` is taken off the path, as the AI SDK's base ends where magpie's `/v1` does. The loader's base is one for all the provider's models, so an Anthropic model whose own URL ends in `/v1` goes under the loader's base + `/v1` when that base doesn't end in it: Copilot's loader says `https://api.githubcopilot.com` (or its enterprise host), its Claude models are on `/v1/messages` (models.dev's `api.url`, and OpenCode's own Copilot provider adds `/v1` for them), and sent to `/messages` they were answered 404 (cyoking1 on X). A model whose own URL has no `/v1` (Kiro's) and a base that ends in it go as before. `TestPluginAnthropicBaseKeepsV1`.
|
||||
|
||||
A plugin model is spoken to on the API of its AI SDK package (`pluginProtocol`: `@ai-sdk/anthropic` is Anthropic's messages, `@ai-sdk/openai` Responses, `@ai-sdk/google` Code Assist, anything else chat completions). A plugin whose vendor serves a model on other APIs too lists their packages on the model as `also` (an array, on the config model or the models hook's; the host passes it as `plugin.Model.Also`). `pluginProtocols` gives the model's own API first and then those, which is what `ListedAPIs` (`pluginAPIs`), the catalog's `APIs` and the provider's bases are built from, so a client's request on any of them is relayed to the plugin's `fetch` as it was sent, and only a request on an API not listed is translated, to the model's own (`usable` puts it first for a plugin). Before, the one API was all a plugin model had: OpenDesign's Anthropic request to an Open Design Cloud model declared on chat completions went upstream as chat completions, though amr-link serves every model on all three (gaubeebangeel on X, plugins#888). A model with no `also` is unchanged. The plugin's `fetch` signs by the request's path, not the declared package (Open Design's `signFor`). `TestPluginModelServedOnMoreAPIsKeepsTheClientAPI`.
|
||||
|
||||
Embeddings, rerank, speech and transcriptions reach a plugin provider whatever API its chat models are spoken on: `serveRetrieval` sends them under `Provider.OpenAIBase`, which is `plugin://<id>/v1` for a plugin (its Chat base for any other provider), so they arrive OpenAI-shaped at the plugin's `fetch`, at `<base>/embeddings`, `/rerank`, `/audio/speech` or `/audio/transcriptions` under the base `pluginFetch` picks for the body's model, with the model's own id. The plugin answers them or puts them in its vendor's shape (XYenon's Google AI Studio plugin: Gemini's `embedContent`, a TTS model's `generateContent`); magpie converts none of them to Gemini's API. Before, a plugin with no `@ai-sdk/openai-compatible` model was turned away 400 "has no OpenAI-style API". The model is named `provider/model`; the retrieval routes' key holds, account holds, masking and usage apply. `TestGooglePluginTakesEmbeddingsAndSpeech`.
|
||||
|
||||
A plugin's model that says it gives video (`capabilities.output.video`, or `modalities.output: ["video"]`) makes videos (`customVideomakers`; the Grok plugin keeps its own). Start, poll and content go OpenAI-shaped through the plugin's `fetch` on the account, to `<base>/videos`, `/videos/{id}` and `/videos/{id}/content` (`videoBase`, `Provider.OpenAIBase`): a POST of OpenAI's video body (`remoteVideoBody`: `model` as the plugin's id for it, `prompt`, `seconds`, `size`, `input_reference` as a data URL), answered `{id, object: "video", status, progress, model}`; the id is the vendor's, path-escaped in the GET. The poll and content GETs carry no model, so `pluginFetch` sends them under the loader's base (else the provider's `api`, else its npm's). The video's id names the account that started it (`keyMark`: `a` + `signer`), and `markedKey` asks after it on that account of the plugin's (`AlsoOn`) while it is signed in. Key account and model holds apply to all three routes (`videoAsker`, `videoModelHeld`, which needs the answer's `model`), and the start is in the usage ledger. `TestPluginMakesVideos`.
|
||||
|
||||
@@ -7963,6 +7963,13 @@ func (s *Server) usable(p provider.Provider, model string) []provider.Protocol {
|
||||
if p.MessagesFirst(model) {
|
||||
sort.SliceStable(out, func(i, j int) bool { return out[i] == provider.Anthropic && out[j] != provider.Anthropic })
|
||||
}
|
||||
if p.IsPlugin() && len(apis) > 1 {
|
||||
// a plugin's model is translated to its own API, the first it
|
||||
// lists: the others its vendor serves it on (Open Design's) take a
|
||||
// client's request as it was sent, and are no default
|
||||
own := apis[0]
|
||||
sort.SliceStable(out, func(i, j int) bool { return out[i] == own && out[j] != own })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// alsoUp is an upstream that answers chat completions, Responses and
|
||||
// Anthropic's messages, as Open Design's amr-link does for every model
|
||||
// (plugins#888), and keeps the path each request came to.
|
||||
type alsoUp struct {
|
||||
mu sync.Mutex
|
||||
paths []string
|
||||
}
|
||||
|
||||
func (u *alsoUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
io.ReadAll(r.Body)
|
||||
u.mu.Lock()
|
||||
u.paths = append(u.paths, r.URL.Path)
|
||||
u.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/messages"):
|
||||
io.WriteString(w, pluginMessagesReply)
|
||||
case strings.HasSuffix(r.URL.Path, "/responses"):
|
||||
io.WriteString(w, sse(
|
||||
`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`,
|
||||
`event: response.output_item.done`+"\n"+`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok","annotations":[]}]}}`,
|
||||
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","object":"response","status":"completed","output":[{"type":"message","id":"m1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ok","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}}`))
|
||||
default:
|
||||
io.WriteString(w, chatSSE("ok", "", ""))
|
||||
}
|
||||
}
|
||||
|
||||
func (u *alsoUp) last(t *testing.T) string {
|
||||
t.Helper()
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
if len(u.paths) == 0 {
|
||||
t.Fatal("the plugin asked its upstream nothing")
|
||||
}
|
||||
return u.paths[len(u.paths)-1]
|
||||
}
|
||||
|
||||
// A plugin's model its vendor serves on other APIs too (m.also: Open
|
||||
// Design's amr-link serves every model on all three) takes a client's
|
||||
// request on any of them as it was sent: OpenDesign's Anthropic request to
|
||||
// a model declared on chat completions went upstream as chat completions
|
||||
// (gaubeebangeel on X), where amr-link serves /messages as well. A model
|
||||
// that says nothing more is still translated to its own API, and a request
|
||||
// on an API the model isn't served on goes to its own one.
|
||||
func TestPluginModelServedOnMoreAPIsKeepsTheClientAPI(t *testing.T) {
|
||||
t.Setenv("FAKE_ALSO", "1")
|
||||
up := &alsoUp{}
|
||||
pid := besideFake(t, "alsoco", up)
|
||||
anthropic := func(model string) string {
|
||||
return `{"model":"` + pid + "/" + model + `","max_tokens":64,"stream":true,"system":"You are a designer.","messages":[{"role":"user","content":"make a poster"}]}`
|
||||
}
|
||||
for _, c := range []struct {
|
||||
path, body, want string
|
||||
}{
|
||||
{"/v1/messages", anthropic("fake-also"), "/messages"},
|
||||
{"/v1/responses", `{"model":"` + pid + `/fake-also","stream":true,"input":"hi"}`, "/responses"},
|
||||
{"/v1/chat/completions", `{"model":"` + pid + `/fake-also","stream":true,"messages":[{"role":"user","content":"hi"}]}`, "/chat/completions"},
|
||||
// a model on chat completions alone is translated to it, as before
|
||||
{"/v1/messages", anthropic("fake-1"), "/chat/completions"},
|
||||
} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", c.path, strings.NewReader(c.body))
|
||||
if c.path == "/v1/messages" {
|
||||
req.Header.Set("anthropic-version", "2023-06-01")
|
||||
}
|
||||
New().Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%s %s: %d %s", c.path, c.body, rec.Code, rec.Body)
|
||||
}
|
||||
if got := up.last(t); !strings.HasSuffix(got, c.want) {
|
||||
t.Errorf("%s %.80s reached the upstream at %s, want …%s", c.path, c.body, got, c.want)
|
||||
}
|
||||
}
|
||||
p, err := provider.Find(pid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// translated, it goes to the model's own API first
|
||||
if to := New().usable(*p, "fake-also"); len(to) != 3 || to[0] != provider.Chat {
|
||||
t.Errorf("usable %v, want chat completions first of the three", to)
|
||||
}
|
||||
if apis := p.ListedAPIs("fake-also"); len(apis) != 3 || apis[0] != provider.Chat {
|
||||
t.Errorf("listed %v, want chat completions first of the three", apis)
|
||||
}
|
||||
}
|
||||
@@ -2217,6 +2217,8 @@ async function info(id, key, strict, limit, quiet, signal) {
|
||||
...(typeof m.decides === "boolean" ? { decides: m.decides } : was?.decides !== undefined ? { decides: was.decides } : {}),
|
||||
// and one that searches the web by itself, asked in plain words
|
||||
...(typeof m.searches === "boolean" ? { searches: m.searches } : was?.searches !== undefined ? { searches: was.searches } : {}),
|
||||
// and the other APIs its vendor serves it on, by their AI SDK packages
|
||||
...(Array.isArray(m.also) ? { also: m.also } : was?.also !== undefined ? { also: was.also } : {}),
|
||||
}
|
||||
}
|
||||
const server = auths().get(id)?.spec
|
||||
@@ -2694,6 +2696,10 @@ function rowOf(id, a, keys, stored, p, own) {
|
||||
// a model that searches the web by itself, asked in plain
|
||||
// words, which magpie may search with for other models
|
||||
searches: m.searches === true,
|
||||
// the other APIs its vendor serves it on besides npm's, by their AI
|
||||
// SDK packages (Open Design's amr-link serves every model on all
|
||||
// three), where a client's request is relayed as it was sent
|
||||
also: Array.isArray(m.also) ? m.also.filter((x) => typeof x === "string" && x !== "") : [],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +136,13 @@ type Model struct {
|
||||
// itself when asked in plain words (m.searches: Trae's search model),
|
||||
// which magpie may then search with for other models.
|
||||
Searches bool `json:"searches,omitempty"`
|
||||
// Also are the AI SDK packages of the other APIs the plugin says its
|
||||
// vendor serves the model on besides its own (NPM), as the packages
|
||||
// name them (m.also: Open Design's amr-link serves every model on
|
||||
// chat completions, Responses and Anthropic's messages, plugins#888).
|
||||
// A client's request on one of them is relayed there as it was sent,
|
||||
// not translated to the model's own API (gaubeebangeel on X).
|
||||
Also []string `json:"also,omitempty"`
|
||||
}
|
||||
|
||||
// Provider is a provider a plugin signs in to.
|
||||
|
||||
+4
@@ -93,6 +93,10 @@ export const FakePlugin = async ({ client }) => ({
|
||||
// a model's -fast (=tier: see the models hook)
|
||||
if (process.env.FAKE_FAST === "1") cfg.provider[ID].models["fake-1-fast"] = { name: "Fake One Fast", limit: { context: 1000, output: 100 } }
|
||||
if (process.env.FAKE_RESPONSES) cfg.provider[ID].models["fake-resp"] = { name: "Fake Responses", provider: { npm: "@ai-sdk/openai" }, limit: { context: 4000, output: 400 } }
|
||||
// $FAKE_ALSO: a model on chat completions whose vendor serves it on
|
||||
// Responses and Anthropic's messages too, as Open Design's amr-link
|
||||
// serves every model (plugins#888)
|
||||
if (process.env.FAKE_ALSO) cfg.provider[ID].models["fake-also"] = { name: "Fake Also", also: ["@ai-sdk/anthropic", "@ai-sdk/openai"], limit: { context: 4000, output: 400 } }
|
||||
// $FAKE_GROK: a Grok model on Responses, as Grok's plugin serves it
|
||||
if (process.env.FAKE_GROK) cfg.provider[ID].models["grok-4.7"] = { name: "Grok 4.7", provider: { npm: "@ai-sdk/openai" }, limit: { context: 4000, output: 400 } }
|
||||
// $FAKE_SENSENOVA: SenseNova's image model as its plugin lists it from
|
||||
|
||||
@@ -261,6 +261,25 @@ func pluginProtocol(provider string, m plugin.Model) Protocol {
|
||||
return Chat
|
||||
}
|
||||
|
||||
// pluginProtocols are the APIs model is served on: its own
|
||||
// (pluginProtocol) first, then each other one the plugin says its vendor
|
||||
// serves it on (m.Also: Open Design's amr-link serves every model on chat
|
||||
// completions, Responses and Anthropic's messages). A client's request on
|
||||
// one of them is relayed as it was sent; an OpenDesign's Anthropic request
|
||||
// to a model declared on chat completions was translated to it
|
||||
// (gaubeebangeel on X).
|
||||
func pluginProtocols(provider string, m plugin.Model) []Protocol {
|
||||
out := []Protocol{pluginProtocol(provider, m)}
|
||||
for _, npm := range m.Also {
|
||||
other := m
|
||||
other.NPM, other.Also = npm, nil
|
||||
if proto := pluginProtocol(provider, other); !slices.Contains(out, proto) {
|
||||
out = append(out, proto)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var gptN = lazyre.New(`^gpt-(\d+)`)
|
||||
|
||||
// copilotAPI is OpenCode's shouldUseCopilotResponsesApi: GPT-5 and after,
|
||||
@@ -340,7 +359,7 @@ func pluginCatalog(pp plugin.Provider) []catalog.Model {
|
||||
}
|
||||
c := catalog.Model{
|
||||
ID: m.ID, Name: m.Name, Provider: pp.ID, Released: m.Released,
|
||||
APIs: []string{string(pluginProtocol(pp.ID, m))}, Images: m.Image,
|
||||
APIs: protocolNames(pluginProtocols(pp.ID, m)), Images: m.Image,
|
||||
Context: catalog.Window(m.Input), Output: m.Output, Free: m.Free,
|
||||
Rate: m.Rate, RateWas: m.RateWas,
|
||||
// the model's own sampling, as its plugin said it (#2492)
|
||||
@@ -589,15 +608,17 @@ func pluginProviderServing(pp plugin.Provider, l pluginLogin, keys []string) Pro
|
||||
}
|
||||
}
|
||||
for _, m := range pp.Models {
|
||||
switch pluginProtocol(pp.ID, m) {
|
||||
case Chat:
|
||||
p.Chat = pluginBase + pp.ID + "/v1"
|
||||
case Responses:
|
||||
p.Responses = pluginBase + pp.ID + "/v1"
|
||||
case Anthropic:
|
||||
p.Anthropic = pluginBase + pp.ID
|
||||
case CodeAssist:
|
||||
a.codeAssist = pluginBase + pp.ID
|
||||
for _, proto := range pluginProtocols(pp.ID, m) {
|
||||
switch proto {
|
||||
case Chat:
|
||||
p.Chat = pluginBase + pp.ID + "/v1"
|
||||
case Responses:
|
||||
p.Responses = pluginBase + pp.ID + "/v1"
|
||||
case Anthropic:
|
||||
p.Anthropic = pluginBase + pp.ID
|
||||
case CodeAssist:
|
||||
a.codeAssist = pluginBase + pp.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
if pp.Decide {
|
||||
@@ -614,18 +635,27 @@ func pluginProviderServing(pp plugin.Provider, l pluginLogin, keys []string) Pro
|
||||
return p
|
||||
}
|
||||
|
||||
// pluginAPIs is the one API a plugin provider's model is spoken to on.
|
||||
// pluginAPIs are the APIs a plugin provider's model is spoken to on, its
|
||||
// own first (pluginProtocols).
|
||||
func (p Provider) pluginAPIs(model string) []Protocol {
|
||||
pp := p.Account.plugin
|
||||
if cur, ok := PluginOf(p.ID); ok {
|
||||
pp = &cur
|
||||
}
|
||||
if m, ok := pluginModel(*pp, model); ok {
|
||||
return []Protocol{pluginProtocol(pp.ID, m)}
|
||||
return pluginProtocols(pp.ID, m)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func protocolNames(ps []Protocol) []string {
|
||||
out := make([]string, len(ps))
|
||||
for i, p := range ps {
|
||||
out[i] = string(p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Origin is the scheme and host p's requests go to, for a URL of the
|
||||
// vendor's own outside its API (WorkBuddy's /v3/config beside its /v2): a
|
||||
// plugin's where its loader sends them, which p.Do then takes there through
|
||||
|
||||
Reference in New Issue
Block a user