diff --git a/docs/integrating.md b/docs/integrating.md index 235a156f0..2a67ce491 100644 --- a/docs/integrating.md +++ b/docs/integrating.md @@ -66,6 +66,19 @@ with `?kind=image,video` (or `?kind=chat,image,video`, or `?kind=all`). Each of them is marked `"kind": "image"` or `"kind": "video"` and goes to `/v1/images/generations` or `/v1/videos`, never to a chat route. +**A vendor's own fields.** `/v1/images/generations` and `/v1/videos` +take OpenAI's fields and pass the others on to a vendor that takes them: +Volcengine Ark's `content` (reference video and audio, `draft_task`), +`ratio`, `resolution`, `duration: -1`, `tools`, `watermark`, +`sequential_image_generation` and the rest. A video's answer carries +Ark's own fields too (`content.last_frame_url`, `usage`, `resolution`). +For the rest of Ark's API (an image stream, the task list, cancelling a +task) use `/v1/magpie/native//`: `POST +images/generations`, `POST` or `GET contents/generations/tasks`, `GET` or +`DELETE contents/generations/tasks/`, sent and answered in Ark's own +shape on the user's Ark key. It takes the same gateway key as every route, +and a key held to models, accounts or a budget is refused it. + **Optional.** Send `X-Magpie-Session: ` with a conversation's requests and `GET /v1/magpie/route?session=` says which model a routing group picked for the turn and the fallbacks it tried, before the first token diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 8b874cb49..8f6355ef7 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -704,7 +704,7 @@ Each vendor is sent its own request: | OpenAI-compatible images API (gpt-image, dall-e, a relay) | JSON `/images/generations` | multipart `/images/edits`, mask included; a URL image is downloaded first | at `/videos` only when its list or the user marks a video model (below) | | ChatGPT account (Codex backend), SenseNova U1 | JSON | JSON `images: [{"image_url"}]`, `mask: {"image_url"}` | none | | Grok subscription | JSON with `aspect_ratio` | JSON `/images/edits`, `images: [{"url"}]` | `/videos/generations`: `duration`, `aspect_ratio`, `resolution`, `image`, `reference_images` | -| Volcengine Ark (`isArk`) | `/images/generations`, `watermark: false`, one request per image, ratio as the doc's 2K size | the same endpoint, images as JSON `image` (URL or data URL); a mask is a 400 that says to describe it in the prompt | Seedance at `/contents/generations/tasks` (below) | +| Volcengine Ark (`isArk`) | `/images/generations`, `watermark: false` unless sent, one request per image, ratio as the doc's 2K size, the caller's other fields as sent (`stream: true` is a 400 pointing to the native route) | the same endpoint, images as JSON `image` (URL or data URL); a mask is a 400 that says to describe it in the prompt | Seedance at `/contents/generations/tasks` (below) | | Gemini at Google, a Google sign-in | `generateContent` asking for images | the images as inline parts | a plugin's Veo through its fetch | | OpenRouter | `/images` for image-only models, chat with modalities for the others | `input_references` | none | | DashScope, ModelScope | their own asynchronous image APIs (`draw_dashscope.go`, `draw_modelscope.go`) | their image fields | none | @@ -783,6 +783,15 @@ that URL (`vendorClient`) and serves a MOV as `video/quicktime` `TestOnlyArkTakesItsOwnVideoAsks`, `TestArkVideoSize`, `TestArkVideoAnswersItsOwnFields`, `TestVideoType`. +Ark's images get the same: the request's fields magpie doesn't read +(`drawingRead`) are `drawing.Extra`, masked as the prompt is and sent to +Ark as they came (`sequential_image_generation` and its options for a +group of images, `optimize_prompt_options`, `tools`, +`layer_decomposition`, which needs no prompt, and `watermark` over +magpie's `false`). `n` stays OpenAI's: that many requests, each one image +or one group. `response_format: "url"` asks Ark for its URL and answers +it; anything else asks for `b64_json`. `TestArkImagesPassOnTheirOwnFields`. + #### The native route `/v1/magpie/native/{provider}/{path...}` ([`native.go`](../../internal/gateway/native.go)) diff --git a/internal/gateway/ark_images_test.go b/internal/gateway/ark_images_test.go new file mode 100644 index 000000000..a98024e5f --- /dev/null +++ b/internal/gateway/ark_images_test.go @@ -0,0 +1,49 @@ +package gateway + +import ( + "bytes" + "mime/multipart" + "strings" + "testing" +) + +// Ark's images fields go as they came: a group with +// sequential_image_generation, optimize_prompt_options, a watermark the +// caller asks for, and an answer as Ark's URL when the caller asks for url. +func TestArkImagesPassOnTheirOwnFields(t *testing.T) { + s, a := arked(t) + body := `{"model":"ark/doubao-seedream-4-5-251128","prompt":"四季","sequential_image_generation":"auto","sequential_image_generation_options":{"max_images":4}, + "optimize_prompt_options":{"mode":"fast"},"watermark":true,"tools":[{"type":"web_search"}],"response_format":"url"}` + if code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", body); code != 200 { + t.Fatalf("%d %s", code, raw) + } + m := a.sent(t)[0] + opts, _ := m["sequential_image_generation_options"].(map[string]any) + opt, _ := m["optimize_prompt_options"].(map[string]any) + tools, _ := m["tools"].([]any) + if m["sequential_image_generation"] != "auto" || opts["max_images"] != float64(4) || opt["mode"] != "fast" || m["watermark"] != true || + len(tools) != 1 || m["response_format"] != "url" { + t.Fatalf("sent %v", m) + } + + // a form's fields are typed as Ark takes them + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + mw.WriteField("model", "ark/doubao-seedream-4-5-251128") + mw.WriteField("prompt", "四季") + mw.WriteField("watermark", "true") + mw.WriteField("sequential_image_generation", "auto") + mw.Close() + if code, _, raw := postImages(t, s, "/v1/images/generations", mw.FormDataContentType(), buf.String()); code != 200 { + t.Fatalf("%d %s", code, raw) + } + if m := a.sent(t)[1]; m["watermark"] != true || m["sequential_image_generation"] != "auto" { + t.Fatalf("sent %v", m) + } + + // a stream is Ark's events, which this route doesn't give + code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"ark/doubao-seedream-4-5-251128","prompt":"四季","stream":true}`) + if code != 400 || !strings.Contains(raw, NativePath) { + t.Fatalf("%d %s", code, raw) + } +} diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 53aba8b2d..0eebf125b 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -504,6 +504,27 @@ type drawing struct { N int Images []picture // to edit, or draw from Mask *picture + // Extra are the request's fields magpie doesn't read, which a + // vendor's own images API that takes them is sent as they came + // (Ark's sequential_image_generation, optimize_prompt_options, + // watermark…; drawingRead). Form: they came in a multipart form, as + // text. + Extra map[string]any + Form bool +} + +// drawingRead are the fields of an images request magpie reads itself. +var drawingRead = []string{"model", "prompt", "size", "quality", "background", "output_format", "response_format", "n", "image", "image[]", "images", "mask", "user"} + +// extraOf keeps v as one of d's Extra under k, unless magpie reads k. +func (d *drawing) extraOf(k string, v any) { + if slices.Contains(drawingRead, k) { + return + } + if d.Extra == nil { + d.Extra = map[string]any{} + } + d.Extra[k] = v } // drawn is what a vendor gave back. @@ -610,6 +631,13 @@ func (s *Server) images(edit bool) http.HandlerFunc { var hits maskHits w, d.Prompt, unmask, hits, err = redactedPromptHits(r.Context(), w, d.Prompt) defer unmask() + // the fields passed on as they came are masked as the prompt is, + // as a video's are + if err == nil { + var extra maskHits + err = maskStrings(r.Context(), d.Extra, &extra) + hits.add(extra) + } if err != nil { fail(maskStatus(err), err.Error()) return @@ -801,6 +829,10 @@ func readDrawing(r *http.Request) (drawing, error) { } d.Model, d.Prompt, d.Size, d.Quality, d.Background, d.Format, d.Want = get("model"), get("prompt"), get("size"), get("quality"), get("background"), get("output_format"), get("response_format") d.N, _ = strconv.Atoi(get("n")) + d.Form = true + for k := range f.Value { + d.extraOf(k, get(k)) + } for _, k := range []string{"image", "image[]"} { for _, fh := range f.File[k] { pic, err := readPart(fh) @@ -839,6 +871,11 @@ func readDrawing(r *http.Request) (drawing, error) { return d, fmt.Errorf("the request isn't JSON: %v", err) } d = drawing{Model: in.Model, Prompt: in.Prompt, Size: in.Size, Quality: in.Quality, Background: in.Background, Format: in.Format, Want: strings.TrimSpace(in.ResponseFormat), N: in.N} + var all map[string]any + json.Unmarshal(body, &all) + for k, v := range all { + d.extraOf(k, v) + } for _, raw := range []json.RawMessage{in.Image, in.Images} { for _, src := range imageSources(raw) { pic, err := pictureOf(src) @@ -857,7 +894,9 @@ func readDrawing(r *http.Request) (drawing, error) { } } d.Model = strings.TrimSpace(d.Model) - if strings.TrimSpace(d.Prompt) == "" { + // Ark's layer_decomposition splits the image it is given into layers, + // and takes no prompt + if strings.TrimSpace(d.Prompt) == "" && (d.Extra["layer_decomposition"] == nil || len(d.Images) == 0) { return d, errors.New("say what to draw in prompt") } if d.N <= 0 { diff --git a/internal/gateway/draw_volcengine.go b/internal/gateway/draw_volcengine.go index 5572a81cc..ccec7eb30 100644 --- a/internal/gateway/draw_volcengine.go +++ b/internal/gateway/draw_volcengine.go @@ -9,16 +9,20 @@ package gateway // - reference images go in the same JSON body, as image (a string, or an // array for several), each a URL or a data:image/;base64 URL; there // is no edits endpoint and no multipart; -// - there is no n: a request draws one image (or a group the model sizes -// itself, which magpie doesn't ask for); +// - there is no n: a request draws one image, or a group of up to 15 +// with sequential_image_generation "auto" (Seedream 4.x, 5.0 lite); // - size is a tier ("1K", "2K", "4K"…) or WIDTHxHEIGHT, never a ratio: // the doc says to give a ratio in the prompt, and lists the WxH each // ratio maps to at 2K; // - there is no quality and no mask. // -// So magpie draws there as the doc says: watermark false, the images as -// JSON, one request per image asked for, and a ratio sent as the doc's 2K -// size for it, or turned away with what to do instead (JL on Discord). +// So magpie draws there as the doc says: watermark false unless the caller +// sends its own, the images as JSON, one request per image n asks for (each +// a group when the caller sends sequential_image_generation), and a ratio +// sent as the doc's 2K size for it, or turned away with what to do instead +// (JL on Discord). The caller's other fields of Ark's own go as they came, +// and response_format url is asked of Ark as url, its link answered +// (axelburks on Discord); stream is turned away, its events being Ark's. import ( "context" @@ -68,7 +72,11 @@ func arkSize(size string) (string, error) { return size, nil } -// arkBody is d as Ark's images API takes it, for one image. +// arkImageTextFields are Ark's images fields that are text, kept as text +// from a multipart form. +var arkImageTextFields = []string{"model", "prompt", "size", "sequential_image_generation", "output_format", "background", "response_format"} + +// arkBody is d as Ark's images API takes it, for one request. func arkBody(model string, d drawing) ([]byte, error) { if d.Mask != nil { return nil, errors.New("Volcengine's images API takes no mask: say in the prompt which part of the image to change") @@ -77,7 +85,30 @@ func arkBody(model string, d drawing) ([]byte, error) { if err != nil { return nil, err } - req := map[string]any{"model": model, "prompt": d.Prompt, "watermark": false, "response_format": "b64_json"} + // the caller's own fields of Ark's first (watermark, + // sequential_image_generation and its options, optimize_prompt_options, + // tools, layer_decomposition…; axelburks on Discord), then what magpie + // reads of OpenAI's: a watermark is off unless the caller asks for + // one, and the image comes as Ark's URL when the caller asks for url + req := map[string]any{"watermark": false} + for k, v := range d.Extra { + if d.Form { + v = formValue(k, v, arkImageTextFields) + } + req[k] = v + } + if on, _ := req["stream"].(bool); on { + return nil, errors.New("Volcengine's images API streams its images in events of its own, which /v1/images/generations doesn't give: leave stream out, or ask Ark's own API through magpie at /v1/magpie/native//images/generations") + } + delete(req, "stream") + req["model"] = model + if d.Prompt != "" { + req["prompt"] = d.Prompt + } + req["response_format"] = "b64_json" + if strings.EqualFold(d.Want, "url") { + req["response_format"] = "url" + } if size != "" { req["size"] = size } diff --git a/site/public/docs/integrate.html b/site/public/docs/integrate.html index 659f9ea33..d9632d7d3 100644 --- a/site/public/docs/integrate.html +++ b/site/public/docs/integrate.html @@ -122,6 +122,8 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"Models

GET /v1/models lists what the user has turned on: id (provider/model, or a routing group’s name, sent as it is), display_name, owned_by (the provider), reasoning and supported_reasoning_levels ([{"effort":"low"},…], and the same as plain names in reasoning_levels), context_window and max_output_tokens when known, and modalities when magpie knows whether it takes images. List them from there rather than shipping a list: the user adds and removes providers in magpie. Reasoning is asked in your API’s own field (reasoning_effort, reasoning.effort, Anthropic’s thinking or output_config.effort). ?format=text gives the ids one a line. The list holds chat models alone: ask for image and video models with ?kind=image,video (or ?kind=all). Each is marked "kind": "image" or "video" and is made on /v1/images/generations or /v1/videos, not a chat route.

+

A vendor’s own fields: /v1/images/generations and /v1/videos take OpenAI’s fields and pass the others on to a vendor that takes them, such as Volcengine Ark’s content (reference video and audio, draft_task), ratio, resolution, duration: -1, tools, watermark and sequential_image_generation, and a video’s answer carries Ark’s own fields (content.last_frame_url, usage). For the rest of Ark’s API (an image stream, the task list, cancelling a task) use /v1/magpie/native/<provider>/<path>: POST images/generations, POST or GET contents/generations/tasks, GET or DELETE contents/generations/tasks/<id>, in Ark’s own shape on the user’s Ark key. It takes the same gateway key as every route, and a key held to models, accounts or a budget is refused it.

+

Optional

Send X-Magpie-Session: <id> with a conversation’s requests and GET /v1/magpie/route?session=<id> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with after=<seq>&wait=<s>). GET /v1/magpie/quotas lists the user’s subscription allowances, and GET /v1/magpie/usage and /v1/magpie/usage/requests the Usage page’s numbers and its requests (with session, and subagent/parent_agent for a Claude Code subagent’s call). They answer only this machine, or another with a gateway key; a key held to a budget, models or accounts sees its own calls and routes alone, and is refused the quotas unless its owner lets it see those of what it may use (magpie gateway-key quotas <id> on; its own limit is GET /v1/magpie/limit). Calls your app makes to its vendor itself can be reported with POST /v1/magpie/usage/requests (one record or up to 5000 a post, in usage.jsonl’s shape, each with a rid; past times are kept, so a history can be backfilled). They show on the Usage page as reported, and never count against a key’s limit. The reference has the details.

diff --git a/site/public/docs/zh/integrate.html b/site/public/docs/zh/integrate.html index 9b7fe1a73..8d3a25caa 100644 --- a/site/public/docs/zh/integrate.html +++ b/site/public/docs/zh/integrate.html @@ -122,6 +122,8 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"模型

GET /v1/models 列出用户打开的模型:id(provider/model,或路由组的名字,原样发送即可)、display_name、owned_by(供应商)、reasoning 与 supported_reasoning_levels([{"effort":"low"},…];同样的档位以纯名字列在 reasoning_levels),已知时还有 context_window、max_output_tokens,以及 magpie 知道是否支持图片时的 modalities。请从这里读取,而不是内置一份列表:用户会在 magpie 里增删供应商。推理强度用你所用 API 自己的字段传(reasoning_effort、reasoning.effort、Anthropic 的 thinking 或 output_config.effort)。?format=text 每行一个 id。列表只有对话模型:要图像和视频模型,请加 ?kind=image,video(或 ?kind=all),它们带 "kind": "image" 或 "video",在 /v1/images/generations 或 /v1/videos 上生成,不走对话接口。

+

厂商自己的字段:/v1/images/generations 和 /v1/videos 读 OpenAI 的字段,其余字段原样转给支持它们的厂商,比如火山方舟的 content(参考视频、参考音频、draft_task)、ratio、resolution、duration: -1、tools、watermark、sequential_image_generation;视频的回答也带上方舟自己的字段(content.last_frame_url、usage)。方舟 API 的其他部分(图片流式输出、任务列表、取消任务)请用 /v1/magpie/native/<provider>/<path>:POST images/generations,POST 或 GET contents/generations/tasks,GET 或 DELETE contents/generations/tasks/<id>,按方舟自己的格式收发,用的是用户的方舟密钥。它和其他接口一样需要网关密钥;限了模型、账号或额度的密钥不能用它。

+

可选

在同一会话的请求里带上 X-Magpie-Session: <id>,GET /v1/magpie/route?session=<id> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 after=<seq>&wait=<s> 长轮询)。GET /v1/magpie/quotas 列出用户各订阅的额度,GET /v1/magpie/usage 和 /v1/magpie/usage/requests 给出用量页的统计和逐条请求(带 session;Claude Code 子代理的调用还有 subagent/parent_agent)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用和路由,额度不告诉它,除非它的主人允许它看自己可用部分的额度(magpie gateway-key quotas <id> on;它自己的限额见 GET /v1/magpie/limit)。你的应用直接发给厂商、不经过 magpie 的调用,可以用 POST /v1/magpie/usage/requests 上报(每次一条,或最多 5000 条,格式同 usage.jsonl 的一行,每条带 rid;过去的时间照原样保留,所以可以补录历史)。它们在用量页上标为上报,且从不计入密钥的限额。细节见参考文档。