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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
docs custom prompt management
Ishaan Jaffe9d9c526fa60
diff --git a/docs/my-website/docs/proxy/custom_prompt_management.md b/docs/my-website/docs/proxy/custom_prompt_management.mdindex 47a6084035f..0e57fcddc90 100644--- a/docs/my-website/docs/proxy/custom_prompt_management.md+++ b/docs/my-website/docs/proxy/custom_prompt_management.md@@ -1,4 +1,3 @@-import Image from '@theme/IdealImage';import Tabs from '@theme/Tabs';import TabItem from '@theme/TabItem';@@ -9,22 +8,22 @@ Follow this guide to implement custom hooks that allow connecting LiteLLM to you## Quick Start-### 1. Implement a `CustomLogger` Class+### 1. Implement a `CustomPromptManagement` Class-A `CustomLogger` class is used to manage prompts and their parameters. It has a key method to retrieve the chat completion prompt.+Create a class that inherits from `CustomPromptManagement` to manage prompts and their parameters. The key method to implement is `get_chat_completion_prompt`.-**Example `CustomLogger` Class**+**Example Implementation**-Create a new file called `custom_logger.py` and add this code to it:+Create a new file called `custom_prompt.py` and add this code:```pythonfrom typing import List, Tuple, Optional-from litellm.integrations.prompt_management_base import PromptManagementBase-from litellm.integrations.custom_logger import CustomLogger-from litellm.types import AllMessageValues, StandardCallbackDynamicParams+from litellm.integrations.custom_prompt_management import CustomPromptManagement+from litellm.types.llms.openai import AllMessageValues+from litellm.types.utils import StandardCallbackDynamicParams-class CustomPromptManagement(CustomLogger, PromptManagementBase):- async def async_get_chat_completion_prompt(+class MyCustomPromptManagement(CustomPromptManagement):+ def get_chat_completion_prompt(self,model: str,messages: List[AllMessageValues],@@ -34,37 +33,52 @@ class CustomPromptManagement(CustomLogger, PromptManagementBase):dynamic_callback_params: StandardCallbackDynamicParams,) -> Tuple[str, List[AllMessageValues], dict]:"""+ Args:+ model: The model name+ messages: List of message objects+ non_default_params: Optional parameters like temperature, max_tokens+ prompt_id: Identifier for the prompt to retrieve+ prompt_variables: Variables to format into the prompt+ dynamic_callback_params: Additional callback parameters+Returns:- - model: str - the model to use (can be pulled from prompt management tool)- - messages: List[AllMessageValues] - the messages to use (can be pulled from prompt management tool)- - non_default_params: dict - update with any optional params (e.g. temperature, max_tokens, etc.) to use (can be pulled from prompt management tool)+ - model: str - the model to use+ - messages: List[AllMessageValues] - the messages to use+ - non_default_params: dict - optional params (e.g. temperature)"""+ # Example 1: Simple prompt retrieval+ if prompt_id == "welcome_prompt":+ messages = [+ {"role": "user", "content": "Welcome to our AI assistant! How can I help you today?"},+ ]+ return model, messages, non_default_params++ # Example 2: Prompt with variables+ elif prompt_id == "personalized_greeting":+ content = "Hello, {name}! You are {age} years old and live in {city}."+ content_with_variables = content.format(**(prompt_variables or {}))+ messages = [+ {"role": "user", "content": content_with_variables},+ ]+ return model, messages, non_default_params++ # Default: Return original messages if no prompt_id matchreturn model, messages, non_default_params-- @property- def custom_logger_name(self) -> str:- return "custom-prompt-management"-proxy_prompt_management_instance = CustomPromptManagement()+prompt_management = MyCustomPromptManagement()```-### 2. Configure Your Logger in LiteLLM `config.yaml`--In the configuration file, specify your custom logger class to manage prompts.--- Python Filename: `custom_logger.py`-- Logger class name: `CustomLogger`+### 2. Configure Your Prompt Manager in LiteLLM `config.yaml````yamlmodel_list:- model_name: gpt-4litellm_params:- model: openai/gpt-4o+ model: openai/gpt-4api_key: os.environ/OPENAI_API_KEYlitellm_settings:- callbacks: custom_logger.proxy_prompt_management_instance # sets litellm.callbacks = [proxy_prompt_management_instance]-+ callbacks: custom_prompt.prompt_management # sets litellm.callbacks = [prompt_management]```### 3. Start LiteLLM Gateway@@ -98,63 +112,190 @@ litellm --config config.yaml --detailed_debug</TabItem></Tabs>-### 4. Test Your Custom Logger+### 4. Test Your Custom Prompt Manager-#### Test `"custom-logger"`+#### Example 1: Simple Prompt ID-**[Langchain, OpenAI SDK Usage Examples](../proxy/user_keys#request-format)**+When you pass `prompt_id="welcome_prompt"`, the custom prompt manager will replace your empty messages with a predefined welcome message: `"Welcome to our AI assistant! How can I help you today?"`.<Tabs>-<TabItem label="Retrieve Prompt" value="retrieve-prompt">+<TabItem value="openai" label="OpenAI Python v1.0.0+">++```python+from openai import OpenAI++client = OpenAI(+ api_key="sk-1234",+ base_url="http://0.0.0.0:4000"+)++response = client.chat.completions.create(+ model="gpt-4",+ messages=[],+ prompt_id="welcome_prompt"+)++print(response.choices[0].message.content)+```+</TabItem>++<TabItem value="langchain" label="Langchain">++```python+from langchain.chat_models import ChatOpenAI+from langchain.schema import HumanMessage++chat = ChatOpenAI(+ model="gpt-4",+ openai_api_key="sk-1234",+ openai_api_base="http://0.0.0.0:4000",+ extra_body={+ "prompt_id": "welcome_prompt"+ }+)++messages = []+response = chat(messages)-Use this to test the retrieval of prompts using your custom logger.+print(response.content)+```+</TabItem>++<TabItem value="curl" label="Curl">```shell-curl -i -X POST http://localhost:4000/v1/chat/completions \+curl -X POST http://0.0.0.0:4000/v1/chat/completions \-H "Content-Type: application/json" \-H "Authorization: Bearer sk-1234" \-d '{- "model": "custom-prompt-management/gpt-4",- "messages": [- {- "role": "user",- "content": "Hello, how can I assist you today?"+ "model": "gpt-4",+ "messages": [],+ "prompt_id": "welcome_prompt"+}'+```+</TabItem>+</Tabs>++Expected response:++```json+{+ "id": "chatcmpl-123",+ "choices": [+ {+ "finish_reason": "stop",+ "index": 0,+ "message": {+ "content": "I'd be happy to assist you today! How can I help?",+ "role": "assistant"+ }+ }+ ]+}+```++#### Example 2: Prompt ID with Variables++When you pass `prompt_id="personalized_greeting"`, the custom prompt manager will:+1. Start with the template: `"Hello, {name}! You are {age} years old and live in {city}."`+2. Replace the variables with your provided values+3. Create a message with the formatted content: `"Hello, John! You are 30 years old and live in New York."`++<Tabs>+<TabItem value="openai" label="OpenAI Python v1.0.0+">++```python+from openai import OpenAI++client = OpenAI(+ api_key="sk-1234",+ base_url="http://0.0.0.0:4000"+)++response = client.chat.completions.create(+ model="gpt-4",+ messages=[],+ prompt_id="personalized_greeting",+ prompt_variables={+ "name": "John",+ "age": 30,+ "city": "New York"+ }+)++print(response.choices[0].message.content)+```+</TabItem>++<TabItem value="langchain" label="Langchain">++```python+from langchain.chat_models import ChatOpenAI+from langchain.schema import HumanMessage++chat = ChatOpenAI(+ model="gpt-4",+ openai_api_key="sk-1234",+ openai_api_base="http://0.0.0.0:4000",+ extra_body={+ "prompt_id": "personalized_greeting",+ "prompt_variables": {+ "name": "John",+ "age": 30,+ "city": "New York"}- ],- "prompt_id": "1234",+ }+)++messages = []+response = chat(messages)++print(response.content)+```+</TabItem>++<TabItem value="curl" label="Curl">++```shell+curl -X POST http://0.0.0.0:4000/v1/chat/completions \+-H "Content-Type: application/json" \+-H "Authorization: Bearer sk-1234" \+-d '{+ "model": "gpt-4",+ "messages": [],+ "prompt_id": "personalized_greeting","prompt_variables": {- "name": "John Doe"+ "name": "John",+ "age": 30,+ "city": "New York"}}'```+</TabItem>+</Tabs>++Expected response:```json{- "id": "chatcmpl-9zREDkBIG20RJB4pMlyutmi1hXQWc",+ "id": "chatcmpl-123","choices": [{"finish_reason": "stop","index": 0,"message": {- "content": "Hello! How can I help you today?",+ "content": "Hi John! I understand you're 30 years old and based in New York. How can I assist you today?","role": "assistant"}}- ],- "created": 1724429701,- "model": "gpt-4o-2024-05-13",- "object": "chat.completion",- "system_fingerprint": "fp_3aa7262c27",- "usage": {- "completion_tokens": 65,- "prompt_tokens": 14,- "total_tokens": 79- },- "service_tier": null+ ]}```-</TabItem>-</Tabs>+The prompt manager will:+1. Intercept the request+2. Check the prompt_id to determine which template to use+3. If variables are provided, format them into the template+4. Send the final prompt to the LLM