mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-01 01:18:34 +00:00
* test: make legacy live tests in spend, batches, openai endpoints and audio dirs offline (partial)
* test: migrate wave-1b live tests offline (guardrails, images, ocr, search, openai endpoints)
* test: fix wave-1b review items, add responses/ocr integration tests and firecrawl unit test
* test: anthropic messages router/bedrock/openai-bridge unit tests for wave-1b nodes
* test: anthropic messages logging, prompt-caching and tool-search unit tests; drop migrated base nodes
* test: finish pass_through_unit_tests nodes, logging drain fix and mutations
* test: migrate anthropic passthrough tests to integration wire tests
* test: fix passthrough migration wire spend row lookup and wildcard config
* test: migrate hosted vllm and openai file passthrough tests offline
* test: move assemblyai and vertex passthrough nodes to in-process unit tests
* test: restore unlisted router node and fix logging worker drain in passthrough unit tests
* test: drop spend-row BUG skip and sharpen non-streaming skip reason for anthropic messages
* test: use public presidio alias after merge
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* test: restore the batch and file unit tests the migration rewrote away
* test: restore full legacy intent in anthropic messages router unit tests
Drop the false BUG skip on non-streaming aanthropic_messages logging (success
callbacks do fire; the skipped body filtered on the wrong model), assert the
logged model_group, messages, cost and usage, cover streaming logging for both
Anthropic and Bedrock invoke, assert dict content blocks for Anthropic, Bedrock
invoke and the OpenAI bridge, add the Bedrock invoke leg of the router test,
fall back from a real 401, test system-prompt caching and streaming
message_start cache fields on converse and invoke, send the legacy tool-search
tools and beta header, remove the type: ignore and bare dict helper, and add
in-process native /anthropic passthrough spend logging tests
* test: fix passthrough migration wire tests and drop false native spend BUG skip
The native spend row test read rows by the shared master-key digest, so it
matched other tests' rows; read each row by its own message id instead and
assert tokens, total, spend, tags, provider, api_base and end_user on both the
non-streaming and streaming native routes. Merge the streaming test that never
checked spend, assert exact tags from litellm_metadata, stop rebinding a Final
in a loop, require cost > 0, and add the chat-completions bridge cost case the
legacy test covered
* test: harden the spend, OCR, image, search and guardrail migration replacements
The OCR spend tests now build fresh kwargs per case instead of mutating a
shared fixture, and every payload case asserts the exact logged spend. The
OCR wire test reads its spend row by request id and checks exact page
pricing. Image edit, Nova Canvas, DuckDuckGo, Firecrawl, Bedrock guardrail
and Presidio replacements now fake only the provider HTTP boundary (respx or
an in-process aiohttp server) and assert the outbound request, so the
DuckDuckGo limit, Azure base_model pricing and guardrail masking are proven
rather than assumed
* test: cover Exa and Perplexity search structure and max_results offline and retire the two base search methods
* test: drive batch and file replacements through the provider HTTP boundary and real logging callback
Replace monkeypatched litellm.afile_content and AsyncHTTPHandler doubles with respx routes,
read batch logging metadata from a registered success callback instead of get_logging_payload,
use the real managed-files hook for the GEN-2166 regression, assert outbound request bodies,
pin poller ownership explicitly in the migrated DB-sync tests, and require the scripted
upstream to be hit in the responses error-status wire tests
* test: assert file content download headers pass through the proxy
* test: point spend coverage references at the tests that replaced the retired spend job
* test: assert passthrough identity, spend and route dispatch from the code under test
The AssemblyAI non-admin test asserted metadata it wrote itself and leaked a
background poll to the real AssemblyAI host. It now drives assemblyai_proxy_route
with a real Request and waits for the success callback for its own transcript id.
The Vertex spend test matches its log by call id instead of taking the first event.
The OpenAI files wire test hit the native /{provider}/v1/files route; it now calls
/openai/files so the passthrough is what forwards the upload and delete.
* test: mock only the HTTP boundary in the migrated audio tests
Vertex TTS tests no longer replace _ensure_access_token or AsyncHTTPHandler.post;
the token comes from a mocked Google OAuth endpoint and the synthesize call from
respx. Speech tests assert the outbound body, the transcription cache test polls
for the cache write instead of relying on test ordering, and the model pass-through
test checks the multipart model field per model.
* test: wait on a logger event instead of polling the clock in anthropic messages unit tests
Recorders keep payloads in a rebound tuple and set an asyncio.Event; tests
await it with asyncio.wait_for instead of a sleep-and-deadline poll loop
* test: freeze module-level batch and file response fixtures as Final MappingProxyType
* test: fake the presidio analyzer with an in-memory aiohttp connector
The blocked-entity tests started an aiohttp TestServer, which binds a local
socket. They now hand the guardrail a ClientSession whose connector answers
/analyze and /anonymize in process, so no socket is opened and the outbound
analyze text and entities are still asserted
* test: type anthropic messages router test helpers with LiteLLM's Anthropic TypedDicts
Messages, cached system blocks and tool-search tools now use
AnthropicMessagesUserMessageParam, AnthropicMessagesTextParam,
AnthropicToolSearchToolRegex and AnthropicMessagesTool instead of bare
dict shapes; tools are converted to plain dicts only at the acreate call,
whose tools parameter is list[dict]
* test: type batch limiter helpers with TypedDicts and wait on the logging callback event instead of polling
* test: give the migrated OCR, image and presidio helpers precise types
OCR spend helpers take ReadOnly TypedDicts for kwargs and responses and use
LiteLLM's OCRResponse/OCRUsageInfo instead of local pydantic stand-ins; spend
metadata is validated with a TypeAdapter. The presidio fake uses LiteLLM's
PresidioAnalyzeRequest/ResponseItem types, and the image-edit logger validates
the logged payload instead of storing an untyped dict
* test: signal callback and cache events instead of polling
Recorders keep tuples and set an asyncio.Event, thread-safely, when the payload
for this test's transcript id or upstream URL arrives. The transcription cache
test waits on a Cache subclass that signals after async_add_cache. No clock
polling or sleeps remain in these tests.
* test: assert the batch limiter hook updates the caller's request in place
* test: tolerate model-list probes and read native passthrough rows by owned key
The router's OpenAI-compatible model-info refresh (litellm/router.py:10710)
sends GET /v1/models to configured openai api_bases, so the wire answers it
with an empty list and excludes it from the provider-call assertions. Native
/anthropic spend rows are now read by a per-request virtual key digest and
call_type, then the row's request_id is checked against the message id
* test: expect the OCR alias in the proxy response model
The proxy restamps every OpenAI-compatible response model to the name the
client requested (_override_openai_response_model), so /v1/ocr returns the
scenario alias. The upstream model is now checked on the drained request body
instead of inside the peer, where a failed assert never reached the test
---------
Co-authored-by: yuneng <yuneng@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
163 lines
5.3 KiB
Python
163 lines
5.3 KiB
Python
"""
|
|
Test Vertex AI Pass Through
|
|
|
|
1. use Credentials client side, Assert SpendLog was created
|
|
"""
|
|
|
|
import vertexai
|
|
from vertexai.preview.generative_models import GenerativeModel
|
|
import tempfile
|
|
import json
|
|
import os
|
|
import pytest
|
|
import asyncio
|
|
import requests
|
|
|
|
# Path to your service account JSON file
|
|
SERVICE_ACCOUNT_FILE = "path/to/your/service-account.json"
|
|
|
|
|
|
def load_vertex_ai_credentials():
|
|
# Define the path to the vertex_key.json file
|
|
print("loading vertex ai credentials")
|
|
filepath = os.path.dirname(os.path.abspath(__file__))
|
|
vertex_key_path = filepath + "/vertex_key.json"
|
|
|
|
# Read the existing content of the file or create an empty dictionary
|
|
try:
|
|
with open(vertex_key_path, "r") as file:
|
|
# Read the file content
|
|
print("Read vertexai file path")
|
|
content = file.read()
|
|
|
|
# If the file is empty or not valid JSON, create an empty dictionary
|
|
if not content or not content.strip():
|
|
service_account_key_data = {}
|
|
else:
|
|
# Attempt to load the existing JSON content
|
|
file.seek(0)
|
|
service_account_key_data = json.load(file)
|
|
except FileNotFoundError:
|
|
# If the file doesn't exist, create an empty dictionary
|
|
service_account_key_data = {}
|
|
|
|
# Update the service_account_key_data with environment variables
|
|
private_key_id = os.environ.get("VERTEX_AI_PRIVATE_KEY_ID", "")
|
|
private_key = os.environ.get("VERTEX_AI_PRIVATE_KEY", "")
|
|
private_key = private_key.replace("\\n", "\n")
|
|
service_account_key_data["private_key_id"] = private_key_id
|
|
service_account_key_data["private_key"] = private_key
|
|
|
|
# print(f"service_account_key_data: {service_account_key_data}")
|
|
# Create a temporary file
|
|
with tempfile.NamedTemporaryFile(mode="w+", delete=False) as temp_file:
|
|
# Write the updated content to the temporary files
|
|
json.dump(service_account_key_data, temp_file, indent=2)
|
|
|
|
# Export the temporary file as GOOGLE_APPLICATION_CREDENTIALS
|
|
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.abspath(temp_file.name)
|
|
|
|
|
|
LITE_LLM_ENDPOINT = "http://localhost:4000"
|
|
|
|
SPEND_LOG_API_KEY = "best-api-key-ever"
|
|
|
|
|
|
def get_tracked_spend() -> float:
|
|
"""
|
|
Total spend recorded under the pass-through key in the global spend view.
|
|
|
|
Sums every day the endpoint returns instead of matching the runner's local
|
|
"today" so a UTC date rollover mid-test can't hide a freshly billed call, and
|
|
treats an unreachable endpoint as "nothing recorded yet" (0.0).
|
|
"""
|
|
url = f"{LITE_LLM_ENDPOINT}/global/spend/logs?api_key={SPEND_LOG_API_KEY}"
|
|
response = requests.get(url, headers={"Authorization": f"Bearer {os.environ['LITELLM_MASTER_KEY']}"})
|
|
if response.status_code != 200:
|
|
print(f"global spend logs endpoint returned {response.status_code}: {response.text}")
|
|
return 0.0
|
|
|
|
rows = response.json()
|
|
print("global spend logs rows", rows)
|
|
return sum(float(row.get("spend") or 0.0) for row in rows)
|
|
|
|
|
|
@pytest.mark.asyncio()
|
|
@pytest.mark.skip(reason="skip flaky test - vertex pass through streaming is flaky")
|
|
async def test_basic_vertex_ai_pass_through_streaming_with_spendlog():
|
|
|
|
spend_before = get_tracked_spend()
|
|
print("spend_before", spend_before)
|
|
load_vertex_ai_credentials()
|
|
|
|
vertexai.init(
|
|
project="litellm-ci-cd",
|
|
location="global",
|
|
api_endpoint=f"{LITE_LLM_ENDPOINT}/vertex_ai",
|
|
api_transport="rest",
|
|
)
|
|
|
|
model = GenerativeModel(model_name="gemini-3.1-flash-lite")
|
|
response = model.generate_content("hi", stream=True)
|
|
|
|
for chunk in response:
|
|
print("chunk", chunk)
|
|
|
|
print("response", response)
|
|
|
|
await asyncio.sleep(20)
|
|
spend_after = get_tracked_spend()
|
|
print("spend_after", spend_after)
|
|
assert (
|
|
spend_after > spend_before
|
|
), "Spend should be greater than before. spend_before: {}, spend_after: {}".format(
|
|
spend_before, spend_after
|
|
)
|
|
|
|
pass
|
|
|
|
|
|
@pytest.mark.skip(
|
|
reason="skip flaky test - google context caching is flaky and not reliable."
|
|
)
|
|
@pytest.mark.asyncio
|
|
async def test_vertex_ai_pass_through_endpoint_context_caching():
|
|
import vertexai
|
|
from vertexai.generative_models import Part
|
|
from vertexai.preview import caching
|
|
import datetime
|
|
|
|
# load_vertex_ai_credentials()
|
|
|
|
vertexai.init(
|
|
project="litellm-ci-cd",
|
|
location="global",
|
|
api_endpoint=f"{LITE_LLM_ENDPOINT}/vertex_ai",
|
|
api_transport="rest",
|
|
)
|
|
|
|
system_instruction = """
|
|
You are an expert researcher. You always stick to the facts in the sources provided, and never make up new facts.
|
|
Now look at these research papers, and answer the following questions.
|
|
"""
|
|
|
|
contents = [
|
|
Part.from_uri(
|
|
"gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
|
|
mime_type="application/pdf",
|
|
),
|
|
Part.from_uri(
|
|
"gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
|
|
mime_type="application/pdf",
|
|
),
|
|
]
|
|
|
|
cached_content = caching.CachedContent.create(
|
|
model_name="gemini-3.1-flash-lite",
|
|
system_instruction=system_instruction,
|
|
contents=contents,
|
|
ttl=datetime.timedelta(minutes=60),
|
|
# display_name="example-cache",
|
|
)
|
|
|
|
print(cached_content.name)
|