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
fix(prompt_templates): do not mutate messages in-place in function_call_prompt (#41676)
mgeorgaklisb3c9d4c1f751
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.pyindex fc4a19f2a1d..898fac6de72 100644--- a/litellm/litellm_core_utils/prompt_templates/factory.py+++ b/litellm/litellm_core_utils/prompt_templates/factory.py@@ -5431,40 +5431,63 @@ def _bedrock_tools_pt(return tool_block_list+def _is_system_message(message: Mapping[str, object]) -> bool:+ role: Final = message.get("role")+ return isinstance(role, str) and "system" in role+++_CONTENT_BLOCKS: Final = TypeAdapter(list[object])+++def _content_with_function_prompt(+ content: object, function_prompt: str, *, model: str, llm_provider: str, drop_params: bool+) -> str | Sequence[object]:+ if isinstance(content, str):+ return f"{content} {function_prompt}"+ if isinstance(content, list):+ return [*_CONTENT_BLOCKS.validate_python(content), {"type": "text", "text": f" {function_prompt}"}]+ if drop_params:+ return function_prompt+ raise litellm.BadRequestError(+ message=(+ f"system message content must be a string or a list of content parts, got {type(content).__name__}. "+ "Pass drop_params=True to send the function prompt in its place"+ ),+ model=model,+ llm_provider=llm_provider,+ )++# Function call templatedef function_call_prompt(messages: list[dict[str, object]],functions: list[object],+ *,+ model: str,+ llm_provider: str,+ drop_params: bool,) -> list[dict[str, object]]:- function_prompt = """To call a function, reply with JSON ONLY in this format {"name": "function_name", "arguments":{"argument_name": "argument_value"}}. Once a function result answers the request, reply to the user in plain text instead of calling a function again. The following functions are available to you:"""- for function in functions:- function_prompt += f"""\n{function}\n"""-- def _append_function_prompt(message: dict[str, object]) -> bool:- role: Final = cast( # cast-ok: preserve dynamic role membership behavior- Container[object], message["role"]+ header: Final = """To call a function, reply with JSON ONLY in this format {"name": "function_name", "arguments":{"argument_name": "argument_value"}}. Once a function result answers the request, reply to the user in plain text instead of calling a function again. The following functions are available to you:"""+ function_prompt: Final = header + "".join(f"\n{function}\n" for function in functions)+ if not any(_is_system_message(message) for message in messages):+ return [*messages, {"role": "system", "content": function_prompt}]+ return [+ (+ {+ **message,+ "content": _content_with_function_prompt(+ message.get("content"),+ function_prompt,+ model=model,+ llm_provider=llm_provider,+ drop_params=drop_params,+ ),+ }+ if _is_system_message(message)+ else message)- if "system" not in role:- return False-- content: Final = message["content"]- if isinstance(content, str):- message["content"] = f"{content} {function_prompt}"- else:- cast( # cast-ok: preserve dynamic content append behavior- list[object], content- ).append({"type": "text", "text": f""" {function_prompt}"""})- return True-- function_added_to_prompt = False- for message in messages:- if _append_function_prompt(message):- function_added_to_prompt = True-- if function_added_to_prompt is False:- messages.append({"role": "system", "content": f"""{function_prompt}"""})-- return messages+ for message in messages+ ]def response_schema_prompt(model: str, response_schema: dict) -> str:diff --git a/litellm/main.py b/litellm/main.pyindex b93c61ead16..d8e62ebcdad 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -4124,6 +4124,7 @@ def _complete_sagemaker(ctx: CompletionDispatchContext) -> _CompletionDispatchRe_ADDITIONAL_DROP_PARAMS_ADAPTER: Final = TypeAdapter(list[str])_OPTIONAL_PARAMS_ADAPTER: Final = TypeAdapter(dict[str, object])+_REQUEST_KWARGS_ADAPTER: Final = TypeAdapter(Mapping[str, object])_PROVIDER_ROUTING_HINTS: Final = TypeAdapter(ProviderRoutingHints)_BASE_URL_HINT: Final = TypeAdapter(BaseUrlRoutingHint)@@ -5698,7 +5699,15 @@ def completion(functions_unsupported_model: Final[list[object]] = TypeAdapter(list[object]).validate_python(optional_params.pop("functions_unsupported_model"))- messages = function_call_prompt(messages=messages, functions=functions_unsupported_model)+ request_kwargs: Final = _REQUEST_KWARGS_ADAPTER.validate_python(kwargs)+ messages = function_call_prompt(+ messages=messages,+ functions=functions_unsupported_model,+ model=model,+ llm_provider=custom_llm_provider,+ drop_params=litellm.drop_params is True+ or normalize_drop_params(request_kwargs.get("drop_params")) is True,+ )# For logging - save the values of the litellm-specific params passed inrequested_litellm_params: Final = get_litellm_params(diff --git a/tests/integration/providers/test_ollama_prompt_tools_chaos.py b/tests/integration/providers/test_ollama_prompt_tools_chaos.pyindex 37529f9f692..3c7e7e95685 100644--- a/tests/integration/providers/test_ollama_prompt_tools_chaos.py+++ b/tests/integration/providers/test_ollama_prompt_tools_chaos.py@@ -156,6 +156,9 @@ def _body(model: str, call: _Call) -> dict[str, JsonValue]:}+_Builder = Callable[[str, _Call], dict[str, JsonValue]]++def _generate_reply(marker: str, stream: bool, drop_connection: bool = False) -> Reply:done: Final = {"model": _BACKEND,@@ -249,11 +252,11 @@ def _successes(statuses: MappingProxyType[str, str]) -> frozenset[str]:return frozenset(identity for identity, status in statuses.items() if status == "success")-async def _send(client: httpx.AsyncClient, key: str, model: str, call: _Call) -> _Served:+async def _send(client: httpx.AsyncClient, key: str, model: str, call: _Call, build: _Builder) -> _Served:async with client.stream("POST",_path(call.endpoint),- json=_body(model, call),+ json=build(model, call),headers={"Authorization": f"Bearer {key}", "anthropic-version": "2023-06-01"},) as response:raw: Final = await response.aread()@@ -261,11 +264,17 @@ async def _send(client: httpx.AsyncClient, key: str, model: str, call: _Call) ->async def _burst(- base_url: str, key: str, model: str, calls: tuple[_Call, ...], *, tolerate_transport_errors: bool = False+ base_url: str,+ key: str,+ model: str,+ calls: tuple[_Call, ...],+ *,+ tolerate_transport_errors: bool = False,+ build: _Builder = _body,) -> tuple[_Served, ...]:async with httpx.AsyncClient(base_url=base_url, timeout=60, trust_env=False) as client:results: Final = await asyncio.gather(- *(_send(client, key, model, call) for call in calls), return_exceptions=tolerate_transport_errors+ *(_send(client, key, model, call, build) for call in calls), return_exceptions=tolerate_transport_errors)for result in results:assert not isinstance(result, BaseException) or isinstance(result, httpx.TransportError), repr(result)@@ -302,6 +311,61 @@ async def test_concurrent_tool_result_turns_across_endpoints_each_get_their_own_assert known <= _successes(statuses)+def _down(request: Request) -> Reply:+ if not _is_generate(request):+ return Reply(body=b"{}")+ return Reply(status=500, body=json.dumps({"error": "primary ollama is down"}).encode())+++def _items(body: dict[str, JsonValue], key: str) -> list[JsonValue]:+ value: Final = body[key]+ assert isinstance(value, list), body+ return value+++def _with_list_system(body: dict[str, JsonValue], endpoint: Endpoint, system: str) -> dict[str, JsonValue]:+ match endpoint:+ case "chat":+ return {+ **body,+ "messages": [{"role": "system", "content": [{"type": "text", "text": system}]}, *_items(body, "messages")],+ }+ case "messages":+ return {**body, "system": [{"type": "text", "text": system}]}+ case "responses":+ return {+ **body,+ "input": [{"role": "system", "content": [{"type": "input_text", "text": system}]}, *_items(body, "input")],+ }+++async def test_concurrent_fallbacks_from_failed_list_system_turns_each_send_the_instruction_once(+ gateway: Gateway,+) -> None:+ calls: Final = _calls(24, ("chat", "messages", "responses"), lambda index: index % 2 == 0)+ markers: Final = frozenset(call.marker for call in calls)+ with wire_server(_down) as primary_wire, wire_server(_echo) as fallback_wire, gateway.scenario() as scenario:+ primary: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=primary_wire.url, api_key=_API_KEY)+ fallback: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=fallback_wire.url, api_key=_API_KEY)++ def build(model: str, call: _Call) -> dict[str, JsonValue]:+ return _with_list_system(+ {**_body(model, call), "fallbacks": [fallback]}, call.endpoint, f"Terse bot marker-{call.marker}."+ )++ served: Final = await _burst(str(gateway.client.base_url), gateway.key, primary, calls, build=build)+ assert len(served) == 24+ for item in served:+ _assert_answered_with_its_own_marker(item)+ _assert_each_prompt_is_instructed_once(primary_wire.drain(), markers)+ _assert_each_prompt_is_instructed_once(fallback_wire.drain(), markers)+ known: Final = frozenset(identity for identity in map(_response_id, served) if identity is not None)+ assert len(known) == 16, known+ statuses: Final = _spend_statuses(fallback, 24)+ assert _successes(statuses) == frozenset(statuses), statuses+ assert known <= _successes(statuses)++async def test_dropped_ollama_connections_fail_their_callers_and_the_rest_keep_their_prompts(gateway: Gateway) -> None:calls: Final = _calls(12, ("chat",), lambda index: index % 2 == 1)dropped: Final = frozenset(call.marker for index, call in enumerate(calls) if index % 3 == 0)diff --git a/tests/integration/providers/test_ollama_prompt_tools_wire.py b/tests/integration/providers/test_ollama_prompt_tools_wire.pyindex f3aa18cb366..59a2ee58a44 100644--- a/tests/integration/providers/test_ollama_prompt_tools_wire.py+++ b/tests/integration/providers/test_ollama_prompt_tools_wire.py@@ -4,17 +4,20 @@ import jsonimport uuidfrom collections.abc import Callable, Iterator, Sequencefrom contextlib import contextmanager-from typing import Final+from pathlib import Path+from typing import Final, Literalimport anthropicimport openaiimport pytest+import yamlfrom openai.types import Completionfrom openai.types.chat import ChatCompletion, ChatCompletionChunkfrom openai.types.chat.chat_completion_chunk import Choice as ChunkChoicefrom openai.types.chat.chat_completion_chunk import ChoiceDeltaToolCallfrom integration._support.client import Gateway, eventually, object_valuefrom integration._support.database import read_rows+from integration._support.process import graceful_stop_seconds, owned_proxyfrom integration._support.wire import Reply, Request, Wire, wire_serverfrom pydantic import JsonValue, TypeAdapter@@ -1398,3 +1401,308 @@ async def test_concurrent_valid_and_malformed_turns_are_each_answered_in_their_oassert statuses == ["failure"] * 4 + ["success"] * 8, statusesfor answer in answers:assert _spend_row(answer.id) == _billed(model)+++_SYSTEM_CONTENT_ERROR: Final = "system message content must be a string or a list of content parts, got"+_PRIMARY_DOWN: Final = Reply(status=500, body=json.dumps({"error": "primary ollama is down"}).encode())++SystemEndpoint = Literal["chat", "messages", "responses"]+++def _terse_system() -> str:+ return f"You are a terse weather bot {uuid.uuid4().hex}."+++def _list_system(text: str) -> dict[str, JsonValue]:+ return {"role": "system", "content": [{"type": "text", "text": text}]}+++def _with_system(system: JsonValue) -> list[JsonValue]:+ return [system, *_first_turn()]+++def _null_system_turn() -> list[dict[str, JsonValue]]:+ return [{"role": "system", "content": None}, *_first_turn()]+++def _path_of(endpoint: SystemEndpoint) -> str:+ match endpoint:+ case "chat":+ return "/v1/chat/completions"+ case "messages":+ return "/v1/messages"+ case "responses":+ return "/v1/responses"+++def _list_system_body(endpoint: SystemEndpoint, model: str, system: str, stream: bool) -> dict[str, JsonValue]:+ match endpoint:+ case "chat":+ return {+ "model": model,+ "stream": stream,+ "tools": [_WEATHER_TOOL],+ "messages": _with_system(_list_system(system)),+ }+ case "messages":+ return {+ "model": model,+ "stream": stream,+ "max_tokens": 64,+ "tools": [_ANTHROPIC_TOOL],+ "system": [{"type": "text", "text": system}],+ "messages": [*_first_turn()],+ }+ case "responses":+ return {+ "model": model,+ "stream": stream,+ "store": False,+ "tools": [_RESPONSES_TOOL],+ "input": _with_system({"role": "system", "content": [{"type": "input_text", "text": system}]}),+ }+++def _reply_in_kind(request: Request) -> Reply:+ streamed: Final = _JSON_OBJECT.validate_json(request.body).get("stream") is True+ return _streamed_reply(_CALL_JSON) if streamed else _generate_reply(_CALL_JSON)+++def _prompts(wire: Wire) -> list[str]:+ return [_prompt_of(_JSON_OBJECT.validate_json(request.body)) for request in _generate_calls(wire)]+++def _assert_system_instructed_once(prompt: str, system: str) -> None:+ _assert_instructed_once(prompt, "get_weather")+ assert prompt.split("### System:\n", 1)[1].startswith(system), prompt+++def _assert_prompt_replaces_the_system_content(prompt: str) -> None:+ _assert_instructed_once(prompt, "get_weather")+ assert prompt.startswith(f"### System:\n{_INSTRUCTION}"), prompt++[email protected]("stream", [pytest.param(False, id="sync"), pytest.param(True, id="stream")])[email protected]("endpoint", ["chat", "messages", "responses"])+def test_fallback_after_a_failed_list_system_turn_sends_the_instruction_once(+ gateway: Gateway, endpoint: SystemEndpoint, stream: bool+) -> None:+ system: Final = _terse_system()+ with (+ _ollama_server(lambda _: _PRIMARY_DOWN) as primary_wire,+ _ollama_server(_reply_in_kind) as fallback_wire,+ gateway.scenario() as scenario,+ ):+ primary: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=primary_wire.url, api_key=_API_KEY)+ fallback: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=fallback_wire.url, api_key=_API_KEY)+ code, text = _post(+ gateway,+ _path_of(endpoint),+ {**_list_system_body(endpoint, primary, system, stream), "fallbacks": [fallback], "num_retries": 0},+ )+ assert code == 200, text+ assert "get_weather" in text, text+ primary_prompts: Final = _prompts(primary_wire)+ assert len(primary_prompts) == 1, primary_prompts+ _assert_system_instructed_once(primary_prompts[0], system)+ fallback_prompts: Final = _prompts(fallback_wire)+ assert len(fallback_prompts) == 1, fallback_prompts+ _assert_system_instructed_once(fallback_prompts[0], system)+++def test_retry_after_a_failed_list_system_turn_sends_the_instruction_once(gateway: Gateway) -> None:+ system: Final = _terse_system()+ attempts: Final = itertools.count()++ def respond(_: Request) -> Reply:+ return _PRIMARY_DOWN if next(attempts) == 0 else _generate_reply(_CALL_JSON)++ with _ollama_server(respond) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)+ payload: Final = _post_chat(+ gateway, model, [_list_system(system), *_first_turn()], tools=[_WEATHER_TOOL], num_retries=1+ )+ prompts: Final = _prompts(wire)+ assert len(prompts) == 2, prompts+ for prompt in prompts:+ _assert_system_instructed_once(prompt, system)+ assert _spend_row(_id_of(payload)) == _billed(model)+++def _post_cacheable_chat(+ gateway: Gateway, model: str, messages: Sequence[dict[str, JsonValue]]+) -> dict[str, JsonValue]:+ response: Final = gateway.request(+ "POST", "/v1/chat/completions", {"model": model, "messages": list(messages), "tools": [_WEATHER_TOOL]}+ )+ assert response.status_code == 200, response.text+ return _JSON_OBJECT.validate_json(response.text)+++def test_identical_list_system_turns_are_answered_from_the_response_cache(gateway: Gateway) -> None:+ messages: Final = [_list_system(_terse_system()), *_first_turn()]+ with _ollama_server(lambda _: _generate_reply(_CALL_JSON)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)+ first: Final = _post_cacheable_chat(gateway, model, messages)+ first_id: Final = _id_of(first)+ assert _spend_row(first_id) == _billed(model)+ second: Final = _post_cacheable_chat(gateway, model, messages)+ assert _id_of(second) == first_id, (first, second)+ assert _first_message(second) == _first_message(first), (first, second)+ assert len(_generate_calls(wire)) == 1+ rows: Final = _cache_rows(model)+ assert [row["request_id"] for row in rows if row["cache_hit"] != "True"] == [first_id], rows+ assert len([row for row in rows if row["cache_hit"] == "True"]) == 1, rows+++ ("system", "type_name"),+ [+ pytest.param({"role": "system", "content": None}, "NoneType", id="null"),+ pytest.param({"role": "system"}, "NoneType", id="missing"),+ pytest.param({"role": "system", "content": {"text": "Be brief, secret-7f3a."}}, "dict", id="dict"),+ ],+)+def test_system_content_that_is_neither_text_nor_parts_is_a_400_naming_only_its_type(+ gateway: Gateway, system: dict[str, JsonValue], type_name: str+) -> None:+ with _ollama_server(lambda _: _generate_reply(_CALL_JSON)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)+ code, text = _post(+ gateway,+ "/v1/chat/completions",+ {"model": model, "messages": _with_system(system), "tools": [_WEATHER_TOOL]},+ )+ assert code == 400, text+ assert f"{_SYSTEM_CONTENT_ERROR} {type_name}." in _error_message(text), text+ assert "secret-7f3a" not in text, text+ assert _generate_calls(wire) == ()+ assert [row["status"] for row in _model_spend_rows(model, 1)] == ["failure"]+ _post_chat(gateway, model, _first_turn(), tools=[_WEATHER_TOOL])+ _assert_instructed_once(_prompt_of(_only_generate(wire)), "get_weather")++[email protected]("content", [pytest.param("", id="empty-string"), pytest.param([], id="empty-list")])+def test_empty_system_content_carries_the_instruction_once(gateway: Gateway, content: JsonValue) -> None:+ with _ollama_server(lambda _: _generate_reply(_CALL_JSON)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)+ _post_chat(gateway, model, [{"role": "system", "content": content}, *_first_turn()], tools=[_WEATHER_TOOL])+ _assert_instructed_once(_prompt_of(_only_generate(wire)), "get_weather")+++ "drop_params", [pytest.param(True, id="true"), pytest.param(1, id="int-1"), pytest.param("true", id="string-true")]+)+def test_drop_params_sends_the_function_prompt_in_place_of_null_system_content(+ gateway: Gateway, drop_params: JsonValue+) -> None:+ with _ollama_server(lambda _: _generate_reply(_CALL_JSON)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)+ payload: Final = _post_chat(gateway, model, _null_system_turn(), tools=[_WEATHER_TOOL], drop_params=drop_params)+ _assert_prompt_replaces_the_system_content(_prompt_of(_only_generate(wire)))+ assert _spend_row(_id_of(payload)) == _billed(model)+++def test_deployment_drop_params_sends_the_function_prompt_in_place_of_null_system_content(gateway: Gateway) -> None:+ with _ollama_server(lambda _: _generate_reply(_CALL_JSON)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=wire.url, api_key=_API_KEY, drop_params=True)+ payload: Final = _post_chat(gateway, model, _null_system_turn(), tools=[_WEATHER_TOOL])+ _assert_prompt_replaces_the_system_content(_prompt_of(_only_generate(wire)))+ assert _spend_row(_id_of(payload)) == _billed(model)+++ "drop_params",+ [pytest.param([True], id="list"), pytest.param("", id="empty-string"), pytest.param("x" * 5120, id="5kb-string")],+)+def test_drop_params_that_does_not_mean_true_keeps_the_400(gateway: Gateway, drop_params: JsonValue) -> None:+ with _ollama_server(lambda _: _generate_reply(_CALL_JSON)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)+ code, text = _post(+ gateway,+ "/v1/chat/completions",+ {"model": model, "messages": [*_null_system_turn()], "tools": [_WEATHER_TOOL], "drop_params": drop_params},+ )+ assert code == 400, text+ assert f"{_SYSTEM_CONTENT_ERROR} NoneType." in _error_message(text), text+ assert _generate_calls(wire) == ()+++def test_the_same_dropped_null_system_turn_twice_is_forwarded_twice(gateway: Gateway) -> None:+ with _ollama_server(lambda _: _generate_reply(_CALL_JSON)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)+ first: Final = _post_chat(gateway, model, _null_system_turn(), tools=[_WEATHER_TOOL], drop_params=True)+ second: Final = _post_chat(gateway, model, _null_system_turn(), tools=[_WEATHER_TOOL], drop_params=True)+ assert first["id"] != second["id"], (first["id"], second["id"])+ prompts: Final = _prompts(wire)+ assert len(prompts) == 2, prompts+ for prompt in prompts:+ _assert_prompt_replaces_the_system_content(prompt)+++def test_null_system_content_on_an_unauthenticated_request_is_a_401_before_translation(gateway: Gateway) -> None:+ with _ollama_server(lambda _: _generate_reply(_CALL_JSON)) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=wire.url, api_key=_API_KEY)+ code, text = _post(+ gateway,+ "/v1/chat/completions",+ {"model": model, "messages": [*_null_system_turn()], "tools": [_WEATHER_TOOL]},+ key=f"sk-not-a-key-{uuid.uuid4().hex}",+ )+ assert code == 401, text+ assert _generate_calls(wire) == ()+++def _config_storing_prompts(directory: Path) -> Path:+ config: Final = _JSON_OBJECT.validate_python(+ yaml.safe_load((Path(__file__).resolve().parents[1] / "proxy_config.yaml").read_text())+ )+ settings: Final = config["general_settings"]+ assert isinstance(settings, dict), config+ path: Final = directory / "store-prompts.yaml"+ path.write_text(+ yaml.safe_dump({**config, "general_settings": {**settings, "store_prompts_in_spend_logs": True}})+ )+ return path+++def _id_of(payload: dict[str, JsonValue]) -> str:+ identity: Final = payload["id"]+ assert isinstance(identity, str), payload+ return identity+++def _first_message(payload: dict[str, JsonValue]) -> JsonValue:+ choices: Final = payload["choices"]+ assert isinstance(choices, list) and choices, payload+ choice: Final = choices[0]+ assert isinstance(choice, dict), payload+ return choice["message"]+++def _stored_messages(request_id: str) -> JsonValue:+ rows: Final = eventually(+ lambda: read_rows('SELECT proxy_server_request FROM "LiteLLM_SpendLogs" WHERE request_id=%s', (request_id,)),+ lambda found: len(found) == 1,+ seconds=70,+ )+ return _JSON_OBJECT.validate_python(rows[0]["proxy_server_request"])["messages"]++[email protected](2 * graceful_stop_seconds() + 120)+def test_spend_row_stores_the_list_system_turn_the_caller_sent(gateway: Gateway, tmp_path: Path) -> None:+ messages: Final = [_list_system(_terse_system()), *_first_turn()]+ with (+ _ollama_server(lambda _: _PRIMARY_DOWN) as primary_wire,+ _ollama_server(lambda _: _generate_reply(_CALL_JSON)) as fallback_wire,+ owned_proxy(gateway, tmp_path, {}, config=_config_storing_prompts(tmp_path), workers=2) as logged,+ logged.scenario() as scenario,+ ):+ primary: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=primary_wire.url, api_key=_API_KEY)+ fallback: Final = scenario.model(model=f"ollama/{_BACKEND}", api_base=fallback_wire.url, api_key=_API_KEY)+ direct: Final = _post_chat(logged, fallback, messages, tools=[_WEATHER_TOOL])+ rescued: Final = _post_chat(+ logged, primary, messages, tools=[_WEATHER_TOOL], fallbacks=[fallback], num_retries=0+ )+ for payload in (direct, rescued):+ assert _stored_messages(_id_of(payload)) == messagesdiff --git a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.pyindex e6d44d350cb..b0e2dcd1321 100644--- a/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py+++ b/tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py@@ -4,6 +4,8 @@ import loggingimport osimport reimport time+from collections.abc import Callable+from copy import deepcopyfrom typing import Final, Listfrom unittest.mock import MagicMock, patch@@ -67,17 +69,98 @@ from litellm.types.llms.bedrock import BedrockConverseReasoningContentBlockfrom litellm.types.llms.openai import AllMessageValues-def test_function_call_prompt_preserves_append_failure_for_non_string_content() -> None:- messages = [{"role": "system", "content": None}]+READ_FILE: Final[list[object]] = [{"name": "read_file", "description": "Read the contents of a file."}]+USER_TURN: Final[dict[str, object]] = {"role": "user", "content": "Read the file."}+HELPFUL_PART: Final[dict[str, object]] = {"type": "text", "text": "You are helpful."}- with pytest.raises(AttributeError):- function_call_prompt(messages, [])++def _ollama_function_call_prompt(+ messages: list[dict[str, object]], functions: list[object], drop_params: bool = False+) -> list[dict[str, object]]:+ return function_call_prompt(messages, functions, model="llama3", llm_provider="ollama", drop_params=drop_params)+++def _read_file_prompt() -> object:+ prompt: Final = _ollama_function_call_prompt([USER_TURN], READ_FILE)[-1]["content"]+ assert "Read the contents of a file." in str(prompt)+ return prompt+++ ("history", "expected"),+ (+ ((USER_TURN,), lambda prompt: [USER_TURN, {"role": "system", "content": prompt}]),+ (+ ({"role": "system", "content": "You are helpful."}, USER_TURN),+ lambda prompt: [{"role": "system", "content": f"You are helpful. {prompt}"}, USER_TURN],+ ),+ (+ ({"role": "system", "content": [HELPFUL_PART]}, USER_TURN),+ lambda prompt: [+ {"role": "system", "content": [HELPFUL_PART, {"type": "text", "text": f" {prompt}"}]},+ USER_TURN,+ ],+ ),+ (+ ({"role": "system", "content": "You are helpful."}, USER_TURN, {"role": "system", "content": "Be brief."}),+ lambda prompt: [+ {"role": "system", "content": f"You are helpful. {prompt}"},+ USER_TURN,+ {"role": "system", "content": f"Be brief. {prompt}"},+ ],+ ),+ ),+ ids=("no_system", "string_content", "list_content", "two_system_messages"),+)+def test_function_call_prompt_sends_the_schema_once_per_turn_of_a_reused_history(+ history: tuple[dict[str, object], ...],+ expected: Callable[[object], list[dict[str, object]]],+) -> None:+ reused_history: Final = deepcopy(list(history))++ turns: Final = tuple(_ollama_function_call_prompt(reused_history, READ_FILE) for _ in range(3))++ assert reused_history == list(history)+ assert all(turn == expected(_read_file_prompt()) for turn in turns)+++UNREADABLE_SYSTEM_CONTENT: Final = pytest.mark.parametrize(+ "content",+ (+ None,+ {"type": "text", "text": "private system prompt"},+ ({"type": "text", "text": "private system prompt"},),+ {"private system prompt"},+ (part for part in ("private system prompt",)),+ ),+ ids=("none", "dict", "tuple", "set", "generator"),+)+++@UNREADABLE_SYSTEM_CONTENT+def test_function_call_prompt_answers_400_for_unreadable_system_content_without_echoing_it(content: object) -> None:+ with pytest.raises(litellm.BadRequestError) as error:+ _ollama_function_call_prompt([{"role": "system", "content": content}, USER_TURN], READ_FILE)++ assert error.value.status_code == 400+ assert "private system prompt" not in str(error.value)+++@UNREADABLE_SYSTEM_CONTENT+def test_function_call_prompt_sends_only_the_function_prompt_for_unreadable_content_under_drop_params(+ content: object,+) -> None:+ prompted: Final = _ollama_function_call_prompt(+ [{"role": "system", "content": content}, USER_TURN], READ_FILE, drop_params=True+ )++ assert prompted == [{"role": "system", "content": _read_file_prompt()}, USER_TURN]def test_function_call_prompt_lets_the_model_answer_after_a_function_result() -> None:messages: Final[list[dict[str, object]]] = [{"role": "system", "content": "Be terse."}]- prompted: Final = function_call_prompt(messages, [{"name": "get_weather"}])+ prompted: Final = _ollama_function_call_prompt(messages, [{"name": "get_weather"}])system: Final = str(prompted[0]["content"])assert "JSON OUTPUT ONLY" not in systemdiff --git a/tests/unit/test_system_message_format_bug.py b/tests/unit/test_system_message_format_bug.pyindex 375c4ea22d4..f4e34c7fc0e 100644--- a/tests/unit/test_system_message_format_bug.py+++ b/tests/unit/test_system_message_format_bug.py@@ -2,6 +2,8 @@Test for GitHub issue #11267 - System message format issue with Ollama + tools"""+from copy import deepcopy+from typing import Finalfrom unittest.mock import patch@@ -31,6 +33,7 @@ def test_system_message_format_issue_reproduction():},]+ messages_before_call: Final = deepcopy(messages)temperature = 1# Add tools to trigger the bug - this is what causes the issue@@ -57,7 +60,7 @@ def test_system_message_format_issue_reproduction():mock_response=True,)- assert len(messages[1]["content"]) == 2+ assert messages == messages_before_callif __name__ == "__main__":