mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-25 22:20:43 +00:00
* fix(anthropic): send extra_body fields at the top level of the Messages request extra_body passed to litellm.completion for an Anthropic model reached the Messages API as a literal nested "extra_body" key, and Anthropic rejected the request with "extra_body: Extra inputs are not permitted". That blocked every Anthropic request field litellm doesn't model yet, including server-side fallbacks AnthropicConfig.transform_request now pops extra_body from the request params and merges its keys into the wire body. The direct Anthropic, Vertex AI and Azure paths all go through this transform. Paths on llm_http_handler, like Bedrock invoke, already pop extra_body before transform_request, so nothing is merged twice. extra_body only adds fields the request doesn't already have. It can't override anything litellm built, can't change the model (EXTRA_BODY_ROUTING_KEYS), and can't set messages or system, so content that pre-call guardrails checked or redacted is the content that is sent fallbacks is registered in BETA_GATED_FIELDS under both betas that unlock it, server-side-fallback-2026-07-01 and server-side-fallback-2026-06-01. Under drop_params a request that doesn't end up sending either of them, like a Vertex AI leg where the 07-01 beta is filtered out or a deployment without the header, drops fallbacks with a warning instead of getting a 400 The proxy rejects fallbacks inside a client's extra_body with a 400. Anthropic runs the fallback model itself, so those targets never reach the key's model access checks. Server-side fallback is set in the deployment's litellm_params instead, next to the beta header the admin already configures there When Anthropic serves a turn from a fallback model, usage.iterations spans models, so its entries are no longer summed. The top-level usage, which Anthropic documents as the attempt that served the turn, is priced at the response's model. Attempts that declined with a billed refusal category are not priced yet The regression tests drive litellm.completion end to end against a mock transport and assert the request body * fix(anthropic): never take tools from extra_body The proxy checks a key's or team's allowed tools against the request's top-level tools only. A tools list inside extra_body skipped that check and still reached Anthropic when the request had no top-level tools, so extra_body now never supplies tools, like messages and system. * fix(anthropic): keep every fallback attempt in usage Dropping usage.iterations for a server-side fallback chain left only the serving attempt in spend, so billed refusals on earlier attempts escaped key and team budgets. Usage is back to adding up every attempt, which can overcount but never lets billed tokens escape. #50556 prices each attempt at its own model's rate. * fix(proxy): reject fallbacks inside a fallback target's extra_body A litellm fallback target can carry its own extra_body, which the router merges into the request when that target runs. The proxy only rejected fallbacks in the request's own extra_body, so a target's extra_body could still pick Anthropic server-side fallback models the key isn't allowed to use. Every fallback target's extra_body now gets the same check. * test(anthropic): type the extra_body request test * fix(anthropic): let extra_body override defaults on every Claude route and admit client fallbacks through the admin opt-ins extra_body now wins over fields litellm set, so its max_tokens takes effect, while model, messages, system, tools, and stream stay litellm's on anthropic/, azure_ai, and Bedrock invoke. A non-object extra_body answers 400 instead of a retried 500. Bedrock invoke drops extra_body fallbacks under drop_params without a fallback beta, like anthropic/. Client extra_body fallbacks go through the banned-param opt-ins (allow_client_side_credentials or configurable_clientside_auth_params) * fix(anthropic): let extra_body lower max_tokens but never raise it past the request's cap The rate limiter reserves output tokens from the top-level max_tokens, so an extra_body max_tokens above it would spend tokens the limiter never reserved. * fix(anthropic): answer 400 for extra_body keys litellm builds unless drop_params is on Setting model, messages, system, tools or stream in extra_body now answers 400 naming them, or drops them under drop_params, on anthropic/, Vertex AI, Azure AI and Bedrock invoke Claude. Databricks keeps sending extra_body as it is, and a non-object extra_body error is returned as a value * fix(vertex_ai): apply the batch row's drop_params to its extra_body A Claude batch row's extra_body merge got an empty litellm_params, so drop_params set on the row or deployment never reached the extra_body rule and a field litellm builds answered 400 instead of being dropped * fix(anthropic): add the beta headers a field sent in extra_body needs A field like context_management sent in extra_body reached Anthropic at the top level without the anthropic-beta header that the same top-level field gets, so Anthropic answered 400. The extra_body fields litellm forwards now count toward the beta headers too * fix(anthropic): answer 400 for a raised extra_body max_tokens and promote system on Azure AI and OpenCode Go An extra_body max_tokens above the request's answers 400 unless drop_params is on, which caps it, so the output tokens the limiters reserved still bound the call. Keys litellm builds that extra_body tries to set are dropped with a warning under drop_params. Azure AI and OpenCode Go send extra_body.system as the system prompt, since litellm moves a top-level system kwarg there. extra_body output_config now wins over the mapped one, and transform_request no longer pops extra_body from the caller's optional_params. * fix(bedrock): keep the extra_body guard on Bedrock Mantle without the invoke beta strip Bedrock Mantle inherits the Bedrock invoke extra_body guard. The invoke strip reads betas from the body's anthropic_beta list, which a Mantle body never carries, so under drop_params it dropped beta-gated thinking fields the client sent. Mantle now runs the Anthropic guard alone, the same way its own request path skips the strip The internal-params wire test now reads the custom key at the top level on anthropic/, where extra_body fields go after this change --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
893 lines
37 KiB
Python
893 lines
37 KiB
Python
import asyncio
|
|
import json
|
|
from collections.abc import AsyncIterator, Iterator, Mapping
|
|
from datetime import datetime
|
|
from typing import Final, cast
|
|
|
|
import httpx
|
|
import pytest
|
|
import respx
|
|
from pydantic import TypeAdapter
|
|
|
|
import litellm
|
|
from litellm.integrations.custom_logger import CustomLogger
|
|
from litellm.litellm_core_utils.core_helpers import RESPONSE_COST_HEADER
|
|
from litellm.litellm_core_utils.litellm_logging import Logging
|
|
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
|
|
from litellm.llms.opencode.chat.transformation import OpenCodeGoMessagesChatConfig
|
|
from litellm.llms.opencode.common_utils import go_headers
|
|
from litellm.types.utils import ModelResponseStream
|
|
|
|
|
|
def _messages_sse(
|
|
tool: bool,
|
|
usage: Mapping[str, object] | None = None,
|
|
usage_at_start: bool = False,
|
|
tool_name: str = "weather",
|
|
arguments: str = '{"city":"Paris"}',
|
|
) -> tuple[str, ...]:
|
|
block: Final = (
|
|
{"type": "tool_use", "id": "call_test", "name": tool_name, "input": {}}
|
|
if tool
|
|
else {"type": "text", "text": ""}
|
|
)
|
|
delta: Final = (
|
|
{"type": "input_json_delta", "partial_json": arguments}
|
|
if tool
|
|
else {"type": "text_delta", "text": "hello"}
|
|
)
|
|
events: Final = (
|
|
{
|
|
"type": "message_start",
|
|
"message": {
|
|
"id": "msg_test",
|
|
"type": "message",
|
|
"role": "assistant",
|
|
"model": "fixture-messages",
|
|
"content": [],
|
|
"usage": {"input_tokens": 10, "output_tokens": 0, **((usage or {}) if usage_at_start else {})},
|
|
},
|
|
},
|
|
{"type": "content_block_start", "index": 0, "content_block": block},
|
|
{"type": "content_block_delta", "index": 0, "delta": delta},
|
|
{"type": "content_block_stop", "index": 0},
|
|
{
|
|
"type": "message_delta",
|
|
"delta": {"stop_reason": "tool_use" if tool else "end_turn"},
|
|
"usage": {"output_tokens": 5, **((usage or {}) if not usage_at_start else {})},
|
|
},
|
|
{"type": "message_stop"},
|
|
)
|
|
return tuple(f"data: {json.dumps(event)}" for event in events)
|
|
|
|
|
|
async def _async_lines(lines: tuple[str, ...]) -> AsyncIterator[str]:
|
|
for line in lines:
|
|
yield line
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("sync", (True, False), ids=("sync", "async"))
|
|
@pytest.mark.parametrize("tool", (False, True), ids=("text", "tool"))
|
|
async def test_messages_stream_translates_deltas_and_finish_reason(sync: bool, tool: bool) -> None:
|
|
lines: Final = _messages_sse(tool)
|
|
stream: Final = OpenCodeGoMessagesChatConfig().get_model_response_iterator_for_request(
|
|
iter(lines) if sync else _async_lines(lines), sync, False, {}
|
|
)
|
|
chunks: Final = (
|
|
tuple(cast(Iterator[ModelResponseStream], stream))
|
|
if sync
|
|
else tuple([chunk async for chunk in cast(AsyncIterator[ModelResponseStream], stream)])
|
|
)
|
|
choices: Final = tuple(chunk.choices[0] for chunk in chunks if chunk.choices)
|
|
assert tuple(choice.finish_reason for choice in choices if choice.finish_reason) == (
|
|
"tool_calls" if tool else "stop",
|
|
)
|
|
if not tool:
|
|
assert "".join(choice.delta.content or "" for choice in choices) == "hello"
|
|
return
|
|
calls: Final = tuple(choice.delta.tool_calls for choice in choices if choice.delta.tool_calls)
|
|
assert calls[0][0].id == "call_test"
|
|
assert calls[0][0].function.name == "weather"
|
|
assert "".join(call[0].function.arguments or "" for call in calls) == '{"city":"Paris"}'
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("sync", (True, False), ids=("sync", "async"))
|
|
@pytest.mark.parametrize("valid_schema", (True, False, None), ids=("schema", "invalid-tools", "no-tools"))
|
|
async def test_messages_json_stream_uses_request_schema(sync: bool, valid_schema: bool | None) -> None:
|
|
answer: Final = {"city": "Paris"}
|
|
arguments: Final = json.dumps({"name": "json_tool_call", "parameters": answer}) if valid_schema else json.dumps(answer)
|
|
lines: Final = _messages_sse(True, tool_name="json_tool_call", arguments=arguments)
|
|
schema: Final = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
|
|
tools: Final = [{"name": "json_tool_call", "input_schema": schema}] if valid_schema else "invalid"
|
|
stream: Final = OpenCodeGoMessagesChatConfig().get_model_response_iterator_for_request(
|
|
iter(lines) if sync else _async_lines(lines), sync, True, {"tools": tools} if valid_schema is not None else {}
|
|
)
|
|
chunks: Final = (
|
|
tuple(cast(Iterator[ModelResponseStream], stream))
|
|
if sync
|
|
else tuple([chunk async for chunk in cast(AsyncIterator[ModelResponseStream], stream)])
|
|
)
|
|
choices: Final = tuple(chunk.choices[0] for chunk in chunks if chunk.choices)
|
|
assert json.loads("".join(choice.delta.content or "" for choice in choices)) == answer
|
|
assert not any(choice.delta.tool_calls for choice in choices)
|
|
assert tuple(choice.finish_reason for choice in choices if choice.finish_reason) == ("stop",)
|
|
|
|
|
|
class _MessagesStream(httpx.SyncByteStream, httpx.AsyncByteStream):
|
|
def __init__(self, body: bytes) -> None:
|
|
self.body = body
|
|
self.closed = False
|
|
|
|
def __iter__(self) -> Iterator[bytes]:
|
|
yield self.body
|
|
|
|
async def __aiter__(self) -> AsyncIterator[bytes]:
|
|
yield self.body
|
|
|
|
def close(self) -> None:
|
|
self.closed = True
|
|
|
|
async def aclose(self) -> None:
|
|
self.closed = True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("mode", ("sync", "async", "async-close-sync"))
|
|
async def test_closing_messages_stream_releases_upstream_response(go_catalog: None, mode: str) -> None:
|
|
upstream: Final = _MessagesStream(("\n\n".join(_messages_sse(False)) + "\n\n").encode())
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post().mock(
|
|
return_value=httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=upstream)
|
|
)
|
|
kwargs: Final = {
|
|
"model": "opencode_go/fixture-messages",
|
|
"api_key": "fake-go-key",
|
|
"messages": [{"role": "user", "content": "hello"}],
|
|
"stream": True,
|
|
}
|
|
if mode != "async":
|
|
stream: Final = litellm.completion(**kwargs)
|
|
next(stream)
|
|
assert not upstream.closed
|
|
if mode == "sync":
|
|
stream.close()
|
|
else:
|
|
await stream.aclose()
|
|
else:
|
|
async_stream: Final = await litellm.acompletion(**kwargs)
|
|
await async_stream.__anext__()
|
|
assert not upstream.closed
|
|
await async_stream.aclose()
|
|
assert upstream.closed
|
|
|
|
|
|
@pytest.fixture
|
|
def go_catalog(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
for route in ("chat/completions", "messages", "responses", "gemini"):
|
|
monkeypatch.setitem(
|
|
litellm.model_cost,
|
|
f"opencode_go/fixture-{route.split('/')[0]}",
|
|
{
|
|
"litellm_provider": "opencode_go",
|
|
"mode": "responses" if route == "responses" else "chat",
|
|
"supported_endpoints": ["/v1beta/models" if route == "gemini" else f"/v1/{route}"],
|
|
"max_output_tokens": 128000,
|
|
"max_input_tokens": 1000000,
|
|
"input_cost_per_token": 0.000002,
|
|
"output_cost_per_token": 0.000005,
|
|
"supports_function_calling": True,
|
|
},
|
|
)
|
|
monkeypatch.delenv("OPENCODE_GO_API_BASE", raising=False)
|
|
|
|
|
|
def upstream_reply(route: str, model: str) -> Mapping[str, object]:
|
|
if route == "gemini":
|
|
return {
|
|
"candidates": [{"content": {"role": "model", "parts": [{"text": "hello"}]}, "finishReason": "STOP"}],
|
|
"usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5, "totalTokenCount": 15},
|
|
}
|
|
if route == "messages":
|
|
return {
|
|
"id": "msg_test",
|
|
"type": "message",
|
|
"role": "assistant",
|
|
"model": model,
|
|
"content": [{"type": "text", "text": "hello"}],
|
|
"stop_reason": "end_turn",
|
|
"usage": {"input_tokens": 10, "output_tokens": 5},
|
|
}
|
|
if route == "responses":
|
|
return {
|
|
"id": "resp_test",
|
|
"object": "response",
|
|
"created_at": 1700000000,
|
|
"model": model,
|
|
"status": "completed",
|
|
"output": [
|
|
{
|
|
"type": "message",
|
|
"id": "msg_test",
|
|
"status": "completed",
|
|
"role": "assistant",
|
|
"content": [{"type": "output_text", "text": "hello", "annotations": []}],
|
|
}
|
|
],
|
|
"usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15},
|
|
}
|
|
return {
|
|
"id": "chatcmpl-test",
|
|
"object": "chat.completion",
|
|
"created": 1700000000,
|
|
"model": model,
|
|
"choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "hello"}}],
|
|
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
|
}
|
|
|
|
|
|
@pytest.fixture
|
|
def reasoning_catalog(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setitem(
|
|
litellm.model_cost,
|
|
"opencode_go/fixture-reasoning",
|
|
{
|
|
"litellm_provider": "opencode_go",
|
|
"mode": "chat",
|
|
"supported_endpoints": ["/v1/chat/completions"],
|
|
"supports_reasoning": True,
|
|
},
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("effort", ("none", "low", "medium", "high"))
|
|
@pytest.mark.parametrize("drop_params", (True, False))
|
|
async def test_chat_reasoning_effort_forwarded_regression(
|
|
reasoning_catalog: None, effort: str, drop_params: bool
|
|
) -> None:
|
|
def respond(request: httpx.Request) -> httpx.Response:
|
|
assert request.url.path.endswith("/chat/completions")
|
|
assert request.headers["authorization"] == "Bearer synthetic-go-key"
|
|
assert json.loads(request.content).get("reasoning_effort") == effort
|
|
return httpx.Response(200, json=upstream_reply("chat/completions", "fixture-reasoning"))
|
|
|
|
with respx.mock(using="httpx") as transport:
|
|
route: Final = transport.post().mock(side_effect=respond)
|
|
response: Final = await litellm.acompletion(
|
|
model="opencode_go/fixture-reasoning",
|
|
messages=[{"role": "user", "content": "hello"}],
|
|
api_key="synthetic-go-key",
|
|
reasoning_effort=effort,
|
|
drop_params=drop_params,
|
|
)
|
|
assert route.called
|
|
assert response.choices[0].message.content == "hello"
|
|
assert response.choices[0].finish_reason == "stop"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("drop_params", (True, False))
|
|
async def test_unknown_chat_reasoning_effort_guard(drop_params: bool) -> None:
|
|
def respond(request: httpx.Request) -> httpx.Response:
|
|
assert request.url.path.endswith("/chat/completions")
|
|
assert "reasoning_effort" not in json.loads(request.content)
|
|
return httpx.Response(200, json=upstream_reply("chat/completions", "not-in-catalog-x"))
|
|
|
|
with respx.mock(using="httpx", assert_all_called=drop_params) as transport:
|
|
route: Final = transport.post().mock(side_effect=respond)
|
|
if not drop_params:
|
|
with pytest.raises(litellm.UnsupportedParamsError, match="reasoning_effort"):
|
|
await litellm.acompletion(
|
|
model="opencode_go/not-in-catalog-x", messages=[{"role": "user", "content": "hello"}],
|
|
api_key="synthetic-go-key", reasoning_effort="high", drop_params=False,
|
|
)
|
|
assert not route.called
|
|
return
|
|
response: Final = await litellm.acompletion(
|
|
model="opencode_go/not-in-catalog-x", messages=[{"role": "user", "content": "hello"}],
|
|
api_key="synthetic-go-key", reasoning_effort="high", drop_params=True,
|
|
)
|
|
assert route.called
|
|
assert response.choices[0].message.content == "hello"
|
|
|
|
|
|
def test_chat_supported_reasoning_params_regression(reasoning_catalog: None, go_catalog: None) -> None:
|
|
base: Final = frozenset(litellm.get_supported_openai_params(model="opencode_go/fixture-chat") or ())
|
|
supported: Final = frozenset(litellm.get_supported_openai_params(model="opencode_go/fixture-reasoning") or ())
|
|
assert "reasoning_effort" not in base
|
|
assert supported == base | {"reasoning_effort"}
|
|
|
|
|
|
def test_unknown_chat_supported_params_guard(go_catalog: None) -> None:
|
|
base: Final = frozenset(litellm.get_supported_openai_params(model="opencode_go/fixture-chat") or ())
|
|
supported: Final = frozenset(litellm.get_supported_openai_params(model="opencode_go/not-in-catalog-x") or ())
|
|
assert "reasoning_effort" not in supported
|
|
assert supported == base
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("upstream", ["chat/completions", "messages", "responses", "gemini"])
|
|
@pytest.mark.parametrize("ingress", ["chat", "responses", "messages"])
|
|
async def test_all_routes_use_model_protocol_and_preserve_session(
|
|
go_catalog: None, upstream: str, ingress: str
|
|
) -> None:
|
|
model: Final = f"fixture-{upstream.split('/')[0]}"
|
|
|
|
def respond(request: httpx.Request) -> httpx.Response:
|
|
family: Final = "anthropic" if upstream == "messages" else "openai"
|
|
expected_path: Final = (
|
|
f"/inference/go/google/v1beta/models/{model}:generateContent"
|
|
if upstream == "gemini"
|
|
else f"/inference/go/{family}/v1/{upstream}"
|
|
)
|
|
assert request.url.path == expected_path
|
|
assert request.headers["authorization"] == "Bearer fake-go-key"
|
|
assert request.headers["x-opencode-session"] == "conversation-1"
|
|
body: Final = json.loads(request.content)
|
|
if upstream == "gemini":
|
|
assert body["contents"][0]["parts"][0]["text"] == "hello"
|
|
else:
|
|
assert body["model"] == model
|
|
assert "input" in body if upstream == "responses" else "messages" in body
|
|
if upstream == "messages":
|
|
assert body["max_tokens"] == 128000
|
|
return httpx.Response(200, json=upstream_reply(upstream, model))
|
|
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post().mock(side_effect=respond)
|
|
kwargs: Final = {
|
|
"model": f"opencode_go/{model}",
|
|
"api_key": "fake-go-key",
|
|
"litellm_session_id": "conversation-1",
|
|
}
|
|
if ingress == "chat":
|
|
response: Final = await litellm.acompletion(messages=[{"role": "user", "content": "hello"}], **kwargs)
|
|
assert response.choices[0].message.content == "hello"
|
|
assert response.usage.total_tokens == 15
|
|
elif ingress == "responses":
|
|
response_api: Final = await litellm.aresponses(input="hello", **kwargs)
|
|
assert response_api.output[0].content[0].text == "hello"
|
|
assert response_api.usage.total_tokens == 15
|
|
else:
|
|
message: Final = await litellm.anthropic.messages.acreate(
|
|
messages=[{"role": "user", "content": "hello"}],
|
|
max_tokens=128000,
|
|
**kwargs,
|
|
)
|
|
assert message["content"][0]["text"] == "hello"
|
|
assert message["usage"]["output_tokens"] == 5
|
|
|
|
|
|
def test_go_never_falls_back_to_other_provider_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.delenv("OPENCODE_API_KEY", raising=False)
|
|
monkeypatch.delenv("OPENCODE_GO_API_KEY", raising=False)
|
|
monkeypatch.setenv("OPENAI_API_KEY", "fake-openai-key")
|
|
monkeypatch.setenv("ANTHROPIC_API_KEY", "fake-anthropic-key")
|
|
with pytest.raises(litellm.AuthenticationError, match="OPENCODE_API_KEY"):
|
|
go_headers({}, {}, None, "fixture-model")
|
|
|
|
|
|
@pytest.mark.parametrize("input_tokens,expected", [(100, 0.00025), (101, 0.000504)])
|
|
def test_go_uses_registered_context_tiers_not_underlying_provider_prices(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
input_tokens: int,
|
|
expected: float,
|
|
) -> None:
|
|
monkeypatch.setitem(
|
|
litellm.model_cost,
|
|
"opencode_go/fixture-priced",
|
|
{
|
|
"litellm_provider": "opencode_go",
|
|
"mode": "chat",
|
|
"input_cost_per_token": 0.000002,
|
|
"output_cost_per_token": 0.000005,
|
|
"tiered_pricing": [
|
|
{"range": [0, 100], "input_cost_per_token": 0.000002, "output_cost_per_token": 0.000005},
|
|
{"range": [100, 1000], "input_cost_per_token": 0.000004, "output_cost_per_token": 0.000010},
|
|
],
|
|
},
|
|
)
|
|
cost: Final = litellm.cost_per_token(
|
|
model="opencode_go/fixture-priced",
|
|
prompt_tokens=input_tokens,
|
|
completion_tokens=10,
|
|
)
|
|
assert sum(cost) == pytest.approx(expected)
|
|
|
|
|
|
@pytest.mark.parametrize("suffix", ["", "/v1", "/v1/messages", "/v1/messages/"])
|
|
def test_messages_custom_base_does_not_duplicate_version_or_route(go_catalog: None, suffix: str) -> None:
|
|
from litellm.llms.opencode.messages.transformation import OpenCodeGoMessagesConfig
|
|
|
|
assert (
|
|
OpenCodeGoMessagesConfig().get_complete_url(
|
|
f"https://gateway.example/go{suffix}",
|
|
None,
|
|
"fixture-messages",
|
|
{},
|
|
{},
|
|
)
|
|
== "https://gateway.example/go/v1/messages"
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("base", [None, "https://gateway.example/go/v1"])
|
|
def test_discovery_returns_qualified_ids_and_accepts_response_metadata(base: str | None) -> None:
|
|
url: Final = "https://gateway.example/go/v1/models" if base else "https://opencode.ai/inference/go/v1/models"
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.get(url).respond(
|
|
json={
|
|
"object": "list",
|
|
"data": [
|
|
{"id": "fixture-chat", "object": "model"},
|
|
{"id": "fixture-messages", "object": "model"},
|
|
],
|
|
}
|
|
)
|
|
assert litellm.get_valid_models(
|
|
check_provider_endpoint=True,
|
|
custom_llm_provider="opencode_go",
|
|
api_key="fake-go-key",
|
|
api_base=base,
|
|
) == [
|
|
"opencode_go/fixture-chat",
|
|
"opencode_go/fixture-messages",
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("explicit_base", [None, "https://explicit-gateway.example/go/v1"])
|
|
def test_discovery_honors_environment_base_and_explicit_override(
|
|
monkeypatch: pytest.MonkeyPatch, explicit_base: str | None
|
|
) -> None:
|
|
from litellm.llms.opencode.chat.transformation import OpenCodeGoChatConfig
|
|
|
|
monkeypatch.setenv("OPENCODE_GO_API_BASE", "https://env-gateway.example/go/v1/")
|
|
expected_base: Final = explicit_base or "https://env-gateway.example/go/v1"
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.get(f"{expected_base}/models").respond(json={"data": [{"id": "gateway-only-model"}]})
|
|
assert OpenCodeGoChatConfig().get_models(api_key="fake-go-key", api_base=explicit_base) == [
|
|
"opencode_go/gateway-only-model"
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("ingress", ["chat", "responses", "messages"])
|
|
async def test_gemini_streams_text_and_usage_through_all_routes(go_catalog: None, ingress: str) -> None:
|
|
def respond(request: httpx.Request) -> httpx.Response:
|
|
assert request.url.path == "/inference/go/google/v1beta/models/fixture-gemini:streamGenerateContent"
|
|
assert request.url.query == b"alt=sse"
|
|
assert "stream" not in json.loads(request.content)
|
|
return httpx.Response(
|
|
200,
|
|
headers={"content-type": "text/event-stream"},
|
|
text="data: " + json.dumps(upstream_reply("gemini", "fixture-gemini")) + "\n\n",
|
|
)
|
|
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post().mock(side_effect=respond)
|
|
kwargs: Final = {"model": "opencode_go/fixture-gemini", "api_key": "fake-go-key", "stream": True}
|
|
if ingress == "chat":
|
|
stream: Final = await litellm.acompletion(
|
|
messages=[{"role": "user", "content": "hello"}], stream_options={"include_usage": True}, **kwargs
|
|
)
|
|
chunks: Final = [chunk async for chunk in stream]
|
|
assert "".join(chunk.choices[0].delta.content or "" for chunk in chunks if chunk.choices) == "hello"
|
|
assert chunks[-1].usage.total_tokens == 15
|
|
elif ingress == "responses":
|
|
responses_stream: Final = await litellm.aresponses(input="hello", **kwargs)
|
|
events: Final = [event async for event in responses_stream]
|
|
assert "".join(event.delta for event in events if event.type == "response.output_text.delta") == "hello"
|
|
assert events[-1].response.usage.total_tokens == 15
|
|
else:
|
|
messages_stream: Final = await litellm.anthropic.messages.acreate(
|
|
messages=[{"role": "user", "content": "hello"}], max_tokens=128000, **kwargs
|
|
)
|
|
wire_events: Final = b"".join([event async for event in messages_stream]).decode()
|
|
message_events: Final = [
|
|
json.loads(line[6:]) for line in wire_events.splitlines() if line.startswith("data: ")
|
|
]
|
|
assert (
|
|
"".join(
|
|
event["delta"].get("text", "") for event in message_events if event["type"] == "content_block_delta"
|
|
)
|
|
== "hello"
|
|
)
|
|
assert (
|
|
next(event["usage"]["output_tokens"] for event in message_events if event["type"] == "message_delta")
|
|
== 5
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("factory_path", [False, True])
|
|
@pytest.mark.parametrize("async_stream", [False, True])
|
|
async def test_gemini_streams_with_dispatcher_and_factory_configs(
|
|
go_catalog: None, factory_path: bool, async_stream: bool
|
|
) -> None:
|
|
messages: Final = [{"role": "user", "content": "hello"}]
|
|
logging_obj: Final = Logging(
|
|
model="fixture-gemini",
|
|
messages=messages,
|
|
stream=True,
|
|
call_type="acompletion" if async_stream else "completion",
|
|
start_time=datetime(2026, 1, 1),
|
|
litellm_call_id="go-stream-regression",
|
|
function_id="go-stream-regression",
|
|
)
|
|
logging_obj.update_environment_variables(
|
|
model="fixture-gemini",
|
|
user="",
|
|
optional_params={"stream_options": {"include_usage": True}},
|
|
litellm_params={},
|
|
custom_llm_provider="opencode_go",
|
|
stream_options={"include_usage": True},
|
|
)
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post(
|
|
"https://opencode.ai/inference/go/google/v1beta/models/fixture-gemini:streamGenerateContent?alt=sse"
|
|
).respond(
|
|
headers={"content-type": "text/event-stream"},
|
|
text="data: " + json.dumps(upstream_reply("gemini", "fixture-gemini")) + "\n\n",
|
|
)
|
|
if factory_path:
|
|
result: Final = BaseLLMHTTPHandler().completion(
|
|
model="fixture-gemini",
|
|
messages=messages,
|
|
api_base=None,
|
|
custom_llm_provider="opencode_go",
|
|
model_response=litellm.ModelResponse(),
|
|
encoding=None,
|
|
logging_obj=logging_obj,
|
|
optional_params={"stream_options": {"include_usage": True}},
|
|
timeout=30,
|
|
litellm_params={},
|
|
acompletion=async_stream,
|
|
stream=True,
|
|
api_key="fake-go-key",
|
|
)
|
|
else:
|
|
completion: Final = litellm.acompletion if async_stream else litellm.completion
|
|
result: Final = completion(
|
|
model="opencode_go/fixture-gemini",
|
|
messages=messages,
|
|
stream=True,
|
|
stream_options={"include_usage": True},
|
|
api_key="fake-go-key",
|
|
)
|
|
if async_stream:
|
|
stream: Final = await result
|
|
chunks: Final = [chunk async for chunk in stream]
|
|
else:
|
|
chunks: Final = tuple(result)
|
|
assert "".join(chunk.choices[0].delta.content or "" for chunk in chunks if chunk.choices) == "hello"
|
|
assert chunks[-1].usage.total_tokens == 15
|
|
|
|
|
|
@pytest.mark.parametrize("suffix", ["", "/v1beta", "/v1beta/models", "/v1beta/models/"])
|
|
def test_gemini_custom_base_normalizes_version_and_models(go_catalog: None, suffix: str) -> None:
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post("https://gateway.example/google/v1beta/models/fixture-gemini:generateContent").respond(
|
|
json=upstream_reply("gemini", "fixture-gemini")
|
|
)
|
|
response: Final = litellm.completion(
|
|
model="opencode_go/fixture-gemini",
|
|
api_key="fake-go-key",
|
|
api_base=f"https://gateway.example/google{suffix}",
|
|
messages=[{"role": "user", "content": "hello"}],
|
|
)
|
|
assert response.choices[0].message.content == "hello"
|
|
|
|
|
|
def test_gemini_hosted_mcp_error_names_the_opencode_go_route(go_catalog: None) -> None:
|
|
with pytest.raises(litellm.UnsupportedParamsError, match="fixture-gemini on opencode_go cannot run"):
|
|
litellm.completion(
|
|
model="opencode_go/fixture-gemini",
|
|
api_key="fake-go-key",
|
|
api_base="https://gateway.example/google",
|
|
messages=[{"role": "user", "content": "hello"}],
|
|
tools=[{"type": "mcp", "server_label": "deepwiki", "server_url": "https://mcp.deepwiki.com/mcp"}],
|
|
)
|
|
|
|
|
|
def test_gemini_sync_stream_preserves_tool_calls_and_usage(go_catalog: None) -> None:
|
|
chunk: Final = {
|
|
"candidates": [
|
|
{
|
|
"content": {
|
|
"role": "model",
|
|
"parts": [
|
|
{
|
|
"functionCall": {"name": "get_weather", "args": {"city": "Paris"}},
|
|
"thoughtSignature": "synthetic-signature",
|
|
}
|
|
],
|
|
},
|
|
"finishReason": "STOP",
|
|
}
|
|
],
|
|
"usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5, "totalTokenCount": 15},
|
|
}
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post(
|
|
"https://opencode.ai/inference/go/google/v1beta/models/fixture-gemini:streamGenerateContent?alt=sse"
|
|
).respond(headers={"content-type": "text/event-stream"}, text="data: " + json.dumps(chunk) + "\n\n")
|
|
stream: Final = litellm.completion(
|
|
model="opencode_go/fixture-gemini",
|
|
api_key="fake-go-key",
|
|
stream=True,
|
|
messages=[{"role": "user", "content": "Weather in Paris?"}],
|
|
tools=[
|
|
{
|
|
"type": "function",
|
|
"function": {
|
|
"name": "get_weather",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {"city": {"type": "string"}},
|
|
"required": ["city"],
|
|
},
|
|
},
|
|
}
|
|
],
|
|
stream_options={"include_usage": True},
|
|
)
|
|
chunks: Final = tuple(stream)
|
|
tool: Final = next(
|
|
c.choices[0].delta.tool_calls[0] for c in chunks if c.choices and c.choices[0].delta.tool_calls
|
|
)
|
|
assert tool.function.name == "get_weather"
|
|
assert json.loads(tool.function.arguments) == {"city": "Paris"}
|
|
assert any(c.choices[0].finish_reason == "tool_calls" for c in chunks if c.choices)
|
|
assert chunks[-1].usage.total_tokens == 15
|
|
|
|
|
|
GO_REPORTED_USAGE: Final = {
|
|
"cost": 0,
|
|
"opencode": {"billing_source": "go", "list_cost": 0.00412, "allowance": 0.00412},
|
|
}
|
|
ROW_PRICE_FOR_FIXTURE_USAGE: Final = 10 * 0.000002 + 5 * 0.000005
|
|
|
|
|
|
def go_priced_reply(route: str, model: str, usage_extra: Mapping[str, object]) -> Mapping[str, object]:
|
|
reply: Final = upstream_reply(route, model)
|
|
key: Final = "usageMetadata" if route == "gemini" else "usage"
|
|
usage: Final = TypeAdapter(Mapping[str, object]).validate_python(reply[key])
|
|
return {**reply, key: {**usage, **usage_extra}}
|
|
|
|
|
|
class CostRecorder(CustomLogger):
|
|
def __init__(self) -> None:
|
|
super().__init__()
|
|
self.costs: list[float | None] = [] # mutable-ok: test probe accumulates logged costs
|
|
|
|
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time) -> None: # noqa: ANN001
|
|
self.costs.append(kwargs.get("response_cost"))
|
|
|
|
def log_success_event(
|
|
self, kwargs: Mapping[str, object], response_obj: object, start_time: datetime, end_time: datetime
|
|
) -> None:
|
|
self.costs.append(TypeAdapter(float | None).validate_python(kwargs.get("response_cost")))
|
|
|
|
|
|
async def logged_cost(recorder: CostRecorder) -> float | None:
|
|
for _ in range(50):
|
|
if recorder.costs:
|
|
return recorder.costs[-1]
|
|
await asyncio.sleep(0.05)
|
|
raise AssertionError("success callback never ran")
|
|
|
|
|
|
@pytest.fixture
|
|
def cost_recorder(monkeypatch: pytest.MonkeyPatch) -> CostRecorder:
|
|
recorder: Final = CostRecorder()
|
|
monkeypatch.setattr(litellm, "callbacks", [recorder])
|
|
return recorder
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("usage_extra", [{}, {"cost": 0}, {"opencode": {"billing_source": "go"}}])
|
|
async def test_rows_price_the_request_when_no_list_cost_is_reported(
|
|
go_catalog: None, cost_recorder: CostRecorder, usage_extra: Mapping[str, object]
|
|
) -> None:
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post().mock(
|
|
return_value=httpx.Response(200, json=go_priced_reply("chat/completions", "fixture-chat", usage_extra))
|
|
)
|
|
response: Final = await litellm.acompletion(
|
|
model="opencode_go/fixture-chat", api_key="fake-go-key", messages=[{"role": "user", "content": "hello"}]
|
|
)
|
|
assert RESPONSE_COST_HEADER not in response._hidden_params.get("additional_headers", {})
|
|
assert await logged_cost(cost_recorder) == pytest.approx(ROW_PRICE_FOR_FIXTURE_USAGE)
|
|
|
|
|
|
def sse(*events: Mapping[str, object]) -> str:
|
|
return "".join(f"data: {json.dumps(event)}\n\n" for event in events) + "data: [DONE]\n\n"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("sync", (True, False), ids=("sync", "async"))
|
|
@pytest.mark.parametrize("usage_at_start", (False, True), ids=("delta-usage", "start-usage"))
|
|
@pytest.mark.parametrize(
|
|
("usage", "expected"),
|
|
(
|
|
(GO_REPORTED_USAGE, 0.00412),
|
|
({"opencode": {"list_cost": 0}}, 0),
|
|
({}, ROW_PRICE_FOR_FIXTURE_USAGE),
|
|
({"opencode": {"list_cost": "invalid"}}, ROW_PRICE_FOR_FIXTURE_USAGE),
|
|
),
|
|
)
|
|
async def test_messages_stream_bills_reported_list_cost(
|
|
go_catalog: None,
|
|
cost_recorder: CostRecorder,
|
|
sync: bool,
|
|
usage_at_start: bool,
|
|
usage: Mapping[str, object],
|
|
expected: float,
|
|
) -> None:
|
|
lines: Final = _messages_sse(False, usage, usage_at_start)
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post().mock(
|
|
return_value=httpx.Response(
|
|
200, headers={"content-type": "text/event-stream"}, text="\n\n".join(lines) + "\n\n"
|
|
)
|
|
)
|
|
kwargs: Final = {
|
|
"model": "opencode_go/fixture-messages",
|
|
"api_key": "fake-go-key",
|
|
"messages": [{"role": "user", "content": "hello"}],
|
|
"stream": True,
|
|
"stream_options": {"include_usage": True},
|
|
}
|
|
stream: Final = litellm.completion(**kwargs) if sync else await litellm.acompletion(**kwargs)
|
|
chunks: Final = tuple(stream) if sync else tuple([chunk async for chunk in stream])
|
|
assert "".join(chunk.choices[0].delta.content or "" for chunk in chunks if chunk.choices) == "hello"
|
|
assert chunks[-1].usage.total_tokens == 15
|
|
assert await logged_cost(cost_recorder) == pytest.approx(expected)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_chat_stream_bills_the_final_usage_chunks_list_cost(
|
|
go_catalog: None, cost_recorder: CostRecorder
|
|
) -> None:
|
|
chunk: Final = {
|
|
"id": "chatcmpl-test",
|
|
"object": "chat.completion.chunk",
|
|
"created": 1700000000,
|
|
"model": "fixture-chat",
|
|
}
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post().mock(
|
|
return_value=httpx.Response(
|
|
200,
|
|
headers={"content-type": "text/event-stream"},
|
|
text=sse(
|
|
{**chunk, "choices": [{"index": 0, "delta": {"role": "assistant", "content": "hello"}}]},
|
|
{**chunk, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
|
|
{
|
|
**chunk,
|
|
"choices": [],
|
|
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15, **GO_REPORTED_USAGE},
|
|
},
|
|
),
|
|
)
|
|
)
|
|
stream: Final = await litellm.acompletion(
|
|
model="opencode_go/fixture-chat",
|
|
api_key="fake-go-key",
|
|
messages=[{"role": "user", "content": "hello"}],
|
|
stream=True,
|
|
stream_options={"include_usage": True},
|
|
)
|
|
chunks: Final = [piece async for piece in stream]
|
|
assert "".join(piece.choices[0].delta.content or "" for piece in chunks if piece.choices) == "hello"
|
|
assert await logged_cost(cost_recorder) == pytest.approx(0.00412)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_responses_stream_bills_the_completed_events_list_cost(
|
|
go_catalog: None, cost_recorder: CostRecorder
|
|
) -> None:
|
|
completed: Final = go_priced_reply("responses", "fixture-responses", GO_REPORTED_USAGE)
|
|
with respx.mock(using="httpx") as transport:
|
|
transport.post().mock(
|
|
return_value=httpx.Response(
|
|
200,
|
|
headers={"content-type": "text/event-stream"},
|
|
text=sse(
|
|
{
|
|
"type": "response.output_text.delta",
|
|
"delta": "hello",
|
|
"item_id": "msg_test",
|
|
"output_index": 0,
|
|
"content_index": 0,
|
|
"sequence_number": 1,
|
|
},
|
|
{"type": "response.completed", "response": completed, "sequence_number": 2},
|
|
),
|
|
)
|
|
)
|
|
stream: Final = await litellm.aresponses(
|
|
model="opencode_go/fixture-responses", api_key="fake-go-key", input="hello", stream=True
|
|
)
|
|
events: Final = [event async for event in stream]
|
|
assert events[-1].type == "response.completed"
|
|
assert events[-1].response._hidden_params["additional_headers"][RESPONSE_COST_HEADER] == pytest.approx(0.00412)
|
|
assert await logged_cost(cost_recorder) == pytest.approx(0.00412)
|
|
|
|
|
|
def test_stream_chunk_builder_reads_list_cost_from_dict_chunks():
|
|
from litellm.litellm_core_utils.litellm_logging import Logging
|
|
|
|
logging_obj = Logging(
|
|
model="opencode_go/glm-5.3",
|
|
messages=[{"role": "user", "content": "hi"}],
|
|
stream=True,
|
|
call_type="completion",
|
|
start_time=datetime.now(),
|
|
litellm_call_id="dict-chunks",
|
|
function_id="1",
|
|
)
|
|
logging_obj.model_call_details["custom_llm_provider"] = "opencode_go"
|
|
chunk = {
|
|
"id": "chatcmpl-go",
|
|
"object": "chat.completion.chunk",
|
|
"created": 1,
|
|
"model": "glm-5.3",
|
|
"choices": [{"index": 0, "delta": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
|
|
}
|
|
final_usage = {**chunk, "choices": [], "usage": dict(GO_REPORTED_USAGE)}
|
|
|
|
assembled = litellm.stream_chunk_builder(chunks=[chunk, final_usage], logging_obj=logging_obj)
|
|
|
|
assert assembled is not None
|
|
assert assembled._hidden_params["response_cost"] == GO_REPORTED_USAGE["opencode"]["list_cost"]
|
|
|
|
|
|
@pytest.mark.parametrize(("model", "cache_marks"), [("qwen3.8-flash", 0), ("minimax-m3", 0), ("claude-haiku-5-5", 4)])
|
|
def test_go_messages_route_carries_prompt_cache_breakpoint_to_cache_control_only_for_claude(
|
|
model: str, cache_marks: int
|
|
):
|
|
marked_notes: Final = [
|
|
{"type": "text", "text": f"Note {n}", "prompt_cache_breakpoint": {"mode": "explicit"}} for n in range(4)
|
|
]
|
|
|
|
request: Final = OpenCodeGoMessagesChatConfig().transform_request(
|
|
model=model,
|
|
messages=[{"role": "user", "content": [*marked_notes, {"type": "text", "text": "Answer in one line."}]}],
|
|
optional_params={"max_tokens": 64},
|
|
litellm_params={},
|
|
headers={},
|
|
)
|
|
|
|
wire: Final = json.dumps(request)
|
|
assert wire.count('"cache_control"') == cache_marks
|
|
assert "prompt_cache_breakpoint" not in wire
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("messages", "sent_system"),
|
|
[
|
|
([{"role": "user", "content": "hello"}], "Answer in French"),
|
|
(
|
|
[{"role": "system", "content": "Answer in German"}, {"role": "user", "content": "hello"}],
|
|
[{"type": "text", "text": "Answer in German"}],
|
|
),
|
|
],
|
|
)
|
|
def test_messages_route_sends_a_system_kwarg_unless_a_system_message_sets_the_prompt(
|
|
go_catalog: None, messages: list[dict[str, str]], sent_system: object
|
|
) -> None:
|
|
with respx.mock(using="httpx") as transport:
|
|
route: Final = transport.post().mock(
|
|
return_value=httpx.Response(200, json=upstream_reply("messages", "fixture-messages"))
|
|
)
|
|
litellm.completion(
|
|
model="opencode_go/fixture-messages",
|
|
api_key="fake-go-key",
|
|
messages=messages,
|
|
system="Answer in French",
|
|
)
|
|
|
|
assert json.loads(route.calls.last.request.content)["system"] == sent_system
|