93 Commits
Author SHA1 Message Date
Seefs 5f56c685d4 fix(gemini): emit stream finish_reason only in dedicated terminal chunk (#8522)
Stop setting finish_reason=tool_calls unconditionally on every Gemini stream chunk containing a functionCall, omit empty content strings on non-text chunks, and strip upstream finish reasons from payload chunks so GeminiChatStreamHandler and GeminiToChatStreamState emit finish_reason once in an empty-delta terminal chunk.
2026-12-02 19:03:33 +08:00
Calcium-Ion 944464420b feat(plugin): 插件渠道可按渠道开关提供商插件的路由 (#8482)
同一个提供商插件绑到多个类型 61 渠道时,各渠道的路由完全相同,无法只在部分渠道上
开启某条转换路由。#8478 用 enabled_by 指向 channelConfig 里的 boolean 字段,已回退;
这里改为由渠道直接保存路由开关,插件不用为每条路由声明配置字段。

- meta.relay 的路由新增 default_enabled(默认 true),写 false 的路由新渠道默认不提供;
  管理路由(/v1/models、余额)始终开启,不能写 false。
- 渠道的 other_settings.plugin_routes 保存路由开关,键为 incoming_path,
  带 models 时追加 "|" 和逗号连接的模型名;保存时只保留与默认值不同的项,
  不认识的键丢弃。
- 选渠道、Responses WebSocket 判断、转发、提供商适配器绑定路由、渠道测试选端点、
  上游模型列表和定价端点都只看对该渠道开启的路由;同一路径的其他路由照常匹配。
- 插件选项接口返回 relayRoutes;渠道编辑「路由与映射」页签顶部列出插件路由,
  每条一个开关,补齐七种语言词条。
- pluginkit/v1.md、v1.d.ts、v1.schema.json 补充 default_enabled 与 plugin_routes。

Refs #8466
2026-11-27 23:25:50 +08:00
zwenooo bea3616473 feat(relay): 路由转换器支持 OpenAI Responses 转 Anthropic Messages (#8465)
relaykit 已注册 openai_responses_to_claude_messages(请求、响应、流式三侧都有实现),
普通 Claude 渠道收到 /v1/responses 时也已经在用它,但高级自定义渠道和提供商插件共用的
路由转换器白名单里没有登记,这两类渠道无法把 /v1/responses 路由到 Anthropic Messages 上游,
插件只能用 converter: "plugin" 在 JS 里重写整套转换。

- relaykit/dto:白名单登记该转换器,incoming_path 限定为 /v1/responses。
- 高级自定义适配器:请求经 ConvertRequestByID 转成 Claude 请求;响应交给 Claude 适配器
  按客户端协议转回 Responses(含流式);发送 anthropic-version 等 Claude 请求头。
- 插件 API 文档、v1.d.ts、v1.schema.json 的转换器表补上该转换器及其 +plugin 链式写法。
- 前端高级自定义路由的转换器选项、默认上游路径(/v1/messages + x-api-key)与路径校验,
  七种语言的选项文案。
2026-11-27 20:13:18 +08:00
Calcium-Ion 5ff8157dd2 fix(relaykit): flatten top-level oneOf/anyOf/allOf in Claude input_schema (#8476)
Claude rejects tools whose input_schema has oneOf, anyOf or allOf at the
top level (400 "input_schema does not support oneOf, allOf, or anyOf at
the top level"). Codex Desktop's automation_update tool has such a schema,
so every Responses -> Claude turn that carried it failed.

FunctionParametersToInputSchema now merges the branches into one object
schema: properties are combined (differing same-name schemas go into a
nested anyOf), required is the intersection for oneOf/anyOf and the union
for allOf plus the top level's, and other top-level keywords are kept.
The tool conversion reports claude_top_level_schema_union_flattened.
Schemas without a top-level union are returned byte for byte.
2026-11-27 19:16:11 +08:00
5f8525d83c fix(claude): map output_tokens_details.thinking_tokens to reasoning_tokens (#8431)
* fix(claude): map output_tokens_details.thinking_tokens to reasoning_tokens

Anthropic reports thinking tokens in usage.output_tokens_details.thinking_tokens,
a subset of output_tokens. ClaudeUsage had no such field, so OpenAI-format
responses converted from a Claude channel always reported
completion_tokens_details.reasoning_tokens = 0.

Decode the field and carry it into CompletionTokenDetails.ReasoningTokens for
non-stream responses and stream message_start/message_delta usage, bounded by
output_tokens. completion_tokens and billing are unchanged.

* fix(claude): apply reported zero thinking_tokens on message_delta

message_delta usage is cumulative. When output_tokens_details is present, use its thinking_tokens even if zero; keep the earlier count only when the breakdown is absent.

* fix(claude): bound delta thinking_tokens by merged output and preserve on merge

- Clamp message_delta thinking_tokens against accumulated completion_tokens so deltas omitting output_tokens do not zero out reasoning_tokens.
- Copy incoming OutputTokensDetails in MergeClaudeUsageNonZero to preserve or replace the breakdown across usage merges.

---------

Co-authored-by: forgottener <8578113+forgottener@users.noreply.github.com>
Co-authored-by: seefs001 <i@seefs.me>
2026-11-27 19:11:48 +08:00
feeeeiandseefs001 c53dcf3356 fix(relaykit): report cached tokens in Gemini usageMetadata built from chat usage (#8333)
* fix(relaykit): report cached tokens in Gemini usageMetadata built from chat usage

Gemini promptTokenCount includes cached content, but responses converted
from chat usage (e.g. a Claude channel serving a Gemini-format request)
always reported cachedContentTokenCount as 0 while billing_usage carried
the cache read. Fill cachedContentTokenCount from the chat usage cache-read
count in the non-stream, stream chunk, and stream state converters.

* fix(relaykit): ignore non-positive cached token counts for Gemini usage

---------

Co-authored-by: seefs001 <i@seefs.me>
2026-11-24 17:46:04 +08:00
CaIon 185e1e51a0 chore(deps): 升级 moego 至 v0.1.0-alpha.5 并统一正则库 2026-11-22 21:52:10 +08:00
Seefs a85f7e844d fix(relaykit): match Gemini 4 thinking levels by family prefix (#8412)
* fix(relaykit): match Gemini 4 thinking levels by family prefix

* fix(relaykit): cap Gemini 4 effort at documented thinking levels
2026-11-21 01:25:05 +08:00
feitianbubu 3546e93827 fix(relay): apply GPT-6 chat parameter rules to gpt-6.2-astra and gpt-6.2-sol (#8375) 2026-11-18 14:19:03 +08:00
Seefs 669d774976 fix(relaykit): map Gemini 4 thinking levels per model (#8367)
Treat gemini-4-hydrogen as a thinkingLevel model so cross-protocol requests apply the requested strength. Pass xhigh and max through on hydrogen, pass max through on argon, and keep mapping minimal to low on both.

Closes #8364
2026-11-17 14:44:49 +08:00
翅膀喵 e8c6a5d953 fix(relaykit): join Gemini text parts verbatim in chat responses (#8136)
Gemini may split one answer across several text parts. The Chat
converters inserted a newline between consecutive text parts and
dropped parts that were exactly "\n", so JSON split inside a key,
string, number or escape reached clients as invalid JSON, and other
text was silently altered.

Plain text parts are now written as-is and empty parts add nothing;
only rendered media, code and stream thought blocks keep their newline
separation. Grounding citations use the byte offsets recorded while
rendering instead of searching the output, so preserved newlines next
to those blocks are cited at their real position.
2026-11-17 14:35:16 +08:00
Calcium-Ion c9c6da2786 fix: 升级 moego 到 v0.1.0-alpha.3,修复无 AVX 的 x86-64 CPU 上的 SIGILL 崩溃 (#8322)
- rc.50 依赖的 moego v0.1.0-alpha.2 只按 AES-NI 选用 hashAES 内核,而该内核是 VEX 编码,需要 AVX。在有 AES-NI、没有 AVX 的 CPU(如 Celeron J4125)上,解析不少于 128 字节的请求 JSON 时进程因 SIGILL 退出,容器反复重启。
- alpha.3 在这类 CPU 上改用 SSE 编码的 AES 指令,结果与其他 CPU 相同。根模块和 relaykit 同步升级,THIRD-PARTY-LICENSES 中的版本号同步更新。

Fixes #8314
2026-11-13 17:25:53 +08:00
Calcium-Ion 7b857f5a1e feat(plugins): add provider plugins, request plugins and a community marketplace (#8271)
* feat(plugins): add provider plugins, request plugins and a community marketplace

- Provider plugins turn an upstream vendor into a channel type: routes,
  protocol conversion, models, static keys, sign-in flows with token
  refresh, balance queries, per-channel config and a scheduled hook.
- Request plugins run on requests and replies (ingress, request,
  outbound, egress, reply, report), with instances by scope, model
  ranges, dry runs and per-log records. Built-ins: request filter,
  request redaction, parameter override, auto reasoning effort, image
  compression and content moderation. Sensitive words move into a
  request filter instance on first start.
- Node sync: a system_sync_topics table lets every node reload settings,
  channels, plugins and other data within seconds, and the system info
  page shows each node's state.
- Marketplace: a community source next to the official one, lookup by
  plugin code for official and community plugins, key rules for
  community plugins, install counts and takedown warnings.

* docs(plugins): name request protocols and host-only members in the plugin API

- Protocol names: ctx.format and samples use relaykit's protocol names.
  The spec lists the client paths and body of each name, so every host
  passes the same names to plugins.
- Host-specific members: channel, group, user, token, channelTypes,
  channelOther and utils.paramOverride exist only on new-api. The types
  mark them optional.
- Relay routes: the spec now writes out the route keys and the converters
  each incoming path accepts. The schema lists the converter names.

* feat(plugins): show recommended plugins from the official list too

The site now marks official plugins as recommended in its index. The
built-in official and community lists both get a Recommended group;
lists added by the administrator still cannot recommend plugins.

* feat(plugins): fall back to www.newapi.pro when www.newapi.ai does not answer

Plugin lists, plugin files and logos from www.newapi.ai are downloaded
from www.newapi.pro, the mainland China site, when newapi.ai gives no
answer within 10 seconds; the browser remembers this for a day. The
marketplace toolbar has a download site picker: Auto, or Mainland China
to always use www.newapi.pro. Saved source addresses stay on newapi.ai,
and every file is still checked against its sha256.

Community install counts go to newapi.ai first and to newapi.pro when
newapi.ai cannot be reached.

* fix(plugins): leaving the page does not switch the plugin site to www.newapi.pro

Reloading or leaving the marketplace cancels requests still running.
That was read as www.newapi.ai not answering, so the browser moved to
www.newapi.pro for a day although newapi.ai was reachable. Requests
cut off by leaving the page are no longer counted.

* feat(plugins): choose the plugin download site by hand

The marketplace no longer switches between plugin sites by itself. The
toolbar menu lists the main site www.newapi.ai, the backup site
www.newapi.pro and the other plugin lists; picking an entry is the only
thing that changes where plugins are downloaded from, and the main site
can always be picked again.

A browser that the earlier automatic switch had moved to www.newapi.pro
opens on the main site again. The download site, the source choice and
managing sources now share one menu in the list header.

* feat(plugins): show plugin usage guides and require README and changelog

Every marketplace plugin version now ships a usage guide, README.md, and a
changelog, CHANGELOG.md, next to plugin.js. The install dialog shows the
guide in the reader's language when a translation is listed, falls back to
English, and links to the source file. A guide or changelog that breaks the
format is reported with its file, line and rule instead of being shown.

The plugin API document describes both formats, the translations they may
list, and the checks the community marketplace runs before it accepts a
version: readme_missing, readme_invalid, changelog_missing and
changelog_invalid. Versions accepted before these checks are not checked
again.

* fix(plugins): address review findings on plugin parts, limits and access

- Only the root user reads request plugin instance configs; an admin who
  may bind instances to channels gets them without configs.
- Outbound hooks that grow the body are held to MAX_REQUEST_BODY_MB, as
  ingress hooks are, and answer 413 without a retry.
- An admin who cannot read plugin options keeps the balance and model
  list actions on plugin channels; the server answers whether they work.
- Reading the parts of a plugin source gives up when the source does not
  parse or code elsewhere refers to meta, as the meta preview does.

* fix(plugins): address review findings on request processing, documents and node sync

- PDF checks resolve indirect parameters and bound every value the parser
  allocates or loops on: predictor columns, object stream counts, nested
  object streams, cross-reference streams and ToUnicode ranges. Font and
  CMap work checks the deadline.
- A WebP frame must match its declared canvas, and keyword search stops at
  its match limit.
- Request processing treats a body as JSON whenever the gateway parses it
  as JSON, keeps Gemini reply parts in place, scopes instances by the
  settled auto group, hides channel header overrides from plugin param
  overrides, and captures replies only for report instances in scope.
- Request processing no longer follows the plugin master switch, which now
  covers plugin tasks and channels only.
- json.patch copies stop at MAX_REQUEST_BODY_MB, and provider prepareRequest
  effects past it answer 413.
- Image billing reads the count from the final upstream body, including the
  count members of SiliconFlow, Imagen and Replicate and the Imagen default.
- Automatic channel status changes no longer reload every node's channel
  cache. A credential refresh holds no channel lock while it waits on the
  vendor. A key that needs login is disabled and the request can retry.
- Balance requests must go to the channel host or allowedHosts, and provider
  stream events a plugin drops keep the stream alive.
- Node sync: OAuth provider writes bump inside their transaction, a failed
  startup load is retried, and each node is judged by its own topics.
- request-filter checks the text the old sensitive-word check did,
  request-redact and content-moderation handle large inputs, and
  image-compress lossless mode leaves JPEG and WebP alone.

* fix(plugins): address the second review on balances, egress and routes

- Channel other_info writes (status changes, balance queries and manual
  multi-key actions) only land while other_info is still the value read,
  and retry otherwise, so a write on one node no longer overwrites another
  node's balance or status reason. They write only their own columns.
- On the Responses path egress reads the body after the channel finalizes
  it, which is the body sent upstream.
- The Vertex AI plugin picks the region by the model the client asked for,
  as the built-in Vertex AI channel does.
- /request-processing and /security are reserved route namespaces, and a
  test checks that every console page is reserved.
- The plugin API docs say what egress reads on a provider plugin channel.

* feat(channels): run the balance update as a system task with progress

"Update all balances" now queues a channel_balance system task instead of
starting a goroutine guarded by an in-process flag. The task row holds the
progress (enabled channels queried of total), so any node can answer it,
and its active key keeps one run at a time across nodes. The
CHANNEL_UPDATE_FREQUENCY schedule becomes the same task's schedule, so
manual and scheduled runs no longer overlap.

GET /api/channel/update_balance answers with the task id, and with the
running one when a run is already queued. GET
/api/channel/update_balance/task/:task_id, under the same channel
permission, returns the status, progress and failure of balance update
tasks only. The channel list follows the task, reloads as more channels
are queried and once more at the end, and reports how the run ended.

* feat(system): sync nodes through system tasks and clean up task history

Node sync no longer needs its own table. A write to synced data adds a
pending sync_<topic> system task. Every node polls the newest task of each
topic it keeps every 3 s and reloads when that task is newer than the one
it applied. Custom OAuth providers still add their task inside the write
transaction, and lock the newest task of the topic first, so tasks commit
in id order. The master marks a sync task succeeded once every online node
that keeps the topic has applied it. Until then the task shows how many
nodes have applied it and why the others have not. The
system_sync_topics table is gone.

A composite (type, id) index answers the newest task of a type from the
index. The latest-per-type and earliest-pending queries now read ids first,
because MySQL 5.7 scanned the whole table for them.

A daily system_task_cleanup task deletes finished system tasks older than
system_task_setting.retention_days (default 30, at least 1), in batches.
It never deletes active tasks or the newest task of any type. The
retention is set under Operations > Log maintenance.
2026-11-12 20:50:58 +08:00
Calcium-Ion f3d8b737b6 perf: 升级 MoeForge moejs/moego,请求体按需流式读取 (#8311)
- moejs 迁到 github.com/MoeForge/moejs v0.1.0,Dockerfile、Electron 构建与发布流程的 PGO 路径同步更新;发布附带 THIRD-PARTY-LICENSES.md,并补充 moejs 附带的第三方声明。
- moego 升级到 v0.1.0-alpha.2:宿主 JSON 编解码经 common/kitutil 封装改用 moego/json,根模块和 relaykit 生产代码的 regexp 改用 moego/regexp。
- 内存中的请求体由校验器零拷贝解析;磁盘缓存的请求体经独立文件读取器解码,且只接受一个 JSON 值,尾随内容会被拒绝。
- 模型/分组提取与重复 model 键检测、渠道亲和 JSON 路径、任务协议 stream/background 标志、multipart 解析在磁盘模式下不再把整份请求体读进内存。图片透传直接转发已存储的请求体,并校验最终发往上游的 n。
- 出站请求体各自持有读取位置。此前透传重试共用存储游标,上一次尝试仍在发送时,下一次尝试可能发出残缺的请求体。收到响应头后不再提前关闭请求体,避免中断仍在发送的请求体。
- 表达式计费只在表达式使用 param() 时冻结请求体,其余情况不再读取并保留整份请求体。
2026-11-12 20:19:51 +08:00
feitianbubu 3374f251e3 feat: forward image complexity and markup for gpt-image-2.6 (#8208) 2026-11-05 22:06:50 +08:00
Seefs ba5f736779 fix(gemini): bill embeddings from upstream usageMetadata (#8182) 2026-11-03 19:33:42 +08:00
Seefs 94b5216645 feat(vertex): add per-channel v1beta1 endpoint switch (#8179)
* feat(gemini): add Argon fields and reasoning mappings

* feat(vertex): add per-channel v1beta1 endpoint switch
2026-11-03 18:32:25 +08:00
Seefs 52c173038e feat(gemini): add Argon fields and reasoning mappings (#8177) 2026-11-03 18:03:30 +08:00
Calcium-Ion 70e6af6429 perf: read and edit request JSON and base64 with moego (#8148)
* perf: read and edit request JSON and base64 with moego

Switch gjson/sjson to moego/ojson and base64 on media, file and plugin
paths to moego/base64. Both keep the same results on valid input.

- Param overrides apply every edit to one ojson.Doc and write the body
  once, instead of copying the whole body for each edit.
- The video proxy and the audio check validate base64 without decoding
  it; plugin icons and inlined plugin files build data URLs directly.
- Login, password, OAuth and signature code keeps gjson and
  encoding/base64.

* perf: rewrite request fields without re-encoding the whole body

Removing disabled fields, the Responses WebSocket create event, AWS Mantle
and pass-through bodies, the OpenAI usage patch, alpha search, video result
redaction and image SSE events now edit the body with ojson.Doc instead of
decoding it into a map and encoding it again. Everything the gateway does
not touch keeps the client's member order, number spelling and characters.

- A key the client repeats is removed or rewritten in every copy, so an
  upstream that reads the last copy sees the same value the gateway routed
  and billed. A key that appears once is rewritten in place.
- Image responses and the video proxy read large values without copying
  them.

* perf: keep member order in param override merges and prune_objects

Merging an object (append/prepend) now replaces existing members where
they stand and appends new members, sorted by key, at the end. prune_objects
deletes the matching objects from the body in place instead of encoding
the pruned part, or the whole body, again. Everything else keeps the
client's member order, number spelling and characters.
2026-11-01 21:56:17 +08:00
RedwindA a2defd2a82 Merge commit from fork
MaskSensitiveInfo trimmed trailing punctuation one byte at a time and
recounted the parentheses of the whole URL for each trailing ')'. Trim
the punctuation set, including ')', with strings.TrimRight; the trimmed
characters are still appended after the masked URL.
2026-10-30 00:55:16 +08:00
feitianbubu ad56112820 fix(relay): apply GPT-6 chat parameter rules to gpt-6.1-sol and gpt-6.1-terra (#8064) 2026-10-28 13:06:23 +08:00
Xudong Zhang 0165fef98d fix(relaykit): preserve Gemini text alongside tool calls (#7998) 2026-10-25 21:01:06 +08:00
Xudong Zhang 4d962e464d fix(relaykit): preserve tool argument numbers in Claude responses (#7996)
* fix(relaykit): preserve tool argument numbers in Claude responses

* test(claude): assert serialized tool input contract
2026-10-25 21:00:00 +08:00
神之间 bc795cc118 fix:修复stop为非字符串和[]string的协议转换问题 (#7935) 2026-10-25 19:18:19 +08:00
yxkong 9823ebc7ea fix(billing): bill cache_creation_input_tokens reported in prompt_tokens_details (#7909)
OpenAI-compatible upstreams with explicit context cache (e.g. Alibaba Bailian)
report cache-write tokens as prompt_tokens_details.cache_creation_input_tokens.
The field was ignored, so cache-write tokens were billed at the plain input
price instead of the cache-creation price.

Parse it into InputTokenDetails.CacheCreationInputTokens and include it in
CacheCreationTokensTotal using max() with the existing cache-write fields, so
the same tokens are never counted twice.
2026-10-25 17:22:51 +08:00
CaIon 1dafb19a42 fix(gemini): preserve top-level imageConfig in chat conversion 2026-10-24 22:29:27 +08:00
Calcium-Ion e9d4d6353c feat(billing): bill OpenAI 12-hour prompt cache writes at their own price (#7965)
OpenAI added a 12-hour prompt cache to the Responses API on 2026-10-20
(prompt_cache_options.ttl "12h", GPT-5.6 and later). A 12-hour write
costs 2.5x the input price, twice the 30-minute write. We already
forwarded the option but billed every cache write at the 30-minute price.

- Read cache_write_tokens_details from Responses usage and keep the split
  through streaming, compaction and format conversion.
- Ratio pricing bills 12-hour writes at twice the cache write ratio, the
  same way Claude 1-hour writes use 6/3.75.
- Expressions get a cc12h price. When an expression leaves the long-lived
  price out, 12-hour writes cost twice the cc price and Claude 1-hour
  writes 6/3.75 times it; without a cc price they bill as input. Claude
  cache writes are no longer free when an expression omits cc or cc1h.
- gpt-6-astra prices 12-hour writes at $25 ($50 above 272K tokens).
- GPT models with a cache write ratio convert to expressions with cc12h.
- Chat Completions forwards prompt_cache_options.
- The pricing editor, cost estimator, pricing pages and usage log details
  show the 12-hour price and tokens.
2026-10-22 22:41:17 +08:00
CaIon d0b840e75f fix(relay): keep the client's JSON Schema property order
Structured outputs fill a schema's properties in the order the schema
lists them. The gateway decoded schemas into maps and encoded them
again, which sorts the keys: a schema that lists reasoning before the
answer reached the upstream with the answer first. Chat Completions
sent through the Responses API lost the order of response_format, and
tool parameters lost it on most paths.

Schemas now reach the upstream as the client wrote them: tool
parameters and Claude input_schema, Chat and Responses format
conversion, the disabled-field filter, Bedrock pass-through, param
override move, copy and append, the output_config edits for DeepSeek
and model modifiers, and the Ollama format.

relaykit: dto.FunctionRequest.Parameters and dto.Tool.InputSchema are
now json.RawMessage.
2026-10-22 20:21:04 +08:00
Roger Chienandseefs001 783735607d fix(relaykit): keep tool calls when merging adjacent assistant messages for Claude (#7921)
* fix(relaykit): keep tool calls when merging adjacent assistant messages

Adjacent assistant messages with string content were merged keeping only
the second message's tool calls, so tool results for the first message's
calls had no matching tool_use and Claude rejected the request.

- concatenate both messages' tool calls in input order
- skip the "..." placeholder of a tool-call message in the merged text

* fix(relaykit): preserve literal ellipses in assistant message merges

---------

Co-authored-by: seefs001 <i@seefs.me>
2026-10-20 22:15:40 +08:00
feitianbubuandCaIon afe73b08ff feat: 支持阿里多模态向量化模型qwen3-vl-embedding (#5179)
* feat: add ali MultimodalEmbedding qwen3-vl-embedding

* fix: report image/video tokens in qwen3-vl-embedding usage for billing

* fix(ali): serve every Bailian multimodal embedding model natively

Route qwen2.5-vl-embedding, the tongyi-embedding-vision series and
multimodal-embedding-v1, dated snapshots included, to the native
multimodal-embedding endpoint like qwen3-vl-embedding. Text embedding
models stay in compatible mode.

Take tongyi-embedding-vision's text and image tokens from
input_tokens_details so the image ratio applies to its image tokens,
and set total_tokens to the billed input tokens: tongyi counts its
unpriced output_tokens in total_tokens. A response without usage bills
the request estimate, as compatible mode does. Return an error code
carried in a 200 body as a 500, close the response body when reading
it fails, and fold the input conversion into one function.

Count the text, image and video parts of embedding input in the request
estimate the way chat content is counted, so image calls are pre-charged
and a response without usage is not free. With the default settings no
image is downloaded for the estimate.

* fix(gemini): reject embedding input that is not plain text

Gemini embeds text only, so the converter kept the strings and dropped
image, video and text parts. The embedding request estimate now counts
those parts, and Gemini embeddings bill that estimate, so a dropped part
would be charged without ever reaching Gemini. A part now fails the
request with a 400 that skips retries, before anything is sent or charged.

---------

Co-authored-by: CaIon <i@caion.me>
2026-10-20 21:38:28 +08:00
Calcium-Ion 6cf0d90b5f feat(deepseek): support V4.1 Flash, the Search and Fetch APIs, and @ reasoning modifiers (#7867)
* fix(model): find channels for @-modified model names without the memory cache

With the channel memory cache off (no Redis and MEMORY_CACHE_ENABLED
unset), channel selection matched abilities by the exact requested name,
so a name such as deepseek-flash@effort:max found no channel. Retry with
the routing name when the exact name has no channel, as the cached path
already does.

* feat(deepseek): support V4.1 Flash, the Search and Fetch APIs, and @ reasoning modifiers

Follows the DeepSeek API update of 2026-10-17.

- Default models: deepseek-flash and deepseek-v4-pro, each with -none,
  -low and -max, plus deepseek-search and deepseek-fetch. The retired
  deepseek-chat, deepseek-reasoner and deepseek-v4-flash names are no
  longer listed.
- Thinking: the -none/-low/-max tails also work on deepseek-flash.
  @thinking and @effort now reach DeepSeek's own fields on Chat
  (thinking, reasoning_effort), Anthropic (thinking, output_config.effort)
  and Responses (reasoning.effort), and take precedence over the tails.
- Built-in prices: peak/off-peak expressions for deepseek-flash (also the
  deepseek-v4-flash aliases) and deepseek-v4-pro, and $0.75 per 1,000
  requests for deepseek-search and deepseek-fetch.
- Server-side search: searches and page fetches DeepSeek runs for Claude
  Code and Codex bill at $0.75 per 1,000 under deepseek_search and
  deepseek_fetch, whatever model name the client sent. Searches whose
  results already arrived stay billed when a stream ends before its final
  usage; this also applies to Alibaba's Anthropic endpoint.
- New endpoints POST /v1/tools/search and /v1/tools/fetch relay the
  DeepSeek APIs like /v1/alpha/search. A call is charged only when
  DeepSeek returns results or page content.

* fix(deepseek): price /v1/tools/search and /v1/tools/fetch by endpoint

A model named in the request body chose the billing model, so a body such
as {"query":"...","model":"deepseek-flash"} was priced as a chat model with
no tokens and the search or fetch cost nothing. Both endpoints now always
use their routing name, deepseek-search or deepseek-fetch. DeepSeek ignores
the body field, so the body is still forwarded unchanged.

* fix(deepseek): bill Claude-format page fetches at the DeepSeek Fetch price

usage.server_tool_use.web_fetch_requests always went to the web_fetch
tool price, which has no built-in value, while only searches used the
DeepSeek key. A channel can now name its own fetch key next to the search
key, and DeepSeek channels bill reported fetches under deepseek_fetch. A
channel retry clears it like the search key.
2026-10-17 23:24:33 +08:00
Calcium-Ion 6461f084ff feat(notify): turn each kind of notification on or off (#7868)
SMTP settings now only decide whether mail can be sent. Verification
codes, password reset, email binding and account security mails depend
on SMTP alone, and no notification switch affects them.

Admins get a site-wide low balance reminder switch, on by default, next
to the SMTP settings. The default threshold is entered as an amount.

Users choose which notifications they receive. Low balance reminders are
on for everyone by default. Admins can also turn channel notifications
and upstream model update notices on or off. The root user receives
channel notifications until it turns them off. Other admins receive them
after they turn them on.

A low balance reminder is sent once, when a charge takes the balance
below the threshold. A top-up above the threshold arms it again.

Channel notifications reach every admin who has them on, in that admin's
language. Email binding codes and account security mails follow the
account's language.

Saving notification settings no longer clears the language, the sidebar
layout or the billing preference.

Existing settings keep their behavior, and old clients that do not send
the new fields keep the stored switches. Webhook, Bark and Gotify
payloads are unchanged.
2026-10-17 22:17:59 +08:00
sicnuyudidiandseefs001 ff3684658f fix(relayconvert): 保留 Chat/Claude → Responses 转换中 input_image 的 detail 字段 (#7855)
* fix(relayconvert): preserve input_image detail in Chat/Claude -> Responses conversion

* fix(relayconvert): preserve original image detail in Responses

Preserve all supported image detail levels during Chat to Responses conversion instead of downgrading original to auto.

Use bogus for unknown-detail fallback coverage and verify auto defaults for Claude message and tool-result images.

---------

Co-authored-by: seefs001 <i@seefs.me>
2026-10-17 12:58:08 +08:00
CaIon d032204733 feat(aws): add Mantle Messages API support
Add an opt-in Mantle interface with top-level cache_control, API key and
SigV4 authentication, and native Claude response handling. Keep InvokeModel
as the default for existing AWS channels.

Strip hop-by-hop headers before signing and map the dated Haiku alias to
Mantle's model ID. Cover signatures over HTTP/1.1 and HTTP/2, cache usage,
legacy routing, and channel configuration with regression tests.

Refs #4791
2026-10-16 14:45:17 +08:00
Roger Chien ca2cae676d fix(relaykit): emit summary on reasoning items announced without one (#7833)
The Responses schema requires summary on every reasoning item, but the
chat-to-Responses stream announces a reasoning item with an empty
summary that omitempty drops. Strict clients reject the item and then
see every summary event that follows as having no active item.

Items that already carry summary text keep their existing encoding.
2026-10-16 13:44:03 +08:00
RedwindA 19d435e7fd fix(relay): mask only the custom upstream address in error messages (#7822)
* fix(relay): mask only the upstream address in error messages

MaskSensitiveInfo masked every URL, domain and IPv4 in upstream error
messages, which garbled documentation links, email domains and dotted
identifiers that clients need to read.

It now takes the upstream addresses of the request: the channel base URL,
the origin the gateway actually dialed (recorded in doRequest, DoWssRequest,
the AWS SDK client and the Xunfei and Volcengine TTS dials, which covers
absolute Advanced Custom routes), the channel proxy and the environment
proxy. URLs and bare hostnames on those hosts and all IPv4 addresses are
masked; other URLs and domains stay readable. With no upstream address no
address is masked. Credentials are masked on every URL regardless of host:
api_key values, query values and userinfo.

The URL matcher also keeps quotes, colons and semicolons that follow a URL,
keeps parentheses and apostrophes inside it, masks an IPv4 URL host whole and
keeps a country-code TLD when the host has a port.

* fix(relay): keep preset official endpoints readable in masked errors

A channel on the base URL new-api presets for its type reaches a public
official endpoint, so its address is not masked. Only addresses the admin
configured are: a custom base URL, the origin of an Advanced Custom route,
and the channel and environment proxies. Preset hosts are compared with
their port so a configured localhost upstream stays apart from the Ollama
preset.

The origins recorded for the AWS SDK, Xunfei and Volcengine TTS dials and the
plugin allowedHosts masking are dropped: they are all official endpoints.

* fix(relay): mask IPv4 addresses and plugin allowed hosts in every error

IPv4 addresses in network errors include the gateway's own address, so they
are masked even when the channel uses a preset base URL. Task plugin build
failures mask the plugin's allowedHosts again: an installed plugin may point
them at private hosts.

* fix(relay): mask bracketed IPv6 addresses in errors

Go network errors write IPv6 addresses in brackets, as in
"dial tcp [2001:db8::1]:443". Like IPv4, they are the resolved upstream or
the gateway's own address, so they are masked on every error once the
bracketed content parses as an IP.
2026-10-15 15:49:45 +08:00
枭钰钰 a0bf6a8a41 fix(vertex): pass project_id in API Key mode to avoid 404 on official endpoints (#6330)
* fix(vertex): pass project_id in API Key mode to avoid 404 on official endpoints

Closes #6250.

Vertex AI channel in vertex_key_type=api_key mode: getRequestUrl passed
an empty string as project_id to BuildGoogleModelURL /
BuildAnthropicModelURL, leaving the URL without the
/projects/{PROJECT_ID}/locations/{REGION}/ segment, so the official
Vertex endpoints returned 404.

In JSON mode project_id is parsed from the service account, so the bug
is specific to api_key mode.

Fix:
- Add VertexProjectID to ChannelOtherSettings (used only in api_key
  mode; JSON mode keeps parsing from the service account, unchanged).
- In adaptor.go's api_key branch, use ChannelOtherSettings.VertexProjectID
  instead of the hardcoded empty string. When unset, fall back to the
  legacy behavior so existing api_key channels are not broken.
- Frontend (web/default): show a Project ID input when
  VertexKeyType=api_key, persist settings.vertex_project_id, and require
  it via superRefine so users cannot save an api_key channel that would
  still 404. Clear the residual field in non-api_key mode or non-Vertex
  channels.
- Add translations across 7 locales (en/zh/zh-TW/ja/fr/ru/vi).

Regression tests (relay/channel/vertex/adaptor_api_key_url_test.go)
cover 4 scenarios:
- api_key mode + configured project_id -> URL contains /projects/.../locations/
- api_key mode + stream suffix -> key joined with &, path contains project_id
- api_key mode + Claude mode -> anthropic publisher path
- api_key mode + empty project_id -> falls back to legacy behavior

* fix(vertex): make the API Key project ID optional

Express-mode API keys are documented without a project, so a required
project ID would block saving those channels. Without one the URL keeps
the express-mode form as before; with one, the URL carries the project
and the deployment region, so a global region is honored.

- Drop the required check and describe the field in plain words.
- Treat vertex_project_id as a sensitive field, like the key format.
- Assert exact request URLs in a table test, including the global case.
- Cover saving, clearing and loading the project ID in the channel form.
2026-10-14 20:16:30 +08:00
RedwindA 767a82b876 fix(claude): forward thinking.block_binding and every anthropic-beta value (#7732)
Claude requests are decoded into dto.Thinking, which had no block_binding
field, so thinking.block_binding.prefix_mismatch_behavior: "drop_block"
was dropped before reaching the upstream. Multi-turn conversations whose
system prompt or tools change then failed with "The block is bound to a
different conversation".

- Thinking keeps block_binding verbatim and round-trips thinking fields
  it does not model yet.
- When a model reasoning suffix re-renders thinking as adaptive, restore
  the client's block_binding; never add one the client did not send.
- Forward every anthropic-beta header line as one comma-separated value,
  and trim entries in the Bedrock anthropic_beta list.
2026-10-12 19:06:04 +08:00
Shawn Wang ba0e478e06 fix(relaykit): preserve assistant text with tool calls (#6871) 2026-10-12 17:34:30 +08:00
CaIon c10780e054 fix(relayconvert): keep JSON Schema constraints in tools and structured output sent to Gemini
Requests converted for Gemini had their tool parameters and structured
output schemas forced into Gemini's typed Schema, and anything it cannot
hold was dropped silently: const, oneOf, $ref and $defs lost their
meaning, non-string enum values were removed from tool parameters, and
structured output with type arrays or non-string enum values got a 400
from Gemini.

A schema the typed Schema holds is sent exactly as before. Any other
schema now goes unchanged in parametersJsonSchema or responseJsonSchema,
which Vertex AI and the Gemini API v1beta accept. When a model is set to
Gemini API v1, which has no parametersJsonSchema, the schema is cleaned
as before and a conversion warning names what was dropped.
additionalProperties and $schema alone still do not switch fields, so
Claude Code, Codex and MCP tools and OpenAI strict structured output are
sent unchanged. Responses custom tools keep their typed parameters.

Fixes #7455
Refs #7704
2026-10-11 17:16:17 +08:00
赵瑞哲 4b13d9388e fix(relayconvert): drop non-string enum values when converting OpenAI tool schemas (#7729)
Gemini's legacy parameters (Schema) only accepts string enum elements, so
an OpenAI tool schema like {"type": "boolean", "enum": [true]} was
forwarded as-is and rejected upstream with HTTP 400 (TYPE_STRING). Keep
the enum constraint only when every element is a string, otherwise drop
it while preserving the declared type, in both the deep and the
depth-capped shallow cleaner. String enums pass through untouched.

Fixes #7704.
2026-10-11 17:08:44 +08:00
CaIon 5ac7562840 fix(relayconvert): keep answer text that shares a stream chunk with reasoning
Some OpenAI-compatible upstreams put the last reasoning token and the
first answer text in one stream chunk. The Chat to Claude Messages
stream converter emitted only the thinking delta for such a chunk and
dropped the text, so Claude clients lost the start of the answer.

Such a chunk now emits the thinking delta, closes the thinking block,
opens a text block and emits the text delta. Usage, stop reason and the
closing events are unchanged.

Refs #7664
2026-10-11 13:56:49 +08:00
CaIon 13c8e90b8f fix(relayconvert): send Responses image URLs to Chat upstreams as objects
A Responses input_image carries image_url as a string, while Chat
Completions defines image_url as an object with a url field. The
converter forwarded the string unchanged, so Chat upstreams that follow
the documented shape, such as vLLM and strict gateways, rejected
requests with images, for example Codex screenshots and images returned
by tools.

A string image_url is now wrapped as {"url": ...}. The detail beside it
is still left out, because Chat upstreams that validate it with older
OpenAI SDKs reject newer values such as "original". Object values and
file_id parts are unchanged.

Fixes #7578
2026-10-11 13:56:49 +08:00
CaIon 036ba376da fix(relaykit): match Claude effort and Gemini 2.5 budgets to each model
RelayKit sent some Claude effort levels that the target model does not
accept. A request with an effort but no thinking reached Opus 4.5 with
max or xhigh. Sonnet 4.5, Haiku 4.5 and other models without effort
support received an effort anyway. When a model-name suffix or modifier
turned thinking off, the client's output_config.effort stayed in the
request unchecked. Opus 5 and Haiku 5.5 then got disabled thinking at
xhigh or max, and Sonnet 5.5 got between_tools at those levels. The API
rejects these combinations with a 400.

Known Claude models now get the nearest effort level they accept, and no
effort when they accept none. Effort works without thinking, so a
thinking-off request keeps the client's effort within those limits. On
Opus 5, Haiku 5.5 and Sonnet 5.5 it is capped at high. Fable, Mythos
and Mythos Preview are now marked as taking effort. These models cannot
turn thinking off, so a thinking-off request runs them at low effort,
as Opus 5.5 already does. The new reasoning.ClaudeEffort returns the
effort a model accepts for a requested level. Native requests without a
suffix or modifier still pass through unchanged, and models RelayKit
does not know keep the effort they were sent.

Claude Haiku 5.5 joins the capability table: adaptive thinking only, on
by default, all five effort levels, and medium as the default effort.
Converted requests no longer send it manual thinking with budget_tokens,
which it rejects. They also drop temperature, top_p and top_k, which it
accepts only at their defaults.

Gemini 2.5 Pro takes thinking budgets up to 32768, but xhigh and max
were rendered as 24576. They now get the model's largest budget: 32768
on 2.5 Pro, and 24576 on 2.5 Flash and Flash-Lite as before. high stays
at 24576, as in Google's OpenAI-compatible mapping.
2026-10-11 12:42:17 +08:00
CaIon c6741c36a9 feat(channel): add a per-channel switch to skip upstream TLS verification
Until now only the global TLS_INSECURE_SKIP_VERIFY setting could accept a
self-signed upstream certificate. A channel's tls_insecure_skip_verify
setting now does it for that channel's API requests: relay and the Responses
and Realtime WebSocket dialer, task submission and polling, plugin fetches,
balance, usage and model-list queries, and media proxied through the channel
proxy. Credential exchanges (Codex OAuth refresh, Vertex and plugin
service-account tokens) keep verifying certificates. The channel drawer shows
the switch under the HTTP protocol settings.
2026-10-10 14:02:06 +08:00
CaIon 1d4328e974 docs(relaykit): rewrite README for the current conversion API
Describe the conversion result diagnostics and loss policy, the
reasoning-state handoff and thinking suffix parsing, hosted web search
and Responses custom tool handling, the usage and cache token fields,
the Responses stream failure and sequence_number options, the JSON
codec and logging hooks, and the full option list. Plain product-page
wording.
2026-10-09 22:59:20 +08:00
CaIon e0483122c7 fix(relayconvert): drop trailing assistant text from Responses input on Claude and Gemini
In Responses, assistant output at the end of input is history and the
model answers with a new item. Claude and Gemini continue a final
assistant turn as a prefill instead, and Claude 4.6 and later and Gemini
3.6 Flash, 3.5 Flash-Lite and later reject it with a 400. Codex sends
such input when it retries a stream that failed after an assistant
message completed: the retry is rebuilt from history, so the received
reasoning and answer end the input.

The Responses converters for Claude and Gemini now drop the assistant
turns without tool calls that follow the last user message or tool
result, and record a trailing_assistant_omitted warning. Input that ends
in a tool call still waiting for its result, or holds only assistant
turns, is sent unchanged. Chat and Messages requests keep their prefill.
2026-10-09 19:53:38 +08:00
CaIon bc82357929 test(relaykit): keep format-conversion tests out of the repository
Format-conversion tests for relaykit are maintained outside the
repository. Remove the conversion tests added in 78bd5b1cb (Gemini
tool-output media and the Opus 5.5 default effort) and c6bac617d
(thinking suffix aliases), and restore the tests those commits extended
to their earlier form. Usage tests such as dto/usage_merge_test.go
stay.
2026-10-08 18:04:56 +08:00
CaIon d10f11ffff feat(gemini): bill Google Search grounding per query or per grounded prompt
Gemini responses grounded with Google Search billed one google_search
call per response on every model. Google bills Gemini 3 per unique
search query ($14 per 1,000) and Gemini 2.5 and older per grounded
prompt ($35 per 1,000). A counter now collects the unique non-empty web
and image search queries across every stream frame and candidate of a
response. It records google_search as that query count and
google_search_grounded_prompt as one grounded prompt, and the tool price
table decides which of the two costs money for a model. The native
generateContent handler now counts grounding too. Google reports no
billed count in the response, so the unique query set is the best
available evidence, not a guaranteed match.

Built-in prices make queries free and grounded prompts $35 per 1,000 on
gemini-2.5*, gemini-2.0*, and gemini-1.5*; other models keep
google_search at $14 per query. Because built-in model-prefix prices
take precedence over a tool default, an operator's own google_search
price no longer applies to those older models; to keep search free
there, set google_search_grounded_prompt:gemini-2.5* (and the 2.0* and
1.5* keys) to 0.
2026-10-08 18:04:55 +08:00
Calcium-Ion acb347a197 feat(relay): web search encoding per channel and vendor-reported search billing (#7690)
* feat(channels): convert Claude and Gemini requests to OpenAI Responses on Advanced Custom channels

Advanced Custom channels could convert Claude Messages and Gemini
generateContent requests only to OpenAI Chat. Two converters,
claude_messages_to_openai_responses and
gemini_generate_content_to_openai_responses, now send them to an OpenAI
Responses upstream and convert the response back to the client's
format. The channel form offers them with the /v1/responses upstream
path and bearer auth by default, and the backend validates their
incoming paths like the existing converters. The IDs keep the values the
relay already uses for these conversions.

* feat(moonshot): forward Responses requests to Kimi unchanged

Moonshot channels answered /v1/responses with "not implemented". They
now forward the request body unchanged to {base}/v1/responses. Kimi
serves only kimi-k3 on that endpoint today; other models are rejected
by the upstream, not by the gateway.

* fix(relay): bill completed image_generation calls when a Responses request ends failed or incomplete

An image_generation call that completed before a response.failed,
response.incomplete, or cancelled terminal had already reached the
client, but the stream accumulator reset the image count to zero on
those terminals, and the non-stream handler skipped image outputs when
the response status was failed, cancelled, or incomplete. Completed
images now bill on every terminal, as they already did when the client
disconnected; image items that never completed still bill nothing.

* feat(relay): let channels encode hosted web search and bill vendor-reported search counts

Converted requests always encoded hosted web search the OpenAI way:
web_search_options on Chat and the native hosted tool on Responses,
Claude, and Gemini. Zhipu and DashScope compatible-mode Chat take their
own search fields, and the search counts that Azure, xAI, and DashScope
report in usage were ignored; only web_search_call items were billed.

relaykit gains a WebSearchEncoder option that a channel adaptor sets in
Init; without one, the default encodings stay. Zhipu sends the GLM
web_search tool with search_std, and Gemini clients on Zhipu now convert
through Chat. DashScope compatible-mode Chat sends enable_search and
search_options with the default turbo strategy and maps allowed domains
to assigned_site_list (up to 25 sites). DashScope Anthropic-compatible
requests that carry a web search tool get the cc_entrypoint system
marker DashScope requires before it searches. Zhipu and DashScope Chat
responses report no search usage, so a forced search bills one call,
which is dropped again if the request retries on another channel; a
Zhipu non-stream response that returns search results also bills one.
Several hosted web search definitions on a Chat target now drop the
extras with a diagnostic instead of failing the request.

Vendor-reported counts replace the counted web_search_call items under
the vendor's price key: Azure tool_usage.web_search.num_requests as
bing_web_search, xAI server_side_tool_usage_details (web_search_calls as
web_search, priced for grok models, plus x_search posts and profiles),
and DashScope usage.x_tools on Responses and server_tool_use on its
Anthropic endpoint as search_strategy_agent. Claude server_tool_use also
counts web_fetch, code_execution, and tool_search, which bill only once
an operator prices them. Tool names with a built-in price and these
Claude server tools are reserved, so a client function of the same name
is never billed under them. The Claude and Gemini search counts move
from gin context keys into the per-request tool counts, and every tool
count is capped at 10,000 at settlement.

Built-in prices are seeded for these keys in each vendor's list currency
(Zhipu and DashScope in CNY, Azure and xAI in USD) and listed on the
tool price settings page. DashScope Responses requests move to
/compatible-mode/v1/responses, because the old /api/v2/apps/protocols
endpoint is no longer maintained.
2026-10-07 23:29:24 +08:00