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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(fireworks_ai): sync chat completions endpoint with full API surface (#30885)
Mateo Wang9f97111edd73
diff --git a/litellm/llms/fireworks_ai/chat/transformation.py b/litellm/llms/fireworks_ai/chat/transformation.pyindex 341c2fc7350..7e4395959b9 100644--- a/litellm/llms/fireworks_ai/chat/transformation.py+++ b/litellm/llms/fireworks_ai/chat/transformation.py@@ -1,5 +1,15 @@import json-from typing import Any, List, Literal, Optional, Tuple, Union, cast+from typing import (+ Any,+ AsyncIterator,+ Iterator,+ List,+ Literal,+ Optional,+ Tuple,+ Union,+ cast,+)import httpx@@ -15,7 +25,6 @@ from litellm.litellm_core_utils.llm_response_utils.get_headers import (from litellm.secret_managers.main import get_secret_strfrom litellm.types.llms.openai import (AllMessageValues,- ChatCompletionImageObject,ChatCompletionToolParam,OpenAIChatCompletionToolParam,)@@ -25,6 +34,7 @@ from litellm.types.utils import (Function,Message,ModelResponse,+ ModelResponseStream,ProviderSpecificModelInfo,)from litellm.utils import (@@ -34,10 +44,34 @@ from litellm.utils import (supports_tool_choice,)-from ...openai.chat.gpt_transformation import OpenAIGPTConfig+from ...openai.chat.gpt_transformation import (+ OpenAIChatCompletionStreamingHandler,+ OpenAIGPTConfig,+)from ..common_utils import FireworksAIException+def _extract_fireworks_hidden_params(payload: dict) -> dict:+ """+ Collect Fireworks-specific response fields (perf_metrics, prompt_token_ids,+ per-choice raw_output and token_ids) from a non-streaming completion payload+ or a single streaming chunk, so the same data lands in ``_hidden_params`` on+ both response paths.+ """+ choices = [c for c in (payload.get("choices") or []) if isinstance(c, dict)]+ top_level = {+ f"fireworks_{field}": payload[field]+ for field in ("perf_metrics", "prompt_token_ids")+ if field in payload+ }+ per_choice = {+ f"fireworks_{dest}": [c[field] for c in choices if field in c]+ for field, dest in (("raw_output", "raw_outputs"), ("token_ids", "token_ids"))+ if any(field in c for c in choices)+ }+ return {**top_level, **per_choice}++class FireworksAIConfig(OpenAIGPTConfig):"""Reference: https://docs.fireworks.ai/api-reference/post-chatcompletions@@ -60,8 +94,7 @@ class FireworksAIConfig(OpenAIGPTConfig):logprobs: Optional[int] = Nonereasoning_effort: Optional[str] = None- # Non OpenAI parameters - Fireworks AI only params- prompt_truncate_length: Optional[int] = None+ prompt_truncate_len: Optional[int] = Nonecontext_length_exceeded_behavior: Optional[Literal["error", "truncate"]] = Nonedef __init__(@@ -80,7 +113,7 @@ class FireworksAIConfig(OpenAIGPTConfig):user: Optional[str] = None,logprobs: Optional[int] = None,reasoning_effort: Optional[str] = None,- prompt_truncate_length: Optional[int] = None,+ prompt_truncate_len: Optional[int] = None,context_length_exceeded_behavior: Optional[Literal["error", "truncate"]] = None,) -> None:locals_ = locals().copy()@@ -108,8 +141,30 @@ class FireworksAIConfig(OpenAIGPTConfig):"response_format","user","logprobs",- "prompt_truncate_length",+ "prompt_truncate_len","context_length_exceeded_behavior",+ "seed",+ "top_logprobs",+ "min_p",+ "typical_p",+ "repetition_penalty",+ "mirostat_target",+ "mirostat_lr",+ "logit_bias",+ "echo",+ "echo_last",+ "ignore_eos",+ "prompt_cache_key",+ "prompt_cache_isolation_key",+ "raw_output",+ "perf_metrics_in_response",+ "return_token_ids",+ "safe_tokenization",+ "service_tier",+ "speculation",+ "prediction",+ "stream_options",+ "sampling_mask",]# Only add tools for models that support function calling@@ -133,9 +188,11 @@ class FireworksAIConfig(OpenAIGPTConfig):if supports_tool_choice(model=model, custom_llm_provider="fireworks_ai"):supported_params.append("tool_choice")- # Only add reasoning_effort for models that support it+ # Only add reasoning params for models that support itif supports_reasoning(model=model, custom_llm_provider="fireworks_ai"):supported_params.append("reasoning_effort")+ supported_params.append("reasoning_history")+ supported_params.append("thinking")return supported_params@@ -151,6 +208,18 @@ class FireworksAIConfig(OpenAIGPTConfig):param == "tools" and value is not Nonefor param, value in non_default_params.items())+ if (+ non_default_params.get("thinking") is not None+ and non_default_params.get("reasoning_effort") is not None+ ):+ raise litellm.BadRequestError(+ message=(+ "Fireworks AI chat completions does not support specifying both "+ "`thinking` and `reasoning_effort` in the same request."+ ),+ model=model,+ llm_provider="fireworks_ai",+ )for param, value in non_default_params.items():if param == "tool_choice":@@ -174,40 +243,19 @@ class FireworksAIConfig(OpenAIGPTConfig):optional_params["response_format"] = valueelif param == "max_completion_tokens":optional_params["max_tokens"] = value+ elif param == "reasoning_effort":+ if value is True:+ optional_params["reasoning_effort"] = "medium"+ elif value is False:+ optional_params["reasoning_effort"] = "none"+ else:+ optional_params["reasoning_effort"] = valueelif param in supported_openai_params:if value is not None:optional_params[param] = valuereturn optional_params- def _add_transform_inline_image_block(- self,- content: ChatCompletionImageObject,- model: str,- disable_add_transform_inline_image_block: Optional[bool],- ) -> ChatCompletionImageObject:- """- Add transform_inline to the image_url (allows non-vision models to parse documents/images/etc.)- - ignore if model is a vision model- - ignore if user has disabled this feature- """- if (- "vision" in model or disable_add_transform_inline_image_block- ): # allow user to toggle this feature.- return content- if isinstance(content["image_url"], str):- # Skip base64 data URLs — appending #transform=inline corrupts the- # base64 payload and causes an "Incorrect padding" decode error on- # the Fireworks side. Data URLs are already inlined by definition.- # Lower-case before checking: URI schemes are case-insensitive (RFC 3986).- if not content["image_url"].lower().startswith("data:"):- content["image_url"] = f"{content['image_url']}#transform=inline"- elif isinstance(content["image_url"], dict):- url = content["image_url"]["url"]- if not url.lower().startswith("data:"):- content["image_url"]["url"] = f"{url}#transform=inline"- return content-def _transform_tools(self, tools: List[OpenAIChatCompletionToolParam]) -> List[OpenAIChatCompletionToolParam]:@@ -225,36 +273,46 @@ class FireworksAIConfig(OpenAIGPTConfig):self, messages: List[AllMessageValues], model: str, litellm_params: dict) -> List[AllMessageValues]:"""- Add 'transform=inline' to the url of the image_url+ Strip fields not permitted by FireworksAI from messages."""from litellm.litellm_core_utils.prompt_templates.common_utils import (filter_value_from_dict,- migrate_file_to_image_url,)- disable_add_transform_inline_image_block = cast(- Optional[bool],- litellm_params.get("disable_add_transform_inline_image_block")- or litellm.disable_add_transform_inline_image_block,+ supports_vision_value = self._get_model_cost_capability_exact(+ model=model, capability="supports_vision")- ## For any 'file' message type with pdf content, move to 'image_url' message type- for message in messages:- if message["role"] == "user":- _message_content = message.get("content")- if _message_content is not None and isinstance(_message_content, list):- for idx, content in enumerate(_message_content):- if content["type"] == "file":- _message_content[idx] = migrate_file_to_image_url(content)for message in messages:if message["role"] == "user":_message_content = message.get("content")if _message_content is not None and isinstance(_message_content, list):for content in _message_content:- if content["type"] == "image_url":- content = self._add_transform_inline_image_block(- content=content,+ if not isinstance(content, dict):+ continue+ if content.get("type") == "file":+ raise litellm.BadRequestError(+ message=(+ "Fireworks AI chat completions does not support "+ "file content blocks. For PDFs, convert pages to "+ "images and send image_url blocks to a Fireworks "+ "vision model, or extract text before calling a "+ "text-only model."+ ),+ model=model,+ llm_provider="fireworks_ai",+ )+ if (+ content.get("type") == "image_url"+ and supports_vision_value is False+ ):+ raise litellm.BadRequestError(+ message=(+ f"Fireworks AI model {model} does not support "+ "image inputs. Use a Fireworks vision model or "+ "remove image_url content blocks."+ ),model=model,- disable_add_transform_inline_image_block=disable_add_transform_inline_image_block,+ llm_provider="fireworks_ai",)filter_value_from_dict(cast(dict, message), "cache_control")# Remove fields not permitted by FireworksAI (additionalProperties: false@@ -317,43 +375,55 @@ class FireworksAIConfig(OpenAIGPTConfig):return Truereturn ("-" + key_short + "-") in short_name- def _get_model_cost_capability(self, model: str, capability: str) -> Optional[bool]:+ @staticmethod+ def _short_model_name(model: str) -> str:short_name = modelif short_name.startswith("fireworks_ai/"):short_name = short_name[len("fireworks_ai/") :]if short_name.startswith("accounts/fireworks/models/"):short_name = short_name[len("accounts/fireworks/models/") :]+ return short_name- candidate_keys = [+ def _get_model_cost_capability_exact(+ self, model: str, capability: str+ ) -> Optional[bool]:+ short_name = self._short_model_name(model)+ candidate_keys = (model,f"fireworks_ai/{short_name}",f"fireworks_ai/accounts/fireworks/models/{short_name}",- ]-+ )for candidate_key in candidate_keys:model_info = litellm.model_cost.get(candidate_key)if model_info is not None and model_info.get(capability) is not None:return cast(Optional[bool], model_info.get(capability))+ return None- # Fallback: preserve historical substring matching for model name- # variants (e.g. fine-tuned or regionally-suffixed versions of a- # known model). Pick the *longest* matching entry so a more specific- # known model (e.g. "qwen3-8b-instruct") wins over a less specific- # one (e.g. "qwen3-8b") when the query model is more specific still.- # Use hyphen-aligned matching to avoid false positives where a short- # known model name is an unrelated substring of a longer one.- best_match_short: Optional[str] = None- best_match_value: Optional[bool] = None- for key_short, model_info in self._get_fireworks_index():- if model_info.get(capability) is None:- continue- if not self._matches_on_hyphen_boundary(short_name, key_short):- continue- if best_match_short is None or len(key_short) > len(best_match_short):- best_match_short = key_short- best_match_value = cast(Optional[bool], model_info.get(capability))-- return best_match_value+ def _get_model_cost_capability(self, model: str, capability: str) -> Optional[bool]:+ exact = self._get_model_cost_capability_exact(+ model=model, capability=capability+ )+ if exact is not None:+ return exact++ # Fallback: substring matching for model name variants (e.g. fine-tuned+ # or regionally-suffixed versions of a known model). Pick the *longest*+ # matching entry so a more specific known model (e.g. "qwen3-8b-instruct")+ # wins over a less specific one (e.g. "qwen3-8b"). Hyphen-aligned matching+ # avoids false positives where a short known name is an unrelated+ # substring of a longer one. This stays a soft signal: capability-gated+ # hard rejections use the exact lookup so a fuzzy match never blocks a+ # custom deployment.+ short_name = self._short_model_name(model)+ matches = [+ (key_short, cast(Optional[bool], model_info.get(capability)))+ for key_short, model_info in self._get_fireworks_index()+ if model_info.get(capability) is not None+ and self._matches_on_hyphen_boundary(short_name, key_short)+ ]+ if not matches:+ return None+ return max(matches, key=lambda match: len(match[0]))[1]def get_provider_info(self, model: str) -> ProviderSpecificModelInfo:supports_function_calling_value = self._get_model_cost_capability(@@ -362,12 +432,16 @@ class FireworksAIConfig(OpenAIGPTConfig):supports_reasoning_value = self._get_model_cost_capability(model=model, capability="supports_reasoning")+ supports_vision_value = self._get_model_cost_capability(+ model=model, capability="supports_vision"+ )+ supports_pdf_input_value = self._get_model_cost_capability(+ model=model, capability="supports_pdf_input"+ )provider_specific_model_info: ProviderSpecificModelInfo = {"supports_function_calling": True,"supports_prompt_caching": True, # https://docs.fireworks.ai/guides/prompt-caching- "supports_pdf_input": True, # via document inlining- "supports_vision": True, # via document inlining}if supports_function_calling_value is not None:@@ -381,6 +455,14 @@ class FireworksAIConfig(OpenAIGPTConfig):supports_reasoning_value)+ if supports_vision_value is not None:+ provider_specific_model_info["supports_vision"] = supports_vision_value++ if supports_pdf_input_value is not None:+ provider_specific_model_info["supports_pdf_input"] = (+ supports_pdf_input_value+ )+return provider_specific_model_infodef transform_request(@@ -402,6 +484,15 @@ class FireworksAIConfig(OpenAIGPTConfig):if "tools" in optional_params and optional_params["tools"] is not None:tools = self._transform_tools(tools=optional_params["tools"])optional_params["tools"] = tools+ if optional_params.get("stream"):+ stream_options = optional_params.get("stream_options")+ if stream_options is None:+ optional_params["stream_options"] = {"include_usage": True}+ elif stream_options.get("include_usage") is not False:+ optional_params["stream_options"] = {+ **stream_options,+ "include_usage": True,+ }return super().transform_request(model=model,messages=messages,@@ -494,10 +585,25 @@ class FireworksAIConfig(OpenAIGPTConfig):))- response._hidden_params = {"additional_headers": additional_headers}+ response._hidden_params = {+ "additional_headers": additional_headers,+ **_extract_fireworks_hidden_params(completion_response),+ }return response+ def get_model_response_iterator(+ self,+ streaming_response: Union[Iterator[str], AsyncIterator[str], ModelResponse],+ sync_stream: bool,+ json_mode: Optional[bool] = False,+ ) -> Any:+ return FireworksAIChatCompletionStreamingHandler(+ streaming_response=streaming_response,+ sync_stream=sync_stream,+ json_mode=json_mode,+ )+def _get_openai_compatible_provider_info(self, api_base: Optional[str], api_key: Optional[str]) -> Tuple[Optional[str], Optional[str]]:@@ -554,3 +660,15 @@ class FireworksAIConfig(OpenAIGPTConfig):or get_secret_str("FIREWORKSAI_API_KEY")or get_secret_str("FIREWORKS_AI_TOKEN"))+++class FireworksAIChatCompletionStreamingHandler(OpenAIChatCompletionStreamingHandler):+ def chunk_parser(self, chunk: dict) -> ModelResponseStream:+ parsed = super().chunk_parser(chunk)+ fireworks_fields = _extract_fireworks_hidden_params(chunk)+ if fireworks_fields:+ parsed.provider_specific_fields = {+ **(getattr(parsed, "provider_specific_fields", None) or {}),+ **fireworks_fields,+ }+ return parseddiff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 7a5f8b9e1e3..5c962cf8440 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -15011,7 +15011,7 @@"supports_reasoning": true,"supports_response_schema": true,"supports_tool_choice": true,- "supports_vision": false+ "supports_vision": true},"fireworks_ai/accounts/fireworks/models/mixtral-8x22b-instruct-hf": {"input_cost_per_token": 1.2e-06,@@ -15314,7 +15314,7 @@"supports_reasoning": true,"supports_response_schema": true,"supports_tool_choice": true,- "supports_vision": false+ "supports_vision": true},"fireworks_ai/qwen3p7-plus": {"cache_read_input_token_cost": 8e-08,diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 47b7190185e..3c50dde9277 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -15019,7 +15019,7 @@"supports_reasoning": true,"supports_response_schema": true,"supports_tool_choice": true,- "supports_vision": false+ "supports_vision": true},"fireworks_ai/accounts/fireworks/models/mixtral-8x22b-instruct-hf": {"input_cost_per_token": 1.2e-06,@@ -15322,7 +15322,7 @@"supports_reasoning": true,"supports_response_schema": true,"supports_tool_choice": true,- "supports_vision": false+ "supports_vision": true},"fireworks_ai/qwen3p7-plus": {"cache_read_input_token_cost": 8e-08,diff --git a/tests/litellm_utils_tests/test_utils.py b/tests/litellm_utils_tests/test_utils.pyindex d64633413a0..697c3837602 100644--- a/tests/litellm_utils_tests/test_utils.py+++ b/tests/litellm_utils_tests/test_utils.py@@ -1588,18 +1588,21 @@ def test_token_counter_with_image_url_with_detail_high():assert _tokens == DEFAULT_IMAGE_TOKEN_COUNT + 7-def test_fireworks_ai_document_inlining():+def test_fireworks_ai_vision_capability_from_cost_map(monkeypatch):"""- With document inlining, all fireworks ai models are now:- - supports_pdf- - supports_vision+ Fireworks deprecated document inlining on 2025-06-30, so vision/PDF support is+ no longer hardcoded to True for every Fireworks model. Capabilities are read+ from the model cost map: unmapped models no longer advertise vision or PDF+ support, while mapped VLMs still do."""+ monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")+ monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url=""))from litellm.utils import supports_pdf_input, supports_vision- litellm._turn_on_debug()+ assert supports_vision("fireworks_ai/llama-3.1-8b-instruct") is False+ assert supports_pdf_input("fireworks_ai/llama-3.1-8b-instruct") is False- assert supports_pdf_input("fireworks_ai/llama-3.1-8b-instruct") is True- assert supports_vision("fireworks_ai/llama-3.1-8b-instruct") is True+ assert supports_vision("fireworks_ai/minimax-m3") is Truedef test_logprobs_type():diff --git a/tests/llm_translation/test_fireworks_ai_translation.py b/tests/llm_translation/test_fireworks_ai_translation.pyindex 4e5bef16b8c..204f4d9e31b 100644--- a/tests/llm_translation/test_fireworks_ai_translation.py+++ b/tests/llm_translation/test_fireworks_ai_translation.py@@ -9,7 +9,6 @@ sys.path.insert(import litellmfrom litellm import transcriptionfrom litellm.llms.fireworks_ai.chat.transformation import FireworksAIConfig-from base_llm_unit_tests import BaseLLMChatTestfrom base_audio_transcription_unit_tests import BaseLLMAudioTranscriptionTestfireworks = FireworksAIConfig()@@ -146,11 +145,8 @@ class TestFireworksAIAudioTranscription(BaseLLMAudioTranscriptionTest):)def test_document_inlining_example(disable_add_transform_inline_image_block):"""- Document inlining appends ``#transform=inline`` to image/PDF URLs in the- outgoing request unless explicitly disabled. Assert the transform on the- serialized payload rather than making a live Fireworks call — the live- call only proved the model responded and broke whenever Fireworks rotated- its serverless model catalog.+ Fireworks document inlining has been removed from the platform. LiteLLM+ must not append ``#transform=inline`` regardless of the legacy disable flag."""from unittest.mock import patch@@ -163,7 +159,7 @@ def test_document_inlining_example(disable_add_transform_inline_image_block):with patch.object(client, "post") as mock_post:try:completion(- model="fireworks_ai/accounts/fireworks/models/deepseek-v3p1",+ model="fireworks_ai/accounts/fireworks/models/minimax-m3",messages=[{"role": "user",@@ -182,89 +178,80 @@ def test_document_inlining_example(disable_add_transform_inline_image_block):disable_add_transform_inline_image_block=disable_add_transform_inline_image_block,client=client,)- except Exception as e:- print(e)+ except Exception:+ passmock_post.assert_called_once()json_data = json.loads(mock_post.call_args.kwargs["data"])sent_url = json_data["messages"][0]["content"][0]["image_url"]["url"]- if disable_add_transform_inline_image_block is True:- assert sent_url == pdf_url- assert "#transform=inline" not in sent_url- else:- assert sent_url == pdf_url + "#transform=inline"+ assert sent_url == pdf_url+ assert "#transform=inline" not in sent_url@pytest.mark.parametrize(- "content, model, expected_url",+ "content, expected_url",[({"image_url": "http://example.com/image.png"},- "gpt-4",- "http://example.com/image.png#transform=inline",+ "http://example.com/image.png",),({"image_url": {"url": "http://example.com/image.png"}},- "gpt-4",- {"url": "http://example.com/image.png#transform=inline"},- ),- (- {"image_url": "http://example.com/image.png"},- "vision-gpt",- "http://example.com/image.png",+ {"url": "http://example.com/image.png"},),- # data: URLs must never have #transform=inline appended — doing so- # corrupts the base64 payload (fixes #23583).- # URI schemes are case-insensitive (RFC 3986) so check all variants.({"image_url": "data:image/png;base64,iVBORw0KGgo="},- "gpt-4","data:image/png;base64,iVBORw0KGgo=",),({"image_url": {"url": "data:image/jpeg;base64,/9j/4AAQ=="}},- "gpt-4",{"url": "data:image/jpeg;base64,/9j/4AAQ=="},),({"image_url": "Data:image/png;base64,iVBORw0KGgo="},- "gpt-4","Data:image/png;base64,iVBORw0KGgo=",),],)-def test_transform_inline(content, model, expected_url):-- result = litellm.FireworksAIConfig()._add_transform_inline_image_block(- content=content, model=model, disable_add_transform_inline_image_block=False+def test_transform_inline_no_longer_added(content, expected_url):+ image_block = {"type": "image_url", **content}+ messages = [{"role": "user", "content": [image_block]}]++ result = litellm.FireworksAIConfig()._transform_messages_helper(+ messages=messages,+ model="accounts/fireworks/models/minimax-m3",+ litellm_params={},)+ result_image_block = result[0]["content"][0]if isinstance(expected_url, str):- assert result["image_url"] == expected_url+ assert result_image_block["image_url"] == expected_urlelse:- assert result["image_url"]["url"] == expected_url["url"]+ assert result_image_block["image_url"]["url"] == expected_url["url"]@pytest.mark.parametrize(- "model, is_disabled, expected_url",- [- ("gpt-4", True, "http://example.com/image.png"),- ("vision-gpt", False, "http://example.com/image.png"),- ("gpt-4", False, "http://example.com/image.png#transform=inline"),- ],+ "is_disabled",+ [True, False],)-def test_global_disable_flag(model, is_disabled, expected_url):- content = {"image_url": "http://example.com/image.png"}- result = litellm.FireworksAIConfig()._add_transform_inline_image_block(- content=content,- model=model,- disable_add_transform_inline_image_block=is_disabled,+def test_global_disable_flag_no_longer_adds_transform_inline(is_disabled):+ url = "http://example.com/image.png"+ litellm.disable_add_transform_inline_image_block = is_disabled+ messages = [+ {+ "role": "user",+ "content": [{"type": "image_url", "image_url": url}],+ }+ ]+ result = litellm.FireworksAIConfig()._transform_messages_helper(+ messages=messages,+ model="accounts/fireworks/models/minimax-m3",+ litellm_params={},)- assert result["image_url"] == expected_url+ assert result[0]["content"][0]["image_url"] == urllitellm.disable_add_transform_inline_image_block = False # Reset for other testsdef test_global_disable_flag_with_transform_messages_helper(monkeypatch):- from openai import OpenAIfrom unittest.mock import patchfrom litellm import completionfrom litellm.llms.custom_httpx.http_handler import HTTPHandler@@ -279,7 +266,7 @@ def test_global_disable_flag_with_transform_messages_helper(monkeypatch):) as mock_post:try:completion(- model="fireworks_ai/accounts/fireworks/models/deepseek-v3p1",+ model="fireworks_ai/accounts/fireworks/models/minimax-m3",messages=[{"role": "user",@@ -296,11 +283,10 @@ def test_global_disable_flag_with_transform_messages_helper(monkeypatch):],client=client,)- except Exception as e:- print(e)+ except Exception:+ passmock_post.assert_called_once()- print(mock_post.call_args.kwargs)json_data = json.loads(mock_post.call_args.kwargs["data"])assert ("#transform=inline"diff --git a/tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py b/tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.pyindex 683ec158f44..03e763a4161 100644--- a/tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py+++ b/tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py@@ -1,9 +1,8 @@import jsonimport osimport sys-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import MagicMock, patch-import httpximport pytestimport litellm@@ -12,10 +11,14 @@ sys.path.insert(0, os.path.abspath("../../../../..")) # Adds the parent directory to the system path-from litellm import get_model_info, supports_reasoning+from litellm import get_model_info, supports_reasoning, supports_visionfrom litellm.llms.fireworks_ai.chat.transformation import FireworksAIConfig-from litellm.types.llms.openai import ChatCompletionToolCallFunctionChunk-from litellm.types.utils import ChatCompletionMessageToolCall, Function, Message+from litellm.types.utils import (+ ChatCompletionMessageToolCall,+ Function,+ Message,+ ModelResponse,+)@pytest.fixture(autouse=True)@@ -98,12 +101,12 @@ def test_supports_reasoning_effort():for model in supported_models:assert (- supports_reasoning(model=model, custom_llm_provider="fireworks_ai") == True+ supports_reasoning(model=model, custom_llm_provider="fireworks_ai") is True), f"{model} should support reasoning_effort"for model in unsupported_models:assert (- supports_reasoning(model=model, custom_llm_provider="fireworks_ai") == False+ supports_reasoning(model=model, custom_llm_provider="fireworks_ai") is False), f"{model} should not support reasoning_effort"@@ -115,11 +118,13 @@ def test_get_supported_openai_params_reasoning_effort():"fireworks_ai/accounts/fireworks/models/glm-5p1")assert "reasoning_effort" in supported_params+ assert "thinking" in supported_paramsunsupported_params = config.get_supported_openai_params("fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct")assert "reasoning_effort" not in unsupported_params+ assert "thinking" not in unsupported_paramsdef test_get_supported_openai_params_parallel_tool_calls():@@ -181,41 +186,6 @@ def test_get_provider_info_omits_false_supports_reasoning(monkeypatch):assert "supports_reasoning" not in info-def test_add_transform_inline_image_block_skips_data_urls():- """- data: URLs must not have #transform=inline appended — doing so corrupts the- base64 payload and raises binascii.Error: Incorrect padding on the Fireworks side.- Regression test for https://github.com/BerriAI/litellm/issues/23583- """- config = FireworksAIConfig()- data_url = "data:image/jpeg;base64,/9j/4AAQSkZJRgAB"-- # str branch- str_content = {"type": "image_url", "image_url": data_url}- result = config._add_transform_inline_image_block(- str_content, model="gpt-4", disable_add_transform_inline_image_block=False- )- assert result["image_url"] == data_url, "data URL must not be modified (str branch)"-- # dict branch- dict_content = {"type": "image_url", "image_url": {"url": data_url}}- result = config._add_transform_inline_image_block(- dict_content, model="gpt-4", disable_add_transform_inline_image_block=False- )- assert (- result["image_url"]["url"] == data_url- ), "data URL must not be modified (dict branch)"-- # regular https URL should still get the suffix- https_content = {"type": "image_url", "image_url": "https://example.com/image.jpg"}- result = config._add_transform_inline_image_block(- https_content, model="gpt-4", disable_add_transform_inline_image_block=False- )- assert result["image_url"].endswith(- "#transform=inline"- ), "https URL should get #transform=inline"--@pytest.mark.parametrize("api_base, expected_url_prefix",[@@ -582,3 +552,549 @@ def test_transform_request_routes_short_form_model_to_models_path():headers={},)assert result["model"] == "accounts/fireworks/models/glm-5p2"+++def _make_fireworks_raw_response(body: dict) -> MagicMock:+ mock = MagicMock()+ mock.status_code = 200+ mock.json.return_value = body+ mock.text = json.dumps(body)+ mock.headers = {}+ return mock+++_BASE_CHAT_COMPLETION_RESPONSE: dict = {+ "id": "resp-test",+ "object": "chat.completion",+ "created": 1234567890,+ "model": "glm-5p1",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "Hello"},+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},+}+++def _run_transform_response(response_body: dict) -> ModelResponse:+ config = FireworksAIConfig()+ raw_response = _make_fireworks_raw_response(response_body)+ logging_obj = MagicMock()+ return config.transform_response(+ model="accounts/fireworks/models/glm-5p1",+ raw_response=raw_response,+ model_response=ModelResponse(),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "Hi"}],+ optional_params={},+ litellm_params={},+ encoding=None,+ api_key="test-key",+ )+++_REASONING_MODEL = "fireworks_ai/accounts/fireworks/models/glm-5p1"+_NON_REASONING_MODEL = "fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct"+++def test_get_supported_openai_params_includes_all_fireworks_params():+ config = FireworksAIConfig()+ params = config.get_supported_openai_params(_REASONING_MODEL)++ required = [+ "seed",+ "top_logprobs",+ "min_p",+ "typical_p",+ "repetition_penalty",+ "mirostat_target",+ "mirostat_lr",+ "logit_bias",+ "echo",+ "echo_last",+ "ignore_eos",+ "prompt_cache_key",+ "prompt_cache_isolation_key",+ "raw_output",+ "perf_metrics_in_response",+ "return_token_ids",+ "safe_tokenization",+ "service_tier",+ "speculation",+ "prediction",+ "stream_options",+ "sampling_mask",+ "thinking",+ "reasoning_history",+ ]+ missing = [p for p in required if p not in params]+ assert missing == [], f"Missing params: {missing}"+++def test_native_openai_params_flow_end_to_end_with_drop_params_false():+ """+ The OpenAI-native params Fireworks supports (seed, top_logprobs, logit_bias,+ prompt_cache_key, service_tier, prediction) previously hit+ ``UnsupportedParamsError`` with ``drop_params=False`` because they were absent+ from ``get_supported_openai_params``. Listing them must let them survive the+ ``get_optional_params`` gate and reach the request, not just appear in the+ supported list. Asserting via ``get_optional_params`` (the real gate) rather+ than ``map_openai_params`` catches a revert of the supported-params additions,+ which a list-membership check would not.+ """+ native = {+ "seed": 42,+ "top_logprobs": 3,+ "logit_bias": {"1": 1},+ "prompt_cache_key": "cache-key",+ "service_tier": "auto",+ "prediction": {"type": "content", "content": "x"},+ }+ optional_params = litellm.get_optional_params(+ model="accounts/fireworks/models/llama-v3-70b-instruct",+ custom_llm_provider="fireworks_ai",+ drop_params=False,+ **native,+ )+ for key, value in native.items():+ assert optional_params.get(key) == value+++def test_prompt_truncate_len_correct_name():+ config = FireworksAIConfig()+ params = config.get_supported_openai_params(_REASONING_MODEL)+ assert "prompt_truncate_len" in params+ assert "prompt_truncate_length" not in params++ result = config.map_openai_params(+ {"prompt_truncate_len": 4096},+ {},+ _REASONING_MODEL,+ drop_params=False,+ )+ assert result == {"prompt_truncate_len": 4096}+++def test_stream_options_include_usage_auto_injected():+ config = FireworksAIConfig()+ result = config.transform_request(+ model="accounts/fireworks/models/glm-5p1",+ messages=[{"role": "user", "content": "Hi"}],+ optional_params={"stream": True},+ litellm_params={},+ headers={},+ )+ assert result["stream_options"] == {"include_usage": True}+++def test_stream_options_not_injected_when_not_streaming():+ config = FireworksAIConfig()+ result = config.transform_request(+ model="accounts/fireworks/models/glm-5p1",+ messages=[{"role": "user", "content": "Hi"}],+ optional_params={},+ litellm_params={},+ headers={},+ )+ assert "stream_options" not in result+++def test_stream_options_preserves_user_override():+ config = FireworksAIConfig()+ result = config.transform_request(+ model="accounts/fireworks/models/glm-5p1",+ messages=[{"role": "user", "content": "Hi"}],+ optional_params={"stream": True, "stream_options": {"include_usage": False}},+ litellm_params={},+ headers={},+ )+ assert result["stream_options"]["include_usage"] is False+++def test_reasoning_history_in_supported_params():+ config = FireworksAIConfig()+ reasoning_params = config.get_supported_openai_params(_REASONING_MODEL)+ assert "reasoning_history" in reasoning_params++ non_reasoning_params = config.get_supported_openai_params(_NON_REASONING_MODEL)+ assert "reasoning_history" not in non_reasoning_params+++def test_thinking_param_passthrough():+ config = FireworksAIConfig()+ thinking = {"type": "disabled"}+ result = config.map_openai_params(+ {"thinking": thinking},+ {},+ _REASONING_MODEL,+ drop_params=False,+ )+ assert result == {"thinking": thinking}+++def test_thinking_and_reasoning_effort_conflict_rejected():+ config = FireworksAIConfig()+ with pytest.raises(+ litellm.BadRequestError,+ match="does not support specifying both `thinking` and `reasoning_effort`",+ ):+ config.map_openai_params(+ {+ "thinking": {"type": "enabled", "budget_tokens": 4096},+ "reasoning_effort": "medium",+ },+ {},+ _REASONING_MODEL,+ drop_params=False,+ )+++def test_minimax_m3_supports_vision_from_model_map():+ config = FireworksAIConfig()++ for model in [+ "fireworks_ai/accounts/fireworks/models/minimax-m3",+ "fireworks_ai/minimax-m3",+ ]:+ assert supports_vision(model=model, custom_llm_provider="fireworks_ai") is True+ assert config.get_provider_info(model)["supports_vision"] is True+++def test_transform_messages_helper_rejects_file_blocks():+ config = FireworksAIConfig()+ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "file",+ "file": {+ "file_data": "data:application/pdf;base64,JVBERi0xLjQKJSVFT0YK",+ "filename": "tiny.pdf",+ },+ },+ {"type": "text", "text": "Describe this"},+ ],+ }+ ]++ with pytest.raises(+ litellm.BadRequestError,+ match="Fireworks AI chat completions does not support file content blocks",+ ):+ config._transform_messages_helper(+ messages, model="accounts/fireworks/models/kimi-k2p6", litellm_params={}+ )+++def test_transform_messages_helper_rejects_non_vision_image_inputs():+ config = FireworksAIConfig()+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Describe this"},+ {+ "type": "image_url",+ "image_url": {+ "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAE="+ },+ },+ ],+ }+ ]++ with pytest.raises(litellm.BadRequestError, match="does not support image inputs"):+ config._transform_messages_helper(+ messages, model="accounts/fireworks/models/glm-5p2", litellm_params={}+ )+++def test_transform_messages_helper_allows_vision_image_inputs():+ config = FireworksAIConfig()+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Describe this"},+ {+ "type": "image_url",+ "image_url": {+ "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAE="+ },+ },+ ],+ }+ ]++ out = config._transform_messages_helper(+ messages, model="accounts/fireworks/models/minimax-m3", litellm_params={}+ )+ assert out == messages+++def test_image_inputs_not_rejected_for_fuzzy_non_vision_match():+ """+ A custom/fine-tuned model id that hyphen-matches a known non-vision model+ (glm-5p2 has supports_vision=False) must not inherit that False via the+ substring fallback and hard-reject valid image_url blocks. The capability+ gate for rejection uses an exact cost-map match; the fuzzy fallback stays a+ soft signal only, so an unmapped vision-capable deployment is not blocked.+ """+ config = FireworksAIConfig()+ custom_model = "accounts/myorg/models/custom-glm-5p2"++ assert config._get_model_cost_capability(custom_model, "supports_vision") is False+ assert (+ config._get_model_cost_capability_exact(custom_model, "supports_vision") is None+ )++ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "image_url",+ "image_url": {+ "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAE="+ },+ },+ ],+ }+ ]+ out = config._transform_messages_helper(+ messages, model=custom_model, litellm_params={}+ )+ assert out == messages+++def test_transform_messages_helper_skips_non_dict_content():+ config = FireworksAIConfig()+ messages = [+ {+ "role": "user",+ "content": ["just a string", {"type": "text", "text": "hello"}],+ }+ ]++ out = config._transform_messages_helper(+ messages, model="accounts/fireworks/models/glm-5p2", litellm_params={}+ )+ assert out == messages+++def test_transform_messages_helper_no_transform_inline():+ config = FireworksAIConfig()+ url = "https://example.com/image.jpg"+ messages = [+ {+ "role": "user",+ "content": [{"type": "image_url", "image_url": url}],+ }+ ]+ out = config._transform_messages_helper(+ messages, model="accounts/fireworks/models/minimax-m3", litellm_params={}+ )+ block = out[0]["content"][0]+ assert block["image_url"] == url+ assert "#transform=inline" not in block["image_url"]+++def test_get_provider_info_vision_from_model_cost(monkeypatch):+ config = FireworksAIConfig()++ vision_model = "fireworks_ai/test-vision-from-cost"+ monkeypatch.setitem(+ litellm.model_cost,+ vision_model,+ {"supports_vision": True, "supports_pdf_input": True},+ )+ info = config.get_provider_info(vision_model)+ assert info["supports_vision"] is True+ assert info["supports_pdf_input"] is True++ no_vision_model = "fireworks_ai/test-no-vision-from-cost"+ monkeypatch.setitem(litellm.model_cost, no_vision_model, {})+ info_no_vision = config.get_provider_info(no_vision_model)+ assert info_no_vision.get("supports_vision") is not True+ assert "supports_pdf_input" not in info_no_vision+++def test_reasoning_effort_boolean_true_to_medium():+ config = FireworksAIConfig()+ result = config.map_openai_params(+ {"reasoning_effort": True},+ {},+ _REASONING_MODEL,+ drop_params=False,+ )+ assert result["reasoning_effort"] == "medium"+++def test_reasoning_effort_boolean_false_to_none():+ config = FireworksAIConfig()+ result = config.map_openai_params(+ {"reasoning_effort": False},+ {},+ _REASONING_MODEL,+ drop_params=False,+ )+ assert result["reasoning_effort"] == "none"+++def test_reasoning_effort_string_passthrough():+ config = FireworksAIConfig()+ result = config.map_openai_params(+ {"reasoning_effort": "high"},+ {},+ _REASONING_MODEL,+ drop_params=False,+ )+ assert result["reasoning_effort"] == "high"+++def test_reasoning_effort_integer_passthrough():+ config = FireworksAIConfig()+ result = config.map_openai_params(+ {"reasoning_effort": 1000},+ {},+ _REASONING_MODEL,+ drop_params=False,+ )+ assert result["reasoning_effort"] == 1000+ assert isinstance(result["reasoning_effort"], int)+++def test_transform_response_captures_perf_metrics():+ body = {+ **_BASE_CHAT_COMPLETION_RESPONSE,+ "perf_metrics": {"prompt-tokens": 10},+ }+ result = _run_transform_response(body)+ assert result._hidden_params["fireworks_perf_metrics"] == {"prompt-tokens": 10}+++def test_transform_response_captures_prompt_token_ids():+ body = {+ **_BASE_CHAT_COMPLETION_RESPONSE,+ "prompt_token_ids": [1, 2, 3],+ }+ result = _run_transform_response(body)+ assert result._hidden_params["fireworks_prompt_token_ids"] == [1, 2, 3]+++def test_transform_response_captures_raw_output():+ raw_output = {+ "prompt_fragments": [],+ "prompt_token_ids": [],+ "completion": "test",+ }+ body = {+ **_BASE_CHAT_COMPLETION_RESPONSE,+ "choices": [+ {+ **_BASE_CHAT_COMPLETION_RESPONSE["choices"][0],+ "raw_output": raw_output,+ }+ ],+ }+ result = _run_transform_response(body)+ assert result._hidden_params["fireworks_raw_outputs"] == [raw_output]+++def test_transform_response_captures_token_ids():+ body = {+ **_BASE_CHAT_COMPLETION_RESPONSE,+ "choices": [+ {+ **_BASE_CHAT_COMPLETION_RESPONSE["choices"][0],+ "token_ids": [4, 5, 6],+ }+ ],+ }+ result = _run_transform_response(body)+ assert result._hidden_params["fireworks_token_ids"] == [[4, 5, 6]]+++def test_streaming_surfaces_fireworks_response_fields():+ """+ The Fireworks-specific response fields captured into _hidden_params for+ non-streaming calls must also reach streamed responses. They ride the+ streamed chunks' provider_specific_fields (litellm rebuilds each streamed+ chunk, so per-chunk _hidden_params does not survive): per-choice+ token_ids/raw_output on the content chunk, response-level+ perf_metrics/prompt_token_ids on the final usage chunk. Driving the real+ litellm.completion(stream=True) path also covers the get_model_response_iterator+ wiring; dropping the Fireworks iterator would leave these fields unset.+ """+ from litellm.llms.custom_httpx.http_handler import HTTPHandler++ model = "accounts/fireworks/models/llama-v3p1-8b-instruct"+ raw_output = {"completion": "Hi"}+ sse_lines = [+ "data: "+ + json.dumps(+ {+ "id": "stream-1",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": model,+ "choices": [+ {+ "index": 0,+ "delta": {"role": "assistant", "content": "Hi"},+ "token_ids": [123],+ "raw_output": raw_output,+ }+ ],+ }+ ),+ "data: "+ + json.dumps(+ {+ "id": "stream-1",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": model,+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ "usage": {+ "prompt_tokens": 5,+ "completion_tokens": 1,+ "total_tokens": 6,+ },+ "perf_metrics": {"prompt-tokens": 5},+ "prompt_token_ids": [1, 2, 3],+ }+ ),+ "data: [DONE]",+ ]++ raw_response = MagicMock()+ raw_response.status_code = 200+ raw_response.headers = {}+ raw_response.iter_lines = lambda: iter(sse_lines)++ client = HTTPHandler()+ with patch.object(client, "post", return_value=raw_response):+ stream = litellm.completion(+ model=f"fireworks_ai/{model}",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ api_key="fw-test-key",+ client=client,+ )+ surfaced: dict = {}+ for chunk in stream:+ fields = getattr(chunk, "provider_specific_fields", None) or {}+ surfaced.update(+ {k: v for k, v in fields.items() if k.startswith("fireworks_")}+ )++ assert surfaced["fireworks_token_ids"] == [[123]]+ assert surfaced["fireworks_raw_outputs"] == [raw_output]+ assert surfaced["fireworks_perf_metrics"] == {"prompt-tokens": 5}+ assert surfaced["fireworks_prompt_token_ids"] == [1, 2, 3]diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.pyindex 44e0b55ee3b..d94a86d8e55 100644--- a/tests/test_litellm/test_utils.py+++ b/tests/test_litellm/test_utils.py@@ -4292,7 +4292,7 @@ _FIREWORKS_MODELS = [6e-08,512000,512000,- False,+ True,True,),(