Skip to content

feat(zai): native Anthropic Messages and Responses API passthrough - #40106

Open
togear wants to merge 5 commits into
BerriAI:mainfrom
togear:feat/zai-native-anthropic-responses-passthrough
Open

togear wants to merge 5 commits into
BerriAI:mainfrom
togear:feat/zai-native-anthropic-responses-passthrough

Conversation

@togear

@togear togear commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Z.AI serves GLM-5.3 over native Anthropic Messages and OpenAI Responses endpoints
  • The zai/ provider only wired the OpenAI chat endpoint, so both proxy routes were chat-bridged
  • Chat bridging loses native Anthropic/Responses wire semantics (thinking signatures, native SSE shapes, native response ids)

How it solves it:

  • Adds a native Anthropic Messages config routing to https://api.z.ai/api/anthropic/v1/messages
  • Adds a native Responses config routing to https://api.z.ai/api/v1/responses
  • The Responses config ignores the chat-only bases (/api/paas/v4, /api/coding/paas/v4) that the generic resolver pre-fills, since Z.AI serves Responses on a different base
  • Registers both in ProviderConfigManager, mirroring the existing DeepSeek Anthropic-messages pattern
  • Both configs authenticate with ZAI_API_KEY (request key → Z.AI key → generic global key, in that order) and honor a per-deployment api_base

User Flow

Before: a Claude-protocol client pointed at the proxy with a Z.AI deployment gets a translated chat call, not the native Anthropic wire format

  1. The proxy admin adds a deployment with model zai/glm-5.3
  2. The client sends POST http://localhost:4000/v1/messages with an Anthropic Messages payload
  3. LiteLLM translates the request to OpenAI chat format and sends it to https://api.z.ai/api/paas/v4 (the Z.AI chat endpoint)
  4. The raw upstream response is a chat.completion object that LiteLLM converts back, so native Anthropic fields such as thinking signatures are absent ("signature": null)
  5. The client sends POST http://localhost:4000/v1/responses and gets the same chat bridge in reverse, with synthesized response ids instead of Z.AI's native ids

After: the same client's Anthropic and Responses traffic is forwarded to Z.AI's native protocol endpoints verbatim

  1. The proxy admin adds the same zai/glm-5.3 deployment (no config change needed)
  2. The client sends POST http://localhost:4000/v1/messages
  3. The request is forwarded natively to https://api.z.ai/api/anthropic/v1/messages with x-api-key auth and returns native Anthropic fields (thinking signature, server_tool_use, service_tier)
  4. The client sends POST http://localhost:4000/v1/responses
  5. The request is forwarded natively to https://api.z.ai/api/v1/responses with Authorization: Bearer auth and returns Z.AI-native response ids and reasoning output items
  6. POST /v1/chat/completions keeps its existing behavior and still reaches https://api.z.ai/api/paas/v4

Relevant issues

Fixes #43974

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/test_litellm/<your test file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Screenshots / Proof of Fix

Shared setup: one proxy, one deployment (model: zai/glm-5.3, no api_base override), ZAI_API_KEY from the environment, proxy master key sk-local-e2e-master-key. Base runs on port 4124, PR tip on port 4123. Upstream URLs below come from the proxy's detailed debug log (POST Request Sent from LiteLLM), so they show where each request actually went.

Before (eeb7732)

/v1/messages

  1. curl http://127.0.0.1:4124/v1/messages -H "Authorization: Bearer sk-local-e2e-master-key" -d '{"model":"glm-5.3","max_tokens":512,"messages":[{"role":"user","content":"Reply with exactly: before-messages-check"}]}'
  2. HTTP 200, but the debug log shows the upstream request went to https://api.z.ai/api/paas/v4/ and the RAW RESPONSE is an OpenAI chat.completion object
  3. The converted reply is Anthropic-shaped but the thinking block carries "signature": null

/v1/responses

  1. curl http://127.0.0.1:4124/v1/responses -H "Authorization: Bearer sk-local-e2e-master-key" -d '{"model":"glm-5.3","max_output_tokens":512,"input":"Reply with exactly: before-responses-check"}'
  2. HTTP 200, but the debug log shows the upstream request went to https://api.z.ai/api/paas/v4/ again
  3. The reply is a synthesized Responses object with LiteLLM-generated ids (rs_6d984630-..., msg_cf1f435f-...), not Z.AI's native response ids

After (1b19dea)

/v1/messages

  1. Same curl against port 4123
  2. HTTP 200; debug log shows POST Request Sent from LiteLLM: https://api.z.ai/api/anthropic/v1/messages
  3. Reply contains Z.AI-native Anthropic fields: a thinking block with a real "signature", "usage": {"input_tokens":22,"output_tokens":63,"cache_read_input_tokens":0,"server_tool_use":{"web_search_requests":0},"service_tier":"standard"}, "stop_reason":"end_turn"

/v1/responses

  1. Same curl against port 4123
  2. HTTP 200; debug log shows POST Request Sent from LiteLLM: https://api.z.ai/api/v1/responses
  3. Reply is a native Z.AI Responses object: "object":"response", a native reasoning output item ("id":"rs_20260907193329c66abe5b3f75454a"), a native message id ("id":"msg_20260907193329c66abe5b3f75454a"), and "usage":{"output_tokens":72,"output_tokens_details":{"reasoning_tokens":65}}

/v1/chat/completions (unchanged baseline)

  1. curl http://127.0.0.1:4123/v1/chat/completions -H "Authorization: Bearer sk-local-e2e-master-key" -d '{"model":"glm-5.3","max_tokens":512,"messages":[{"role":"user","content":"Reply with exactly: chat-completions-ok"}]}'
  2. HTTP 200 with a normal chat.completion; the debug log shows the upstream request still goes to https://api.z.ai/api/paas/v4/, so the existing chat route is untouched

Unit tests and gates

  1. uv run --no-sync pytest tests/test_litellm/llms/zai tests/test_litellm/llms/deepseek/messages -q
  2. Output: 28 passed in 15.46s
  3. uv run --no-sync python scripts/ruff_strict_gate.py --base bde58f9b415ad6e398f7813d668d4473e2621c3d
  4. Output: OK: every strict rule is within its codebase ceiling
  5. uv run --no-sync python scripts/type_discipline_gate.py --base bde58f9b415ad6e398f7813d668d4473e2621c3d
  6. Output: OK: every LIT rule is within its codebase ceiling
  7. uv run --no-sync ruff check ... && uv run --no-sync ruff format --check ... on the touched files: clean

Type

🆕 New Feature

Caveats (if any)

Low

  • A custom api_base is honored on both routes unless it is one of Z.AI's chat-only bases (/api/paas/v4, /api/coding/paas/v4), which are ignored on the Responses route because Z.AI serves Responses on a different base

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@togear
togear requested a review from a team September 7, 2026 10:45
@CLAassistant

CLAassistant commented Sep 7, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@greptile-apps

greptile-apps Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds native Z.AI routing for Anthropic Messages and OpenAI Responses requests while preserving the existing chat-completions path. It also installs the MongoDB optional dependency in proxy Docker images

  • Registers provider-specific Messages and Responses configurations
  • Adds native endpoint and authentication handling
  • Adds focused registry, URL, and header tests
  • Adds the MongoDB extra to four proxy image variants

Confidence Score: 3/5

This PR is not yet safe to merge because both native protocol paths can select or add the wrong authentication credential

The Responses path prioritizes the generic API key over ZAI_API_KEY, while the Messages path fails to recognize differently cased caller authentication headers. The new signatures also violate an explicit typing requirement

Files Needing Attention: litellm/llms/zai/messages/transformation.py, litellm/llms/zai/responses/transformation.py

Important Files Changed

Filename Overview
litellm/llms/zai/messages/transformation.py Adds native Anthropic Messages routing, but authentication-header matching is case-sensitive and signatures violate typing requirements
litellm/llms/zai/responses/transformation.py Adds native Responses routing, but generic API-key precedence can select the wrong provider credential
litellm/utils.py Registers both new Z.AI protocol configurations in ProviderConfigManager
tests/test_litellm/llms/zai/test_zai_anthropic_messages_transformation.py Covers registry, URL, defaults, and basic header behavior but not mixed-case caller authentication headers
tests/test_litellm/llms/zai/test_zai_responses_transformation.py Covers registry, URL, and isolated key fallback behavior but not coexistence with litellm.api_key
Dockerfile Installs the defined and locked MongoDB optional dependency in the primary proxy image
docker/Dockerfile.database Installs the MongoDB optional dependency in the database image
docker/Dockerfile.non_root Installs the MongoDB optional dependency in both non-root installation branches
gateway/Dockerfile Installs the MongoDB optional dependency in both gateway image stages

Reviews (1): Last reviewed commit: "feat(zai): native Anthropic Messages and..." | Re-trigger Greptile

) -> dict:
litellm_params = litellm_params or GenericLiteLLMParams()

api_key: Final = litellm_params.api_key or litellm.api_key or get_secret_str("ZAI_API_KEY")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Wrong API key precedence If both keys are set, litellm.api_key overrides ZAI_API_KEY, sending the wrong credential and causing Z.AI authentication failure

Suggested change
api_key: Final = litellm_params.api_key or litellm.api_key or get_secret_str("ZAI_API_KEY")
api_key: Final = litellm_params.api_key or get_secret_str("ZAI_API_KEY") or litellm.api_key

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 75ffe21: key resolution is now litellm_params.api_key → ZAI_API_KEY → generic litellm.api_key, so the provider-specific key is never shadowed by the global one. Added a regression test (test_zai_responses_headers_prefer_zai_key_over_global_key).

) -> tuple[dict, str | None]:
dynamic_api_key: Final = self.get_api_key(api_key=api_key)

if "x-api-key" not in headers and "authorization" not in headers and dynamic_api_key is not None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Authentication check is case-sensitive Title-case Authorization or X-Api-Key is missed, adding another credential and causing incorrect authentication or upstream rejection

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 75ffe21: the check now lowercases existing header names before looking for auth headers, so Authorization / X-Api-Key in any casing are respected and no second credential is injected. Added test_zai_anthropic_messages_respects_existing_case_insensitive_auth_headers.

Comment on lines +40 to +45
model: str,
messages: list[Any],
optional_params: dict,
litellm_params: dict,
api_key: str | None = None,
api_base: str | None = None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Parameters are not strongly typed These methods use bare dict and Any, violating the repository directive. This requirement must be satisfied before merging

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 75ffe21: typing.Any is removed and signatures now use concrete types (dict[str, str], list[dict[str, object]], dict[str, object]); the strict ruff gate (scripts/ruff_strict_gate.py) passes with zero added violations.

@codspeed

codspeed Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing togear:feat/zai-native-anthropic-responses-passthrough (234a4b6) with litellm_internal_staging (02522a5)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (168a005) during the generation of this report, so 02522a5 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@veria-ai

veria-ai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@codecov

codecov Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: zai/glm-5.3 /v1/messages and /v1/responses are bridged through Chat Completions instead of native Z.AI endpoints

3 participants