Pass-Through Endpunkte erstellen
Leiten Sie Routen an den LiteLLM Proxy weiter
Beispiel: Fügen Sie eine Route /v1/rerank hinzu, die Anfragen an https://api.cohere.com/v1/rerank über den LiteLLM Proxy weiterleitet
💡 Dies ermöglicht die folgenden Anfragen an den LiteLLM Proxy
curl --request POST \
--url https://:4000/v1/rerank \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--data '{
"model": "rerank-english-v3.0",
"query": "What is the capital of the United States?",
"top_n": 3,
"documents": ["Carson City is the capital city of the American state of Nevada."]
}'
Tutorial - Cohere Re-Rank Endpoint weiterleiten
Schritt 1 Definieren Sie Weiterleitungsrouten in litellm config.yaml
general_settings:
master_key: sk-1234
pass_through_endpoints:
- path: "/v1/rerank" # route you want to add to LiteLLM Proxy Server
target: "https://api.cohere.com/v1/rerank" # URL this route should forward requests to
headers: # headers to forward to this URL
Authorization: "bearer os.environ/COHERE_API_KEY" # (Optional) Auth Header to forward to your Endpoint
content-type: application/json # (Optional) Extra Headers to pass to this endpoint
accept: application/json
forward_headers: True # (Optional) Forward all headers from the incoming request to the target endpoint
Schritt 2 Starten Sie den Proxy-Server im detaillierten Debug-Modus
litellm --config config.yaml --detailed_debug
Schritt 3 Senden Sie eine Anfrage an den Weiterleitungs-Endpunkt
Hier ist https://:4000 Ihr LiteLLM Proxy-Endpunkt
curl --request POST \
--url https://:4000/v1/rerank \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--data '{
"model": "rerank-english-v3.0",
"query": "What is the capital of the United States?",
"top_n": 3,
"documents": ["Carson City is the capital city of the American state of Nevada.",
"The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean. Its capital is Saipan.",
"Washington, D.C. (also known as simply Washington or D.C., and officially as the District of Columbia) is the capital of the United States. It is a federal district.",
"Capitalization or capitalisation in English grammar is the use of a capital letter at the start of a word. English usage varies from capitalization in other languages.",
"Capital punishment (the death penalty) has existed in the United States since beforethe United States was a country. As of 2017, capital punishment is legal in 30 of the 50 states."]
}'
🎉 Erwartete Antwort
Diese Anfrage wurde vom LiteLLM Proxy weitergeleitet -> Definierte Ziel-URL (mit Headern)
{
"id": "37103a5b-8cfb-48d3-87c7-da288bedd429",
"results": [
{
"index": 2,
"relevance_score": 0.999071
},
{
"index": 4,
"relevance_score": 0.7867867
},
{
"index": 0,
"relevance_score": 0.32713068
}
],
"meta": {
"api_version": {
"version": "1"
},
"billed_units": {
"search_units": 1
}
}
}
Tutorial - Langfuse-Anfragen weiterleiten
Schritt 1 Definieren Sie Weiterleitungsrouten in litellm config.yaml
general_settings:
master_key: sk-1234
pass_through_endpoints:
- path: "/api/public/ingestion" # route you want to add to LiteLLM Proxy Server
target: "https://us.cloud.langfuse.com/api/public/ingestion" # URL this route should forward
headers:
LANGFUSE_PUBLIC_KEY: "os.environ/LANGFUSE_DEV_PUBLIC_KEY" # your langfuse account public key
LANGFUSE_SECRET_KEY: "os.environ/LANGFUSE_DEV_SK_KEY" # your langfuse account secret key
Schritt 2 Starten Sie den Proxy-Server im detaillierten Debug-Modus
litellm --config config.yaml --detailed_debug
Schritt 3 Senden Sie eine Anfrage an den Weiterleitungs-Endpunkt
Führen Sie diesen Code aus, um eine Beispiel-Trace zu erstellen
from langfuse import Langfuse
langfuse = Langfuse(
host="https://:4000", # your litellm proxy endpoint
public_key="anything", # no key required since this is a pass through
secret_key="anything", # no key required since this is a pass through
)
print("sending langfuse trace request")
trace = langfuse.trace(name="test-trace-litellm-proxy-passthrough")
print("flushing langfuse request")
langfuse.flush()
print("flushed langfuse request")
🎉 Erwartete Antwort
Bei Erfolg sehen Sie die folgende Trace, die auf Ihrem Langfuse Dashboard generiert wurde
Sie werden den folgenden Endpunkt in Ihren LiteLLM Proxy-Serverprotokollen sehen
POST /api/public/ingestion HTTP/1.1" 207 Multi-Status
✨[Enterprise]- LiteLLM-Schlüssel/Authentifizierung auf Weiterleitungs-Endpunkten verwenden
Verwenden Sie dies, wenn der Weiterleitungs-Endpunkt LiteLLM-Schlüssel/Authentifizierung honorieren soll
Dadurch werden auch die RPM-Limits der Schlüssel für Weiterleitungs-Endpunkte durchgesetzt.
Verwendung - setzen Sie auth: true in der Konfiguration
general_settings:
master_key: sk-1234
pass_through_endpoints:
- path: "/v1/rerank"
target: "https://api.cohere.com/v1/rerank"
auth: true # 👈 Key change to use LiteLLM Auth / Keys
headers:
Authorization: "bearer os.environ/COHERE_API_KEY"
content-type: application/json
accept: application/json
Testanfrage mit LiteLLM-Schlüssel
curl --request POST \
--url https://:4000/v1/rerank \
--header 'accept: application/json' \
--header 'Authorization: Bearer sk-1234'\
--header 'content-type: application/json' \
--data '{
"model": "rerank-english-v3.0",
"query": "What is the capital of the United States?",
"top_n": 3,
"documents": ["Carson City is the capital city of the American state of Nevada.",
"The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean. Its capital is Saipan.",
"Washington, D.C. (also known as simply Washington or D.C., and officially as the District of Columbia) is the capital of the United States. It is a federal district.",
"Capitalization or capitalisation in English grammar is the use of a capital letter at the start of a word. English usage varies from capitalization in other languages.",
"Capital punishment (the death penalty) has existed in the United States since beforethe United States was a country. As of 2017, capital punishment is legal in 30 of the 50 states."]
}'
Verwenden Sie das Langfuse Client SDK mit LiteLLM-Schlüssel
Verwendung
- YAML-Konfiguration zum Weiterleiten von Langfuse /api/public/ingestion
general_settings:
master_key: sk-1234
pass_through_endpoints:
- path: "/api/public/ingestion" # route you want to add to LiteLLM Proxy Server
target: "https://us.cloud.langfuse.com/api/public/ingestion" # URL this route should forward
auth: true # 👈 KEY CHANGE
custom_auth_parser: "langfuse" # 👈 KEY CHANGE
headers:
LANGFUSE_PUBLIC_KEY: "os.environ/LANGFUSE_DEV_PUBLIC_KEY" # your langfuse account public key
LANGFUSE_SECRET_KEY: "os.environ/LANGFUSE_DEV_SK_KEY" # your langfuse account secret key
- Proxy starten
litellm --config /path/to/config.yaml
- Testen Sie mit dem Langfuse SDK
from langfuse import Langfuse
langfuse = Langfuse(
host="https://:4000", # your litellm proxy endpoint
public_key="sk-1234", # your litellm proxy api key
secret_key="anything", # no key required since this is a pass through
)
print("sending langfuse trace request")
trace = langfuse.trace(name="test-trace-litellm-proxy-passthrough")
print("flushing langfuse request")
langfuse.flush()
print("flushed langfuse request")
pass_through_endpoints Spezifikation in config.yaml
Alle möglichen Werte für pass_through_endpoints und ihre Bedeutung
Beispielkonfiguration
general_settings:
pass_through_endpoints:
- path: "/v1/rerank" # route you want to add to LiteLLM Proxy Server
target: "https://api.cohere.com/v1/rerank" # URL this route should forward requests to
headers: # headers to forward to this URL
Authorization: "bearer os.environ/COHERE_API_KEY" # (Optional) Auth Header to forward to your Endpoint
content-type: application/json # (Optional) Extra Headers to pass to this endpoint
accept: application/json
Spezifikation
pass_through_endpointsListe: Eine Sammlung von Endpunktkonfigurationen für die Anfrageweiterleitung.pathString: Die Route, die dem LiteLLM Proxy Server hinzugefügt werden soll.targetString: Die URL, an die Anfragen für diesen Pfad weitergeleitet werden sollen.headersObjekt: Schlüssel-Wert-Paare von Headern, die mit der Anfrage weitergeleitet werden sollen. Sie können hier jedes Schlüssel-Wert-Paar festlegen, und es wird an Ihren Zielendpunkt weitergeleitet.AuthorizationString: Der Authentifizierungsheader für die Ziel-API.content-typeString: Die Formatangabe für den Anfragekörper.acceptString: Das erwartete Antwortformat vom Server.LANGFUSE_PUBLIC_KEYString: Ihr öffentlicher Schlüssel für das Langfuse-Konto - nur setzen, wenn Sie an Langfuse weiterleiten.LANGFUSE_SECRET_KEYString: Ihr geheimer Schlüssel für das Langfuse-Konto - nur setzen, wenn Sie an Langfuse weiterleiten.<Ihr-benutzerdefinierter-Header>String: Weiterleiten eines beliebigen benutzerdefinierten Header-Schlüssel-/Wert-Paares
forward_headersOptional(boolean): Wenn true, werden alle Header aus der eingehenden Anfrage an den Zielendpunkt weitergeleitet. Standard istFalse.
Benutzerdefinierte Chat-Endpunkte (Anthropic/Bedrock/Vertex)
Ermöglicht Entwicklern, den Proxy mit Anthropic/boto3/etc. Client SDKs aufzurufen.
Sehen Sie sich unseren Anthropic Adapter als Referenz an Code
1. Schreiben Sie einen Adapter
Übersetzen Sie die Anfrage/Antwort von Ihrem benutzerdefinierten API-Schema in das OpenAI-Schema (verwendet von litellm.completion()) und zurück.
Für anbieterspezifische Parameter siehe 👉 Anbieterspezifische Parameter
from litellm import adapter_completion
import litellm
from litellm import ChatCompletionRequest, verbose_logger
from litellm.integrations.custom_logger import CustomLogger
from litellm.types.llms.anthropic import AnthropicMessagesRequest, AnthropicResponse
import os
# What is this?
## Translates OpenAI call to Anthropic `/v1/messages` format
import json
import os
import traceback
import uuid
from typing import Literal, Optional
import dotenv
import httpx
from pydantic import BaseModel
###################
# CUSTOM ADAPTER ##
###################
class AnthropicAdapter(CustomLogger):
def __init__(self) -> None:
super().__init__()
def translate_completion_input_params(
self, kwargs
) -> Optional[ChatCompletionRequest]:
"""
- translate params, where needed
- pass rest, as is
"""
request_body = AnthropicMessagesRequest(**kwargs) # type: ignore
translated_body = litellm.AnthropicConfig().translate_anthropic_to_openai(
anthropic_message_request=request_body
)
return translated_body
def translate_completion_output_params(
self, response: litellm.ModelResponse
) -> Optional[AnthropicResponse]:
return litellm.AnthropicConfig().translate_openai_response_to_anthropic(
response=response
)
def translate_completion_output_params_streaming(self) -> Optional[BaseModel]:
return super().translate_completion_output_params_streaming()
anthropic_adapter = AnthropicAdapter()
###########
# TEST IT #
###########
## register CUSTOM ADAPTER
litellm.adapters = [{"id": "anthropic", "adapter": anthropic_adapter}]
## set ENV variables
os.environ["OPENAI_API_KEY"] = "your-openai-key"
os.environ["COHERE_API_KEY"] = "your-cohere-key"
messages = [{ "content": "Hello, how are you?","role": "user"}]
# openai call
response = adapter_completion(model="gpt-3.5-turbo", messages=messages, adapter_id="anthropic")
# cohere call
response = adapter_completion(model="command-nightly", messages=messages, adapter_id="anthropic")
print(response)
2. Erstellen Sie einen neuen Endpunkt
Wir übergeben die benutzerdefinierte Callback-Klasse aus Schritt 1 an die config.yaml. Setzen Sie callbacks auf python_filename.logger_instance_name
In der folgenden Konfiguration übergeben wir
python_filename: custom_callbacks.py logger_instance_name: anthropic_adapter. Dies ist in Schritt 1 definiert
target: custom_callbacks.proxy_handler_instance
model_list:
- model_name: my-fake-claude-endpoint
litellm_params:
model: gpt-3.5-turbo
api_key: os.environ/OPENAI_API_KEY
general_settings:
master_key: sk-1234
pass_through_endpoints:
- path: "/v1/messages" # route you want to add to LiteLLM Proxy Server
target: custom_callbacks.anthropic_adapter # Adapter to use for this route
headers:
litellm_user_api_key: "x-api-key" # Field in headers, containing LiteLLM Key
3. Testen!
Proxy starten
litellm --config /path/to/config.yaml
Curl
curl --location 'http://0.0.0.0:4000/v1/messages' \
-H 'x-api-key: sk-1234' \
-H 'anthropic-version: 2023-06-01' \ # ignored
-H 'content-type: application/json' \
-D '{
"model": "my-fake-claude-endpoint",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, world"}
]
}'