Skip to content

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]

log failure calls on gcs + testing

Ishaan Jaff326d79711122
diff --git a/litellm/integrations/gcs_bucket.py b/litellm/integrations/gcs_bucket.py
index 6525f680a1a..be7f8e39c23 100644
--- a/litellm/integrations/gcs_bucket.py
+++ b/litellm/integrations/gcs_bucket.py
@@ -129,13 +129,20 @@ class GCSBucketLogger(CustomLogger):
)
logging_payload["log_event_type"] = "failed_api_call"
+ _litellm_params = kwargs.get("litellm_params") or {}
+ metadata = _litellm_params.get("metadata") or {}
+
json_logged_payload = json.dumps(logging_payload)
# Get the current date
current_date = datetime.now().strftime("%Y-%m-%d")
# Modify the object_name to include the date-based folder
- object_name = f"{current_date}/{uuid.uuid4().hex}"
+ object_name = f"{current_date}/failure-{uuid.uuid4().hex}"
+
+ if "gcs_log_id" in metadata:
+ object_name = metadata["gcs_log_id"]
+
response = await self.async_httpx_client.post(
headers=headers,
url=f"https://storage.googleapis.com/upload/storage/v1/b/{self.BUCKET_NAME}/o?uploadType=media&name={object_name}",
diff --git a/litellm/tests/test_gcs_bucket.py b/litellm/tests/test_gcs_bucket.py
index b26dfec0382..f0aaf8d8ddb 100644
--- a/litellm/tests/test_gcs_bucket.py
+++ b/litellm/tests/test_gcs_bucket.py
@@ -162,3 +162,113 @@ async def test_basic_gcs_logger():
# Delete Object from GCS
print("deleting object from GCS")
await gcs_logger.delete_gcs_object(object_name=object_name)
+
+
+async def test_basic_gcs_logger_failure():
+ load_vertex_ai_credentials()
+ gcs_logger = GCSBucketLogger()
+ print("GCSBucketLogger", gcs_logger)
+
+ gcs_log_id = f"failure-test-{uuid.uuid4().hex}"
+
+ litellm.callbacks = [gcs_logger]
+
+ try:
+ response = await litellm.acompletion(
+ model="gpt-3.5-turbo",
+ temperature=0.7,
+ messages=[{"role": "user", "content": "This is a test"}],
+ max_tokens=10,
+ user="ishaan-2",
+ mock_response=litellm.BadRequestError(
+ model="gpt-3.5-turbo",
+ message="Error: 400: Bad Request: Invalid API key, please check your API key and try again.",
+ llm_provider="openai",
+ ),
+ metadata={
+ "gcs_log_id": gcs_log_id,
+ "tags": ["model-anthropic-claude-v2.1", "app-ishaan-prod"],
+ "user_api_key": "88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",
+ "user_api_key_alias": None,
+ "user_api_end_user_max_budget": None,
+ "litellm_api_version": "0.0.0",
+ "global_max_parallel_requests": None,
+ "user_api_key_user_id": "116544810872468347480",
+ "user_api_key_org_id": None,
+ "user_api_key_team_id": None,
+ "user_api_key_team_alias": None,
+ "user_api_key_metadata": {},
+ "requester_ip_address": "127.0.0.1",
+ "spend_logs_metadata": {"hello": "world"},
+ "headers": {
+ "content-type": "application/json",
+ "user-agent": "PostmanRuntime/7.32.3",
+ "accept": "*/*",
+ "postman-token": "92300061-eeaa-423b-a420-0b44896ecdc4",
+ "host": "localhost:4000",
+ "accept-encoding": "gzip, deflate, br",
+ "connection": "keep-alive",
+ "content-length": "163",
+ },
+ "endpoint": "http://localhost:4000/chat/completions",
+ "model_group": "gpt-3.5-turbo",
+ "deployment": "azure/chatgpt-v-2",
+ "model_info": {
+ "id": "4bad40a1eb6bebd1682800f16f44b9f06c52a6703444c99c7f9f32e9de3693b4",
+ "db_model": False,
+ },
+ "api_base": "https://openai-gpt-4-test-v-1.openai.azure.com/",
+ "caching_groups": None,
+ "raw_request": "\n\nPOST Request Sent from LiteLLM:\ncurl -X POST \\\nhttps://openai-gpt-4-test-v-1.openai.azure.com//openai/ \\\n-H 'Authorization: *****' \\\n-d '{'model': 'chatgpt-v-2', 'messages': [{'role': 'system', 'content': 'you are a helpful assistant.\\n'}, {'role': 'user', 'content': 'bom dia'}], 'stream': False, 'max_tokens': 10, 'user': '116544810872468347480', 'extra_body': {}}'\n",
+ },
+ )
+ except:
+ pass
+
+ await asyncio.sleep(5)
+
+ # Get the current date
+ # Get the current date
+ current_date = datetime.now().strftime("%Y-%m-%d")
+
+ # Modify the object_name to include the date-based folder
+ object_name = gcs_log_id
+
+ print("object_name", object_name)
+
+ # Check if object landed on GCS
+ object_from_gcs = await gcs_logger.download_gcs_object(object_name=object_name)
+ print("object from gcs=", object_from_gcs)
+ # convert object_from_gcs from bytes to DICT
+ parsed_data = json.loads(object_from_gcs)
+ print("object_from_gcs as dict", parsed_data)
+
+ print("type of object_from_gcs", type(parsed_data))
+
+ gcs_payload = GCSBucketPayload(**parsed_data)
+
+ print("gcs_payload", gcs_payload)
+
+ assert gcs_payload["request_kwargs"]["model"] == "gpt-3.5-turbo"
+ assert gcs_payload["request_kwargs"]["messages"] == [
+ {"role": "user", "content": "This is a test"}
+ ]
+
+ assert gcs_payload["response_cost"] == 0
+ assert gcs_payload["log_event_type"] == "failed_api_call"
+
+ gcs_payload["spend_log_metadata"] = json.loads(gcs_payload["spend_log_metadata"])
+
+ assert (
+ gcs_payload["spend_log_metadata"]["user_api_key"]
+ == "88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b"
+ )
+ assert (
+ gcs_payload["spend_log_metadata"]["user_api_key_user_id"]
+ == "116544810872468347480"
+ )
+
+ # Delete Object from GCS
+ print("deleting object from GCS")
+ await gcs_logger.delete_gcs_object(object_name=object_name)