|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT license. |
| 3 | + |
| 4 | +"""Verify trace headers through real LiteLLM adapters against a loopback server.""" |
| 5 | + |
| 6 | +import hashlib |
| 7 | +import json |
| 8 | +import os |
| 9 | +import threading |
| 10 | +from collections.abc import Callable, Iterator |
| 11 | +from email.message import Message as HTTPHeaders |
| 12 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 13 | +from pathlib import Path |
| 14 | +from typing import TYPE_CHECKING |
| 15 | +from unittest.mock import patch |
| 16 | + |
| 17 | +import pytest |
| 18 | + |
| 19 | +from pyrit.models import Message, MessagePiece, RequestTraceContext |
| 20 | +from pyrit.prompt_target import LiteLLMChatTarget, TargetTraceConfig |
| 21 | + |
| 22 | +if TYPE_CHECKING: |
| 23 | + import tiktoken |
| 24 | + |
| 25 | +pytestmark = [pytest.mark.run_only_if_all_tests, pytest.mark.usefixtures("patch_central_database")] |
| 26 | + |
| 27 | +_TOKENIZER_URL = "https://openaipublic.blob.core.windows.net/encodings/cl100k_base.tiktoken" |
| 28 | +_TOKENIZER_SHA256 = "223921b76ee99bde995b7ff738513eef100fb51d18c93597a113bcffe865b2a7" |
| 29 | +_OPENAI_REPLY = { |
| 30 | + "id": "chatcmpl-1", |
| 31 | + "object": "chat.completion", |
| 32 | + "created": 0, |
| 33 | + "model": "gpt-4o", |
| 34 | + "choices": [{"index": 0, "message": {"role": "assistant", "content": "hello"}, "finish_reason": "stop"}], |
| 35 | + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, |
| 36 | +} |
| 37 | +_ANTHROPIC_REPLY = { |
| 38 | + "id": "msg_1", |
| 39 | + "type": "message", |
| 40 | + "role": "assistant", |
| 41 | + "model": "claude-sonnet-4-6", |
| 42 | + "content": [{"type": "text", "text": "hello"}], |
| 43 | + "stop_reason": "end_turn", |
| 44 | + "stop_sequence": None, |
| 45 | + "usage": {"input_tokens": 1, "output_tokens": 1}, |
| 46 | +} |
| 47 | +_WIRE_PROVIDERS = pytest.mark.parametrize( |
| 48 | + ("model_name", "base_path", "request_path"), |
| 49 | + [ |
| 50 | + ("openai/gpt-4o", "/v1", "/v1/chat/completions"), |
| 51 | + ("anthropic/claude-sonnet-4-6", "", "/v1/messages"), |
| 52 | + ], |
| 53 | +) |
| 54 | + |
| 55 | + |
| 56 | +@pytest.fixture |
| 57 | +def official_cl100k_encoding(tmp_path: Path) -> Iterator["tiktoken.Encoding"]: |
| 58 | + cache_dir = tmp_path / "official-tokenizer" |
| 59 | + with patch.dict( |
| 60 | + os.environ, |
| 61 | + { |
| 62 | + "TIKTOKEN_CACHE_DIR": str(cache_dir), |
| 63 | + "LITELLM_LOCAL_MODEL_COST_MAP": "true", |
| 64 | + "LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS": "true", |
| 65 | + }, |
| 66 | + ): |
| 67 | + pytest.importorskip("litellm") |
| 68 | + import tiktoken |
| 69 | + import tiktoken.registry |
| 70 | + |
| 71 | + source = os.environ.get("PYRIT_TEST_TIKTOKEN_ASSET") |
| 72 | + if not source: |
| 73 | + raise RuntimeError( |
| 74 | + "Set PYRIT_TEST_TIKTOKEN_ASSET to the official cl100k_base.tiktoken file. " |
| 75 | + "See doc/contributing/6_integration_tests.md for offline preparation." |
| 76 | + ) |
| 77 | + content = Path(source).read_bytes() |
| 78 | + if hashlib.sha256(content).hexdigest() != _TOKENIZER_SHA256: |
| 79 | + raise ValueError(f"Official cl100k_base asset SHA-256 mismatch: {source}") |
| 80 | + cache_dir.mkdir() |
| 81 | + (cache_dir / hashlib.sha1(_TOKENIZER_URL.encode("utf-8")).hexdigest()).write_bytes(content) |
| 82 | + with patch.dict(tiktoken.registry.ENCODINGS, {}, clear=True): |
| 83 | + yield tiktoken.get_encoding("cl100k_base") |
| 84 | + |
| 85 | + |
| 86 | +@pytest.fixture |
| 87 | +def chat_endpoint( |
| 88 | + official_cl100k_encoding: "tiktoken.Encoding", |
| 89 | +) -> Iterator[tuple[str, list[tuple[str, HTTPHeaders]]]]: |
| 90 | + received: list[tuple[str, HTTPHeaders]] = [] |
| 91 | + |
| 92 | + class _Handler(BaseHTTPRequestHandler): |
| 93 | + def do_POST(self) -> None: |
| 94 | + self.rfile.read(int(self.headers.get("Content-Length", 0))) |
| 95 | + received.append((self.path, self.headers)) |
| 96 | + reply = _ANTHROPIC_REPLY if self.path.endswith("/v1/messages") else _OPENAI_REPLY |
| 97 | + payload = json.dumps(reply).encode() |
| 98 | + self.send_response(200) |
| 99 | + self.send_header("Content-Type", "application/json") |
| 100 | + self.send_header("Content-Length", str(len(payload))) |
| 101 | + self.end_headers() |
| 102 | + self.wfile.write(payload) |
| 103 | + |
| 104 | + def log_message(self, format: str, *args: object) -> None: # noqa: A002 |
| 105 | + pass |
| 106 | + |
| 107 | + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) |
| 108 | + thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 109 | + thread.start() |
| 110 | + try: |
| 111 | + yield f"http://127.0.0.1:{server.server_address[1]}", received |
| 112 | + finally: |
| 113 | + server.shutdown() |
| 114 | + server.server_close() |
| 115 | + thread.join() |
| 116 | + |
| 117 | + |
| 118 | +def _user_message() -> Message: |
| 119 | + return MessagePiece(role="user", conversation_id="convo", original_value="test prompt").to_message() |
| 120 | + |
| 121 | + |
| 122 | +@_WIRE_PROVIDERS |
| 123 | +async def test_recorded_trace_context_reaches_wire_through_litellm_async( |
| 124 | + *, |
| 125 | + chat_endpoint: tuple[str, list[tuple[str, HTTPHeaders]]], |
| 126 | + model_name: str, |
| 127 | + base_path: str, |
| 128 | + request_path: str, |
| 129 | +) -> None: |
| 130 | + url, received = chat_endpoint |
| 131 | + provider = model_name.split("/")[0] |
| 132 | + target = LiteLLMChatTarget( |
| 133 | + model_name=model_name, |
| 134 | + endpoint=url + base_path, |
| 135 | + api_key="test-key", |
| 136 | + extra_body_parameters={ |
| 137 | + "provider_specific_header": {"custom_llm_provider": provider, "extra_headers": {"X-Route": "a"}} |
| 138 | + }, |
| 139 | + trace_config=TargetTraceConfig(enabled=True), |
| 140 | + ) |
| 141 | + request = _user_message() |
| 142 | + responses = await target.send_prompt_async(message=request) |
| 143 | + |
| 144 | + link = RequestTraceContext.from_metadata(request.get_piece().prompt_metadata) |
| 145 | + assert link is not None |
| 146 | + assert len(received) == 1 |
| 147 | + path, headers = received[0] |
| 148 | + assert path == request_path |
| 149 | + assert headers.get_all("traceparent") == [link.traceparent] |
| 150 | + assert headers.get_all("tracestate") is None |
| 151 | + assert headers["X-Route"] == "a" |
| 152 | + assert responses[0].get_value() == "hello" |
| 153 | + |
| 154 | + |
| 155 | +def _single_scope(provider: str) -> object: |
| 156 | + return {"custom_llm_provider": provider, "extra_headers": {"TraceParent": f"00-{'3' * 32}-{'4' * 16}-01"}} |
| 157 | + |
| 158 | + |
| 159 | +def _list_scope(provider: str) -> object: |
| 160 | + return [ |
| 161 | + {"custom_llm_provider": "bedrock", "extra_headers": {"X-Other": "1"}}, |
| 162 | + {"custom_llm_provider": f"bedrock, {provider}", "extra_headers": {"tracestate": "vendor=manual"}}, |
| 163 | + ] |
| 164 | + |
| 165 | + |
| 166 | +@_WIRE_PROVIDERS |
| 167 | +@pytest.mark.parametrize("scoped_headers", [_single_scope, _list_scope]) |
| 168 | +async def test_provider_specific_trace_header_is_rejected_through_litellm_async( |
| 169 | + *, |
| 170 | + chat_endpoint: tuple[str, list[tuple[str, HTTPHeaders]]], |
| 171 | + model_name: str, |
| 172 | + base_path: str, |
| 173 | + request_path: str, |
| 174 | + scoped_headers: Callable[[str], object], |
| 175 | +) -> None: |
| 176 | + url, received = chat_endpoint |
| 177 | + target = LiteLLMChatTarget( |
| 178 | + model_name=model_name, |
| 179 | + endpoint=url + base_path, |
| 180 | + api_key="test-key", |
| 181 | + extra_body_parameters={"provider_specific_header": scoped_headers(model_name.split("/")[0])}, |
| 182 | + trace_config=TargetTraceConfig(enabled=True), |
| 183 | + ) |
| 184 | + with pytest.raises(ValueError, match="Manual trace headers"): |
| 185 | + await target.send_prompt_async(message=_user_message()) |
| 186 | + assert received == [] |
0 commit comments