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.
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.
* 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>
* 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>
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
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.
* 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.
* 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.
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.
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.
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.
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.
* 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>
* 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>
* 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.
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.
* 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>
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
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.
* 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.
* 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.
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.
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
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.
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
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
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.
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.
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.
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.
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.
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.
* 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.