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]

Merge branch 'main' into stevefarthing/bing-search-pass-thru

Steve Farthingdbfb7ebdaf69
diff --cc litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
index e919cb1a60f,db11cb5b6e6..075c9769826
--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
@@@ -3,8 -3,8 +3,8 @@@ import asynci
import json
from base64 import b64encode
from datetime import datetime
-from typing import List, Optional
-from urllib.parse import urlparse
+from typing import List, Optional, Union, Dict
- from urllib.parse import urlencode, parse_qs
++from urllib.parse import urlencode, parse_qs, urlparse
import httpx
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
@@@ -259,67 -260,85 +260,99 @@@ async def chat_completion_pass_through_
code=getattr(e, "status_code", 500),
)
-
- def forward_headers_from_request(
- request: Request,
- headers: dict,
- forward_headers: Optional[bool] = False,
- ):
- """
- Helper to forward headers from original request
- """
- if forward_headers is True:
- request_headers = dict(request.headers)
-
- # Header We Should NOT forward
- request_headers.pop("content-length", None)
- request_headers.pop("host", None)
-
- # Combine request headers with custom headers
- headers = {**request_headers, **headers}
- return headers
-
-
- def get_response_headers(
- headers: httpx.Headers, litellm_call_id: Optional[str] = None
- ) -> dict:
- excluded_headers = {"transfer-encoding", "content-encoding"}
-
- return_headers = {
- key: value
- for key, value in headers.items()
- if key.lower() not in excluded_headers
- }
- if litellm_call_id:
- return_headers["x-litellm-call-id"] = litellm_call_id
-
- return return_headers
-
-
- def get_merged_query_parameters(
- existing_url: httpx.URL, request_query_params: Dict[str, Union[str, list]]
- ) -> Dict[str, Union[str, List[str]]]:
- # Get the existing query params from the target URL
- existing_query_string = existing_url.query.decode("utf-8")
- existing_query_params = parse_qs(existing_query_string)
-
- # parse_qs returns a dict where each value is a list, so let's flatten it
- existing_query_params = {
- k: v[0] if len(v) == 1 else v for k, v in existing_query_params.items()
- }
-
- # Merge the query params, giving priority to the existing ones
- return {**request_query_params, **existing_query_params}
-
-
- 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:
- return EndpointType.ANTHROPIC
- return EndpointType.GENERIC
--
+ class HttpPassThroughEndpointHelpers:
+ @staticmethod
+ def forward_headers_from_request(
+ request: Request,
+ headers: dict,
+ forward_headers: Optional[bool] = False,
+ ):
+ """
+ Helper to forward headers from original request
+ """
+ if forward_headers is True:
+ request_headers = dict(request.headers)
+
+ # Header We Should NOT forward
+ request_headers.pop("content-length", None)
+ request_headers.pop("host", None)
+
+ # Combine request headers with custom headers
+ headers = {**request_headers, **headers}
+ return headers
+
+ @staticmethod
+ def get_response_headers(
+ headers: httpx.Headers, litellm_call_id: Optional[str] = None
+ ) -> dict:
+ excluded_headers = {"transfer-encoding", "content-encoding"}
+
+ return_headers = {
+ key: value
+ for key, value in headers.items()
+ if key.lower() not in excluded_headers
+ }
+ if litellm_call_id:
+ return_headers["x-litellm-call-id"] = litellm_call_id
+
+ return return_headers
+
+ @staticmethod
+ def get_endpoint_type(url: str) -> EndpointType:
+ parsed_url = urlparse(url)
+ if ("generateContent") in url or ("streamGenerateContent") in url:
+ return EndpointType.VERTEX_AI
+ elif parsed_url.hostname == "api.anthropic.com":
+ return EndpointType.ANTHROPIC
+ return EndpointType.GENERIC
+
++ @staticmethod
++ def get_merged_query_parameters(
++ existing_url: httpx.URL, request_query_params: Dict[str, Union[str, list]]
++ ) -> Dict[str, Union[str, List[str]]]:
++ # Get the existing query params from the target URL
++ existing_query_string = existing_url.query.decode("utf-8")
++ existing_query_params = parse_qs(existing_query_string)
++
++ # parse_qs returns a dict where each value is a list, so let's flatten it
++ existing_query_params = {
++ k: v[0] if len(v) == 1 else v for k, v in existing_query_params.items()
++ }
++
++ # Merge the query params, giving priority to the existing ones
++ return {**request_query_params, **existing_query_params}
++
+ @staticmethod
+ async def _make_non_streaming_http_request(
+ request: Request,
+ async_client: httpx.AsyncClient,
+ url: str,
+ headers: dict,
+ requested_query_params: Optional[dict] = None,
+ custom_body: Optional[dict] = None,
+ ) -> httpx.Response:
+ """
+ Make a non-streaming HTTP request
+
+ If request is GET, don't include a JSON body
+ """
+ if request.method == "GET":
+ response = await async_client.request(
+ method=request.method,
+ url=url,
+ headers=headers,
+ params=requested_query_params,
+ )
+ else:
+ response = await async_client.request(
+ method=request.method,
+ url=url,
+ headers=headers,
+ params=requested_query_params,
+ json=custom_body,
+ )
+ return response
-
async def pass_through_request( # noqa: PLR0915
request: Request,
target: str,
@@@ -343,19 -361,9 +376,23 @@@
request=request, headers=headers, forward_headers=forward_headers
)
++
+ if merge_query_params:
+
+ # Create a new URL with the merged query params
+ url = url.copy_with(
+ query=urlencode(
- get_merged_query_parameters(
++ HttpPassThroughEndpointHelpers.get_merged_query_parameters(
+ existing_url=url,
+ request_query_params=dict(request.query_params),
+ )
+ ).encode("ascii")
+ )
+
- endpoint_type: EndpointType = get_endpoint_type(str(url))
++
+ endpoint_type: EndpointType = HttpPassThroughEndpointHelpers.get_endpoint_type(
+ str(url)
+ )
_parsed_body = None
if custom_body: