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(utils): skip null tool_calls when formatting prompts for moderation hooks

yucheng4e6bf1cfe380
diff --git a/litellm/litellm_core_utils/llm_response_utils/get_formatted_prompt.py b/litellm/litellm_core_utils/llm_response_utils/get_formatted_prompt.py
index 549a2d153a2..2c1befb7ac3 100644
--- a/litellm/litellm_core_utils/llm_response_utils/get_formatted_prompt.py
+++ b/litellm/litellm_core_utils/llm_response_utils/get_formatted_prompt.py
@@ -30,7 +30,7 @@ def get_formatted_prompt(
if c["type"] == "text":
prompt += c["text"]
if "tool_calls" in message:
- for tool_call in message["tool_calls"]:
+ for tool_call in message["tool_calls"] or ():
if "function" in tool_call:
function_arguments = tool_call["function"]["arguments"]
prompt += function_arguments
diff --git a/tests/test_litellm/litellm_core_utils/llm_response_utils/test_get_formatted_prompt.py b/tests/test_litellm/litellm_core_utils/llm_response_utils/test_get_formatted_prompt.py
new file mode 100644
index 00000000000..64dd79bb918
--- /dev/null
+++ b/tests/test_litellm/litellm_core_utils/llm_response_utils/test_get_formatted_prompt.py
@@ -0,0 +1,24 @@
+from typing import Final, Literal
+
+import pytest
+
+from litellm.litellm_core_utils.llm_response_utils.get_formatted_prompt import (
+ get_formatted_prompt,
+)
+
+
[email protected]("call_type", ["acompletion", "completion"])
+def test_null_tool_calls_are_skipped(call_type: Literal["acompletion", "completion"]) -> None:
+ data: Final = {
+ "messages": [
+ {"role": "user", "content": "ping"},
+ {"role": "assistant", "content": "pong", "tool_calls": None},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"function": {"name": "f", "arguments": '{"x":1}'}}],
+ },
+ ]
+ }
+
+ assert get_formatted_prompt(data=data, call_type=call_type) == 'pingpong{"x":1}'