litellm/tests/unit/integrations/test_custom_prompt_management.py
Mateo Wang 5084cef13c
refactor(typing): clear 1146 basedpyright Any errors across 365 files (#52768)
* refactor(typing): clear basedpyright Any errors in proxy, router and core utils

* refactor(typing): clear basedpyright Any errors in proxy server, logging and provider handlers

* refactor(typing): clear basedpyright Any errors in types, proxy client and single-Any modules

* refactor(typing): clear basedpyright Any errors in providers, responses and proxy endpoints

* refactor(typing): clear basedpyright Any errors in key management, prometheus, gigachat and http handler

* refactor(typing): clear basedpyright Any errors in a long-tail family sweep

* refactor(typing): clear basedpyright Any errors in decode, guardrail and passthrough paths

* refactor(typing): clear basedpyright Any errors in decode, realtime and management paths

* refactor(typing): clear basedpyright Any errors in source-owned proxy, cache and provider paths

* refactor(typing): clear basedpyright Any errors in wave 10 narrow deep pass

* refactor(typing): clear basedpyright Any errors in wave 11 hotspot and route request pass

* refactor(typing): clear basedpyright Any errors in wave 12 deep coupled pass

* refactor(typing): clear basedpyright Any errors in wave 13 family pass

* refactor(typing): clear basedpyright Any errors in wave 14 single-hotspot pass

* refactor(typing): clear basedpyright Any errors in wave 15 single-hotspot pass

* fix(typing): keep main's merged behavior typed after syncing with main

* refactor(typing): share one int_of helper across batch, file and key endpoints

* test: give mocked Anthropic calls a real message body

The Anthropic chat transform now rejects a decoded body that is not a JSON
object. Four tests mocked the HTTP client with a bare MagicMock, whose json()
is never a real decoded response, so they now return a real Anthropic message.

* fix(utils): keep FileTypes importable from litellm.utils

The wave 14 pass dropped the now-unused FileTypes import, which also removed the litellm.utils.FileTypes attribute SDK users could import. Re-export it as a TypeAlias the same way TextChoices is.

* fix: run real builtins instead of copied CPython errors and keep client SDK types

Replace hand-copied CPython error sites with the real operations through
small core_helpers wrappers, restore main's typed client SDK returns, and
add tests that compare each helper's result and error with the builtin's

* fix: raise instead of recursing in the typed narrowing helpers

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: call the value directly so the helpers test collects on Python 3.10

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* refactor(typing): mark the three widened TypedDict fields read-only

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-21 04:25:33 +00:00

154 lines
5.8 KiB
Python

import datetime
import json
import unittest
from typing import List, Optional, Tuple
from unittest.mock import ANY, Mock, patch
import httpx
import pytest
import litellm
from litellm.integrations.custom_prompt_management import CustomPromptManagement
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.types.llms.openai import AllMessageValues
from litellm.types.prompts.init_prompts import PromptSpec
from litellm.types.utils import StandardCallbackDynamicParams
@pytest.fixture(autouse=True)
def setup_anthropic_api_key(monkeypatch):
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-some-key")
def _anthropic_message_response() -> httpx.Response:
return httpx.Response(
200,
json={
"id": "msg_1",
"type": "message",
"role": "assistant",
"model": "claude-3-5-sonnet",
"content": [{"type": "text", "text": "Hi"}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 1, "output_tokens": 1},
},
request=httpx.Request("POST", "https://api.anthropic.com/v1/messages"),
)
class TestCustomPromptManagement(CustomPromptManagement):
def get_chat_completion_prompt(
self,
model: str,
messages: List[AllMessageValues],
non_default_params: dict,
prompt_id: Optional[str],
prompt_variables: Optional[dict],
dynamic_callback_params: StandardCallbackDynamicParams,
prompt_spec: Optional[PromptSpec] = None,
prompt_label: Optional[str] = None,
prompt_version: Optional[int] = None,
ignore_prompt_manager_model: Optional[bool] = False,
ignore_prompt_manager_optional_params: Optional[bool] = False,
) -> Tuple[str, List[AllMessageValues], dict]:
print(
"TestCustomPromptManagement: running get_chat_completion_prompt for prompt_id: ",
prompt_id,
)
if prompt_id == "test_prompt_id":
messages = [
{"role": "user", "content": "This is the prompt for test_prompt_id"},
]
return model, messages, non_default_params
elif prompt_id == "prompt_with_variables":
content = "Hello, {name}! You are {age} years old and live in {city}."
content_with_variables = content.format(**(prompt_variables or {}))
messages = [
{"role": "user", "content": content_with_variables},
]
return model, messages, non_default_params
else:
return model, messages, non_default_params
@pytest.mark.asyncio
async def test_custom_prompt_management_with_prompt_id(monkeypatch):
custom_prompt_management = TestCustomPromptManagement()
litellm.callbacks = [custom_prompt_management]
# Mock AsyncHTTPHandler.post method
client = AsyncHTTPHandler()
with patch.object(client, "post", return_value=_anthropic_message_response()) as mock_post:
await litellm.acompletion(
model="anthropic/claude-3-5-sonnet",
messages=[{"role": "user", "content": "Hello, how are you?"}],
client=client,
prompt_id="test_prompt_id",
)
mock_post.assert_called_once()
print(mock_post.call_args.kwargs)
request_body = mock_post.call_args.kwargs["json"]
print("request_body: ", json.dumps(request_body, indent=4))
assert request_body["model"] == "claude-3-5-sonnet"
# the message gets applied to the prompt from the custom prompt management callback
assert (
request_body["messages"][0]["content"][0]["text"]
== "This is the prompt for test_prompt_id"
)
@pytest.mark.asyncio
async def test_custom_prompt_management_with_prompt_id_and_prompt_variables():
custom_prompt_management = TestCustomPromptManagement()
litellm.callbacks = [custom_prompt_management]
# Mock AsyncHTTPHandler.post method
client = AsyncHTTPHandler()
with patch.object(client, "post", return_value=_anthropic_message_response()) as mock_post:
await litellm.acompletion(
model="anthropic/claude-3-5-sonnet",
messages=[],
client=client,
prompt_id="prompt_with_variables",
prompt_variables={"name": "John", "age": 30, "city": "New York"},
)
mock_post.assert_called_once()
print(mock_post.call_args.kwargs)
request_body = mock_post.call_args.kwargs["json"]
print("request_body: ", json.dumps(request_body, indent=4))
assert request_body["model"] == "claude-3-5-sonnet"
# the message gets applied to the prompt from the custom prompt management callback
assert (
request_body["messages"][0]["content"][0]["text"]
== "Hello, John! You are 30 years old and live in New York."
)
@pytest.mark.asyncio
async def test_custom_prompt_management_without_prompt_id():
custom_prompt_management = TestCustomPromptManagement()
litellm.callbacks = [custom_prompt_management]
# Mock AsyncHTTPHandler.post method
client = AsyncHTTPHandler()
with patch.object(client, "post", return_value=_anthropic_message_response()) as mock_post:
await litellm.acompletion(
model="anthropic/claude-3-5-sonnet",
messages=[{"role": "user", "content": "Hello, how are you?"}],
client=client,
)
mock_post.assert_called_once()
print(mock_post.call_args.kwargs)
request_body = mock_post.call_args.kwargs["json"]
print("request_body: ", json.dumps(request_body, indent=4))
assert request_body["model"] == "claude-3-5-sonnet"
# the message does not get applied to the prompt from the custom prompt management callback since we did not pass a prompt_id
assert (
request_body["messages"][0]["content"][0]["text"] == "Hello, how are you?"
)