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]

feat(fireworks_ai): translate NIM/vLLM extra params to Fireworks-native args

Miles Adkins0c0e1e8374d7
diff --git a/litellm/llms/fireworks_ai/chat/transformation.py b/litellm/llms/fireworks_ai/chat/transformation.py
index a796aa47b70..4740e84d513 100644
--- a/litellm/llms/fireworks_ai/chat/transformation.py
+++ b/litellm/llms/fireworks_ai/chat/transformation.py
@@ -1,5 +1,5 @@
import json
-from collections.abc import AsyncIterator, Iterator
+from collections.abc import AsyncIterator, Iterator, Mapping
from typing import Any, Final, Literal, cast
import httpx
@@ -61,6 +61,36 @@ def _extract_fireworks_hidden_params(payload: dict) -> dict:
return {**top_level, **per_choice}
+def _json_schema_response_format(schema: object) -> Mapping[str, object]:
+ return {"type": "json_schema", "json_schema": {"schema": schema}} # mutable-ok: JSON request body
+
+
+_NIM_VLLM_STRIP_PARAMS: Final = frozenset(
+ {
+ "min_tokens",
+ "stop_token_ids",
+ "include_stop_str_in_output",
+ "skip_special_tokens",
+ "spaces_between_special_tokens",
+ "best_of",
+ "use_beam_search",
+ "guided_decoding_backend",
+ "guided_regex",
+ "add_generation_prompt",
+ "continue_final_message",
+ "add_special_tokens",
+ "detokenize",
+ "allowed_token_ids",
+ "bad_words",
+ }
+)
+
+_EXTRA_BODY_CONSUMED_PARAMS: Final = (
+ frozenset({"truncate_prompt_tokens", "chat_template_kwargs", "guided_json", "guided_grammar", "guided_choice"})
+ | _NIM_VLLM_STRIP_PARAMS
+)
+
+
class FireworksAIConfig(FireworksAIMixin, OpenAIGPTConfig):
"""
Reference: https://docs.fireworks.ai/api-reference/post-chatcompletions
@@ -273,6 +303,136 @@ class FireworksAIConfig(FireworksAIMixin, OpenAIGPTConfig):
return optional_params
+ def map_extra_body_params(self, optional_params: Mapping[str, object], model: str) -> dict: # noqa: LIT001 # http handler pops extra_body off the returned dict
+ extra_body: Final = optional_params.get("extra_body")
+ if not isinstance(extra_body, dict):
+ return dict(optional_params) # mutable-ok: JSON request body
+
+ self._validate_extra_body_conflicts(extra_body=extra_body, optional_params=optional_params, model=model)
+ stripped: Final = tuple(sorted(k for k in extra_body if k in _NIM_VLLM_STRIP_PARAMS))
+ if stripped:
+ verbose_logger.debug(
+ "fireworks_ai does not support NIM/vLLM params %s for model=%s; dropping them from the request.",
+ stripped,
+ model,
+ )
+ promoted: Final = (
+ *self._translate_truncate_prompt_tokens(extra_body),
+ *self._translate_chat_template_kwargs(extra_body, model),
+ *self._translate_guided_params(extra_body),
+ )
+ remaining: Final = tuple((k, v) for k, v in extra_body.items() if k not in _EXTRA_BODY_CONSUMED_PARAMS)
+ base: Final = {k: v for k, v in optional_params.items() if k != "extra_body"} # mutable-ok: JSON request body
+ return { # mutable-ok: JSON request body
+ **base,
+ **dict(promoted), # mutable-ok: JSON request body
+ **({"extra_body": dict(remaining)} if remaining else {}), # mutable-ok: JSON request body
+ }
+
+ def _validate_extra_body_conflicts(
+ self, extra_body: Mapping[str, object], optional_params: Mapping[str, object], model: str
+ ) -> None:
+ if "truncate_prompt_tokens" in extra_body and (
+ "prompt_truncate_len" in extra_body or "prompt_truncate_len" in optional_params
+ ):
+ raise litellm.BadRequestError(
+ message=(
+ "Fireworks AI chat completions received both `truncate_prompt_tokens` and "
+ "`prompt_truncate_len`; they are aliases, send only one."
+ ),
+ model=model,
+ llm_provider="fireworks_ai",
+ )
+ chat_template_kwargs: Final = extra_body.get("chat_template_kwargs")
+ if (
+ isinstance(chat_template_kwargs, dict)
+ and "enable_thinking" in chat_template_kwargs
+ and ("reasoning_effort" in optional_params or "thinking" in optional_params)
+ ):
+ raise litellm.BadRequestError(
+ message=(
+ "Fireworks AI chat completions does not support specifying both "
+ "`chat_template_kwargs.enable_thinking` and `reasoning_effort`/`thinking` in the same request."
+ ),
+ model=model,
+ llm_provider="fireworks_ai",
+ )
+ guided_params: Final = tuple(
+ k for k in ("guided_json", "guided_grammar", "guided_choice") if extra_body.get(k) is not None
+ )
+ if len(guided_params) > 1:
+ raise litellm.BadRequestError(
+ message=(
+ f"Fireworks AI chat completions received multiple guided decoding params "
+ f"{guided_params}; send only one."
+ ),
+ model=model,
+ llm_provider="fireworks_ai",
+ )
+ if guided_params and "response_format" in optional_params:
+ raise litellm.BadRequestError(
+ message=(
+ f"Fireworks AI chat completions received both `{guided_params[0]}` and "
+ "`response_format`; they are competing output constraints, send only one."
+ ),
+ model=model,
+ llm_provider="fireworks_ai",
+ )
+
+ @staticmethod
+ def _translate_truncate_prompt_tokens(extra_body: Mapping[str, object]) -> tuple[tuple[str, object], ...]:
+ if extra_body.get("truncate_prompt_tokens") is None:
+ return ()
+ return (("prompt_truncate_len", extra_body["truncate_prompt_tokens"]),)
+
+ def _translate_chat_template_kwargs(
+ self, extra_body: Mapping[str, object], model: str
+ ) -> tuple[tuple[str, object], ...]:
+ chat_template_kwargs: Final = extra_body.get("chat_template_kwargs")
+ if chat_template_kwargs is None:
+ return ()
+ if not isinstance(chat_template_kwargs, dict):
+ raise litellm.BadRequestError(
+ message="Fireworks AI chat completions expects `chat_template_kwargs` to be an object.",
+ model=model,
+ llm_provider="fireworks_ai",
+ )
+ other_keys: Final = tuple(sorted(k for k in chat_template_kwargs if k != "enable_thinking"))
+ if other_keys:
+ verbose_logger.debug(
+ "fireworks_ai does not support chat_template_kwargs keys %s for model=%s; dropping them.",
+ other_keys,
+ model,
+ )
+ if "enable_thinking" not in chat_template_kwargs:
+ return ()
+ if not supports_reasoning(model=model, custom_llm_provider="fireworks_ai"):
+ verbose_logger.debug(
+ "fireworks_ai model %r does not support reasoning; dropping chat_template_kwargs.enable_thinking.",
+ model,
+ )
+ return ()
+ effort: Final = "medium" if chat_template_kwargs["enable_thinking"] else "none"
+ return (("reasoning_effort", effort),)
+
+ @staticmethod
+ def _translate_guided_params(extra_body: Mapping[str, object]) -> tuple[tuple[str, object], ...]:
+ if extra_body.get("guided_json") is not None:
+ return (("response_format", _json_schema_response_format(extra_body["guided_json"])),)
+ if extra_body.get("guided_grammar") is not None:
+ grammar_response_format: Final = { # mutable-ok: JSON request body
+ "type": "grammar",
+ "grammar": extra_body["guided_grammar"],
+ }
+ return (("response_format", grammar_response_format),)
+ if extra_body.get("guided_choice") is not None:
+ choice_schema: Final = { # mutable-ok: JSON request body
+ "type": "string",
+ "enum": extra_body["guided_choice"],
+ }
+ return (("response_format", _json_schema_response_format(choice_schema)),)
+ return ()
+
def _transform_tools(self, tools: list[OpenAIChatCompletionToolParam]) -> list[OpenAIChatCompletionToolParam]:
for tool in tools:
if tool.get("type") != "function":
diff --git a/litellm/main.py b/litellm/main.py
index f906c78f9ae..660e024b113 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -1711,11 +1711,15 @@ def _complete_fireworks_ai(
messages: Final = ctx.messages
model: Final = ctx.model
model_response: Final = ctx.model_response
- optional_params: Final = ctx.optional_params
provider_config: Final = ctx.provider_config
shared_session: Final = ctx.shared_session
stream: Final = ctx.stream
timeout: Final = ctx.timeout
+ optional_params: Final = (
+ provider_config.map_extra_body_params(optional_params=ctx.optional_params, model=model)
+ if isinstance(provider_config, litellm.FireworksAIConfig)
+ else ctx.optional_params
+ )
try:
response: Final = base_llm_http_handler.completion(
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.py
index 94945ed4bfb..3fbbc70916a 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
@@ -1282,3 +1282,252 @@ def test_streaming_surfaces_fireworks_response_fields():
assert surfaced["fireworks_raw_outputs"] == [raw_output]
assert surfaced["fireworks_perf_metrics"] == {"prompt-tokens": 5}
assert surfaced["fireworks_prompt_token_ids"] == [1, 2, 3]
+
+
+def test_map_extra_body_params_translates_truncate_prompt_tokens():
+ config = FireworksAIConfig()
+ result = config.map_extra_body_params(
+ {"extra_body": {"truncate_prompt_tokens": 4096}}, _REASONING_MODEL
+ )
+ assert result == {"prompt_truncate_len": 4096}
+
+
+def test_map_extra_body_params_truncate_prompt_tokens_conflicts_with_alias():
+ config = FireworksAIConfig()
+ with pytest.raises(litellm.BadRequestError, match="aliases"):
+ config.map_extra_body_params(
+ {"prompt_truncate_len": 2048, "extra_body": {"truncate_prompt_tokens": 4096}},
+ _REASONING_MODEL,
+ )
+ with pytest.raises(litellm.BadRequestError, match="aliases"):
+ config.map_extra_body_params(
+ {"extra_body": {"truncate_prompt_tokens": 4096, "prompt_truncate_len": 2048}},
+ _REASONING_MODEL,
+ )
+
+
+def test_map_extra_body_params_chat_template_kwargs_enable_thinking():
+ config = FireworksAIConfig()
+ disabled = config.map_extra_body_params(
+ {"extra_body": {"chat_template_kwargs": {"enable_thinking": False}}},
+ _REASONING_MODEL,
+ )
+ assert disabled == {"reasoning_effort": "none"}
+
+ enabled = config.map_extra_body_params(
+ {"extra_body": {"chat_template_kwargs": {"enable_thinking": True}}},
+ _REASONING_MODEL,
+ )
+ assert enabled == {"reasoning_effort": "medium"}
+
+
+def test_map_extra_body_params_chat_template_kwargs_conflicts_with_reasoning_effort():
+ config = FireworksAIConfig()
+ with pytest.raises(litellm.BadRequestError, match="enable_thinking"):
+ config.map_extra_body_params(
+ {
+ "reasoning_effort": "high",
+ "extra_body": {"chat_template_kwargs": {"enable_thinking": False}},
+ },
+ _REASONING_MODEL,
+ )
+
+
+def test_map_extra_body_params_chat_template_kwargs_conflicts_with_thinking():
+ config = FireworksAIConfig()
+ with pytest.raises(litellm.BadRequestError, match="enable_thinking"):
+ config.map_extra_body_params(
+ {
+ "thinking": {"type": "enabled", "budget_tokens": 4096},
+ "extra_body": {"chat_template_kwargs": {"enable_thinking": True}},
+ },
+ _REASONING_MODEL,
+ )
+
+
+def test_map_extra_body_params_chat_template_kwargs_dropped_for_non_reasoning_model():
+ config = FireworksAIConfig()
+ result = config.map_extra_body_params(
+ {"extra_body": {"chat_template_kwargs": {"enable_thinking": False, "custom_flag": 1}}},
+ _NON_REASONING_MODEL,
+ )
+ assert result == {}
+
+
+def test_map_extra_body_params_guided_json():
+ config = FireworksAIConfig()
+ schema = {"type": "object", "properties": {"x": {"type": "string"}}}
+ result = config.map_extra_body_params(
+ {"extra_body": {"guided_json": schema}}, _REASONING_MODEL
+ )
+ assert result == {
+ "response_format": {"type": "json_schema", "json_schema": {"schema": schema}}
+ }
+
+
+def test_map_extra_body_params_guided_grammar_and_choice():
+ config = FireworksAIConfig()
+ grammar = config.map_extra_body_params(
+ {"extra_body": {"guided_grammar": "root ::= 'hello'"}}, _REASONING_MODEL
+ )
+ assert grammar == {
+ "response_format": {"type": "grammar", "grammar": "root ::= 'hello'"}
+ }
+
+ choice = config.map_extra_body_params(
+ {"extra_body": {"guided_choice": ["yes", "no"]}}, _REASONING_MODEL
+ )
+ assert choice == {
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {"schema": {"type": "string", "enum": ["yes", "no"]}},
+ }
+ }
+
+
+def test_map_extra_body_params_guided_conflicts_with_response_format():
+ config = FireworksAIConfig()
+ with pytest.raises(litellm.BadRequestError, match="response_format"):
+ config.map_extra_body_params(
+ {
+ "response_format": {"type": "json_object"},
+ "extra_body": {"guided_json": {"type": "object"}},
+ },
+ _REASONING_MODEL,
+ )
+
+
+def test_map_extra_body_params_multiple_guided_params_rejected():
+ config = FireworksAIConfig()
+ with pytest.raises(litellm.BadRequestError, match="multiple guided decoding params"):
+ config.map_extra_body_params(
+ {"extra_body": {"guided_json": {"type": "object"}, "guided_grammar": "root ::= 'x'"}},
+ _REASONING_MODEL,
+ )
+
+
+ "param,value",
+ [
+ ("min_tokens", 10),
+ ("stop_token_ids", [1, 2]),
+ ("include_stop_str_in_output", True),
+ ("skip_special_tokens", False),
+ ("spaces_between_special_tokens", True),
+ ("best_of", 2),
+ ("use_beam_search", True),
+ ("guided_decoding_backend", "outlines"),
+ ("guided_regex", "[0-9]+"),
+ ("add_generation_prompt", True),
+ ("continue_final_message", True),
+ ("add_special_tokens", False),
+ ("detokenize", True),
+ ("allowed_token_ids", [1]),
+ ("bad_words", ["foo"]),
+ ],
+)
+def test_map_extra_body_params_strips_unsupported_nim_vllm_params(param, value, caplog):
+ import logging
+
+ config = FireworksAIConfig()
+ with caplog.at_level(logging.DEBUG):
+ result = config.map_extra_body_params(
+ {"extra_body": {param: value}}, _REASONING_MODEL
+ )
+ assert result == {}
+ assert param in caplog.text
+
+
+def test_map_extra_body_params_preserves_unknown_passthrough():
+ config = FireworksAIConfig()
+ result = config.map_extra_body_params(
+ {"extra_body": {"top_k": 40, "some_future_param": "x", "truncate_prompt_tokens": 100}},
+ _REASONING_MODEL,
+ )
+ assert result == {
+ "prompt_truncate_len": 100,
+ "extra_body": {"top_k": 40, "some_future_param": "x"},
+ }
+
+
+def test_map_extra_body_params_no_extra_body():
+ config = FireworksAIConfig()
+ assert config.map_extra_body_params({}, _REASONING_MODEL) == {}
+ unchanged = {"temperature": 0.5, "extra_body": None}
+ assert config.map_extra_body_params(unchanged, _REASONING_MODEL) == unchanged
+
+
+def test_nim_vllm_extras_translated_end_to_end_in_request_body():
+ """
+ Passing NIM/vLLM extras to litellm.completion must reach the Fireworks
+ request body translated, not verbatim: truncate_prompt_tokens becomes
+ prompt_truncate_len, chat_template_kwargs.enable_thinking becomes
+ reasoning_effort, min_tokens is dropped, and fireworks-native top_k still
+ passes through. Asserts on the actual JSON posted to the API, so a revert
+ of the _complete_fireworks_ai wiring fails this test.
+ """
+ from litellm.llms.custom_httpx.http_handler import HTTPHandler
+
+ model = "accounts/fireworks/models/glm-5p1"
+ body = {
+ "id": "chat-1",
+ "object": "chat.completion",
+ "created": 1,
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "Hi"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ }
+ raw_response = MagicMock()
+ raw_response.status_code = 200
+ raw_response.headers = {}
+ raw_response.text = json.dumps(body)
+ raw_response.json = lambda: body
+
+ client = HTTPHandler()
+ with patch.object(client, "post", return_value=raw_response) as mock_post:
+ litellm.completion(
+ model=f"fireworks_ai/{model}",
+ messages=[{"role": "user", "content": "hi"}],
+ api_key="fw-test-key",
+ client=client,
+ truncate_prompt_tokens=4096,
+ chat_template_kwargs={"enable_thinking": False},
+ min_tokens=10,
+ top_k=40,
+ )
+
+ request_body = json.loads(mock_post.call_args.kwargs["data"])
+ assert request_body["prompt_truncate_len"] == 4096
+ assert "truncate_prompt_tokens" not in request_body
+ assert request_body["reasoning_effort"] == "none"
+ assert "chat_template_kwargs" not in request_body
+ assert "min_tokens" not in request_body
+ assert request_body["top_k"] == 40
+
+
+def test_in_schema_unsupported_params_still_raise():
+ """
+ The extras translation channel does not weaken the supported-params gate
+ for in-schema OpenAI params: store is still rejected with drop_params=False
+ and dropped with drop_params=True.
+ """
+ with pytest.raises(litellm.UnsupportedParamsError):
+ litellm.get_optional_params(
+ model="accounts/fireworks/models/llama-v3-70b-instruct",
+ custom_llm_provider="fireworks_ai",
+ drop_params=False,
+ store=True,
+ )
+ optional_params = litellm.get_optional_params(
+ model="accounts/fireworks/models/llama-v3-70b-instruct",
+ custom_llm_provider="fireworks_ai",
+ drop_params=True,
+ store=True,
+ )
+ assert "store" not in optional_params