mirror of
https://github.com/tiennm99/litellm.git
synced 2026-06-17 16:48:54 +00:00
2c733c00f5
* test: modernize models used in CircleCI e2e test suites
Replaces obsolete models (gpt-4o, gpt-4o-mini, gpt-3.5-turbo,
claude-3-5-sonnet-20240620, claude-sonnet-4-20250514) with current
equivalents across the e2e_openai_endpoints and
proxy_e2e_anthropic_messages_tests CircleCI jobs.
- gpt-4o -> gpt-5.5 (responses API e2e tests)
- gpt-4o-mini -> gpt-5-mini (websocket responses, oai_misc_config)
- gpt-4o-mini-2024-07-18 -> gpt-4.1-mini-2025-04-14 (fine-tuning,
still actively fine-tunable)
- gpt-4 / gpt-3.5-turbo target_model_names example -> gpt-5.5 /
gpt-5-mini
- bedrock claude-3-5-sonnet-20240620 batch entry -> haiku-4-5-20251001
(also aligning oai_misc_config model_name with what
test_bedrock_batches_api.py actually requests)
- bedrock claude-sonnet-4-20250514 (deprecated, retires 2026-06-15)
-> claude-sonnet-4-5-20250929
* test: point bedrock-claude-sonnet-4 alias at Sonnet 4.6, not 4.5
Greptile/Cursor flagged that after the previous commit, the
bedrock-claude-sonnet-4 alias collided with bedrock-claude-sonnet-4.5
(both pointed to claude-sonnet-4-5-20250929). Rename to
bedrock-claude-sonnet-4.6 and point it at the Sonnet 4.6 Bedrock ID
(us.anthropic.claude-sonnet-4-6, already in the litellm model
registry) so the alias name matches the underlying model version.
* test: modernize models across remaining CI-mounted configs & tests
Expands the modernization sweep to all CircleCI-mounted proxy configs
and to test directories where the model literal is a fixture/route key
(not the test's subject).
Config changes:
- proxy_server_config.yaml: bump gpt-3.5-turbo / gpt-3.5-turbo-1106 /
gpt-4o / gemini-1.5-flash / dall-e-3 underlying models; rename
gpt-3.5-turbo-end-user-test alias to gpt-5-mini-end-user-test; bump
text-embedding-ada-002 underlying to text-embedding-3-small. User-
facing aliases (gpt-3.5-turbo, gpt-4, text-embedding-ada-002, etc.)
preserved for backward compatibility with tests.
- simple_config.yaml, otel_test_config.yaml, spend_tracking_config.yaml:
bump gpt-3.5-turbo underlying to gpt-5-mini.
- pass_through_config.yaml: claude-3-5-sonnet / claude-3-7-sonnet /
claude-3-haiku entries replaced with claude-sonnet-4-5 / claude-
haiku-4-5 / claude-opus-4-7.
- oai_misc_config.yaml: align alias name with the gpt-5-mini rename.
Test changes (proactive: claude-sonnet-4-20250514 / claude-opus-4-
20250514 retire 2026-06-15):
- tests/llm_translation/test_anthropic_completion.py: bump 3 references
+ paired Vertex AI ID to claude-sonnet-4-5.
- tests/llm_translation/test_optional_params.py: bump 2 references.
- tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
and test_bedrock_anthropic_messages_test.py: bump router fixtures
using the deprecated model IDs.
- tests/pass_through_unit_tests/base_anthropic_messages_tool_search_test.py:
modernize docstring examples.
- tests/test_end_users.py: update references to renamed alias.
* test: modernize placeholder model literals in router_unit_tests
Mass replace_all on fixture/placeholder model literals across the
router_unit_tests/ suite (model name is a routing key / label, not the
test subject). Sub-agent sweep so far — additional commits will follow
for logging_callback_tests/, enterprise/, top-level tests/test_*.py,
and other CI-mounted dirs.
Mappings applied:
- gpt-3.5-turbo -> gpt-5-mini
- gpt-4 (bare) -> gpt-5.5
- gpt-4o (bare) -> gpt-5
- text-embedding-ada-002 -> text-embedding-3-small
- claude-3-sonnet-20240229 / claude-3-opus-20240229 /
claude-3-haiku-20240307 / claude-3-5-sonnet-20240620 ->
claude-sonnet-4-5-20250929 / claude-opus-4-7 /
claude-haiku-4-5-20251001 as appropriate
Explicitly preserved:
- gpt-4o-mini-* variants (transcribe, tts, etc.) where they're current
- gpt-4-turbo / gpt-4-vision-preview / gpt-4-0613 (subject literals)
- JSONL batch body literals
- Mock LLM response model fields (must match upstream)
- Fake/mock identifiers
* test: modernize placeholder model literals across remaining CI suites
Sub-agent sweep across logging_callback_tests/, guardrails_tests/,
enterprise/, pass_through_unit_tests/, otel_tests/,
llm_responses_api_testing/, batches_tests/, spend_tracking_tests/,
litellm_utils_tests/, unified_google_tests/, and a few top-level
tests/test_*.py files where the model literal is a fixture or
placeholder (router model_list, mock standard logging payload, mock
callback data) rather than the test's subject.
Mappings applied (see scope notes below):
- gpt-3.5-turbo -> gpt-5-mini
- gpt-4 (bare) -> gpt-5.5
- gpt-4o (bare) -> gpt-5.5 (corrected from initial gpt-5 — bare gpt-5
is not a valid OpenAI alias; only gpt-5.5 / gpt-5.4 / gpt-5.2-codex
/ gpt-5-mini exist)
- gpt-4o-mini (bare) -> gpt-5-mini
- text-embedding-ada-002 -> text-embedding-3-small
- claude-3-sonnet-20240229 -> claude-sonnet-4-5-20250929
- claude-3-opus-20240229 -> claude-opus-4-7
- claude-3-haiku-20240307 -> claude-haiku-4-5-20251001
- claude-3-5-sonnet-20240620/20241022 -> claude-sonnet-4-5-20250929
- claude-3-7-sonnet-20250219 -> claude-sonnet-4-6
- gemini-1.5-flash -> gemini-2.5-flash
- gemini-1.5-pro -> gemini-2.5-pro
Explicitly preserved (not modernized):
- llm_translation/ tests where model is the SUBJECT (provider-specific
translation/transformation logic). Only the deprecated 20250514
references were already bumped in a prior commit.
- Cost-calc / tokenizer subject tests in test_utils.py (skip-ranges
documented by the sub-agent).
- Bedrock model IDs in test_health_check.py path-stripping tests.
- JSONL batch request bodies and mock LLM response bodies (must match
upstream literal).
- Langfuse expected-request-body JSON fixtures (cost values are exact-
match-asserted; changing the model would shift response_cost).
- gpt-3.5-turbo-instruct (text-completion endpoint; no modern OpenAI
equivalent).
- Top-level tests calling the proxy through user-facing aliases
(gpt-3.5-turbo, gpt-4, text-embedding-ada-002, dall-e-3) — aliases
in proxy_server_config.yaml stay; only the underlying model was
bumped.
- tests/test_gpt5_azure_temperature_support.py (the test's whole point
is model-name handling).
- Fake / mock / openai/fake identifiers.
Notable side fixes:
- test_spend_accuracy_tests.py: UPSTREAM_MODEL now matches what
spend_tracking_config.yaml's proxy actually routes to (gpt-5-mini),
resolving a latent inconsistency.
- proxy_server_config.yaml: bare `gpt-5` alias renamed to `gpt-5.5`
(bare gpt-5 is not a valid OpenAI alias).
- test_batches_logging_unit_tests.py: explicit_models list entries
kept distinct (gpt-5-mini + gpt-5.5) after bulk rename.
* test: fix CI failures from model modernization sweep
CI surfaced 4 categories of regression from the bulk modernization:
1. Azure deployment names are customer-specific. Reverted:
- tests/litellm_utils_tests/test_health_check.py: azure/text-
embedding-3-small -> azure/text-embedding-ada-002 (the CI Azure
account does not have a text-embedding-3-small deployment).
- tests/logging_callback_tests/test_custom_callback_router.py:
same revert for two router fixtures driving aembedding.
2. gpt-5 family does not accept temperature != 1. Tests that pass a
custom temperature swapped from gpt-5-mini to gpt-4.1-mini (modern
non-reasoning OpenAI mini that still accepts temperature/logprobs):
- tests/logging_callback_tests/test_datadog.py
- tests/logging_callback_tests/test_langsmith_unit_test.py
- tests/logging_callback_tests/test_otel_logging.py
3. proxy_server_config.yaml's gpt-3.5-turbo-large alias was routing to
gpt-5.5 (a reasoning model that rejects logprobs). The proxy test
tests/test_openai_endpoints.py::test_chat_completion_streaming
exercises logprobs/top_logprobs through that alias. Bumped the
underlying model to gpt-4.1 (non-reasoning, still modern).
4. tests/logging_callback_tests/test_gcs_pub_sub.py asserts against a
pinned JSON fixture (gcs_pub_sub_body/spend_logs_payload.json) with
hardcoded model="gpt-4o" and a model-specific spend value. Reverted
the litellm.acompletion calls in the test to model="gpt-4o" so the
fixture's exact-match assertions still hold.
5. tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py:
anthropic.messages.create routing to openai/gpt-5-mini returned an
empty content[0] with max_tokens=100 (reasoning-token consumption).
Swapped to openai/gpt-4.1-mini.
* test: fix Assistants API model + 2 cursor[bot] review nits
1. pass_through_unit_tests/test_custom_logger_passthrough.py: gpt-5.5
isn't accepted by the /v1/assistants endpoint
("unsupported_model"). Switch to gpt-4.1-mini (modern, Assistants-
API-supported, non-reasoning).
2. example_config_yaml/pass_through_config.yaml: the previous sweep
bumped the claude-3-7-sonnet alias to claude-opus-4-7, which is a
tier change (Sonnet -> Opus). Map to claude-sonnet-4-6 to keep the
Sonnet tier intact. (Cursor bugbot review.)
3. example_config_yaml/simple_config.yaml: model_name was left as
gpt-3.5-turbo while the underlying was bumped to gpt-5-mini, which
muddles the "simple" example. Make both sides gpt-5-mini so the
most basic example is a straight 1:1 mapping again. (Cursor bugbot
review.)
* fix: revert gpt-4/gpt-3.5-turbo alias underlying to non-reasoning models
tests/test_openai_endpoints.py::test_completion calls the proxy alias
"gpt-4" with temperature=0, and other tests call gpt-3.5-turbo with
custom temperature / logprobs / the legacy /v1/completions endpoint.
The earlier modernization mapped both aliases to gpt-5.5 / gpt-5-mini,
which are reasoning models that reject temperature != 1 and don't
expose /v1/completions. Map the aliases to gpt-4.1 / gpt-4.1-mini
(modern non-reasoning OpenAI models) instead — keeps user-facing
aliases preserved while picking a current underlying that still
supports the parameters/endpoints the tests exercise.
518 lines
17 KiB
Python
518 lines
17 KiB
Python
import io
|
|
import os
|
|
import sys
|
|
|
|
|
|
sys.path.insert(0, os.path.abspath("../.."))
|
|
|
|
import asyncio
|
|
import gzip
|
|
import json
|
|
import logging
|
|
import time
|
|
from unittest.mock import AsyncMock, patch, MagicMock
|
|
import pytest
|
|
from datetime import datetime, timezone
|
|
from litellm.integrations.langsmith import (
|
|
LangsmithLogger,
|
|
LangsmithQueueObject,
|
|
CredentialsKey,
|
|
BatchGroup,
|
|
)
|
|
|
|
import litellm
|
|
|
|
|
|
# Test get_credentials_from_env
|
|
@pytest.mark.asyncio
|
|
async def test_get_credentials_from_env():
|
|
# Test with direct parameters
|
|
logger = LangsmithLogger(
|
|
langsmith_api_key="test-key",
|
|
langsmith_project="test-project",
|
|
langsmith_base_url="http://test-url",
|
|
)
|
|
|
|
credentials = logger.get_credentials_from_env(
|
|
langsmith_api_key="custom-key",
|
|
langsmith_project="custom-project",
|
|
langsmith_base_url="http://custom-url",
|
|
)
|
|
|
|
assert credentials["LANGSMITH_API_KEY"] == "custom-key"
|
|
assert credentials["LANGSMITH_PROJECT"] == "custom-project"
|
|
assert credentials["LANGSMITH_BASE_URL"] == "http://custom-url"
|
|
|
|
# assert that the default api base is used if not provided
|
|
credentials = logger.get_credentials_from_env()
|
|
assert credentials["LANGSMITH_BASE_URL"] == "https://api.smith.langchain.com"
|
|
|
|
# Test with tenant_id
|
|
credentials = logger.get_credentials_from_env(langsmith_tenant_id="test-tenant-id")
|
|
assert credentials["LANGSMITH_TENANT_ID"] == "test-tenant-id"
|
|
|
|
# Test tenant_id from environment variable
|
|
import os
|
|
|
|
os.environ["LANGSMITH_TENANT_ID"] = "env-tenant-id"
|
|
credentials = logger.get_credentials_from_env()
|
|
assert credentials["LANGSMITH_TENANT_ID"] == "env-tenant-id"
|
|
del os.environ["LANGSMITH_TENANT_ID"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_group_batches_by_credentials():
|
|
|
|
logger = LangsmithLogger(langsmith_api_key="test-key")
|
|
|
|
# Create test queue objects
|
|
queue_obj1 = LangsmithQueueObject(
|
|
data={"test": "data1"},
|
|
credentials={
|
|
"LANGSMITH_API_KEY": "key1",
|
|
"LANGSMITH_PROJECT": "proj1",
|
|
"LANGSMITH_BASE_URL": "url1",
|
|
"LANGSMITH_TENANT_ID": None,
|
|
},
|
|
)
|
|
|
|
queue_obj2 = LangsmithQueueObject(
|
|
data={"test": "data2"},
|
|
credentials={
|
|
"LANGSMITH_API_KEY": "key1",
|
|
"LANGSMITH_PROJECT": "proj1",
|
|
"LANGSMITH_BASE_URL": "url1",
|
|
"LANGSMITH_TENANT_ID": None,
|
|
},
|
|
)
|
|
|
|
logger.log_queue = [queue_obj1, queue_obj2]
|
|
|
|
grouped = logger._group_batches_by_credentials()
|
|
|
|
# Check grouping
|
|
assert len(grouped) == 1 # Should have one group since credentials are same
|
|
key = list(grouped.keys())[0]
|
|
assert isinstance(key, CredentialsKey)
|
|
assert len(grouped[key].queue_objects) == 2
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_group_batches_by_credentials_multiple_credentials():
|
|
|
|
# Test with multiple different credentials
|
|
logger = LangsmithLogger(langsmith_api_key="test-key")
|
|
|
|
queue_obj1 = LangsmithQueueObject(
|
|
data={"test": "data1"},
|
|
credentials={
|
|
"LANGSMITH_API_KEY": "key1",
|
|
"LANGSMITH_PROJECT": "proj1",
|
|
"LANGSMITH_BASE_URL": "url1",
|
|
"LANGSMITH_TENANT_ID": None,
|
|
},
|
|
)
|
|
|
|
queue_obj2 = LangsmithQueueObject(
|
|
data={"test": "data2"},
|
|
credentials={
|
|
"LANGSMITH_API_KEY": "key2", # Different API key
|
|
"LANGSMITH_PROJECT": "proj1",
|
|
"LANGSMITH_BASE_URL": "url1",
|
|
"LANGSMITH_TENANT_ID": None,
|
|
},
|
|
)
|
|
|
|
queue_obj3 = LangsmithQueueObject(
|
|
data={"test": "data3"},
|
|
credentials={
|
|
"LANGSMITH_API_KEY": "key1",
|
|
"LANGSMITH_PROJECT": "proj2", # Different project
|
|
"LANGSMITH_BASE_URL": "url1",
|
|
"LANGSMITH_TENANT_ID": None,
|
|
},
|
|
)
|
|
|
|
logger.log_queue = [queue_obj1, queue_obj2, queue_obj3]
|
|
|
|
grouped = logger._group_batches_by_credentials()
|
|
|
|
# Check grouping
|
|
assert len(grouped) == 3 # Should have three groups since credentials differ
|
|
for key, batch_group in grouped.items():
|
|
assert isinstance(key, CredentialsKey)
|
|
assert len(batch_group.queue_objects) == 1 # Each group should have one object
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_group_batches_by_credentials_with_tenant_id():
|
|
|
|
# Test that different tenant_ids create separate groups
|
|
logger = LangsmithLogger(langsmith_api_key="test-key")
|
|
|
|
queue_obj1 = LangsmithQueueObject(
|
|
data={"test": "data1"},
|
|
credentials={
|
|
"LANGSMITH_API_KEY": "key1",
|
|
"LANGSMITH_PROJECT": "proj1",
|
|
"LANGSMITH_BASE_URL": "url1",
|
|
"LANGSMITH_TENANT_ID": "tenant1",
|
|
},
|
|
)
|
|
|
|
queue_obj2 = LangsmithQueueObject(
|
|
data={"test": "data2"},
|
|
credentials={
|
|
"LANGSMITH_API_KEY": "key1",
|
|
"LANGSMITH_PROJECT": "proj1",
|
|
"LANGSMITH_BASE_URL": "url1",
|
|
"LANGSMITH_TENANT_ID": "tenant2", # Different tenant_id
|
|
},
|
|
)
|
|
|
|
queue_obj3 = LangsmithQueueObject(
|
|
data={"test": "data3"},
|
|
credentials={
|
|
"LANGSMITH_API_KEY": "key1",
|
|
"LANGSMITH_PROJECT": "proj1",
|
|
"LANGSMITH_BASE_URL": "url1",
|
|
"LANGSMITH_TENANT_ID": "tenant1", # Same as queue_obj1
|
|
},
|
|
)
|
|
|
|
logger.log_queue = [queue_obj1, queue_obj2, queue_obj3]
|
|
|
|
grouped = logger._group_batches_by_credentials()
|
|
|
|
# Should have two groups: one for tenant1 (queue_obj1 and queue_obj3), one for tenant2 (queue_obj2)
|
|
assert len(grouped) == 2
|
|
for key, batch_group in grouped.items():
|
|
assert isinstance(key, CredentialsKey)
|
|
assert key.tenant_id in ["tenant1", "tenant2"]
|
|
if key.tenant_id == "tenant1":
|
|
assert len(batch_group.queue_objects) == 2
|
|
else:
|
|
assert len(batch_group.queue_objects) == 1
|
|
|
|
|
|
# Test make_dot_order
|
|
@pytest.mark.asyncio
|
|
async def test_make_dot_order():
|
|
logger = LangsmithLogger(langsmith_api_key="test-key")
|
|
run_id = "729cff0e-f30c-4336-8b79-45d6b61c64b4"
|
|
dot_order = logger.make_dot_order(run_id)
|
|
|
|
print("dot_order=", dot_order)
|
|
|
|
# Check format: YYYYMMDDTHHMMSSfffZ + run_id
|
|
# Check the timestamp portion (first 23 characters)
|
|
timestamp_part = dot_order[:-36] # 36 is length of run_id
|
|
assert len(timestamp_part) == 22
|
|
assert timestamp_part[8] == "T" # Check T separator
|
|
assert timestamp_part[-1] == "Z" # Check Z suffix
|
|
|
|
# Verify timestamp format
|
|
try:
|
|
# Parse the timestamp portion (removing the Z)
|
|
datetime.strptime(timestamp_part[:-1], "%Y%m%dT%H%M%S%f")
|
|
except ValueError:
|
|
pytest.fail("Timestamp portion is not in correct format")
|
|
|
|
# Verify run_id portion
|
|
assert dot_order[-36:] == run_id
|
|
|
|
|
|
# Test is_serializable
|
|
@pytest.mark.asyncio
|
|
async def test_is_serializable():
|
|
from litellm.integrations.langsmith import is_serializable
|
|
from pydantic import BaseModel
|
|
|
|
# Test basic types
|
|
assert is_serializable("string") is True
|
|
assert is_serializable(123) is True
|
|
assert is_serializable({"key": "value"}) is True
|
|
|
|
# Test non-serializable types
|
|
async def async_func():
|
|
pass
|
|
|
|
assert is_serializable(async_func) is False
|
|
|
|
class TestModel(BaseModel):
|
|
field: str
|
|
|
|
assert is_serializable(TestModel(field="test")) is False
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_send_batch():
|
|
logger = LangsmithLogger(langsmith_api_key="test-key")
|
|
|
|
# Mock the httpx client
|
|
mock_response = AsyncMock()
|
|
mock_response.status_code = 200
|
|
logger.async_httpx_client = AsyncMock()
|
|
logger.async_httpx_client.post.return_value = mock_response
|
|
|
|
# Add test data to queue
|
|
logger.log_queue = [
|
|
LangsmithQueueObject(
|
|
data={"test": "data"}, credentials=logger.default_credentials
|
|
)
|
|
]
|
|
|
|
await logger.async_send_batch()
|
|
|
|
# Verify the API call
|
|
logger.async_httpx_client.post.assert_called_once()
|
|
call_args = logger.async_httpx_client.post.call_args
|
|
assert "runs/batch" in call_args[1]["url"]
|
|
assert "x-api-key" in call_args[1]["headers"]
|
|
# tenant_id should not be in headers if not provided
|
|
assert "x-tenant-id" not in call_args[1]["headers"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_send_batch_with_tenant_id():
|
|
logger = LangsmithLogger(
|
|
langsmith_api_key="test-key", langsmith_tenant_id="test-tenant-id"
|
|
)
|
|
|
|
# Mock the httpx client
|
|
mock_response = AsyncMock()
|
|
mock_response.status_code = 200
|
|
logger.async_httpx_client = AsyncMock()
|
|
logger.async_httpx_client.post.return_value = mock_response
|
|
|
|
# Add test data to queue
|
|
logger.log_queue = [
|
|
LangsmithQueueObject(
|
|
data={"test": "data"}, credentials=logger.default_credentials
|
|
)
|
|
]
|
|
|
|
await logger.async_send_batch()
|
|
|
|
# Verify the API call includes tenant_id header
|
|
logger.async_httpx_client.post.assert_called_once()
|
|
call_args = logger.async_httpx_client.post.call_args
|
|
assert "runs/batch" in call_args[1]["url"]
|
|
assert "x-api-key" in call_args[1]["headers"]
|
|
assert "x-tenant-id" in call_args[1]["headers"]
|
|
assert call_args[1]["headers"]["x-tenant-id"] == "test-tenant-id"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_langsmith_key_based_logging():
|
|
"""
|
|
In key based logging langsmith_api_key and langsmith_project are passed directly to litellm.acompletion
|
|
"""
|
|
try:
|
|
# Mock the httpx post request
|
|
# We need to mock get_async_httpx_client to return a mock AsyncHTTPHandler
|
|
# because LangsmithLogger creates its own instance
|
|
mock_async_httpx_handler = AsyncMock()
|
|
mock_response = MagicMock() # Use MagicMock for response to allow sync methods
|
|
mock_response.status_code = 200
|
|
mock_response.raise_for_status = (
|
|
MagicMock()
|
|
) # raise_for_status is sync in httpx
|
|
mock_response.text = ""
|
|
mock_async_httpx_handler.post = AsyncMock(return_value=mock_response)
|
|
|
|
mock_get_client = patch(
|
|
"litellm.integrations.langsmith.get_async_httpx_client",
|
|
return_value=mock_async_httpx_handler,
|
|
)
|
|
mock_get_client.start()
|
|
|
|
litellm.set_verbose = True
|
|
litellm.DEFAULT_FLUSH_INTERVAL_SECONDS = 1
|
|
|
|
litellm.callbacks = [LangsmithLogger()]
|
|
response = await litellm.acompletion(
|
|
model="gpt-4.1-mini",
|
|
messages=[{"role": "user", "content": "Test message"}],
|
|
max_tokens=10,
|
|
temperature=0.2,
|
|
mock_response="This is a mock response",
|
|
langsmith_api_key="fake_key_project2",
|
|
langsmith_project="fake_project2",
|
|
)
|
|
print("Waiting for logs to be flushed to Langsmith.....")
|
|
await asyncio.sleep(3)
|
|
|
|
print("done sleeping 3 seconds...")
|
|
|
|
# Verify the post request was made with correct parameters
|
|
mock_async_httpx_handler.post.assert_called_once()
|
|
call_args = mock_async_httpx_handler.post.call_args
|
|
|
|
print("call_args", call_args)
|
|
|
|
# Check URL contains /runs/batch
|
|
assert "/runs/batch" in call_args[1]["url"]
|
|
|
|
# Check headers contain the correct API key
|
|
assert call_args[1]["headers"]["x-api-key"] == "fake_key_project2"
|
|
# tenant_id should not be in headers if not provided
|
|
assert "x-tenant-id" not in call_args[1]["headers"]
|
|
|
|
# Verify the request body contains the expected data
|
|
request_body = call_args[1]["json"]
|
|
assert "post" in request_body
|
|
assert len(request_body["post"]) == 1 # Should contain one run
|
|
|
|
# EXPECTED BODY
|
|
expected_body = {
|
|
"post": [
|
|
{
|
|
"name": "LLMRun",
|
|
"run_type": "llm",
|
|
"inputs": {
|
|
"id": "chatcmpl-82699ee4-7932-4fc0-9585-76abc8caeafa",
|
|
"call_type": "acompletion",
|
|
"model": "gpt-4.1-mini",
|
|
"messages": [{"role": "user", "content": "Test message"}],
|
|
"model_parameters": {
|
|
"temperature": 0.2,
|
|
"max_tokens": 10,
|
|
},
|
|
},
|
|
"outputs": {
|
|
"id": "chatcmpl-82699ee4-7932-4fc0-9585-76abc8caeafa",
|
|
"model": "gpt-4.1-mini",
|
|
"choices": [
|
|
{
|
|
"finish_reason": "stop",
|
|
"index": 0,
|
|
"message": {
|
|
"content": "This is a mock response",
|
|
"role": "assistant",
|
|
"tool_calls": None,
|
|
"function_call": None,
|
|
},
|
|
}
|
|
],
|
|
"usage": {
|
|
"completion_tokens": 20,
|
|
"prompt_tokens": 10,
|
|
"total_tokens": 30,
|
|
},
|
|
},
|
|
"session_name": "fake_project2",
|
|
}
|
|
]
|
|
}
|
|
|
|
# Print both bodies for debugging
|
|
actual_body = call_args[1]["json"]
|
|
print("\nExpected body:")
|
|
print(json.dumps(expected_body, indent=2))
|
|
print("\nActual body:")
|
|
print(json.dumps(actual_body, indent=2))
|
|
|
|
assert len(actual_body["post"]) == 1
|
|
|
|
# Assert only the critical parts we care about
|
|
assert actual_body["post"][0]["name"] == expected_body["post"][0]["name"]
|
|
assert (
|
|
actual_body["post"][0]["run_type"] == expected_body["post"][0]["run_type"]
|
|
)
|
|
assert (
|
|
actual_body["post"][0]["inputs"]["messages"]
|
|
== expected_body["post"][0]["inputs"]["messages"]
|
|
)
|
|
assert (
|
|
actual_body["post"][0]["inputs"]["model_parameters"]
|
|
== expected_body["post"][0]["inputs"]["model_parameters"]
|
|
)
|
|
assert (
|
|
actual_body["post"][0]["outputs"]["choices"]
|
|
== expected_body["post"][0]["outputs"]["choices"]
|
|
)
|
|
assert (
|
|
actual_body["post"][0]["outputs"]["usage"]["completion_tokens"]
|
|
== expected_body["post"][0]["outputs"]["usage"]["completion_tokens"]
|
|
)
|
|
assert (
|
|
actual_body["post"][0]["outputs"]["usage"]["prompt_tokens"]
|
|
== expected_body["post"][0]["outputs"]["usage"]["prompt_tokens"]
|
|
)
|
|
assert (
|
|
actual_body["post"][0]["outputs"]["usage"]["total_tokens"]
|
|
== expected_body["post"][0]["outputs"]["usage"]["total_tokens"]
|
|
)
|
|
assert (
|
|
actual_body["post"][0]["session_name"]
|
|
== expected_body["post"][0]["session_name"]
|
|
)
|
|
|
|
mock_get_client.stop()
|
|
|
|
except Exception as e:
|
|
pytest.fail(f"Error occurred: {e}")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_langsmith_queue_logging():
|
|
try:
|
|
# Initialize LangsmithLogger
|
|
test_langsmith_logger = LangsmithLogger()
|
|
|
|
litellm.callbacks = [test_langsmith_logger]
|
|
test_langsmith_logger.batch_size = 6
|
|
litellm.set_verbose = True
|
|
|
|
# Make multiple calls to ensure we don't hit the batch size
|
|
for _ in range(5):
|
|
response = await litellm.acompletion(
|
|
model="gpt-4.1-mini",
|
|
messages=[{"role": "user", "content": "Test message"}],
|
|
max_tokens=10,
|
|
temperature=0.2,
|
|
mock_response="This is a mock response",
|
|
)
|
|
|
|
# Poll for async callbacks to complete (up to 10s)
|
|
for _ in range(20):
|
|
if len(test_langsmith_logger.log_queue) >= 5:
|
|
break
|
|
await asyncio.sleep(0.5)
|
|
|
|
# Check that logs are in the queue
|
|
assert len(test_langsmith_logger.log_queue) == 5
|
|
|
|
# Now make calls to exceed the batch size
|
|
for _ in range(3):
|
|
response = await litellm.acompletion(
|
|
model="gpt-4.1-mini",
|
|
messages=[{"role": "user", "content": "Test message"}],
|
|
max_tokens=10,
|
|
temperature=0.2,
|
|
mock_response="This is a mock response",
|
|
)
|
|
|
|
# Poll for flush to complete (up to 10s)
|
|
for _ in range(20):
|
|
if len(test_langsmith_logger.log_queue) < 5:
|
|
break
|
|
await asyncio.sleep(0.5)
|
|
|
|
print(
|
|
"Length of langsmith log queue: {}".format(
|
|
len(test_langsmith_logger.log_queue)
|
|
)
|
|
)
|
|
# Check that the queue was flushed after exceeding batch size
|
|
assert len(test_langsmith_logger.log_queue) < 5
|
|
|
|
# Clean up
|
|
for cb in litellm.callbacks:
|
|
if isinstance(cb, LangsmithLogger):
|
|
await cb.async_httpx_client.client.aclose()
|
|
|
|
except Exception as e:
|
|
pytest.fail(f"Error occurred: {e}")
|