Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(friendliai): drop litellm-internal message fields before sending (#45092)

Joshua Wang2754da5391d3
diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.yml
index 5e42f182345..1514c58d022 100644
--- a/.github/workflows/test-unit.yml
+++ b/.github/workflows/test-unit.yml
@@ -266,6 +266,7 @@ jobs:
tests/unit/llms/featherless_ai
tests/unit/llms/firecrawl
tests/unit/llms/fireworks_ai
+ tests/unit/llms/friendliai
tests/unit/llms/gdc
tests/unit/llms/gemini
tests/unit/llms/gigachat
diff --git a/litellm/llms/friendliai/chat/transformation.py b/litellm/llms/friendliai/chat/transformation.py
index 168549142f3..d4df4636218 100644
--- a/litellm/llms/friendliai/chat/transformation.py
+++ b/litellm/llms/friendliai/chat/transformation.py
@@ -2,8 +2,40 @@
Translate from OpenAI's `/v1/chat/completions` to Friendliai's `/v1/chat/completions`
"""
+from collections.abc import Coroutine
+from typing import Literal, overload
+
+from litellm.litellm_core_utils.prompt_templates.common_utils import strip_litellm_response_only_fields
+from litellm.types.llms.openai import AllMessageValues
+
from ...openai_like.chat.handler import OpenAILikeChatConfig
class FriendliaiChatConfig(OpenAILikeChatConfig):
- pass
+ @overload
+ def _transform_messages(
+ self,
+ messages: list[AllMessageValues], # mutable-ok: inherited contract
+ model: str,
+ is_async: Literal[True],
+ ) -> Coroutine[object, object, list[AllMessageValues]]: ... # mutable-ok: inherited contract
+
+ @overload
+ def _transform_messages(
+ self,
+ messages: list[AllMessageValues], # mutable-ok: inherited contract
+ model: str,
+ is_async: Literal[False] = False,
+ ) -> list[AllMessageValues]: ... # mutable-ok: inherited contract
+
+ def _transform_messages(
+ self,
+ messages: list[AllMessageValues], # mutable-ok: inherited contract
+ model: str,
+ is_async: bool = False,
+ ) -> list[AllMessageValues] | Coroutine[object, object, list[AllMessageValues]]: # mutable-ok: inherited contract
+ return super()._transform_messages(
+ messages=[strip_litellm_response_only_fields(message) for message in messages],
+ model=model,
+ is_async=is_async,
+ )
diff --git a/tests/integration/providers/test_friendliai_replay_wire.py b/tests/integration/providers/test_friendliai_replay_wire.py
new file mode 100644
index 00000000000..1e41b5489f6
--- /dev/null
+++ b/tests/integration/providers/test_friendliai_replay_wire.py
@@ -0,0 +1,122 @@
+import json
+from typing import Final
+
+from integration._support.client import Gateway
+from integration._support.wire import Reply, Request, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+_MODEL: Final = "zai-org/GLM-5.3"
+_API_KEY: Final = "synthetic-friendliai-key"
+_PROMPT: Final = "What is the weather in Paris? Use the tool."
+_REASONING: Final = "The user wants the weather in Paris, so call get_weather."
+_TOOL_RESULT: Final = "18C and sunny"
+_ANSWER: Final = "It is 18C and sunny in Paris."
+_LITELLM_ONLY_FIELDS: Final = frozenset({"thinking_blocks", "reasoning_items", "provider_specific_fields"})
+_JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+_MESSAGES: Final = TypeAdapter(tuple[dict[str, JsonValue], ...])
+_CALL: Final[JsonValue] = {
+ "id": "call_paris",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'},
+}
+_PARAMETERS: Final[JsonValue] = {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+}
+
+
+def _respond(request: Request) -> Reply:
+ assert (request.method, request.target) == ("POST", "/chat/completions")
+ assert request.headers["authorization"] == f"Bearer {_API_KEY}"
+ return Reply(
+ body=json.dumps(
+ {
+ "id": "friendliai-replay",
+ "object": "chat.completion",
+ "created": 1,
+ "model": _MODEL,
+ "choices": [
+ {"index": 0, "message": {"role": "assistant", "content": _ANSWER}, "finish_reason": "stop"}
+ ],
+ "usage": {"prompt_tokens": 40, "completion_tokens": 9, "total_tokens": 49},
+ }
+ ).encode()
+ )
+
+
+def _sent_messages(requests: tuple[Request, ...]) -> tuple[dict[str, JsonValue], ...]:
+ assert len(requests) == 1
+ body: Final = _JSON_OBJECT.validate_json(requests[0].body)
+ assert body["model"] == _MODEL
+ return _MESSAGES.validate_python(body["messages"])
+
+
+def test_chat_replay_of_returned_assistant_message_reaches_friendliai_without_litellm_fields(gateway: Gateway) -> None:
+ with wire_server(_respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(model=f"friendliai/{_MODEL}", api_base=wire.url, api_key=_API_KEY)
+ response: Final = gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {
+ "model": model,
+ "messages": [
+ {"role": "user", "content": _PROMPT},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{**_CALL, "provider_specific_fields": {"thought_signature": "sig"}}],
+ "reasoning_content": _REASONING,
+ "thinking_blocks": [{"type": "thinking", "thinking": _REASONING, "signature": "sig"}],
+ "provider_specific_fields": {"reasoning": _REASONING},
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_paris",
+ "content": _TOOL_RESULT,
+ "provider_specific_fields": {},
+ },
+ ],
+ "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": _PARAMETERS}}],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert _sent_messages(wire.drain()) == (
+ {"role": "user", "content": _PROMPT},
+ {"role": "assistant", "tool_calls": [_CALL], "reasoning_content": _REASONING},
+ {"role": "tool", "tool_call_id": "call_paris", "content": _TOOL_RESULT},
+ )
+
+
+def test_messages_replay_of_thinking_and_tool_use_reaches_friendliai_without_litellm_fields(gateway: Gateway) -> None:
+ with wire_server(_respond) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(model=f"friendliai/{_MODEL}", api_base=wire.url, api_key=_API_KEY)
+ response: Final = gateway.request(
+ "POST",
+ "/v1/messages",
+ {
+ "model": model,
+ "max_tokens": 256,
+ "messages": [
+ {"role": "user", "content": _PROMPT},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": _REASONING, "signature": "sig"},
+ {"type": "tool_use", "id": "call_paris", "name": "get_weather", "input": {"city": "Paris"}},
+ ],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "call_paris", "content": _TOOL_RESULT}],
+ },
+ ],
+ "tools": [{"name": "get_weather", "input_schema": _PARAMETERS}],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert _JSON_OBJECT.validate_json(response.content)["content"] == [{"type": "text", "text": _ANSWER}]
+ messages: Final = _sent_messages(wire.drain())
+ assert [sorted(_LITELLM_ONLY_FIELDS & message.keys()) for message in messages] == [[]] * len(messages)
+ assistant: Final = next(message for message in messages if message["role"] == "assistant")
+ assert assistant["reasoning_content"] == _REASONING
diff --git a/tests/unit/llms/friendliai/__init__.py b/tests/unit/llms/friendliai/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/unit/llms/friendliai/chat/__init__.py b/tests/unit/llms/friendliai/chat/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/unit/llms/friendliai/chat/test_transformation.py b/tests/unit/llms/friendliai/chat/test_transformation.py
new file mode 100644
index 00000000000..48fc08a3ccd
--- /dev/null
+++ b/tests/unit/llms/friendliai/chat/test_transformation.py
@@ -0,0 +1,42 @@
+from typing import Final
+
+from litellm.llms.friendliai.chat.transformation import FriendliaiChatConfig
+from litellm.types.llms.openai import AllMessageValues
+
+_TOOL_CALLS: Final = [
+ {"id": "toolu_01", "type": "function", "function": {"name": "Bash", "arguments": '{"command": "echo hi"}'}}
+]
+
+
+def _replayed_thinking_tool_turn() -> list[AllMessageValues]:
+ return [
+ {"role": "user", "content": "run echo hi"},
+ {
+ "role": "assistant",
+ "thinking_blocks": [{"type": "thinking", "thinking": "run the Bash tool", "signature": ""}],
+ "tool_calls": _TOOL_CALLS,
+ "reasoning_content": "run the Bash tool",
+ "provider_specific_fields": {},
+ },
+ {"role": "tool", "tool_call_id": "toolu_01", "content": "hi"},
+ ]
+
+
+async def test_transform_request_drops_internal_fields_friendliai_rejects():
+ messages: Final = _replayed_thinking_tool_turn()
+ config: Final = FriendliaiChatConfig()
+
+ sync_request: Final = config.transform_request(
+ model="zai-org/GLM-5.3", messages=messages, optional_params={}, litellm_params={}, headers={}
+ )
+ async_request: Final = await config.async_transform_request(
+ model="zai-org/GLM-5.3", messages=messages, optional_params={}, litellm_params={}, headers={}
+ )
+
+ expected_assistant: Final = {
+ "role": "assistant",
+ "tool_calls": _TOOL_CALLS,
+ "reasoning_content": "run the Bash tool",
+ }
+ assert sync_request["messages"] == async_request["messages"] == [messages[0], expected_assistant, messages[2]]
+ assert messages == _replayed_thinking_tool_turn()