Buckets:

download
raw
44.6 kB
""" CRUD ENDPOINTS FOR PROMPTS """ import tempfile from collections.abc import Awaitable, Mapping, Sequence from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Final, Protocol, cast from fastapi import ( APIRouter, Depends, File, HTTPException, Request, Response, UploadFile, ) from pydantic import BaseModel from litellm._logging import verbose_proxy_logger from litellm.proxy._types import ( CommonProxyErrors, LitellmUserRoles, UserAPIKeyAuth, user_api_key_has_admin_view, ) from litellm.proxy.auth.auth_utils import is_request_body_safe from litellm.proxy.auth.user_api_key_auth import user_api_key_auth from litellm.proxy.common_utils.path_utils import safe_filename from litellm.proxy.prompts.prompt_registry import ( DEFAULT_PROMPT_ENVIRONMENT, get_base_prompt_id, get_version_number, prompt_environment_or_default, ) from litellm.repositories.table_repositories import PromptRepository from litellm.types.prompts.init_prompts import ( ListPromptsResponse, PromptInfo, PromptInfoResponse, PromptLiteLLMParams, PromptSpec, PromptTemplateBase, ) from litellm.types.proxy.prompt_endpoints import TestPromptRequest if TYPE_CHECKING: from litellm.proxy.prompts.prompt_registry import InMemoryPromptRegistry from litellm.proxy.utils import PrismaClient router: Final = APIRouter() class _PromptRow(Protocol): @property def id(self) -> str: ... @property def prompt_id(self) -> str: ... @property def version(self) -> int: ... @property def environment(self) -> str: ... @property def created_by(self) -> str | None: ... @property def created_at(self) -> "datetime": ... @property def updated_at(self) -> "datetime": ... @property def litellm_params(self) -> str | Mapping[str, object]: ... @property def prompt_info(self) -> str | Mapping[str, object] | None: ... def model_dump(self) -> Mapping[str, object]: ... class _PromptRowData(BaseModel): prompt_id: str version: int = 1 environment: str = "development" created_by: str | None = None litellm_params: str | Mapping[str, object] | None = None prompt_info: str | Mapping[str, object] | None = None created_at: datetime | None = None updated_at: datetime | None = None class _PromptTableActions(Protocol): def find_many( self, *, where: Mapping[str, str | int], order: Mapping[str, str] = ..., take: int = ..., distinct: Sequence[str] = ..., ) -> Awaitable[Sequence[_PromptRow]]: ... def create(self, *, data: Mapping[str, str | int | None]) -> Awaitable[_PromptRow]: ... def update(self, *, where: Mapping[str, str | int], data: Mapping[str, str]) -> Awaitable[_PromptRow | None]: ... def delete_many(self, *, where: Mapping[str, str]) -> Awaitable[int]: ... def _prompt_table(prisma_client: "PrismaClient") -> _PromptTableActions: return PromptRepository(prisma_client).table def get_latest_prompt_versions(prompts: list[PromptSpec]) -> list[PromptSpec]: """ Filter prompts down to the latest version per (base prompt id, environment). """ sorted_prompts: Final = sorted(prompts, key=lambda prompt: get_version_number(prompt_id=prompt.prompt_id)) latest_prompts: Final = { (get_base_prompt_id(prompt_id=prompt.prompt_id), prompt_environment_or_default(prompt.environment)): prompt for prompt in sorted_prompts } return list(latest_prompts.values()) async def get_next_version_for_prompt( prisma_client: "PrismaClient", prompt_id: str, environment: str = DEFAULT_PROMPT_ENVIRONMENT ) -> int: """ Get the next version number for a prompt in a specific environment. Args: prisma_client: Prisma database client prompt_id: Base prompt ID environment: The environment to check versions for Returns: Next version number (1 if no versions exist, max_version + 1 otherwise) """ existing_prompts: Final = await _prompt_table(prisma_client).find_many( where={"prompt_id": prompt_id, "environment": environment} ) if existing_prompts: max_version: Final = max(p.version for p in existing_prompts) return max_version + 1 else: return 1 def create_versioned_prompt_spec(db_prompt: _PromptRow) -> PromptSpec: """ Helper function to create a PromptSpec with versioned prompt_id from a DB prompt entry. Args: db_prompt: The DB prompt object (from prisma) Returns: PromptSpec with versioned prompt_id (e.g., "chat_prompt.v1") """ import json from litellm.types.prompts.init_prompts import PromptLiteLLMParams row: Final = _PromptRowData.model_validate(db_prompt.model_dump()) litellm_params_data: Final = row.litellm_params litellm_params_dict: Final[Mapping[str, object] | None] = ( json.loads(litellm_params_data) if isinstance(litellm_params_data, str) else litellm_params_data ) litellm_params: Final = PromptLiteLLMParams.model_validate(litellm_params_dict) prompt_info_data: Final = row.prompt_info if prompt_info_data: prompt_info_dict: Final[Mapping[str, object]] = ( json.loads(prompt_info_data) if isinstance(prompt_info_data, str) else prompt_info_data ) prompt_info = PromptInfo.model_validate(prompt_info_dict) else: prompt_info = PromptInfo(prompt_type="db") versioned_prompt_id: Final = f"{row.prompt_id}.v{row.version}" return PromptSpec( prompt_id=versioned_prompt_id, litellm_params=litellm_params, prompt_info=prompt_info, created_at=row.created_at, updated_at=row.updated_at, version=row.version, environment=row.environment, created_by=row.created_by, ) class Prompt(BaseModel): prompt_id: str litellm_params: PromptLiteLLMParams prompt_info: PromptInfo | None = None AMBIGUOUS_PROMPT_DATA_ERROR: Final = ( "litellm_params.prompt_id cannot be combined with prompt_data keyed by template name. " 'Send a flat template, prompt_data={"content": "...", "metadata": {...}}, together with litellm_params.prompt_id, ' 'or send prompt_data={"<template_id>": {"content": "...", "metadata": {...}}} without litellm_params.prompt_id.' ) def is_ambiguous_keyed_prompt_data(litellm_params: PromptLiteLLMParams) -> bool: extra_fields: Final = litellm_params.model_extra or {} prompt_data: Final = extra_fields.get("prompt_data") if not litellm_params.prompt_id or not isinstance(prompt_data, dict): return False return bool(prompt_data) and "content" not in prompt_data class PatchPromptRequest(BaseModel): litellm_params: PromptLiteLLMParams | None = None prompt_info: PromptInfo | None = None @router.get( "/prompts/list", tags=["Prompt Management"], dependencies=[Depends(user_api_key_auth)], response_model=ListPromptsResponse, ) async def list_prompts( environment: str | None = None, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ): """ List the prompts that are available on the proxy server 👉 [Prompt docs](https://docs.litellm.ai/docs/proxy/prompt_management) Example Request: ```bash curl -X GET "http://localhost:4000/prompts/list" -H "Authorization: Bearer <your_api_key>" ``` Example Response: ```json { "prompts": [ { "prompt_id": "my_prompt_id", "litellm_params": { "prompt_id": "my_prompt_id", "prompt_integration": "dotprompt", "prompt_directory": "/path/to/prompts" }, "prompt_info": { "prompt_type": "config" }, "created_at": "2023-11-09T12:34:56.789Z", "updated_at": "2023-11-09T12:34:56.789Z" } ] } ``` """ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY # check key metadata for prompts key_metadata: Final = user_api_key_dict.metadata if key_metadata is not None: prompts: Final = cast(list[str] | None, key_metadata.get("prompts", None)) if prompts is not None: allowed_prompt_ids: Final = frozenset(prompts) allowed_prompts: Final = [ spec for spec in IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS.values() if spec.prompt_id in allowed_prompt_ids or get_base_prompt_id(prompt_id=spec.prompt_id) in allowed_prompt_ids ] all_prompts = get_latest_prompt_versions(prompts=allowed_prompts) if environment: all_prompts = [p for p in all_prompts if p.environment == environment] prompt_list: Final = [] for original_prompt in all_prompts: # Create a copy with base prompt_id (without version suffix) prompt_copy = PromptSpec( prompt_id=get_base_prompt_id(prompt_id=original_prompt.prompt_id), litellm_params=original_prompt.litellm_params, prompt_info=original_prompt.prompt_info, created_at=original_prompt.created_at, updated_at=original_prompt.updated_at, environment=original_prompt.environment, created_by=original_prompt.created_by, ) prompt_list.append(prompt_copy) return ListPromptsResponse(prompts=prompt_list) # check if user is proxy admin - show all prompts if user_api_key_has_admin_view(user_api_key_dict): # Get all prompts and filter to show only the latest version of each all_prompts = list(IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS.values()) if environment: all_prompts = [p for p in all_prompts if p.environment == environment] latest_prompts: Final = get_latest_prompt_versions(prompts=all_prompts) # Create copies with base prompt_id (without version suffix) for display prompts_for_display: Final = [] for original_prompt in latest_prompts: prompt_copy = PromptSpec( prompt_id=get_base_prompt_id(prompt_id=original_prompt.prompt_id), litellm_params=original_prompt.litellm_params, prompt_info=original_prompt.prompt_info, created_at=original_prompt.created_at, updated_at=original_prompt.updated_at, environment=original_prompt.environment, created_by=original_prompt.created_by, ) prompts_for_display.append(prompt_copy) return ListPromptsResponse(prompts=prompts_for_display) else: return ListPromptsResponse(prompts=[]) @router.get( "/prompts/{prompt_id}/versions", tags=["Prompt Management"], dependencies=[Depends(user_api_key_auth)], response_model=ListPromptsResponse, ) async def get_prompt_versions( prompt_id: str, environment: str | None = None, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ): """ Get all versions of a specific prompt by base prompt ID 👉 [Prompt docs](https://docs.litellm.ai/docs/proxy/prompt_management) Example Request: ```bash curl -X GET "http://localhost:4000/prompts/jack_success/versions" \\ -H "Authorization: Bearer <your_api_key>" ``` Example Response: ```json { "prompts": [ { "prompt_id": "jack_success.v1", "litellm_params": {...}, "prompt_info": {"prompt_type": "db"}, "created_at": "2023-11-09T12:34:56.789Z", "updated_at": "2023-11-09T12:34:56.789Z" }, { "prompt_id": "jack_success.v2", "litellm_params": {...}, "prompt_info": {"prompt_type": "db"}, "created_at": "2023-11-09T13:45:12.345Z", "updated_at": "2023-11-09T13:45:12.345Z" } ] } ``` """ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY from litellm.proxy.proxy_server import prisma_client # Only allow proxy admins to view version history if not user_api_key_has_admin_view(user_api_key_dict): raise HTTPException(status_code=403, detail="Only proxy admins can view prompt versions") base_prompt_id: Final = get_base_prompt_id(prompt_id=prompt_id) # Query DB for versions versioned_prompts: Final = [] if prisma_client is not None: where_clause: Final[dict[str, str]] = {"prompt_id": base_prompt_id} if environment: where_clause["environment"] = environment db_prompts: Final = await _prompt_table(prisma_client).find_many( where=where_clause, order={"version": "desc"}, ) for db_prompt in db_prompts: spec = create_versioned_prompt_spec(db_prompt=db_prompt) versioned_prompts.append( PromptSpec( prompt_id=base_prompt_id, litellm_params=spec.litellm_params, prompt_info=spec.prompt_info, created_at=spec.created_at, updated_at=spec.updated_at, version=get_version_number(prompt_id=spec.prompt_id), environment=spec.environment, created_by=spec.created_by, ) ) else: # Fallback: in-memory registry (no DB) all_prompts: Final = list(IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS.values()) prompt_versions: Final = [ prompt for prompt in all_prompts if get_base_prompt_id(prompt_id=prompt.prompt_id) == base_prompt_id and (environment is None or prompt.environment == environment) ] for prompt in prompt_versions: version_number = get_version_number(prompt_id=prompt.prompt_id) versioned_prompts.append( PromptSpec( prompt_id=base_prompt_id, litellm_params=prompt.litellm_params, prompt_info=prompt.prompt_info, created_at=prompt.created_at, updated_at=prompt.updated_at, version=version_number, environment=prompt.environment, created_by=prompt.created_by, ) ) versioned_prompts.sort(key=lambda p: p.version or 1, reverse=True) if not versioned_prompts: raise HTTPException(status_code=404, detail=f"No versions found for prompt ID {base_prompt_id}") return ListPromptsResponse(prompts=versioned_prompts) def _get_prompt_template(prompt_spec: PromptSpec, base_prompt_id: str) -> PromptTemplateBase | None: """Resolve the raw prompt template from dotprompt content or the in-memory registry.""" from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY try: dotprompt_content: Final = prompt_spec.litellm_params.dotprompt_content if dotprompt_content: from litellm.integrations.dotprompt import ( _get_prompt_data_from_dotprompt_content, ) parsed: Final = _get_prompt_data_from_dotprompt_content(dotprompt_content) if parsed: return PromptTemplateBase( litellm_prompt_id=base_prompt_id, content=parsed.get("content", ""), metadata=parsed.get("metadata"), ) else: prompt_callback: Final = IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_for_prompt(prompt=prompt_spec) if prompt_callback is not None: integration_name: Final = prompt_callback.integration_name if integration_name == "dotprompt": from litellm.integrations.dotprompt.dotprompt_manager import ( DotpromptManager, ) if isinstance(prompt_callback, DotpromptManager): template: Final = prompt_callback.prompt_manager.get_all_prompts_as_json() if template is not None and len(template) == 1: template_id: Final = list(template.keys())[0] return PromptTemplateBase( litellm_prompt_id=template_id, content=template[template_id]["content"], metadata=template[template_id]["metadata"], ) except Exception: pass return None @router.get( "/prompts/{prompt_id}", tags=["Prompt Management"], dependencies=[Depends(user_api_key_auth)], response_model=PromptInfoResponse, ) @router.get( "/prompts/{prompt_id}/info", tags=["Prompt Management"], dependencies=[Depends(user_api_key_auth)], response_model=PromptInfoResponse, ) async def get_prompt_info( prompt_id: str, environment: str | None = None, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ): """ Get detailed information about a specific prompt by ID, including prompt content 👉 [Prompt docs](https://docs.litellm.ai/docs/proxy/prompt_management) Example Request: ```bash curl -X GET "http://localhost:4000/prompts/my_prompt_id/info" \\ -H "Authorization: Bearer <your_api_key>" ``` Example Response: ```json { "prompt_id": "my_prompt_id", "litellm_params": { "prompt_id": "my_prompt_id", "prompt_integration": "dotprompt", "prompt_directory": "/path/to/prompts" }, "prompt_info": { "prompt_type": "config" }, "created_at": "2023-11-09T12:34:56.789Z", "updated_at": "2023-11-09T12:34:56.789Z", "content": "System: You are a helpful assistant.\n\nUser: {{user_message}}" } ``` """ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY from litellm.proxy.proxy_server import prisma_client ## CHECK IF USER HAS ACCESS TO PROMPT prompts: list[str] | None = None if user_api_key_dict.metadata is not None: prompts = cast(list[str] | None, user_api_key_dict.metadata.get("prompts", None)) if prompts is not None and prompt_id not in prompts: raise HTTPException(status_code=400, detail=f"Prompt {prompt_id} not found") if not user_api_key_has_admin_view(user_api_key_dict): raise HTTPException( status_code=403, detail=f"You are not authorized to access this prompt. Your role - {user_api_key_dict.user_role}, Your key's prompts - {prompts}", ) base_prompt_id: Final = get_base_prompt_id(prompt_id=prompt_id) # Query all environments this prompt exists in (lightweight: distinct on environment) all_environments: list[str] = [] if prisma_client is not None: all_prompt_rows: Final = await _prompt_table(prisma_client).find_many( where={"prompt_id": base_prompt_id}, distinct=["environment"], ) all_environments = sorted(set(row.environment for row in all_prompt_rows if row.environment)) # If environment is specified, find the version in that environment from DB # If prompt_id has a version suffix (e.g., "testprompt.v2"), fetch that specific version # Otherwise fetch the latest version in that environment prompt_spec = None requested_version: Final = get_version_number(prompt_id=prompt_id) if prompt_id != base_prompt_id else None if environment and prisma_client is not None: where_clause: Final[dict[str, str | int]] = { "prompt_id": base_prompt_id, "environment": environment, } if requested_version is not None: where_clause["version"] = requested_version env_prompts: Final = await _prompt_table(prisma_client).find_many( where=where_clause, order={"version": "desc"}, take=1, ) if env_prompts: prompt_spec = create_versioned_prompt_spec(db_prompt=env_prompts[0]) if prompt_spec is None: prompt_spec = IN_MEMORY_PROMPT_REGISTRY.resolve_prompt_spec( prompt_id, version=requested_version, environment=environment ) if prompt_spec is None: raise HTTPException( status_code=400, detail=f"Prompt {prompt_id} not found" + (f" in environment {environment}" if environment else ""), ) # Extract version number from the prompt_id version_number: Final = get_version_number(prompt_id=prompt_spec.prompt_id) # Create a copy of the prompt spec with the base prompt ID (stripped of version) prompt_spec_response: Final = PromptSpec( prompt_id=get_base_prompt_id(prompt_id=prompt_spec.prompt_id), litellm_params=prompt_spec.litellm_params, prompt_info=prompt_spec.prompt_info, created_at=prompt_spec.created_at, updated_at=prompt_spec.updated_at, version=version_number, environment=prompt_spec.environment, created_by=prompt_spec.created_by, ) # Get prompt content prompt_template: Final = _get_prompt_template(prompt_spec, base_prompt_id) return PromptInfoResponse( prompt_spec=prompt_spec_response, raw_prompt_template=prompt_template, environments=all_environments, ) @router.post( "/prompts", tags=["Prompt Management"], dependencies=[Depends(user_api_key_auth)], ) async def create_prompt( request: Prompt, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ): """ Create a new prompt 👉 [Prompt docs](https://docs.litellm.ai/docs/proxy/prompt_management) Example Request: ```bash curl -X POST "http://localhost:4000/prompts" \\ -H "Authorization: Bearer <your_api_key>" \\ -H "Content-Type: application/json" \\ -d '{ "prompt_id": "my_prompt", "litellm_params": { "prompt_id": "my_prompt", "prompt_integration": "dotprompt", "prompt_data": {"content": "This is a prompt", "metadata": {"model": "gpt-4"}} }, "prompt_info": { "prompt_type": "config" } }' ``` """ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY from litellm.proxy.proxy_server import prisma_client # Only allow proxy admins to create prompts if user_api_key_dict.user_role is None or ( user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN and user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN.value ): raise HTTPException(status_code=403, detail="Only proxy admins can create prompts") if prisma_client is None: raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value) if is_ambiguous_keyed_prompt_data(request.litellm_params): raise HTTPException(status_code=400, detail=AMBIGUOUS_PROMPT_DATA_ERROR) try: # Extract environment from request environment: Final = ( request.prompt_info.environment if request.prompt_info and request.prompt_info.environment else DEFAULT_PROMPT_ENVIRONMENT ) # Get next version number new_version: Final = await get_next_version_for_prompt( prisma_client=prisma_client, prompt_id=request.prompt_id, environment=environment, ) # Store prompt in db with version prompt_db_entry: Final = await _prompt_table(prisma_client).create( data={ "prompt_id": request.prompt_id, "version": new_version, "environment": environment, "created_by": user_api_key_dict.user_id, "litellm_params": request.litellm_params.model_dump_json(), "prompt_info": ( request.prompt_info.model_dump_json() if request.prompt_info else PromptInfo(prompt_type="db").model_dump_json() ), } ) # Create versioned prompt spec prompt_spec: Final = create_versioned_prompt_spec(db_prompt=prompt_db_entry) # Initialize the prompt initialized_prompt = IN_MEMORY_PROMPT_REGISTRY.initialize_prompt(prompt=prompt_spec, config_file_path=None) if initialized_prompt is None: raise HTTPException(status_code=500, detail="Failed to initialize prompt") return initialized_prompt except Exception as e: verbose_proxy_logger.exception("Error creating prompt: %s", e) raise HTTPException(status_code=500, detail=str(e)) @router.put( "/prompts/{prompt_id}", tags=["Prompt Management"], dependencies=[Depends(user_api_key_auth)], ) async def update_prompt( prompt_id: str, request: Prompt, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ): """ Update an existing prompt 👉 [Prompt docs](https://docs.litellm.ai/docs/proxy/prompt_management) Example Request: ```bash curl -X PUT "http://localhost:4000/prompts/my_prompt_id" \\ -H "Authorization: Bearer <your_api_key>" \\ -H "Content-Type: application/json" \\ -d '{ "prompt_id": "my_prompt", "litellm_params": { "prompt_id": "my_prompt", "prompt_integration": "dotprompt", "prompt_directory": "/path/to/prompts" }, "prompt_info": { "prompt_type": "config" } } }' ``` """ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY from litellm.proxy.proxy_server import prisma_client # Only allow proxy admins to update prompts if user_api_key_dict.user_role is None or ( user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN and user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN.value ): raise HTTPException(status_code=403, detail="Only proxy admins can update prompts") if prisma_client is None: raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value) if is_ambiguous_keyed_prompt_data(request.litellm_params): raise HTTPException(status_code=400, detail=AMBIGUOUS_PROMPT_DATA_ERROR) try: # Strip version suffix from prompt_id if present (e.g., "jack_success.v1" -> "jack_success") base_prompt_id: Final = get_base_prompt_id(prompt_id=prompt_id) # Extract environment from request environment: Final = ( request.prompt_info.environment if request.prompt_info and request.prompt_info.environment else DEFAULT_PROMPT_ENVIRONMENT ) # Check if any version of this prompt exists (in any environment) existing_prompts = await _prompt_table(prisma_client).find_many(where={"prompt_id": base_prompt_id}) if not existing_prompts: raise HTTPException( status_code=404, detail=f"Prompt with ID {base_prompt_id} not found", ) if IN_MEMORY_PROMPT_REGISTRY.has_config_prompt(base_prompt_id=base_prompt_id): raise HTTPException( status_code=400, detail="Cannot update config prompts.", ) # Get next version number (UPDATE creates a new version) new_version: Final = await get_next_version_for_prompt( prisma_client=prisma_client, prompt_id=base_prompt_id, environment=environment, ) # Store new version in db prompt_db_entry: Final = await _prompt_table(prisma_client).create( data={ "prompt_id": base_prompt_id, "version": new_version, "environment": environment, "created_by": user_api_key_dict.user_id, "litellm_params": request.litellm_params.model_dump_json(), "prompt_info": ( request.prompt_info.model_dump_json() if request.prompt_info else PromptInfo(prompt_type="db").model_dump_json() ), } ) # Create versioned prompt spec prompt_spec: Final = create_versioned_prompt_spec(db_prompt=prompt_db_entry) # Initialize the new version initialized_prompt = IN_MEMORY_PROMPT_REGISTRY.initialize_prompt(prompt=prompt_spec, config_file_path=None) if initialized_prompt is None: raise HTTPException(status_code=500, detail="Failed to update prompt") return initialized_prompt except HTTPException as e: raise e except Exception as e: verbose_proxy_logger.exception("Error updating prompt: %s", e) raise HTTPException(status_code=500, detail=str(e)) @router.delete( "/prompts/{prompt_id}", tags=["Prompt Management"], dependencies=[Depends(user_api_key_auth)], ) async def delete_prompt( prompt_id: str, environment: str | None = None, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ): """ Delete a prompt 👉 [Prompt docs](https://docs.litellm.ai/docs/proxy/prompt_management) Example Request: ```bash curl -X DELETE "http://localhost:4000/prompts/my_prompt_id" \\ -H "Authorization: Bearer <your_api_key>" ``` Example Response: ```json { "message": "Prompt my_prompt_id deleted successfully" } ``` """ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY from litellm.proxy.proxy_server import prisma_client # Only allow proxy admins to delete prompts if user_api_key_dict.user_role is None or ( user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN and user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN.value ): raise HTTPException(status_code=403, detail="Only proxy admins can delete prompts") if prisma_client is None: raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value) try: base_prompt_id: Final = get_base_prompt_id(prompt_id=prompt_id) existing_prompt: Final = IN_MEMORY_PROMPT_REGISTRY.resolve_prompt_spec(prompt_id, environment=environment) if existing_prompt is None: raise HTTPException(status_code=404, detail=f"Prompt with ID {prompt_id} not found") if IN_MEMORY_PROMPT_REGISTRY.has_config_prompt(base_prompt_id=base_prompt_id): raise HTTPException( status_code=400, detail="Cannot delete config prompts.", ) delete_where: Final[dict[str, str]] = { "prompt_id": base_prompt_id, **({"environment": environment} if environment else {}), } await _prompt_table(prisma_client).delete_many(where=delete_where) IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id( base_prompt_id=base_prompt_id, environment=environment or None ) env_msg: Final = f" from {environment}" if environment else "" return {"message": f"Prompt {base_prompt_id} deleted successfully{env_msg}"} except HTTPException as e: raise e except Exception as e: verbose_proxy_logger.exception("Error deleting prompt: %s", e) raise HTTPException(status_code=500, detail=str(e)) def _reload_prompt_in_registry(registry: "InMemoryPromptRegistry", updated_prompt_spec: PromptSpec) -> PromptSpec: initialized: Final = registry.reload_prompt(prompt=updated_prompt_spec) if initialized is None: raise HTTPException(status_code=500, detail="Failed to patch prompt") return initialized @router.patch( "/prompts/{prompt_id}", tags=["Prompt Management"], dependencies=[Depends(user_api_key_auth)], ) async def patch_prompt( prompt_id: str, request: PatchPromptRequest, environment: str | None = None, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ): """ Partially update an existing prompt 👉 [Prompt docs](https://docs.litellm.ai/docs/proxy/prompt_management) This endpoint allows updating specific fields of a prompt without sending the entire object. Only the following fields can be updated: - litellm_params: LiteLLM parameters for the prompt - prompt_info: Additional information about the prompt Example Request: ```bash curl -X PATCH "http://localhost:4000/prompts/my_prompt_id" \\ -H "Authorization: Bearer <your_api_key>" \\ -H "Content-Type: application/json" \\ -d '{ "prompt_info": { "prompt_type": "db" } }' ``` """ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY from litellm.proxy.proxy_server import prisma_client # Only allow proxy admins to patch prompts if user_api_key_dict.user_role is None or ( user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN and user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN.value ): raise HTTPException(status_code=403, detail="Only proxy admins can patch prompts") if prisma_client is None: raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value) if request.litellm_params is not None and is_ambiguous_keyed_prompt_data(request.litellm_params): raise HTTPException(status_code=400, detail=AMBIGUOUS_PROMPT_DATA_ERROR) try: # Resolve the target row: find the latest version in the given environment base_prompt_id: Final = get_base_prompt_id(prompt_id=prompt_id) env: Final = prompt_environment_or_default(environment) requested_version: Final = get_version_number(prompt_id=prompt_id) if prompt_id != base_prompt_id else None # Build query to find the exact row by composite unique key find_where: Final[dict[str, str | int]] = { "prompt_id": base_prompt_id, "environment": env, } if requested_version is not None: find_where["version"] = requested_version db_rows: Final = await _prompt_table(prisma_client).find_many( where=find_where, order={"version": "desc"}, take=1, ) if not db_rows: raise HTTPException( status_code=404, detail=f"Prompt with ID {base_prompt_id} not found in environment {env}", ) target_row: Final = db_rows[0] if IN_MEMORY_PROMPT_REGISTRY.has_config_prompt(base_prompt_id=base_prompt_id): raise HTTPException( status_code=400, detail="Cannot update config prompts.", ) current_spec: Final = create_versioned_prompt_spec(db_prompt=target_row) updated_litellm_params: Final = ( request.litellm_params if request.litellm_params is not None else current_spec.litellm_params ) updated_prompt_info: Final = ( request.prompt_info if request.prompt_info is not None else current_spec.prompt_info ) # Build update data dict update_data: Final[dict[str, str]] = { "litellm_params": updated_litellm_params.model_dump_json(), "prompt_info": updated_prompt_info.model_dump_json(), } if user_api_key_dict.user_id: update_data["created_by"] = user_api_key_dict.user_id # Update by primary key (id) to target exactly one row updated_prompt_db_entry: Final = await _prompt_table(prisma_client).update( where={"id": target_row.id}, data=update_data, ) if updated_prompt_db_entry is None: raise HTTPException( status_code=404, detail=f"Prompt with ID {base_prompt_id} not found in environment {env}", ) updated_prompt_spec: Final = create_versioned_prompt_spec(db_prompt=updated_prompt_db_entry) return _reload_prompt_in_registry(IN_MEMORY_PROMPT_REGISTRY, updated_prompt_spec) except HTTPException as e: raise e except Exception as e: verbose_proxy_logger.exception("Error patching prompt: %s", e) raise HTTPException(status_code=500, detail=str(e)) @router.post( "/prompts/test", tags=["Prompt Management"], dependencies=[Depends(user_api_key_auth)], ) async def test_prompt( request: TestPromptRequest, fastapi_request: Request, fastapi_response: Response, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ): """ Test a prompt by rendering it with variables and executing an LLM call. This endpoint allows testing prompts before saving them to the database. The response is always streamed. 👉 [Prompt docs](https://docs.litellm.ai/docs/proxy/prompt_management) Example Request: ```bash curl -X POST "http://localhost:4000/prompts/test" \\ -H "Authorization: Bearer <your_api_key>" \\ -H "Content-Type: application/json" \\ -d '{ "dotprompt_content": "---\\nmodel: gpt-4o\\ntemperature: 0.7\\n---\\n\\nUser: Hello {{name}}", "prompt_variables": { "name": "World" } }' ``` """ from pydantic import BaseModel from litellm.integrations.dotprompt.dotprompt_manager import DotpromptManager from litellm.integrations.dotprompt.prompt_manager import ( PromptManager, PromptTemplate, ) from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing from litellm.proxy.proxy_server import ( general_settings, llm_router, proxy_config, proxy_logging_obj, select_data_generator, user_api_base, user_max_tokens, user_model, user_request_timeout, user_temperature, version, ) try: # Parse the dotprompt content and create PromptTemplate prompt_manager: Final = PromptManager() frontmatter, template_content = prompt_manager._parse_frontmatter(content=request.dotprompt_content) # Create PromptTemplate to leverage existing parameter extraction logic template: Final = PromptTemplate(content=template_content, metadata=frontmatter, template_id="test_prompt") # Extract model from template if not template.model: raise HTTPException(status_code=400, detail="Model is required in dotprompt metadata") # Always render the template to extract system messages and other metadata variables: Final = request.prompt_variables or {} rendered_content: Final = prompt_manager.jinja_env.from_string(template_content).render(**variables) # Convert rendered content to messages using DotpromptManager's method dotprompt_manager: Final = DotpromptManager() rendered_messages: Final = dotprompt_manager._convert_to_messages(rendered_content=rendered_content) if not rendered_messages: raise HTTPException(status_code=400, detail="No messages found in rendered prompt") # If conversation history is provided, use it but preserve system messages if request.conversation_history: # Extract system messages from rendered prompt system_messages: Final = [msg for msg in rendered_messages if msg.get("role") == "system"] # Use conversation history for user/assistant messages messages = system_messages + request.conversation_history else: messages = rendered_messages # Use PromptTemplate's optional_params which already extracts all parameters optional_params: Final = template.optional_params.copy() # Always stream the response optional_params["stream"] = True # Build request data for chat completion data: Final = { "model": template.model, "messages": messages, } data.update(optional_params) is_request_body_safe( request_body=data, general_settings=general_settings, llm_router=llm_router, model=data.get("model", ""), ) # Use ProxyBaseLLMRequestProcessing to go through all proxy logic base_llm_response_processor: Final = ProxyBaseLLMRequestProcessing(data=data) result: Final[object] = await base_llm_response_processor.base_process_llm_request( request=fastapi_request, fastapi_response=fastapi_response, user_api_key_dict=user_api_key_dict, route_type="acompletion", proxy_logging_obj=proxy_logging_obj, llm_router=llm_router, general_settings=general_settings, proxy_config=proxy_config, select_data_generator=select_data_generator, model=None, user_model=user_model, user_temperature=user_temperature, user_request_timeout=user_request_timeout, user_max_tokens=user_max_tokens, user_api_base=user_api_base, version=version, ) if isinstance(result, BaseModel): return result.model_dump(exclude_none=True, exclude_unset=True) else: return result except HTTPException as e: raise e except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) except Exception as e: verbose_proxy_logger.exception("Error testing prompt: %s", e) raise HTTPException(status_code=500, detail=str(e)) @router.post( "/utils/dotprompt_json_converter", tags=["prompts", "utils"], dependencies=[Depends(user_api_key_auth)], ) async def convert_prompt_file_to_json( file: UploadFile = File(...), user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), ) -> Mapping[str, object]: """ Convert a .prompt file to JSON format. This endpoint accepts a .prompt file upload and returns the equivalent JSON representation that can be stored in a database or used programmatically. Returns the JSON structure with 'content' and 'metadata' fields. """ global general_settings from litellm.integrations.dotprompt.prompt_manager import PromptManager # Validate file extension if not file.filename or not file.filename.endswith(".prompt"): raise HTTPException(status_code=400, detail="File must have .prompt extension") temp_file_path = None try: # Read file content file_content: Final = await file.read() # Create temporary file — use safe_filename to prevent path traversal temp_file_path = Path(tempfile.mkdtemp()) / safe_filename(file.filename) temp_file_path.write_bytes(file_content) # Create a PromptManager instance just for conversion prompt_manager: Final = PromptManager() # Convert to JSON json_data: Final = prompt_manager.prompt_file_to_json(temp_file_path) # Extract prompt ID from filename prompt_id: Final = temp_file_path.stem return { "prompt_id": prompt_id, "json_data": json_data, } except Exception as e: raise HTTPException(status_code=500, detail=f"Error converting prompt file: {e}") finally: # Clean up temp file if temp_file_path and temp_file_path.exists(): temp_file_path.unlink() # Also try to remove the temp directory if it's empty try: temp_file_path.parent.rmdir() except OSError: pass # Directory not empty or other error
"""
CRUD ENDPOINTS FOR PROMPTS
"""
import tempfile
from collections.abc import Awaitable, Mapping, Sequence
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Final, Protocol, cast
from fastapi import (
APIRouter,
Depends,
File,
HTTPException,
Request,
Response,
UploadFile,
)
from pydantic import BaseModel
from litellm._logging import verbose_proxy_logger
from litellm.proxy._types import (
CommonProxyErrors,
LitellmUserRoles,
UserAPIKeyAuth,
user_api_key_has_admin_view,
)
from litellm.proxy.auth.auth_utils import is_request_body_safe
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_utils.path_utils import safe_filename
from litellm.proxy.prompts.prompt_registry import (
DEFAULT_PROMPT_ENVIRONMENT,
get_base_prompt_id,
get_version_number,
prompt_environment_or_default,
)
from litellm.repositories.table_repositories import PromptRepository
from litellm.types.prompts.init_prompts import (
ListPromptsResponse,
PromptInfo,
PromptInfoResponse,
PromptLiteLLMParams,
PromptSpec,
PromptTemplateBase,
)
from litellm.types.proxy.prompt_endpoints import TestPromptRequest
if TYPE_CHECKING:
from litellm.proxy.prompts.prompt_registry import InMemoryPromptRegistry
from litellm.proxy.utils import PrismaClient
router: Final = APIRouter()
class _PromptRow(Protocol):
@property
def id(self) -> str: ...
@property
def prompt_id(self) -> str: ...
@property
def version(self) -> int: ...
@property
def environment(self) -> str: ...
@property
def created_by(self) -> str | None: ...
@property
def created_at(self) -> "datetime": ...
@property
def updated_at(self) -> "datetime": ...
@property
def litellm_params(self) -> str | Mapping[str, object]: ...
@property
def prompt_info(self) -> str | Mapping[str, object] | None: ...
def model_dump(self) -> Mapping[str, object]: ...
class _PromptRowData(BaseModel):
prompt_id: str
version: int = 1
environment: str = "development"
created_by: str | None = None
litellm_params: str | Mapping[str, object] | None = None
prompt_info: str | Mapping[str, object] | None = None
created_at: datetime | None = None
updated_at: datetime | None = None
class _PromptTableActions(Protocol):
def find_many(
self,
*,
where: Mapping[str, str | int],
order: Mapping[str, str] = ...,
take: int = ...,
distinct: Sequence[str] = ...,
) -> Awaitable[Sequence[_PromptRow]]: ...
def create(self, *, data: Mapping[str, str | int | None]) -> Awaitable[_PromptRow]: ...

Xet Storage Details

Size:
44.6 kB
·
Xet hash:
62f5a573975ec982ced822d36f9fd62575a719a295bc980488f9b9a873d13884

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.