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]

[Feat] Allow using query_params for setting API Key for generateContent routes (#13100)

Ishaan Jaffa6f7c7018520
diff --git a/litellm/proxy/auth/route_checks.py b/litellm/proxy/auth/route_checks.py
index e483ac6a662..cd158fd70a7 100644
--- a/litellm/proxy/auth/route_checks.py
+++ b/litellm/proxy/auth/route_checks.py
@@ -386,3 +386,16 @@ class RouteChecks:
if "thread" in request.url.path or "assistant" in request.url.path:
return True
return False
+
+ @staticmethod
+ def is_generate_content_route(route: str) -> bool:
+ """
+ Returns True if this is a google generateContent or streamGenerateContent route
+
+ These routes from google allow passing key=api_key in the query params
+ """
+ if "generateContent" in route:
+ return True
+ if "streamGenerateContent" in route:
+ return True
+ return False
diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py
index 4b223d4802d..70f9636adf5 100644
--- a/litellm/proxy/auth/user_api_key_auth.py
+++ b/litellm/proxy/auth/user_api_key_auth.py
@@ -255,12 +255,13 @@ def get_api_key(
Returns:
Tuple[Optional[str], Optional[str]]: Tuple of the api_key and the passed_in_key
"""
+ from litellm.proxy.auth.route_checks import RouteChecks
api_key = api_key
passed_in_key: Optional[str] = None
if isinstance(custom_litellm_key_header, str):
passed_in_key = custom_litellm_key_header
api_key = _get_bearer_token_or_received_api_key(custom_litellm_key_header)
- elif isinstance(api_key, str):
+ elif isinstance(api_key, str) and len(api_key) > 0:
passed_in_key = api_key
api_key = _get_bearer_token(api_key=api_key)
elif isinstance(azure_api_key_header, str):
@@ -275,14 +276,18 @@ def get_api_key(
elif isinstance(azure_apim_header, str):
passed_in_key = azure_apim_header
api_key = azure_apim_header
+ elif RouteChecks.is_generate_content_route(route=route) and request is not None and request.query_params.get("key"):
+ google_auth_key: str = request.query_params.get("key") or ""
+ passed_in_key = google_auth_key
+ api_key = google_auth_key
elif pass_through_endpoints is not None:
for endpoint in pass_through_endpoints:
if endpoint.get("path", "") == route:
headers: Optional[dict] = endpoint.get("headers", None)
if headers is not None:
header_key: str = headers.get("litellm_user_api_key", "")
- if request.headers.get(key=header_key) is not None:
- api_key = request.headers.get(key=header_key)
+ if request.headers.get(header_key) is not None:
+ api_key = request.headers.get(header_key) or ""
passed_in_key = api_key
return api_key, passed_in_key
diff --git a/tests/proxy_unit_tests/test_user_api_key_auth.py b/tests/proxy_unit_tests/test_user_api_key_auth.py
index e4330d96475..1eb1eef4c22 100644
--- a/tests/proxy_unit_tests/test_user_api_key_auth.py
+++ b/tests/proxy_unit_tests/test_user_api_key_auth.py
@@ -1044,3 +1044,38 @@ async def test_x_litellm_api_key():
valid_token = await user_api_key_auth(request=request, api_key="Bearer " + ignored_key, custom_litellm_key_header=master_key)
assert valid_token.token == hash_token(master_key)
+
+async def test_user_api_key_from_query_param():
+ """Ensure user_api_key_auth reads API key from `key` query parameter."""
+ from fastapi import Request
+ from starlette.datastructures import URL
+
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
+ from litellm.proxy.proxy_server import hash_token, user_api_key_cache
+
+ user_key = "sk-query-1234"
+ user_api_key_cache.set_cache(key=hash_token(user_key), value=UserAPIKeyAuth(token=hash_token(user_key)))
+
+ setattr(litellm.proxy.proxy_server, "user_api_key_cache", user_api_key_cache)
+ setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
+ setattr(litellm.proxy.proxy_server, "prisma_client", "hello-world")
+
+ request = Request(
+ scope={
+ "type": "http",
+ "path": "/v1beta/models/gemini:streamGenerateContent",
+ "query_string": f"alt=sse&key={user_key}".encode(),
+ }
+ )
+ request._url = URL(url=f"/v1beta/models/gemini:streamGenerateContent?alt=sse&key={user_key}")
+
+ async def return_body():
+ return b"{}"
+
+ request.body = return_body
+
+ valid_token = await user_api_key_auth(request=request, api_key="")
+ assert valid_token.token == hash_token(user_key)
+