Skip to content

(feat) add usage / cost tracking for Anthropic passthrough routes - #6835

Merged
ishaan-jaff merged 7 commits into
mainfrom
litellm_add_passthrough_cost_tracking
Nov 21, 2024
Merged

ishaan-jaff merged 7 commits into
mainfrom
litellm_add_passthrough_cost_tracking

Conversation

@ishaan-jaff

@ishaan-jaff ishaan-jaff commented Nov 20, 2024 •

Copy link
Copy Markdown
Contributor

Title

  • Anthropic pass-through routes to include usage and cost tracking
  • Fix check for responses that are streaming responses (previously anthropic pass through streaming was not working)

Relevant issues

Type

🆕 New Feature
🐛 Bug Fix
🧹 Refactoring
📖 Documentation
🚄 Infrastructure
✅ Test

Changes

[REQUIRED] Testing - Attach a screenshot of any new tests passing locall

If UI changes, send a screenshot/GIF of working UI fixes

Description by Korbit AI

What change is being made?

Refactor and enhance the Anthropic pass-through routes to include usage and cost tracking, moving response processing logic into a new AnthropicConfig class, and updating logging behavior for improved consistency.

Why are these changes being made?

This change aims to improve the system's clarity and efficiency by modularizing the code and enhancing it with usage/cost tracking capabilities. It addresses the need for consistent transforming and logging of responses from Anthropic routes and adds missing features to support cost management, aligning with existing OpenAI response formats.

Is this description stale? Ask me to generate a new description by commenting /korbit-generate-pr-description

@korbit-ai

korbit-ai Bot commented Nov 20, 2024

Copy link
Copy Markdown

Hey there, my name is Korbit. I've joined the team as your AI code reviewer. I'll automatically scan your PRs and raise any issues I find. I can also help you write a PR description. As you work with me, I'll learn about your priorities and codebase and get smarter over time. My goal is to help improve your code quality and save time for the human reviewers on your team. Let's get started!

@vercel

vercel Bot commented Nov 20, 2024 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
litellm ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 21, 2024 0:12am

@korbit-ai korbit-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary by Korbit AI

Code Health Comments

  • Log exception details with a logging library before raising AnthropicError to assist in debugging and monitoring.
Files scanned ​
File Path Reviewed
litellm/proxy/pass_through_endpoints/success_handler.py ✅
litellm/proxy/pass_through_endpoints/pass_through_endpoints.py ✅
litellm/llms/anthropic/chat/transformation.py ✅
litellm/llms/anthropic/chat/handler.py ✅

Explore our documentation to understand the languages and file types we support and the files we ignore.

Need a new review? Comment /korbit-review on this PR and I'll review your latest changes.

Korbit Guide: Usage and Customization

Interacting with Korbit

  • You can manually ask Korbit to review your PR using the /korbit-review command in a comment at the root of your PR.
  • You can ask Korbit to generate a new PR description using the /korbit-generate-pr-description command in any comment on your PR.
  • Too many Korbit comments? I can resolve all my comment threads if you use the /korbit-resolve command in any comment on your PR.
  • Chat with Korbit on issues we post by tagging @korbit-ai in your reply.
  • Help train Korbit to improve your reviews by giving a 👍 or 👎 on the comments Korbit posts.

Customizing Korbit

  • Check out our docs on how you can make Korbit work best for you and your team.
  • Customize Korbit for your organization through the Korbit Console.

Current Korbit Configuration

General Settings ​
Setting Value
Review Schedule Automatic excluding drafts
Max Issue Count 10
Automatic PR Descriptions ✅
Issue Categories ​
Category Enabled
Naming ✅
Database Operations ✅
Documentation ✅
Logging ✅
Error Handling ✅
Systems and Environment ✅
Objects and Data Structures ✅
Readability and Maintainability ✅
Asynchronous Processing ✅
Design Patterns ✅
Third-Party Libraries ✅
Performance ✅
Security ✅
Functionality ✅

Feedback and Support

Comment on lines +586 to +594
except Exception as e:
response_headers = getattr(response, "headers", None)
raise AnthropicError(
message="Unable to get json response - {}, Original Response: {}".format(
str(e), response.text
),
status_code=response.status_code,
headers=response_headers,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

category Error Handling severity potentially major

Log exception details before raising AnthropicError.

Tell me more ​

Consider logging the exception details before raising the AnthropicError. This can help with debugging and monitoring. You can use a logging library or your existing logging_obj to log the error message, status code, and original response.

Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

def get_endpoint_type(url: str) -> EndpointType:
if ("generateContent") in url or ("streamGenerateContent") in url:
return EndpointType.VERTEX_AI
elif ("api.anthropic.com") in url:

Check failure

Code scanning / CodeQL

Incomplete URL substring sanitization

The string [api.anthropic.com](1) may be at an arbitrary position in the sanitized URL.

Copilot Autofix

AI almost 2 years ago

To fix the problem, we need to ensure that the URL is parsed and the hostname is checked correctly. Instead of using a simple substring check, we should use the urlparse function from the urllib.parse module to extract the hostname from the URL and then check if it matches the expected hostname.

The best way to fix the problem without changing existing functionality is to modify the get_endpoint_type function to parse the URL and check the hostname. We will import the urlparse function and use it to extract the hostname from the URL, then check if the hostname matches "api.anthropic.com".

Suggested changeset 1
litellm/proxy/pass_through_endpoints/pass_through_endpoints.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
@@ -7,3 +7,3 @@
 from typing import AsyncIterable, List, Optional
-
+from urllib.parse import urlparse
 import httpx
@@ -303,5 +303,6 @@
 def get_endpoint_type(url: str) -> EndpointType:
-    if ("generateContent") in url or ("streamGenerateContent") in url:
+    parsed_url = urlparse(url)
+    if ("generateContent") in parsed_url.path or ("streamGenerateContent") in parsed_url.path:
         return EndpointType.VERTEX_AI
-    elif ("api.anthropic.com") in url:
+    elif parsed_url.hostname == "api.anthropic.com":
         return EndpointType.ANTHROPIC
EOF
@@ -7,3 +7,3 @@
from typing import AsyncIterable, List, Optional

from urllib.parse import urlparse
import httpx
@@ -303,5 +303,6 @@
def get_endpoint_type(url: str) -> EndpointType:
if ("generateContent") in url or ("streamGenerateContent") in url:
parsed_url = urlparse(url)
if ("generateContent") in parsed_url.path or ("streamGenerateContent") in parsed_url.path:
return EndpointType.VERTEX_AI
elif ("api.anthropic.com") in url:
elif parsed_url.hostname == "api.anthropic.com":
return EndpointType.ANTHROPIC
Copilot is powered by AI and may make mistakes. Always verify output.
@ishaan-jaff
ishaan-jaff merged commit c107bae into main Nov 21, 2024
@ishaan-berri
ishaan-berri deleted the litellm_add_passthrough_cost_tracking branch March 26, 2026 21:51
fzowl pushed a commit to fzowl/litellm that referenced this pull request Jun 24, 2026
…rriAI#6835)

* move _process_response in transformation

* fix AnthropicConfig test

* add AnthropicConfig

* fix anthropic_passthrough_handler

* fix get_response_body

* fix check for streaming response

* use 1 helper to return stream_response on passthrough

This branch was successfully deployed

1 active deployment
Preview — 97ecedf9 Deployed Nov 21, 2024 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants