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]

Litellm ishaan april1 try2 (#25110)

ishaan-berric6aa3ea45226
diff --git a/docs/my-website/docs/providers/bedrock_image_gen.md b/docs/my-website/docs/providers/bedrock_image_gen.md
index 799c6d46437..e6e8429817d 100644
--- a/docs/my-website/docs/providers/bedrock_image_gen.md
+++ b/docs/my-website/docs/providers/bedrock_image_gen.md
@@ -111,6 +111,29 @@ curl -L -X POST 'http://0.0.0.0:4000/v1/images/generations' \
</TabItem>
</Tabs>
+## Amazon Nova Canvas - Image Edit
+
+Use OpenAI-compatible `image_edit()` with Bedrock Nova Canvas (`amazon.nova-canvas-v1:0`). Requests use the same `InvokeModel` API as generation; LiteLLM maps inputs to [Nova Canvas task types](https://docs.aws.amazon.com/nova/latest/userguide/image-gen-access.html):
+
+| Scenario | `taskType` sent to Bedrock |
+|----------|----------------------------|
+| Image + prompt (no mask) | `IMAGE_VARIATION` |
+| Image + prompt + mask | `INPAINTING` (`inPaintingParams.image`, `maskImage` or `maskPrompt`) |
+| `taskType: OUTPAINTING` + `mask` or `maskPrompt` | `OUTPAINTING` (Bedrock requires one; LiteLLM raises a clear error if both are missing) |
+| `taskType: BACKGROUND_REMOVAL` | `BACKGROUND_REMOVAL` |
+
+```python
+from litellm import image_edit
+
+response = image_edit(
+ image=open("photo.png", "rb"),
+ prompt="Add soft sunset lighting",
+ model="bedrock/amazon.nova-canvas-v1:0",
+)
+```
+
+For **`BACKGROUND_REMOVAL`**, the AWS request must not include `imageGenerationConfig`; LiteLLM omits it for that task even if you pass `size`, `n`, `seed`, etc. Additional Nova Canvas inference IDs for image edit should set **`supports_nova_canvas_image_edit`: true** in `model_prices_and_context_window.json` (see `amazon.nova-canvas-v1:0`).
+
## Using Inference Profiles with Image Generation
For AWS Bedrock Application Inference Profiles with image generation, use the `model_id` parameter to specify the inference profile ARN:
@@ -147,4 +170,3 @@ model_list:
## Authentication
All standard Bedrock authentication methods are supported for image generation. See [Bedrock Authentication](./bedrock#boto3---authentication) for details.
-
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260331000000_add_prompt_environment_and_created_by/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260331000000_add_prompt_environment_and_created_by/migration.sql
new file mode 100644
index 00000000000..74357814d8d
--- /dev/null
+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260331000000_add_prompt_environment_and_created_by/migration.sql
@@ -0,0 +1,12 @@
+-- AlterTable
+ALTER TABLE "LiteLLM_PromptTable" ADD COLUMN "environment" TEXT NOT NULL DEFAULT 'development';
+ALTER TABLE "LiteLLM_PromptTable" ADD COLUMN "created_by" TEXT;
+
+-- DropIndex (old unique constraint)
+DROP INDEX IF EXISTS "LiteLLM_PromptTable_prompt_id_version_key";
+
+-- CreateIndex (new unique constraint)
+CREATE UNIQUE INDEX "LiteLLM_PromptTable_prompt_id_version_environment_key" ON "LiteLLM_PromptTable"("prompt_id", "version", "environment");
+
+-- CreateIndex (new composite index)
+CREATE INDEX "LiteLLM_PromptTable_prompt_id_environment_idx" ON "LiteLLM_PromptTable"("prompt_id", "environment");
diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
index d8d6015ce87..5d804d75b6a 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
@@ -321,11 +321,12 @@ model LiteLLM_MCPServerTable {
byok_description String[] @default([])
byok_api_key_help_url String?
source_url String?
- approval_status String? @default("active")
- submitted_by String?
- submitted_at DateTime?
- reviewed_at DateTime?
- review_notes String?
+ // BYOM submission lifecycle
+ approval_status String? @default("active")
+ submitted_by String?
+ submitted_at DateTime?
+ reviewed_at DateTime?
+ review_notes String?
@@index([approval_status])
}
@@ -1001,12 +1002,15 @@ model LiteLLM_PromptTable {
id String @id @default(uuid())
prompt_id String
version Int @default(1)
+ environment String @default("development")
+ created_by String?
litellm_params Json
prompt_info Json?
created_at DateTime @default(now())
updated_at DateTime @updatedAt
- @@unique([prompt_id, version])
+ @@unique([prompt_id, version, environment])
+ @@index([prompt_id, environment])
@@index([prompt_id])
}
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py
index 80afea78504..7fc9b00f2c7 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py
@@ -38,6 +38,102 @@ class FakeAnthropicMessagesStreamIterator:
self.chunks = self._create_streaming_chunks()
self.current_index = 0
+ def _create_content_block_chunks(
+ self, block_dict: Dict[str, Any], index: int
+ ) -> List[bytes]:
+ """Build SSE chunks for a single content block."""
+ chunks = []
+ block_type = block_dict.get("type")
+
+ if block_type == "text":
+ content_block_start = {
+ "type": "content_block_start",
+ "index": index,
+ "content_block": {"type": "text", "text": ""},
+ }
+ chunks.append(
+ f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()
+ )
+ text = block_dict.get("text", "")
+ content_block_delta = {
+ "type": "content_block_delta",
+ "index": index,
+ "delta": {"type": "text_delta", "text": text},
+ }
+ chunks.append(
+ f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()
+ )
+
+ elif block_type == "thinking":
+ content_block_start = {
+ "type": "content_block_start",
+ "index": index,
+ "content_block": {"type": "thinking", "thinking": "", "signature": ""},
+ }
+ chunks.append(
+ f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()
+ )
+ thinking_text = block_dict.get("thinking", "")
+ if thinking_text:
+ content_block_delta = {
+ "type": "content_block_delta",
+ "index": index,
+ "delta": {"type": "thinking_delta", "thinking": thinking_text},
+ }
+ chunks.append(
+ f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()
+ )
+ signature = block_dict.get("signature", "")
+ if signature:
+ signature_delta = {
+ "type": "content_block_delta",
+ "index": index,
+ "delta": {"type": "signature_delta", "signature": signature},
+ }
+ chunks.append(
+ f"event: content_block_delta\ndata: {json.dumps(signature_delta)}\n\n".encode()
+ )
+
+ elif block_type == "redacted_thinking":
+ content_block_start = {
+ "type": "content_block_start",
+ "index": index,
+ "content_block": {"type": "redacted_thinking"},
+ }
+ chunks.append(
+ f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()
+ )
+
+ elif block_type == "tool_use":
+ content_block_start = {
+ "type": "content_block_start",
+ "index": index,
+ "content_block": {
+ "type": "tool_use",
+ "id": block_dict.get("id"),
+ "name": block_dict.get("name"),
+ "input": {},
+ },
+ }
+ chunks.append(
+ f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()
+ )
+ input_data = block_dict.get("input", {})
+ content_block_delta = {
+ "type": "content_block_delta",
+ "index": index,
+ "delta": {"type": "input_json_delta", "partial_json": json.dumps(input_data)},
+ }
+ chunks.append(
+ f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()
+ )
+
+ content_block_stop = {"type": "content_block_stop", "index": index}
+ chunks.append(
+ f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()
+ )
+ return chunks
+
def _create_streaming_chunks(self) -> List[bytes]:
"""Convert the non-streaming response to streaming chunks"""
chunks = []
@@ -69,152 +165,34 @@ class FakeAnthropicMessagesStreamIterator:
# 2-4. For each content block, send start/delta/stop events
content_blocks = response_dict.get("content", [])
- if content_blocks:
- for index, block in enumerate(content_blocks):
- # Cast block to dict for easier access
- block_dict = cast(Dict[str, Any], block)
- block_type = block_dict.get("type")
-
- if block_type == "text":
- # content_block_start
- content_block_start = {
- "type": "content_block_start",
- "index": index,
- "content_block": {"type": "text", "text": ""},
- }
- chunks.append(
- f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()
- )
-
- # content_block_delta (send full text as one delta for simplicity)
- text = block_dict.get("text", "")
- content_block_delta = {
- "type": "content_block_delta",
- "index": index,
- "delta": {"type": "text_delta", "text": text},
- }
- chunks.append(
- f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()
- )
-
- # content_block_stop
- content_block_stop = {"type": "content_block_stop", "index": index}
- chunks.append(
- f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()
- )
-
- elif block_type == "thinking":
- # content_block_start for thinking
- content_block_start = {
- "type": "content_block_start",
- "index": index,
- "content_block": {
- "type": "thinking",
- "thinking": "",
- "signature": "",
- },
- }
- chunks.append(
- f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()
- )
-
- # content_block_delta for thinking text
- thinking_text = block_dict.get("thinking", "")
- if thinking_text:
- content_block_delta = {
- "type": "content_block_delta",
- "index": index,
- "delta": {
- "type": "thinking_delta",
- "thinking": thinking_text,
- },
- }
- chunks.append(
- f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()
- )
-
- # content_block_delta for signature (if present)
- signature = block_dict.get("signature", "")
- if signature:
- signature_delta = {
- "type": "content_block_delta",
- "index": index,
- "delta": {
- "type": "signature_delta",
- "signature": signature,
- },
- }
- chunks.append(
- f"event: content_block_delta\ndata: {json.dumps(signature_delta)}\n\n".encode()
- )
-
- # content_block_stop
- content_block_stop = {"type": "content_block_stop", "index": index}
- chunks.append(
- f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()
- )
-
- elif block_type == "redacted_thinking":
- # content_block_start for redacted_thinking
- content_block_start = {
- "type": "content_block_start",
- "index": index,
- "content_block": {"type": "redacted_thinking"},
- }
- chunks.append(
- f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()
- )
-
- # content_block_stop (no delta for redacted thinking)
- content_block_stop = {"type": "content_block_stop", "index": index}
- chunks.append(
- f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()
- )
-
- elif block_type == "tool_use":
- # content_block_start
- content_block_start = {
- "type": "content_block_start",
- "index": index,
- "content_block": {
- "type": "tool_use",
- "id": block_dict.get("id"),
- "name": block_dict.get("name"),
- "input": {},
- },
- }
- chunks.append(
- f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()
- )
-
- # content_block_delta (send input as JSON delta)
- input_data = block_dict.get("input", {})
- content_block_delta = {
- "type": "content_block_delta",
- "index": index,
- "delta": {
- "type": "input_json_delta",
- "partial_json": json.dumps(input_data),
- },
- }
- chunks.append(
- f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()
- )
-
- # content_block_stop
- content_block_stop = {"type": "content_block_stop", "index": index}
- chunks.append(
- f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()
- )
+ for index, block in enumerate(content_blocks):
+ block_dict = cast(Dict[str, Any], block)
+ chunks.extend(self._create_content_block_chunks(block_dict, index))
# 5. message_delta event (with final usage and stop_reason)
+ # Include cache usage fields so clients that only read message_delta
+ # (like Claude Code's SDK) see the full input token breakdown.
+ delta_usage: Dict[str, Any] = {
+ "output_tokens": usage.get("output_tokens", 0) if usage else 0,
+ }
+ if usage:
+ if usage.get("input_tokens") is not None:
+ delta_usage["input_tokens"] = usage["input_tokens"]
+ if usage.get("cache_creation_input_tokens") is not None:
+ delta_usage["cache_creation_input_tokens"] = usage[
+ "cache_creation_input_tokens"
+ ]
+ if usage.get("cache_read_input_tokens") is not None:
+ delta_usage["cache_read_input_tokens"] = usage[
+ "cache_read_input_tokens"
+ ]
message_delta = {
"type": "message_delta",
"delta": {
"stop_reason": response_dict.get("stop_reason"),
"stop_sequence": response_dict.get("stop_sequence"),
},
- "usage": {"output_tokens": usage.get("output_tokens", 0) if usage else 0},
+ "usage": delta_usage,
}
chunks.append(
f"event: message_delta\ndata: {json.dumps(message_delta)}\n\n".encode()
diff --git a/litellm/llms/bedrock/image_edit/amazon_nova_canvas_image_edit_transformation.py b/litellm/llms/bedrock/image_edit/amazon_nova_canvas_image_edit_transformation.py
new file mode 100644
index 00000000000..f806cd2a81a
--- /dev/null
+++ b/litellm/llms/bedrock/image_edit/amazon_nova_canvas_image_edit_transformation.py
@@ -0,0 +1,515 @@
+"""
+Amazon Nova Canvas image edit on Bedrock (InvokeModel).
+
+Maps OpenAI-style image edit (image + prompt, optional mask) to Nova Canvas task types:
+- With mask: INPAINTING (inPaintingParams per AWS docs)
+- Without mask: IMAGE_VARIATION (imageVariationParams)
+
+Refs:
+- https://docs.aws.amazon.com/nova/latest/userguide/image-gen-access.html
+- https://docs.aws.amazon.com/nova/latest/userguide/image-gen-req-resp-structure.html
+"""
+
+from __future__ import annotations
+
+import base64
+import os
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
+
+import httpx
+
+from litellm._logging import verbose_logger
+from litellm.llms.base_llm.image_edit.transformation import BaseImageEditConfig
+from litellm.types.images.main import ImageEditOptionalRequestParams
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import FileTypes, ImageObject, ImageResponse
+from litellm.utils import (
+ _get_model_cost_key,
+ _get_potential_model_names,
+ get_model_info,
+)
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
+
+ LiteLLMLoggingObj = _LiteLLMLoggingObj
+else:
+ LiteLLMLoggingObj = Any
+
+
+def _nova_canvas_task_body(
+ *,
+ image_b64: str,
+ mask_b64: Optional[str],
+ text: str,
+ negative_text: Optional[str],
+ similarity_strength: Optional[float],
+ task_type: Optional[str],
+ mask_prompt: Optional[str],
+ out_painting_mode: Optional[str],
+) -> Dict[str, Any]:
+ """Build InvokeModel body task section (without imageGenerationConfig)."""
+ if task_type == "BACKGROUND_REMOVAL":
+ return {
+ "taskType": "BACKGROUND_REMOVAL",
+ "backgroundRemovalParams": {"image": image_b64},
+ }
+ if task_type == "OUTPAINTING":
+ if mask_prompt is None and mask_b64 is None:
+ raise ValueError(
+ "OUTPAINTING requires either a mask image or a mask prompt. "
+ "Pass mask=<file> or maskPrompt=<str> in the request."
+ )
+ out_params: Dict[str, Any] = {
+ "image": image_b64,
+ "text": text,
+ }
+ if mask_prompt is not None:
+ out_params["maskPrompt"] = mask_prompt
+ elif mask_b64 is not None:
+ out_params["maskImage"] = mask_b64
+ if negative_text is not None:
+ out_params["negativeText"] = negative_text
+ if out_painting_mode is not None:
+ out_params["outPaintingMode"] = out_painting_mode
+ return {
+ "taskType": "OUTPAINTING",
+ "outPaintingParams": out_params,
+ }
+ # Honour explicit IMAGE_VARIATION even when a mask is present (mask is ignored
+ # for this task type; callers use INPAINTING when they want mask semantics).
+ if task_type == "IMAGE_VARIATION":
+ var_params_explicit: Dict[str, Any] = {
+ "images": [image_b64],
+ "text": text,
+ }
+ if negative_text is not None:
+ var_params_explicit["negativeText"] = negative_text
+ if similarity_strength is not None:
+ var_params_explicit["similarityStrength"] = similarity_strength
+ return {
+ "taskType": "IMAGE_VARIATION",
+ "imageVariationParams": var_params_explicit,
+ }
+ # Explicit taskType must be INPAINTING or omitted from here on; anything else is invalid.
+ if task_type is not None and str(task_type).strip() != "":
+ if task_type != "INPAINTING":
+ raise ValueError(
+ f"Unsupported Amazon Nova Canvas taskType: {task_type!r}. "
+ "Use BACKGROUND_REMOVAL, OUTPAINTING, IMAGE_VARIATION, INPAINTING, "
+ "or omit taskType for automatic routing (mask → INPAINTING, else IMAGE_VARIATION)."
+ )
+ if mask_b64 is not None or mask_prompt is not None or task_type == "INPAINTING":
+ in_params: Dict[str, Any] = {"image": image_b64, "text": text}
+ if mask_prompt is not None:
+ in_params["maskPrompt"] = mask_prompt
+ elif mask_b64 is not None:
+ in_params["maskImage"] = mask_b64
+ if negative_text is not None:
+ in_params["negativeText"] = negative_text
+ if "maskPrompt" not in in_params and "maskImage" not in in_params:
+ raise ValueError(
+ "Amazon Nova Canvas INPAINTING requires either maskPrompt or maskImage "
+ "(use OpenAI mask= for maskImage, or pass maskPrompt in optional params). "
+ "See https://docs.aws.amazon.com/nova/latest/userguide/image-gen-req-resp-structure.html"
+ )
+ return {"taskType": "INPAINTING", "inPaintingParams": in_params}
+ var_params: Dict[str, Any] = {
+ "images": [image_b64],
+ "text": text,
+ }
+ if negative_text is not None:
+ var_params["negativeText"] = negative_text
+ if similarity_strength is not None:
+ var_params["similarityStrength"] = similarity_strength
+ return {
+ "taskType": "IMAGE_VARIATION",
+ "imageVariationParams": var_params,
+ }
+
+
+def _file_types_to_b64(image: Optional[FileTypes]) -> str:
+ """Encode OpenAI image input to base64 string for Nova Canvas."""
+ if image is None:
+ raise ValueError("Nova Canvas image edit requires an image input")
+ if hasattr(image, "read") and callable(getattr(image, "read", None)):
+ if hasattr(image, "seek"):
+ image.seek(0) # type: ignore[union-attr]
+ image_bytes = image.read() # type: ignore[union-attr]
+ return base64.b64encode(image_bytes).decode("utf-8")
+ if isinstance(image, bytes):
+ return base64.b64encode(image).decode("utf-8")
+ if isinstance(image, str):
+ return image
+ if isinstance(image, os.PathLike):
+ with open(image, "rb") as f:
+ return base64.b64encode(f.read()).decode("utf-8")
+ if isinstance(image, tuple):
+ raise ValueError(
+ "Nova Canvas image edit does not support tuple FileTypes. "
+ "Pass a file-like object, bytes, or a base64-encoded string."
+ )
+ return base64.b64encode(bytes(image)).decode("utf-8") # type: ignore[arg-type]
+
+
+def _supports_nova_canvas_image_edit_from_model_cost(model: str) -> bool:
+ """
+ True when model_cost has supports_nova_canvas_image_edit for a resolved catalog key.
+
+ get_model_info / ModelInfoBase omit arbitrary JSON keys, so we read model_cost
+ directly (same idea as supports_* bare_entry fallback).
+ """
+ import litellm as _litellm
+
+ if not model:
+ return False
+
+ seen: set[str] = set()
+ candidates: List[str] = []
+
+ def _add(name: Optional[str]) -> None:
+ if name and name not in seen:
+ seen.add(name)
+ candidates.append(name)
+
+ _add(model)
+ if "/" in model:
+ suffix = model.split("/")[-1]
+ _add(suffix)
+ _add(f"bedrock/{suffix}")
+
+ # Cross-region inference ids (e.g. us.amazon.nova-canvas-v1:0) share pricing with
+ # the base model id (amazon.nova-canvas-v1:0) in model_cost.
+ try:
+ from litellm.llms.bedrock.common_utils import BedrockModelInfo
+
+ base_model = BedrockModelInfo.get_base_model(model)
+ if base_model and base_model != model:
+ _add(base_model)
+ _add(f"bedrock/{base_model}")
+ except Exception:
+ pass
+
+ try:
+ potential = _get_potential_model_names(model=model, custom_llm_provider=None)
+ for field in (
+ "combined_model_name",
+ "combined_stripped_model_name",
+ "stripped_model_name",
+ "split_model",
+ ):
+ raw = potential.get(field)
+ if isinstance(raw, str):
+ _add(raw)
+ except Exception:
+ pass
+
+ for name in candidates:
+ key = _get_model_cost_key(name)
+ if key is None:
+ continue
+ entry = _litellm.model_cost.get(key) or {}
+ if entry.get("supports_nova_canvas_image_edit") is True:
+ return True
+ return False
+
+
+class BedrockAmazonNovaCanvasImageEditConfig(BaseImageEditConfig):
+ """
+ Bedrock InvokeModel image edit for amazon.nova-canvas-v1:0 and regional variants.
+ """
+
+ @classmethod
+ def _is_nova_canvas_image_edit_model(cls, model: Optional[str] = None) -> bool:
+ """
+ Use model_cost.supports_nova_canvas_image_edit so new Nova Canvas inference IDs
+ are added via model_prices_and_context_window.json only (not get_model_info, which
+ drops keys not on ModelInfoBase).
+ """
+ return _supports_nova_canvas_image_edit_from_model_cost(model or "")
+
+ def get_supported_openai_params(self, model: str) -> list:
+ return [
+ "n",
+ "size",
+ "response_format",
+ "mask",
+ "negativeText",
+ "similarityStrength",
+ "cfgScale",
+ "seed",
+ "quality",
+ "taskType",
+ "maskPrompt",
+ "outPaintingMode",
+ "imageGenerationConfig",
+ ]
+
+ def map_openai_params(
+ self,
+ image_edit_optional_params: ImageEditOptionalRequestParams,
+ model: str,
+ drop_params: bool,
+ ) -> Dict[str, Any]:
+ supported = set(self.get_supported_openai_params(model))
+ mapped: Dict[str, Any] = dict(image_edit_optional_params)
+ _size = mapped.pop("size", None)
+ if _size is not None and isinstance(_size, str) and "x" in _size:
+ w, h = _size.split("x", 1)
+ try:
+ mapped["width"], mapped["height"] = int(w), int(h)
+ except ValueError:
+ pass
+ _n = mapped.pop("n", None)
+ if _n is not None:
+ mapped["numberOfImages"] = _n
+ _quality = mapped.pop("quality", None)
+ if _quality is not None:
+ if _quality in ("hd", "premium"):
+ mapped["quality"] = "premium"
+ elif _quality == "standard":
+ mapped["quality"] = "standard"
+ else:
+ # Re-emit unknown values (e.g. OpenAI "auto") so transform_image_edit_request
+ # forwards them and the API can reject, or drop_params can still apply upstream.
+ mapped["quality"] = _quality
+ # Accepted for OpenAI compatibility but ignored for Nova Canvas image edit;
+ # Bedrock returns base64 images only (no URL mode).
+ response_format = mapped.pop("response_format", None)
+ if response_format not in (None, "b64_json"):
+ verbose_logger.debug(
+ "Nova Canvas image edit ignores response_format=%s and returns base64 images",
+ response_format,
+ )
+ # Drop unknown keys if drop_params
+ if drop_params:
+ for k in list(mapped.keys()):
+ if k.startswith("_"):
+ continue
+ if k not in supported and k not in (
+ "width",
+ "height",
+ "numberOfImages",
+ "mask",
+ ):
+ mapped.pop(k, None)
+ return mapped
+
+ def transform_image_edit_request(
+ self,
+ model: str,
+ prompt: Optional[str],
+ image: Optional[FileTypes],
+ image_edit_optional_request_params: Dict,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict,
+ ) -> Tuple[Dict, Any]:
+ op = dict(image_edit_optional_request_params)
+ image_b64 = _file_types_to_b64(image)
+
+ mask_raw = op.pop("mask", None)
+ mask_b64: Optional[str] = None
+ if mask_raw is not None:
+ mask_b64 = _file_types_to_b64(mask_raw) # type: ignore[arg-type]
+
+ _size = op.pop("size", None)
+ width = op.pop("width", None)
+ height = op.pop("height", None)
+ if (
+ width is None
+ and height is None
+ and _size is not None
+ and isinstance(_size, str)
+ and "x" in _size
+ ):
+ w, h = _size.split("x", 1)
+ try:
+ width, height = int(w), int(h)
+ except ValueError:
+ pass
+
+ number_of_images = op.pop("numberOfImages", None)
+ quality = op.pop("quality", None)
+ cfg_scale = op.pop("cfgScale", None)
+ seed = op.pop("seed", None)
+
+ image_generation_config: Dict[str, Any] = {}
+ nested_igc = op.pop("imageGenerationConfig", None)
+ if isinstance(nested_igc, dict):
+ image_generation_config.update(nested_igc)
+ if width is not None:
+ image_generation_config["width"] = width
+ if height is not None:
+ image_generation_config["height"] = height
+ if number_of_images is not None:
+ image_generation_config["numberOfImages"] = number_of_images
+ if quality is not None:
+ image_generation_config["quality"] = quality
+ if cfg_scale is not None:
+ image_generation_config["cfgScale"] = cfg_scale
+ if seed is not None:
+ image_generation_config["seed"] = seed
+
+ task_type = op.pop("taskType", None)
+ if (prompt is None or prompt == "") and task_type in (
+ "INPAINTING",
+ "OUTPAINTING",
+ ):
+ raise ValueError(
+ f"Amazon Nova Canvas {task_type} requires a text prompt. "
+ "Pass a non-empty `prompt` in your request."
+ )
+ text = prompt if prompt is not None and prompt != "" else " "
+ negative_text = op.pop("negativeText", None)
+ similarity_strength = op.pop("similarityStrength", None)
+ mask_prompt = op.pop("maskPrompt", None)
+ out_painting_mode = op.pop("outPaintingMode", None)
+
+ body = _nova_canvas_task_body(
+ image_b64=image_b64,
+ mask_b64=mask_b64,
+ text=text,
+ negative_text=negative_text,
+ similarity_strength=similarity_strength,
+ task_type=task_type,
+ mask_prompt=mask_prompt,
+ out_painting_mode=out_painting_mode,
+ )
+
+ # BACKGROUND_REMOVAL InvokeModel body must not include imageGenerationConfig (AWS rejects it).
+ if image_generation_config and body.get("taskType") != "BACKGROUND_REMOVAL":
+ body["imageGenerationConfig"] = image_generation_config
+
+ return body, {}
+
+ def transform_image_edit_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ logging_obj: LiteLLMLoggingObj,
+ api_key: Optional[str] = None,
+ json_mode: Optional[bool] = None,
+ ) -> ImageResponse:
+ try:
+ response_data = raw_response.json()
+ except Exception as e:
+ raise self.get_error_class(
+ error_message=f"Error parsing Nova Canvas image edit response: {e}",
+ status_code=raw_response.status_code,
+ headers=raw_response.headers,
+ )
+
+ if raw_response.status_code not in (200,):
+ raise self.get_error_class(
+ error_message=f"Nova Canvas image edit error: {response_data}",
+ status_code=raw_response.status_code,
+ headers=raw_response.headers,
+ )
+
+ images: List[str] = response_data.get("images") or []
+
+ if "errors" in response_data and not images:
+ raise self.get_error_class(
+ error_message=f"Nova Canvas image edit error: {response_data['errors']}",
+ status_code=raw_response.status_code,
+ headers=raw_response.headers,
+ )
+
+ # Nova Canvas InvokeModel success body uses "images" and optional "error" (AWS docs);
+ # it does not use Stability-style "finish_reasons".
+ error_msg = response_data.get("message") or response_data.get("error")
+ if error_msg and not images:
+ if not isinstance(error_msg, str):
+ error_msg = str(error_msg)
+ raise self.get_error_class(
+ error_message=f"Nova Canvas image edit error: {error_msg}",
+ status_code=raw_response.status_code,
+ headers=raw_response.headers,
+ )
+
+ model_response = ImageResponse()
+ model_response.data = []
+ for image_b64 in images:
+ if image_b64:
+ model_response.data.append(
+ ImageObject(
+ b64_json=image_b64,
+ url=None,
+ revised_prompt=None,
+ )
+ )
+
+ if not model_response.data:
+ raise self.get_error_class(
+ error_message="Nova Canvas image edit returned no images",
+ status_code=raw_response.status_code,
+ headers=raw_response.headers,
+ )
+
+ if not hasattr(model_response, "_hidden_params"):
+ model_response._hidden_params = {}
+ if "additional_headers" not in model_response._hidden_params:
+ model_response._hidden_params["additional_headers"] = {}
+
+ try:
+ model_info = get_model_info(model, custom_llm_provider="bedrock")
+ cost_per_image = model_info.get("output_cost_per_image", 0)
+ if cost_per_image is not None and model_response.data:
+ model_response._hidden_params["additional_headers"][
+ "llm_provider-x-litellm-response-cost"
+ ] = float(cost_per_image) * len(model_response.data)
+ except Exception:
+ pass
+
+ return model_response
+
+ def use_multipart_form_data(self) -> bool:
+ return False
+
+ def get_complete_url(
+ self,
+ model: str,
+ api_base: Optional[str],
+ litellm_params: dict,
+ ) -> str:
+ raise NotImplementedError(
+ "Nova Canvas image edit URLs are built in BedrockImageEdit._prepare_request "
+ "(AWS runtime endpoint + model invoke path). Do not use get_complete_url for "
+ "this config."
+ )
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ api_key: Optional[str] = None,
+ ) -> dict:
+ if headers is None:
+ headers = {}
+ if "Content-Type" not in headers:
+ headers["Content-Type"] = "application/json"
+ return headers
+
+
+def get_bedrock_image_edit_config_for_model(
+ model: str,
+) -> BaseImageEditConfig:
+ """
+ Return the correct Bedrock image-edit config for the model id.
+
+ Same routing as ``BedrockImageEdit.get_config_class``: Stability edit models,
+ Nova Canvas when marked in model_cost; otherwise raises ``ValueError``.
+ """
+ from litellm.llms.bedrock.image_edit.stability_transformation import (
+ BedrockStabilityImageEditConfig,
+ )
+
+ if BedrockStabilityImageEditConfig._is_stability_edit_model(model):
+ return BedrockStabilityImageEditConfig()
+ if BedrockAmazonNovaCanvasImageEditConfig._is_nova_canvas_image_edit_model(model):
+ return BedrockAmazonNovaCanvasImageEditConfig()
+ raise ValueError(
+ f"Unsupported Bedrock image-edit model: {model!r}. "
+ "Use a stability.* image-edit model id or add supports_nova_canvas_image_edit "
+ "in model_prices for this id."
+ )
diff --git a/litellm/llms/bedrock/image_edit/handler.py b/litellm/llms/bedrock/image_edit/handler.py
index 867944f8796..90344310746 100644
--- a/litellm/llms/bedrock/image_edit/handler.py
+++ b/litellm/llms/bedrock/image_edit/handler.py
@@ -15,6 +15,9 @@ from pydantic import BaseModel
import litellm
from litellm._logging import verbose_logger
from litellm.litellm_core_utils.litellm_logging import Logging as LitellmLogging
+from litellm.llms.bedrock.image_edit.amazon_nova_canvas_image_edit_transformation import (
+ BedrockAmazonNovaCanvasImageEditConfig,
+)
from litellm.llms.bedrock.image_edit.stability_transformation import (
BedrockStabilityImageEditConfig,
)
@@ -55,8 +58,15 @@ class BedrockImageEdit(BaseAWSLLM):
def get_config_class(cls, model: str | None):
if BedrockStabilityImageEditConfig._is_stability_edit_model(model):
return BedrockStabilityImageEditConfig
- else:
- raise ValueError(f"Unsupported model for bedrock image edit: {model}")
+ if BedrockAmazonNovaCanvasImageEditConfig._is_nova_canvas_image_edit_model(
+ model
+ ):
+ return BedrockAmazonNovaCanvasImageEditConfig
+ raise ValueError(
+ f"Unsupported Bedrock image-edit model: {model!r}. "
+ "Use a stability.* image-edit model id or add supports_nova_canvas_image_edit "
+ "in model_prices for this id."
+ )
def image_edit(
self,
diff --git a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
index 784c6a50cfd..c1eccaebd04 100644
--- a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
+++ b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
@@ -502,6 +502,12 @@ class AmazonAnthropicClaudeMessagesConfig(
):
"""
Bedrock invoke does not return SSE formatted data. This function is a wrapper to ensure litellm chunks are SSE formatted.
+
+ Bedrock's Anthropic-compatible streaming puts cache usage fields
+ (cache_creation_input_tokens, cache_read_input_tokens) only on
+ message_stop, not on message_start or message_delta. Claude Code's
+ SDK only merges usage from message_delta, so we promote those fields
+ from message_stop onto message_delta before yielding.
"""
from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (
BaseAnthropicMessagesStreamingIterator,
@@ -512,9 +518,81 @@ class AmazonAnthropicClaudeMessagesConfig(
request_body=request_body,
)
- async for chunk in handler.async_sse_wrapper(completion_stream):
+ patched_stream = self._promote_message_stop_usage(completion_stream)
+
+ async for chunk in handler.async_sse_wrapper(patched_stream):
yield chunk
+ @staticmethod
+ async def _promote_message_stop_usage(
+ completion_stream: AsyncIterator[
+ Union[bytes, GenericStreamingChunk, ModelResponseStream, dict]
+ ],
+ ) -> AsyncIterator[Union[bytes, GenericStreamingChunk, ModelResponseStream, dict]]:
+ """
+ Promote cache usage fields from message_stop onto message_delta.
+
+ Bedrock reports input_tokens (uncached only) on message_start, and
+ the full breakdown (input_tokens, cache_creation_input_tokens,
+ cache_read_input_tokens) only on message_stop. Claude Code's SDK
+ merges usage from message_start and message_delta but ignores
+ message_stop. This method buffers message_delta and, when
+ message_stop arrives with cache usage, merges those fields into the
+ message_delta usage and also updates the input_tokens on
+ message_delta to include the full count (uncached + cache_creation +
+ cache_read).
+ """
+ _CACHE_FIELDS = ("cache_creation_input_tokens", "cache_read_input_tokens")
+ pending_delta = None
+
+ async for chunk in completion_stream:
+ if not isinstance(chunk, dict):
+ if pending_delta is not None:
+ yield pending_delta
+ pending_delta = None
+ yield chunk
+ continue
+
+ chunk_type = chunk.get("type")
+
+ if chunk_type == "message_delta":
+ pending_delta = chunk
+ continue
+
+ if chunk_type == "message_stop" and pending_delta is not None:
+ stop_usage = dict(chunk.get("usage") or {})
+ delta_usage = dict(pending_delta.get("usage") or {})
+
+ for field in _CACHE_FIELDS:
+ if field in stop_usage:
+ delta_usage[field] = stop_usage[field]
+
+ raw_input = stop_usage.get("input_tokens")
+ if raw_input is not None:
+ uncached = raw_input if isinstance(raw_input, int) else 0
+ raw_cc = delta_usage.get("cache_creation_input_tokens", 0)
+ cache_creation = raw_cc if isinstance(raw_cc, int) else 0
+ raw_cr = delta_usage.get("cache_read_input_tokens", 0)
+ cache_read = raw_cr if isinstance(raw_cr, int) else 0
+ delta_usage["input_tokens"] = uncached + cache_creation + cache_read
+
+ if delta_usage:
+ pending_delta["usage"] = delta_usage # type: ignore[arg-type]
+
+ yield pending_delta
+ pending_delta = None
+ yield chunk
+ continue
+
+ if pending_delta is not None:
+ yield pending_delta
+ pending_delta = None
+
+ yield chunk
+
+ if pending_delta is not None:
+ yield pending_delta
+
class AmazonAnthropicClaudeMessagesStreamDecoder(AWSEventStreamDecoder):
def __init__(
diff --git a/litellm/llms/firecrawl/search/transformation.py b/litellm/llms/firecrawl/search/transformation.py
index 61b589218cc..71136e1d3b3 100644
--- a/litellm/llms/firecrawl/search/transformation.py
+++ b/litellm/llms/firecrawl/search/transformation.py
@@ -159,15 +159,13 @@ class FirecrawlSearchConfig(BaseSearchConfig):
"""
Transform Firecrawl API response to LiteLLM unified SearchResponse format.
- Firecrawl → LiteLLM mappings:
- - data.web[].title → SearchResult.title
- - data.web[].url → SearchResult.url
- - data.web[].description OR data.web[].markdown → SearchResult.snippet
- - No date field in web results (set to None)
- - No last_updated field in Firecrawl response (set to None)
+ Supports both response formats:
- Note: Firecrawl v2 returns results organized by source type (web, images, news).
- We primarily use web results for the unified format.
+ Firecrawl Cloud (v2):
+ {"data": {"web": [...], "news": [...]}}
+
+ Firecrawl Self-Hosted (v1):
+ {"success": true, "data": [{"url": "...", "title": "...", ...}, ...]}
Args:
raw_response: Raw httpx response from Firecrawl API
@@ -181,36 +179,52 @@ class FirecrawlSearchConfig(BaseSearchConfig):
# Transform results to SearchResult objects
results = []
- # Process web results (primary source)
data = response_json.get("data", {})
- web_results = data.get("web", [])
-
- for result in web_results:
- # Use markdown if available, otherwise fall back to description
- snippet = result.get("markdown") or result.get("description", "")
-
- search_result = SearchResult(
- title=result.get("title", ""),
- url=result.get("url", ""),
- snippet=snippet,
- date=None, # Web results don't include date
- last_updated=None, # Firecrawl doesn't provide last_updated in response
- )
- results.append(search_result)
-
- # Process news results if available (they have date field)
- news_results = data.get("news", [])
- for result in news_results:
- snippet = result.get("markdown") or result.get("snippet", "")
-
- search_result = SearchResult(
- title=result.get("title", ""),
- url=result.get("url", ""),
- snippet=snippet,
- date=result.get("date"), # News results include date
- last_updated=None,
- )
- results.append(search_result)
+
+ if isinstance(data, list):
+ # Self-hosted Firecrawl (v1) format: data is a flat list of results
+ for result in data:
+ snippet = (
+ result.get("markdown") or result.get("description", "")
+ )
+ search_result = SearchResult(
+ title=result.get("title", ""),
+ url=result.get("url", ""),
+ snippet=snippet,
+ date=None,
+ last_updated=None,
+ )
+ results.append(search_result)
+ elif isinstance(data, dict):
+ # Firecrawl Cloud (v2) format: data is a dict with web/news keys
+ web_results = data.get("web", [])
+
+ for result in web_results:
+ # Use markdown if available, otherwise fall back to description
+ snippet = result.get("markdown") or result.get("description", "")
+
+ search_result = SearchResult(
+ title=result.get("title", ""),
+ url=result.get("url", ""),
+ snippet=snippet,
+ date=None,
+ last_updated=None,
+ )
+ results.append(search_result)
+
+ # Process news results if available (they have date field)
+ news_results = data.get("news", [])
+ for result in news_results:
+ snippet = result.get("markdown") or result.get("snippet", "")
+
+ search_result = SearchResult(
+ title=result.get("title", ""),
+ url=result.get("url", ""),
+ snippet=snippet,
+ date=result.get("date"), # News results include date
+ last_updated=None,
+ )
+ results.append(search_result)
return SearchResponse(
results=results,
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index 4072aab6544..4e1c7f4ac80 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -277,7 +277,15 @@
"litellm_provider": "bedrock",
"max_input_tokens": 2600,
"mode": "image_generation",
- "output_cost_per_image": 0.06
+ "output_cost_per_image": 0.06,
+ "supports_nova_canvas_image_edit": true
+ },
+ "us.amazon.nova-canvas-v1:0": {
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 2600,
+ "mode": "image_generation",
+ "output_cost_per_image": 0.06,
+ "supports_nova_canvas_image_edit": true
},
"us.writer.palmyra-x4-v1:0": {
"input_cost_per_token": 2.5e-06,
diff --git a/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py b/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
index 3ee8e6a27bd..3250e0bb7cf 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
@@ -760,8 +760,8 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):
error_obj = dict(error_value)
else:
error_obj = {"message": str(error_value)}
- error_obj["code"] = e.status_code
- yield f"data: {json.dumps({'error': error_obj})}\n\n"
+ error_obj["code"] = str(e.status_code)
+ yield f"data: {json.dumps({'error': error_obj})}\n\n" # type: ignore[misc]
return
except Exception as e:
verbose_proxy_logger.error(
diff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.py
index 948d6dd33af..46000f4fe6e 100644
--- a/litellm/proxy/hooks/proxy_track_cost_callback.py
+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py
@@ -112,6 +112,14 @@ class _ProxyDBLogger(CustomLogger):
_litellm_logging_obj, "litellm_trace_id", None
)
+ # Use the actual request start time from the logging object so that
+ # failed requests record the real duration instead of 0.
+ actual_start_time = datetime.now()
+ if _litellm_logging_obj is not None:
+ obj_start = getattr(_litellm_logging_obj, "start_time", None)
+ if obj_start is not None:
+ actual_start_time = obj_start
+
await proxy_logging_obj.db_spend_update_writer.update_database(
token=user_api_key_dict.api_key,
response_cost=0.0,
@@ -120,7 +128,7 @@ class _ProxyDBLogger(CustomLogger):
team_id=user_api_key_dict.team_id,
kwargs=request_data,
completion_response=original_exception,
- start_time=datetime.now(),
+ start_time=actual_start_time,
end_time=datetime.now(),
org_id=user_api_key_dict.org_id,
)
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index e105d9b8586..6f9166909c0 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -18,7 +18,7 @@ import re
import secrets
import traceback
from datetime import datetime, timedelta, timezone
-from typing import Any, Dict, List, Literal, Optional, Tuple, cast
+from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, cast
import fastapi
import yaml
@@ -487,6 +487,59 @@ async def validate_team_id_used_in_service_account_request(
return True
+def _enforce_upperbound_key_params(
+ data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ fill_defaults: bool = True,
+) -> None:
+ """
+ Enforce upperbound limits on key parameters.
+
+ For key generation (fill_defaults=True): fills None values with upperbound defaults.
+ For key update (fill_defaults=False): only validates explicitly provided values.
+ """
+ if litellm.upperbound_key_generate_params is None:
+ return
+
+ for elem in data:
+ key, value = elem
+ upperbound_value = getattr(
+ litellm.upperbound_key_generate_params, key, None
+ )
+ if upperbound_value is not None:
+ if value is None:
+ if fill_defaults:
+ setattr(data, key, upperbound_value)
+ else:
+ if key in [
+ "max_budget",
+ "max_parallel_requests",
+ "tpm_limit",
+ "rpm_limit",
+ ]:
+ if value > upperbound_value:
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": f"{key} is over max limit set in config - user_value={value}; max_value={upperbound_value}"
+ },
+ )
+ elif key in ["budget_duration", "duration"]:
+ upperbound_duration = duration_in_seconds(
+ duration=upperbound_value
+ )
+ if value == "-1":
+ user_duration = float("inf")
+ else:
+ user_duration = duration_in_seconds(duration=value)
+ if user_duration > upperbound_duration:
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": f"{key} is over max limit set in config - user_value={value}; max_value={upperbound_value}"
+ },
+ )
+
+
async def _common_key_generation_helper( # noqa: PLR0915
data: GenerateKeyRequest,
user_api_key_dict: UserAPIKeyAuth,
@@ -537,49 +590,8 @@ async def _common_key_generation_helper( # noqa: PLR0915
elif key == "metadata" and value == {}:
setattr(data, key, litellm.default_key_generate_params.get(key, {}))
- # check if user set default key/generate params on config.yaml
- if litellm.upperbound_key_generate_params is not None:
- for elem in data:
- key, value = elem
- upperbound_value = getattr(
- litellm.upperbound_key_generate_params, key, None
- )
- if upperbound_value is not None:
- if value is None:
- # Use the upperbound value if user didn't provide a value
- setattr(data, key, upperbound_value)
- else:
- # Compare with upperbound for numeric fields
- if key in [
- "max_budget",
- "max_parallel_requests",
- "tpm_limit",
- "rpm_limit",
- ]:
- if value > upperbound_value:
- raise HTTPException(
- status_code=400,
- detail={
- "error": f"{key} is over max limit set in config - user_value={value}; max_value={upperbound_value}"
- },
- )
- # Compare durations
- elif key in ["budget_duration", "duration"]:
- upperbound_duration = duration_in_seconds(
- duration=upperbound_value
- )
- # Handle special case where duration is None or "-1" (never expires)
- if value is None or value == "-1":
- user_duration = float("inf") # Infinite duration
- else:
- user_duration = duration_in_seconds(duration=value)
- if user_duration > upperbound_duration:
- raise HTTPException(
- status_code=400,
- detail={
- "error": f"{key} is over max limit set in config - user_value={value}; max_value={upperbound_value}"
- },
- )
+ # check if user set upperbound key/generate params on config.yaml
+ _enforce_upperbound_key_params(data, fill_defaults=True)
# APPLY ENTERPRISE KEY MANAGEMENT PARAMS
try:
@@ -1687,6 +1699,7 @@ async def _process_single_key_update(
user_api_key_cache: DualCache,
proxy_logging_obj: Any,
llm_router: Optional[Router],
+ user_custom_key_update: Optional[Callable] = None,
) -> Dict[str, Any]:
"""
Process a single key update with all validations and checks.
@@ -1737,6 +1750,22 @@ async def _process_single_key_update(
tags=key_update_item.tags,
)
+ # Custom key update hook
+ if user_custom_key_update is not None:
+ if inspect.iscoroutinefunction(user_custom_key_update):
+ result = await user_custom_key_update(update_key_request)
+ else:
+ raise ValueError("user_custom_key_update must be a coroutine")
+ decision = result.get("decision", True)
+ message = result.get("message", "Authentication Failed - Custom Auth Rule")
+ if not decision:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN, detail=message
+ )
+
+ # Enforce upperbound key params on update (don't fill defaults)
+ _enforce_upperbound_key_params(update_key_request, fill_defaults=False)
+
# Get team object and check team limits if team_id is provided
team_obj: Optional[LiteLLM_TeamTableCachedObj] = None
if update_key_request.team_id is not None:
@@ -2014,7 +2043,7 @@ async def _validate_update_key_data(
"/key/update", tags=["key management"], dependencies=[Depends(user_api_key_auth)]
)
@management_endpoint_wrapper
-async def update_key_fn(
+async def update_key_fn( # noqa: PLR0915
request: Request,
data: UpdateKeyRequest,
user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
@@ -2095,6 +2124,7 @@ async def update_key_fn(
prisma_client,
proxy_logging_obj,
user_api_key_cache,
+ user_custom_key_update,
)
try:
@@ -2126,6 +2156,21 @@ async def update_key_fn(
user_api_key_cache=user_api_key_cache,
)
+ # Custom key update hook
+ if user_custom_key_update is not None:
+ if inspect.iscoroutinefunction(user_custom_key_update):
+ result = await user_custom_key_update(data)
+ else:
+ raise ValueError("user_custom_key_update must be a coroutine")
+ decision = result.get("decision", True)
+ message = result.get("message", "Authentication Failed - Custom Auth Rule")
+ if not decision:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN, detail=message
+ )
+
+ # Enforce upperbound key params on update (don't fill defaults)
+ _enforce_upperbound_key_params(data, fill_defaults=False)
non_default_values = await prepare_key_update_data(
data=data, existing_key_row=existing_key_row
)
@@ -2261,6 +2306,7 @@ async def bulk_update_keys(
prisma_client,
proxy_logging_obj,
user_api_key_cache,
+ user_custom_key_update,
)
if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN.value:
@@ -2304,6 +2350,7 @@ async def bulk_update_keys(
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
llm_router=llm_router,
+ user_custom_key_update=user_custom_key_update,
)
successful_updates.append(
diff --git a/litellm/proxy/prompts/prompt_endpoints.py b/litellm/proxy/prompts/prompt_endpoints.py
index 73e0ece3e2c..483107a3759 100644
--- a/litellm/proxy/prompts/prompt_endpoints.py
+++ b/litellm/proxy/prompts/prompt_endpoints.py
@@ -192,19 +192,22 @@ def get_latest_prompt_versions(prompts: List[PromptSpec]) -> List[PromptSpec]:
return list(latest_prompts.values())
-async def get_next_version_for_prompt(prisma_client, prompt_id: str) -> int:
+async def get_next_version_for_prompt(
+ prisma_client, prompt_id: str, environment: str = "development"
+) -> int:
"""
- Get the next version number for a prompt.
+ 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 = await prisma_client.db.litellm_prompttable.find_many(
- where={"prompt_id": prompt_id}
+ where={"prompt_id": prompt_id, "environment": environment}
)
if existing_prompts:
@@ -231,6 +234,8 @@ def create_versioned_prompt_spec(db_prompt) -> PromptSpec:
prompt_dict = db_prompt.model_dump()
base_prompt_id = prompt_dict["prompt_id"]
version = prompt_dict.get("version", 1)
+ environment = prompt_dict.get("environment", "development")
+ created_by = prompt_dict.get("created_by")
# Parse litellm_params
litellm_params_data = prompt_dict.get("litellm_params")
@@ -256,6 +261,8 @@ def create_versioned_prompt_spec(db_prompt) -> PromptSpec:
prompt_info=prompt_info,
created_at=prompt_dict.get("created_at"),
updated_at=prompt_dict.get("updated_at"),
+ environment=environment,
+ created_by=created_by,
)
@@ -277,6 +284,7 @@ class PatchPromptRequest(BaseModel):
response_model=ListPromptsResponse,
)
async def list_prompts(
+ environment: Optional[str] = None,
user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
):
"""
@@ -318,23 +326,26 @@ async def list_prompts(
if key_metadata is not None:
prompts = cast(Optional[List[str]], key_metadata.get("prompts", None))
if prompts is not None:
+ all_prompts = [
+ IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS[prompt_id]
+ for prompt_id in prompts
+ if prompt_id in IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS
+ ]
+ if environment:
+ all_prompts = [p for p in all_prompts if p.environment == environment]
prompt_list = []
- for prompt_id in prompts:
- if prompt_id in IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS:
- original_prompt = IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS[
- prompt_id
- ]
- # 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,
- )
- prompt_list.append(prompt_copy)
+ 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_dict.user_role is not None and (
@@ -343,6 +354,8 @@ async def list_prompts(
):
# 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 = get_latest_prompt_versions(prompts=all_prompts)
# Create copies with base prompt_id (without version suffix) for display
prompts_for_display = []
@@ -353,6 +366,8 @@ async def list_prompts(
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)
@@ -368,6 +383,7 @@ async def list_prompts(
)
async def get_prompt_versions(
prompt_id: str,
+ environment: Optional[str] = None,
user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
):
"""
@@ -404,6 +420,7 @@ async def get_prompt_versions(
```
"""
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 user_api_key_dict.user_role is None or (
@@ -414,47 +431,110 @@ async def get_prompt_versions(
status_code=403, detail="Only proxy admins can view prompt versions"
)
- # Strip version suffix if provided (e.g., "jack_success.v1" -> "jack_success")
base_prompt_id = get_base_prompt_id(prompt_id=prompt_id)
- # Get all prompts and filter by base_prompt_id
- all_prompts = list(IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS.values())
- prompt_versions = [
- prompt
- for prompt in all_prompts
- if get_base_prompt_id(prompt_id=prompt.prompt_id) == base_prompt_id
- ]
+ # Query DB for versions
+ versioned_prompts = []
+ if prisma_client is not None:
+ where_clause: Dict[str, Any] = {"prompt_id": base_prompt_id}
+ if environment:
+ where_clause["environment"] = environment
+ db_prompts = await prisma_client.db.litellm_prompttable.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 = list(IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS.values())
+ prompt_versions = [
+ 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 prompt_versions:
+ if not versioned_prompts:
raise HTTPException(
status_code=404, detail=f"No versions found for prompt ID {base_prompt_id}"
)
- # Create response with explicit version field for each prompt
- versioned_prompts = []
- for prompt in prompt_versions:
- # Extract version number from the root prompt_id which has version suffix
- # (e.g., "jack-sparrow.v3" -> 3)
- version_number = get_version_number(prompt_id=prompt.prompt_id)
-
- # Strip version from prompt_id for clean display
- base_prompt_id = get_base_prompt_id(prompt_id=prompt.prompt_id)
-
- # Create a copy with explicit version field and clean prompt_id
- versioned_prompt = PromptSpec(
- prompt_id=base_prompt_id, # Clean ID without version (e.g., "jack-sparrow")
- litellm_params=prompt.litellm_params,
- prompt_info=prompt.prompt_info,
- created_at=prompt.created_at,
- updated_at=prompt.updated_at,
- version=version_number, # Explicit version field (e.g., 3)
- )
- versioned_prompts.append(versioned_prompt)
+ return ListPromptsResponse(prompts=versioned_prompts)
- # Sort by version number (descending - newest first)
- versioned_prompts.sort(key=lambda p: p.version or 1, reverse=True)
- return ListPromptsResponse(prompts=versioned_prompts)
+def _get_prompt_template(
+ prompt_spec: PromptSpec, base_prompt_id: str
+) -> Optional[PromptTemplateBase]:
+ """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 = prompt_spec.litellm_params.dotprompt_content
+ if dotprompt_content:
+ from litellm.integrations.dotprompt import (
+ _get_prompt_data_from_dotprompt_content,
+ )
+
+ parsed = _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 = IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id(
+ prompt_spec.prompt_id
+ )
+ if prompt_callback is not None:
+ integration_name = prompt_callback.integration_name
+ if integration_name == "dotprompt":
+ from litellm.integrations.dotprompt.dotprompt_manager import (
+ DotpromptManager,
+ )
+
+ if isinstance(prompt_callback, DotpromptManager):
+ template = (
+ prompt_callback.prompt_manager.get_all_prompts_as_json()
+ )
+ if template is not None and len(template) == 1:
+ template_id = 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(
@@ -471,6 +551,7 @@ async def get_prompt_versions(
)
async def get_prompt_info(
prompt_id: str,
+ environment: Optional[str] = None,
user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
):
"""
@@ -503,6 +584,7 @@ async def get_prompt_info(
```
"""
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: Optional[List[str]] = None
@@ -523,68 +605,80 @@ async def get_prompt_info(
detail=f"You are not authorized to access this prompt. Your role - {user_api_key_dict.user_role}, Your key's prompts - {prompts}",
)
- # Try to get prompt directly first
- prompt_spec = IN_MEMORY_PROMPT_REGISTRY.get_prompt_by_id(prompt_id)
+ base_prompt_id = get_base_prompt_id(prompt_id=prompt_id)
- # If not found, try to find the latest version
- if prompt_spec is None:
- latest_prompt_id = get_latest_version_prompt_id(
- prompt_id=prompt_id,
- all_prompt_ids=IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS,
+ # Query all environments this prompt exists in (lightweight: distinct on environment)
+ all_environments: List[str] = []
+ if prisma_client is not None:
+ all_prompt_rows = await prisma_client.db.litellm_prompttable.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)
)
- prompt_spec = IN_MEMORY_PROMPT_REGISTRY.get_prompt_by_id(latest_prompt_id)
+
+ # 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 = (
+ 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: Dict[str, Any] = {
+ "prompt_id": base_prompt_id,
+ "environment": environment,
+ }
+ if requested_version is not None:
+ where_clause["version"] = requested_version
+ env_prompts = await prisma_client.db.litellm_prompttable.find_many(
+ where=where_clause,
+ order={"version": "desc"},
+ take=1,
+ )
+ if env_prompts:
+ prompt_spec = create_versioned_prompt_spec(db_prompt=env_prompts[0])
+
+ # Fallback: use in-memory registry (no environment filter)
+ if prompt_spec is None and environment is None:
+ prompt_spec = IN_MEMORY_PROMPT_REGISTRY.get_prompt_by_id(prompt_id)
+ if prompt_spec is None:
+ latest_prompt_id = get_latest_version_prompt_id(
+ prompt_id=prompt_id,
+ all_prompt_ids=IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS,
+ )
+ prompt_spec = IN_MEMORY_PROMPT_REGISTRY.get_prompt_by_id(latest_prompt_id)
if prompt_spec is None:
- raise HTTPException(status_code=400, detail=f"Prompt {prompt_id} not found")
+ 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 = get_version_number(prompt_id=prompt_spec.prompt_id)
# Create a copy of the prompt spec with the base prompt ID (stripped of version)
- # and explicit version field for consistency with list_prompts and versions endpoints
prompt_spec_response = PromptSpec(
prompt_id=get_base_prompt_id(prompt_id=prompt_spec.prompt_id),
- litellm_params=prompt_spec.litellm_params, # This preserves the versioned 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, # Explicit version field
+ version=version_number,
+ environment=prompt_spec.environment,
+ created_by=prompt_spec.created_by,
)
- # Get prompt content from the callback
- prompt_template: Optional[PromptTemplateBase] = None
- try:
- prompt_callback = IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id(
- prompt_spec.prompt_id
- )
- if prompt_callback is not None:
- # Extract content based on integration type
- integration_name = prompt_callback.integration_name
-
- if integration_name == "dotprompt":
- # For dotprompt integration, get content from the prompt manager
- from litellm.integrations.dotprompt.dotprompt_manager import (
- DotpromptManager,
- )
-
- if isinstance(prompt_callback, DotpromptManager):
- template = prompt_callback.prompt_manager.get_all_prompts_as_json()
- if template is not None and len(template) == 1:
- template_id = list(template.keys())[0]
- prompt_template = PromptTemplateBase(
- litellm_prompt_id=template_id, # id sent to prompt management tool
- content=template[template_id]["content"],
- metadata=template[template_id]["metadata"],
- )
-
- except Exception:
- # If content extraction fails, continue without content
- pass
+ # Get prompt content
+ prompt_template = _get_prompt_template(prompt_spec, base_prompt_id)
- # Create response with content
return PromptInfoResponse(
prompt_spec=prompt_spec_response,
raw_prompt_template=prompt_template,
+ environments=all_environments,
)
@@ -641,9 +735,18 @@ async def create_prompt(
)
try:
+ # Extract environment from request
+ environment = (
+ request.prompt_info.environment
+ if request.prompt_info and request.prompt_info.environment
+ else "development"
+ )
+
# Get next version number
new_version = await get_next_version_for_prompt(
- prisma_client=prisma_client, prompt_id=request.prompt_id
+ prisma_client=prisma_client,
+ prompt_id=request.prompt_id,
+ environment=environment,
)
# Store prompt in db with version
@@ -651,6 +754,8 @@ async def create_prompt(
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()
@@ -733,14 +838,22 @@ async def update_prompt(
# Strip version suffix from prompt_id if present (e.g., "jack_success.v1" -> "jack_success")
base_prompt_id = get_base_prompt_id(prompt_id=prompt_id)
- # Check if any version exists
+ # Extract environment from request
+ environment = (
+ request.prompt_info.environment
+ if request.prompt_info and request.prompt_info.environment
+ else "development"
+ )
+
+ # Check if any version of this prompt exists (in any environment)
existing_prompts = await prisma_client.db.litellm_prompttable.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"
+ status_code=404,
+ detail=f"Prompt with ID {base_prompt_id} not found",
)
# Check if it's a config prompt
@@ -756,7 +869,9 @@ async def update_prompt(
# Get next version number (UPDATE creates a new version)
new_version = await get_next_version_for_prompt(
- prisma_client=prisma_client, prompt_id=base_prompt_id
+ prisma_client=prisma_client,
+ prompt_id=base_prompt_id,
+ environment=environment,
)
# Store new version in db
@@ -764,6 +879,8 @@ async def update_prompt(
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()
@@ -800,6 +917,7 @@ async def update_prompt(
)
async def delete_prompt(
prompt_id: str,
+ environment: Optional[str] = None,
user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
):
"""
@@ -867,15 +985,31 @@ async def delete_prompt(
# Get the base prompt ID (without version suffix) for database deletion
base_prompt_id = get_base_prompt_id(prompt_id=prompt_id)
- # Delete all versions of the prompt from the database
- await prisma_client.db.litellm_prompttable.delete_many(
- where={"prompt_id": base_prompt_id}
- )
-
- # Remove all versions of the prompt from memory
- IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id(base_prompt_id)
+ # Build delete filter; scope to environment if provided
+ delete_where: Dict[str, Any] = {"prompt_id": base_prompt_id}
+ if environment:
+ delete_where["environment"] = environment
+
+ # Delete versions from the database (scoped to environment if provided)
+ await prisma_client.db.litellm_prompttable.delete_many(where=delete_where)
+
+ # Remove matching prompts from memory — scope to environment if provided
+ if environment:
+ prompts_to_delete = [
+ pid
+ for pid, prompt in IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS.items()
+ if get_base_prompt_id(prompt_id=pid) == base_prompt_id
+ and prompt.environment == environment
+ ]
+ for pid in prompts_to_delete:
+ del IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS[pid]
+ if pid in IN_MEMORY_PROMPT_REGISTRY.prompt_id_to_custom_prompt:
+ del IN_MEMORY_PROMPT_REGISTRY.prompt_id_to_custom_prompt[pid]
+ else:
+ IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id(base_prompt_id)
- return {"message": f"Prompt {base_prompt_id} deleted successfully"}
+ env_msg = f" from {environment}" if environment else ""
+ return {"message": f"Prompt {base_prompt_id} deleted successfully{env_msg}"}
except HTTPException as e:
raise e
@@ -884,6 +1018,22 @@ async def delete_prompt(
raise HTTPException(status_code=500, detail=str(e))
+def _reload_prompt_in_registry(
+ registry: Any, versioned_id: str, updated_prompt_spec: PromptSpec
+) -> PromptSpec:
+ """Remove stale entry and re-initialize the prompt in the in-memory registry."""
+ if versioned_id in registry.IN_MEMORY_PROMPTS:
+ del registry.IN_MEMORY_PROMPTS[versioned_id]
+ if versioned_id in registry.prompt_id_to_custom_prompt:
+ del registry.prompt_id_to_custom_prompt[versioned_id]
+ initialized = registry.initialize_prompt(
+ prompt=updated_prompt_spec, config_file_path=None
+ )
+ if initialized is None:
+ raise HTTPException(status_code=500, detail="Failed to patch prompt")
+ return initialized
+
+
@router.patch(
"/prompts/{prompt_id}",
tags=["Prompt Management"],
@@ -892,6 +1042,7 @@ async def delete_prompt(
async def patch_prompt(
prompt_id: str,
request: PatchPromptRequest,
+ environment: Optional[str] = None,
user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
):
"""
@@ -935,61 +1086,93 @@ async def patch_prompt(
)
try:
- # Check if prompt exists and get current data
- existing_prompt = IN_MEMORY_PROMPT_REGISTRY.get_prompt_by_id(prompt_id)
- if existing_prompt is None:
+ # Resolve the target row: find the latest version in the given environment
+ base_prompt_id = get_base_prompt_id(prompt_id=prompt_id)
+ env = environment or "development"
+ requested_version = (
+ 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: Dict[str, Any] = {
+ "prompt_id": base_prompt_id,
+ "environment": env,
+ }
+ if requested_version is not None:
+ find_where["version"] = requested_version
+
+ db_rows = await prisma_client.db.litellm_prompttable.find_many(
+ where=find_where,
+ order={"version": "desc"},
+ take=1,
+ )
+ if not db_rows:
raise HTTPException(
- status_code=404, detail=f"Prompt with ID {prompt_id} not found"
+ status_code=404,
+ detail=f"Prompt with ID {base_prompt_id} not found in environment {env}",
)
- if existing_prompt.prompt_info.prompt_type == "config":
+ target_row = db_rows[0]
+
+ # Check if prompt exists in memory
+ versioned_id = f"{base_prompt_id}.v{target_row.version}"
+ existing_prompt = IN_MEMORY_PROMPT_REGISTRY.get_prompt_by_id(versioned_id)
+
+ if existing_prompt and existing_prompt.prompt_info.prompt_type == "config":
raise HTTPException(
status_code=400,
detail="Cannot update config prompts.",
)
+ # Use existing prompt from memory or build from DB row for field merging
+ if existing_prompt:
+ current_litellm_params = existing_prompt.litellm_params
+ current_prompt_info = existing_prompt.prompt_info
+ else:
+ current_spec = create_versioned_prompt_spec(db_prompt=target_row)
+ current_litellm_params = current_spec.litellm_params
+ current_prompt_info = current_spec.prompt_info
+
# Update fields if provided
updated_litellm_params = (
request.litellm_params
if request.litellm_params is not None
- else existing_prompt.litellm_params
+ else current_litellm_params
)
updated_prompt_info = (
request.prompt_info
if request.prompt_info is not None
- else existing_prompt.prompt_info
+ else current_prompt_info
)
# Ensure we have valid litellm_params
if updated_litellm_params is None:
raise HTTPException(status_code=400, detail="litellm_params cannot be None")
- # Create updated prompt spec - cast to satisfy typing
+ # Build update data dict
+ update_data: Dict[str, Any] = {
+ "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 = await prisma_client.db.litellm_prompttable.update(
- where={"prompt_id": prompt_id},
- data={
- "litellm_params": updated_litellm_params.model_dump_json(),
- "prompt_info": updated_prompt_info.model_dump_json(),
- },
+ where={"id": target_row.id},
+ data=update_data,
)
- updated_prompt_spec = PromptSpec(**updated_prompt_db_entry.model_dump())
-
- # Remove the old prompt from memory
- del IN_MEMORY_PROMPT_REGISTRY.IN_MEMORY_PROMPTS[prompt_id]
- if prompt_id in IN_MEMORY_PROMPT_REGISTRY.prompt_id_to_custom_prompt:
- del IN_MEMORY_PROMPT_REGISTRY.prompt_id_to_custom_prompt[prompt_id]
-
- # Initialize the updated prompt
- initialized_prompt = IN_MEMORY_PROMPT_REGISTRY.initialize_prompt(
- prompt=updated_prompt_spec, config_file_path=None
+ updated_prompt_spec = create_versioned_prompt_spec(
+ db_prompt=updated_prompt_db_entry
)
- if initialized_prompt is None:
- raise HTTPException(status_code=500, detail="Failed to patch prompt")
-
- return initialized_prompt
+ return _reload_prompt_in_registry(
+ IN_MEMORY_PROMPT_REGISTRY, versioned_id, updated_prompt_spec
+ )
except HTTPException as e:
raise e
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index d83e3500ebe..8a122a13506 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -690,7 +690,7 @@ _description = (
def cleanup_router_config_variables():
- global master_key, user_config_file_path, otel_logging, user_custom_auth, user_custom_auth_path, user_custom_key_generate, user_custom_sso, user_custom_ui_sso_sign_in_handler, use_background_health_checks, use_shared_health_check, health_check_interval, health_check_concurrency, prisma_client
+ global master_key, user_config_file_path, otel_logging, user_custom_auth, user_custom_auth_path, user_custom_key_generate, user_custom_key_update, user_custom_sso, user_custom_ui_sso_sign_in_handler, use_background_health_checks, use_shared_health_check, health_check_interval, health_check_concurrency, prisma_client
# Set all variables to None
master_key = None
@@ -699,6 +699,7 @@ def cleanup_router_config_variables():
user_custom_auth = None
user_custom_auth_path = None
user_custom_key_generate = None
+ user_custom_key_update = None
user_custom_sso = None
user_custom_ui_sso_sign_in_handler = None
use_background_health_checks = None
@@ -709,7 +710,7 @@ def cleanup_router_config_variables():
async def proxy_shutdown_event():
- global prisma_client, master_key, user_custom_auth, user_custom_key_generate
+ global prisma_client, master_key, user_custom_auth, user_custom_key_generate, user_custom_key_update
verbose_proxy_logger.info("Shutting down LiteLLM Proxy Server")
if prisma_client:
verbose_proxy_logger.debug("Disconnecting from Prisma")
@@ -1564,6 +1565,7 @@ user_custom_key_generate = None
# Tests that need to reset it can patch 'litellm.proxy.proxy_server._pkce_no_redis_warning_emitted'.
_pkce_no_redis_warning_emitted: bool = False
_cp_no_redis_warning_emitted: bool = False
+user_custom_key_update = None
user_custom_sso = None
user_custom_ui_sso_sign_in_handler = None
use_background_health_checks = None
@@ -2935,7 +2937,7 @@ class ProxyConfig:
"""
Load config values into proxy global state
"""
- global master_key, user_config_file_path, otel_logging, user_custom_auth, user_custom_auth_path, user_custom_key_generate, user_custom_sso, user_custom_ui_sso_sign_in_handler, use_background_health_checks, use_shared_health_check, health_check_interval, health_check_concurrency, use_queue, proxy_budget_rescheduler_max_time, proxy_budget_rescheduler_min_time, ui_access_mode, litellm_master_key_hash, proxy_batch_write_at, disable_spend_logs, prompt_injection_detection_obj, redis_usage_cache, store_model_in_db, premium_user, open_telemetry_logger, health_check_details, proxy_batch_polling_interval, config_passthrough_endpoints
+ global master_key, user_config_file_path, otel_logging, user_custom_auth, user_custom_auth_path, user_custom_key_generate, user_custom_key_update, user_custom_sso, user_custom_ui_sso_sign_in_handler, use_background_health_checks, use_shared_health_check, health_check_interval, health_check_concurrency, use_queue, proxy_budget_rescheduler_max_time, proxy_budget_rescheduler_min_time, ui_access_mode, litellm_master_key_hash, proxy_batch_write_at, disable_spend_logs, prompt_injection_detection_obj, redis_usage_cache, store_model_in_db, premium_user, open_telemetry_logger, health_check_details, proxy_batch_polling_interval, config_passthrough_endpoints
config: dict = await self.get_config(config_file_path=config_file_path)
@@ -3356,6 +3358,12 @@ class ProxyConfig:
value=custom_key_generate, config_file_path=config_file_path
)
+ custom_key_update = general_settings.get("custom_key_update", None)
+ if custom_key_update is not None:
+ user_custom_key_update = get_instance_fn(
+ value=custom_key_update, config_file_path=config_file_path
+ )
+
custom_sso = general_settings.get("custom_sso", None)
if custom_sso is not None:
user_custom_sso = get_instance_fn(
diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prisma
index 46be6b31e1f..5d804d75b6a 100644
--- a/litellm/proxy/schema.prisma
+++ b/litellm/proxy/schema.prisma
@@ -1002,12 +1002,15 @@ model LiteLLM_PromptTable {
id String @id @default(uuid())
prompt_id String
version Int @default(1)
+ environment String @default("development")
+ created_by String?
litellm_params Json
prompt_info Json?
created_at DateTime @default(now())
updated_at DateTime @updatedAt
- @@unique([prompt_id, version])
+ @@unique([prompt_id, version, environment])
+ @@index([prompt_id, environment])
@@index([prompt_id])
}
diff --git a/litellm/types/prompts/init_prompts.py b/litellm/types/prompts/init_prompts.py
index 2d9f807bc26..838271a2f31 100644
--- a/litellm/types/prompts/init_prompts.py
+++ b/litellm/types/prompts/init_prompts.py
@@ -17,6 +17,7 @@ class SupportedPromptIntegrations(str, Enum):
class PromptInfo(BaseModel):
prompt_type: Literal["config", "db"]
+ environment: Optional[str] = "development"
model_config = ConfigDict(extra="allow", protected_namespaces=())
@@ -48,6 +49,8 @@ class PromptSpec(BaseModel):
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
version: Optional[int] = None # Version number for version history
+ environment: Optional[str] = "development"
+ created_by: Optional[str] = None
def __init__(self, **data):
if "prompt_info" not in data:
@@ -70,6 +73,9 @@ class PromptTemplateBase(BaseModel):
class PromptInfoResponse(BaseModel):
prompt_spec: PromptSpec
raw_prompt_template: Optional[PromptTemplateBase] = None
+ environments: Optional[
+ List[str]
+ ] = None # All environments this prompt is deployed to
class ListPromptsResponse(BaseModel):
diff --git a/litellm/utils.py b/litellm/utils.py
index e2dac1c9f62..37bc35af299 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -9030,11 +9030,11 @@ class ProviderConfigManager:
return get_stability_image_edit_config(model)
elif LlmProviders.BEDROCK == provider:
- from litellm.llms.bedrock.image_edit.stability_transformation import (
- BedrockStabilityImageEditConfig,
+ from litellm.llms.bedrock.image_edit.amazon_nova_canvas_image_edit_transformation import (
+ get_bedrock_image_edit_config_for_model,
)
- return BedrockStabilityImageEditConfig()
+ return get_bedrock_image_edit_config_for_model(model)
elif LlmProviders.OPENROUTER == provider:
from litellm.llms.openrouter.image_edit import (
get_openrouter_image_edit_config,
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index 71918ed049b..35fa2206761 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -277,7 +277,15 @@
"litellm_provider": "bedrock",
"max_input_tokens": 2600,
"mode": "image_generation",
- "output_cost_per_image": 0.06
+ "output_cost_per_image": 0.06,
+ "supports_nova_canvas_image_edit": true
+ },
+ "us.amazon.nova-canvas-v1:0": {
+ "litellm_provider": "bedrock",
+ "max_input_tokens": 2600,
+ "mode": "image_generation",
+ "output_cost_per_image": 0.06,
+ "supports_nova_canvas_image_edit": true
},
"us.writer.palmyra-x4-v1:0": {
"input_cost_per_token": 2.5e-06,
diff --git a/schema.prisma b/schema.prisma
index 46be6b31e1f..5d804d75b6a 100644
--- a/schema.prisma
+++ b/schema.prisma
@@ -1002,12 +1002,15 @@ model LiteLLM_PromptTable {
id String @id @default(uuid())
prompt_id String
version Int @default(1)
+ environment String @default("development")
+ created_by String?
litellm_params Json
prompt_info Json?
created_at DateTime @default(now())
updated_at DateTime @updatedAt
- @@unique([prompt_id, version])
+ @@unique([prompt_id, version, environment])
+ @@index([prompt_id, environment])
@@index([prompt_id])
}
diff --git a/tests/test_litellm/llms/bedrock/image_edit/test_amazon_nova_canvas_image_edit.py b/tests/test_litellm/llms/bedrock/image_edit/test_amazon_nova_canvas_image_edit.py
new file mode 100644
index 00000000000..020b8df1276
--- /dev/null
+++ b/tests/test_litellm/llms/bedrock/image_edit/test_amazon_nova_canvas_image_edit.py
@@ -0,0 +1,657 @@
+"""Unit tests for Bedrock Amazon Nova Canvas image edit (issue #24267)."""
+
+import base64
+import io
+from typing import cast
+
+import httpx
+import pytest
+
+import litellm
+from litellm.llms.bedrock.image_edit.amazon_nova_canvas_image_edit_transformation import (
+ BedrockAmazonNovaCanvasImageEditConfig,
+ get_bedrock_image_edit_config_for_model,
+)
+from litellm.llms.bedrock.image_edit.handler import BedrockImageEdit
+from litellm.llms.bedrock.image_edit.stability_transformation import (
+ BedrockStabilityImageEditConfig,
+)
+from litellm.types.images.main import ImageEditOptionalRequestParams
+
+
[email protected](autouse=True)
+def ensure_nova_canvas_image_edit_model_cost_flags(monkeypatch):
+ """Routing uses ``supports_nova_canvas_image_edit`` on ``litellm.model_cost``.
+
+ Full ``model_prices_and_context_window.json`` includes these flags, but CI or
+ alternate cost maps may omit them—merge minimal entries so tests match production.
+ """
+ from litellm.utils import _invalidate_model_cost_lowercase_map
+
+ for key in (
+ "amazon.nova-canvas-v1:0",
+ "us.amazon.nova-canvas-v1:0",
+ ):
+ entry = litellm.model_cost.get(key) or {}
+ if entry.get("supports_nova_canvas_image_edit") is True:
+ continue
+ monkeypatch.setitem(
+ litellm.model_cost,
+ key,
+ {
+ **entry,
+ "litellm_provider": entry.get("litellm_provider", "bedrock"),
+ "mode": entry.get("mode", "image_generation"),
+ "supports_nova_canvas_image_edit": True,
+ },
+ )
+ _invalidate_model_cost_lowercase_map()
+
+ yield
+
+ _invalidate_model_cost_lowercase_map()
+
+
+def test_get_config_class_nova_canvas():
+ """Nova Canvas model resolves to BedrockAmazonNovaCanvasImageEditConfig."""
+ cls = BedrockImageEdit.get_config_class("amazon.nova-canvas-v1:0")
+ assert cls is BedrockAmazonNovaCanvasImageEditConfig
+
+
+def test_get_config_class_us_cross_region_nova_canvas():
+ """Cross-region inference id us.amazon.nova-canvas-v1:0 maps via model_prices."""
+ cls = BedrockImageEdit.get_config_class("us.amazon.nova-canvas-v1:0")
+ assert cls is BedrockAmazonNovaCanvasImageEditConfig
+
+
+def test_get_config_class_stability_unchanged():
+ """Stability edit models still use stability config."""
+ cls = BedrockImageEdit.get_config_class(
+ "stability.stable-image-inpaint-v1:0",
+ )
+ assert cls is BedrockStabilityImageEditConfig
+
+
+def test_provider_config_router_returns_nova_for_canvas():
+ """ProviderConfigManager routes Nova Canvas to Nova image-edit config."""
+ cfg = get_bedrock_image_edit_config_for_model("amazon.nova-canvas-v1:0")
+ assert isinstance(cfg, BedrockAmazonNovaCanvasImageEditConfig)
+
+
+def test_provider_config_router_returns_stability_for_sd():
+ """Non-Nova Bedrock image edit still uses Stability config."""
+ cfg = get_bedrock_image_edit_config_for_model(
+ "stability.stable-image-inpaint-v1:0",
+ )
+ assert isinstance(cfg, BedrockStabilityImageEditConfig)
+
+
+def test_get_bedrock_helper_matches_handler_get_config_class():
+ """Handler and get_bedrock_image_edit_config_for_model must agree."""
+ for model in (
+ "amazon.nova-canvas-v1:0",
+ "stability.stable-image-inpaint-v1:0",
+ ):
+ handler_cls = BedrockImageEdit.get_config_class(model)
+ helper_cfg = get_bedrock_image_edit_config_for_model(model)
+ assert isinstance(helper_cfg, handler_cls)
+
+
+def test_get_config_class_unknown_bedrock_image_model_raises():
+ with pytest.raises(ValueError, match="Unsupported Bedrock image-edit model"):
+ BedrockImageEdit.get_config_class("amazon.titan-image-generator-v1")
+
+
+def test_get_bedrock_image_edit_config_unknown_raises():
+ with pytest.raises(ValueError, match="Unsupported Bedrock image-edit model"):
+ get_bedrock_image_edit_config_for_model("amazon.titan-image-generator-v1")
+
+
+def test_provider_config_manager_bedrock_nova_canvas():
+ """ProviderConfigManager.get_provider_image_edit_config matches handler routing."""
+ from litellm.utils import ProviderConfigManager
+
+ cfg = ProviderConfigManager.get_provider_image_edit_config(
+ "amazon.nova-canvas-v1:0",
+ litellm.LlmProviders.BEDROCK,
+ )
+ assert isinstance(cfg, BedrockAmazonNovaCanvasImageEditConfig)
+
+
+def test_provider_config_manager_bedrock_stability_inpaint():
+ """ProviderConfigManager returns Stability config for Stability edit models."""
+ from litellm.utils import ProviderConfigManager
+
+ cfg = ProviderConfigManager.get_provider_image_edit_config(
+ "stability.stable-image-inpaint-v1:0",
+ litellm.LlmProviders.BEDROCK,
+ )
+ assert isinstance(cfg, BedrockStabilityImageEditConfig)
+
+
+def test_provider_config_manager_bedrock_unknown_raises():
+ from litellm.utils import ProviderConfigManager
+
+ with pytest.raises(ValueError, match="Unsupported Bedrock image-edit model"):
+ ProviderConfigManager.get_provider_image_edit_config(
+ "amazon.titan-image-generator-v1",
+ litellm.LlmProviders.BEDROCK,
+ )
+
+
+def test_provider_config_manager_bedrock_dispatches_to_nova_transform_outpainting():
+ """
+ Full dispatch: utils.ProviderConfigManager -> get_bedrock_image_edit_config_for_model
+ -> Nova config.transform_image_edit_request (not only direct helper calls).
+ """
+ from litellm.utils import ProviderConfigManager
+
+ cfg = ProviderConfigManager.get_provider_image_edit_config(
+ "amazon.nova-canvas-v1:0",
+ litellm.LlmProviders.BEDROCK,
+ )
+ assert cfg is not None
+ img = io.BytesIO(b"scene")
+ mask = io.BytesIO(b"mask-bytes")
+ body, _ = cfg.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="expand left",
+ image=img,
+ image_edit_optional_request_params={
+ "taskType": "OUTPAINTING",
+ "mask": mask,
+ },
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "OUTPAINTING"
+ assert "maskImage" in body["outPaintingParams"]
+
+
+def test_transform_request_image_variation_without_mask():
+ """No mask -> IMAGE_VARIATION with images + text."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"fake-png")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="make it warmer",
+ image=img,
+ image_edit_optional_request_params={},
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "IMAGE_VARIATION"
+ assert body["imageVariationParams"]["text"] == "make it warmer"
+ assert len(body["imageVariationParams"]["images"]) == 1
+
+
+def test_transform_request_image_pathlike_input(tmp_path):
+ """PathLike image input should be read and base64-encoded."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ image_path = tmp_path / "img.bin"
+ image_bytes = b"pathlike-image-bytes"
+ image_path.write_bytes(image_bytes)
+
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="pathlike",
+ image=image_path,
+ image_edit_optional_request_params={},
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+
+ assert body["taskType"] == "IMAGE_VARIATION"
+ assert body["imageVariationParams"]["images"][0] == base64.b64encode(
+ image_bytes
+ ).decode("utf-8")
+
+
+def test_transform_request_inpainting_with_mask():
+ """Mask present -> INPAINTING with inPaintingParams (AWS field names)."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ main = io.BytesIO(b"img-bytes")
+ mask = io.BytesIO(b"mask-bytes")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="add a hat",
+ image=main,
+ image_edit_optional_request_params={"mask": mask},
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "INPAINTING"
+ ip = body["inPaintingParams"]
+ assert ip["text"] == "add a hat"
+ assert "maskImage" in ip
+ assert ip["image"] # base64
+
+
+def test_transform_request_explicit_image_variation_with_mask_honors_task_type():
+ """Explicit taskType=IMAGE_VARIATION must not be overridden by mask presence."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ main = io.BytesIO(b"img-bytes")
+ mask = io.BytesIO(b"mask-bytes")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="vary style",
+ image=main,
+ image_edit_optional_request_params={
+ "taskType": "IMAGE_VARIATION",
+ "mask": mask,
+ },
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "IMAGE_VARIATION"
+ assert "imageVariationParams" in body
+ assert body["imageVariationParams"]["text"] == "vary style"
+ assert len(body["imageVariationParams"]["images"]) == 1
+
+
+def test_transform_request_outpainting_with_mask():
+ """OUTPAINTING with OpenAI mask -> outPaintingParams.maskImage."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ main = io.BytesIO(b"img")
+ mask = io.BytesIO(b"mask")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="extend the sky",
+ image=main,
+ image_edit_optional_request_params={
+ "taskType": "OUTPAINTING",
+ "mask": mask,
+ },
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "OUTPAINTING"
+ assert "maskImage" in body["outPaintingParams"]
+ assert body["outPaintingParams"]["text"] == "extend the sky"
+
+
+def test_transform_request_outpainting_with_mask_prompt():
+ """OUTPAINTING with maskPrompt only (no binary mask)."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"img")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="new background",
+ image=img,
+ image_edit_optional_request_params={
+ "taskType": "OUTPAINTING",
+ "maskPrompt": "the area behind the subject",
+ },
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "OUTPAINTING"
+ assert body["outPaintingParams"]["maskPrompt"] == "the area behind the subject"
+
+
+def test_transform_request_outpainting_prefers_mask_prompt_over_binary_mask():
+ """OUTPAINTING chooses maskPrompt over maskImage when both are set (_nova_canvas_task_body)."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ main = io.BytesIO(b"img")
+ mask = io.BytesIO(b"mask")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="extend scene",
+ image=main,
+ image_edit_optional_request_params={
+ "taskType": "OUTPAINTING",
+ "mask": mask,
+ "maskPrompt": "sky region",
+ },
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "OUTPAINTING"
+ op = body["outPaintingParams"]
+ assert op["maskPrompt"] == "sky region"
+ assert "maskImage" not in op
+
+
+def test_transform_request_outpainting_with_out_painting_mode():
+ """OUTPAINTING forwards outPaintingMode into outPaintingParams."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"img")
+ mask = io.BytesIO(b"m")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="widen",
+ image=img,
+ image_edit_optional_request_params={
+ "taskType": "OUTPAINTING",
+ "mask": mask,
+ "outPaintingMode": "PRECISE",
+ },
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "OUTPAINTING"
+ assert body["outPaintingParams"]["outPaintingMode"] == "PRECISE"
+
+
+def test_get_supported_openai_params_includes_outpainting_fields():
+ """Documented OUTPAINTING-related optional params are advertised for routing/UI."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ supported = config.get_supported_openai_params("amazon.nova-canvas-v1:0")
+ assert "taskType" in supported
+ assert "maskPrompt" in supported
+ assert "outPaintingMode" in supported
+ assert "mask" in supported
+
+
+def test_transform_request_outpainting_without_mask_raises():
+ """OUTPAINTING without maskPrompt or maskImage must fail fast with a clear error."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"img")
+ with pytest.raises(
+ ValueError,
+ match="OUTPAINTING requires either a mask image or a mask prompt",
+ ):
+ config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="extend",
+ image=img,
+ image_edit_optional_request_params={"taskType": "OUTPAINTING"},
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+
+
+def test_transform_request_inpainting_explicit_task_without_mask_raises():
+ """INPAINTING taskType without mask or maskPrompt must fail fast."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"img")
+ with pytest.raises(
+ ValueError, match="INPAINTING requires either maskPrompt or maskImage"
+ ):
+ config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="fix it",
+ image=img,
+ image_edit_optional_request_params={"taskType": "INPAINTING"},
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+
+
+def test_transform_request_unknown_task_type_raises():
+ """Unknown taskType must not silently map to IMAGE_VARIATION or INPAINTING."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"img")
+ with pytest.raises(ValueError, match="Unsupported Amazon Nova Canvas taskType"):
+ config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="x",
+ image=img,
+ image_edit_optional_request_params={"taskType": "TEXT_IMAGE"},
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+
+
+def test_transform_request_background_removal():
+ """taskType BACKGROUND_REMOVAL builds minimal body."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"x")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="ignored",
+ image=img,
+ image_edit_optional_request_params={"taskType": "BACKGROUND_REMOVAL"},
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "BACKGROUND_REMOVAL"
+ assert "image" in body["backgroundRemovalParams"]
+
+
+def test_transform_request_background_removal_omits_image_generation_config():
+ """AWS Nova Canvas does not allow imageGenerationConfig on BACKGROUND_REMOVAL."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"x")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="ignored",
+ image=img,
+ image_edit_optional_request_params={
+ "taskType": "BACKGROUND_REMOVAL",
+ "size": "512x512",
+ "seed": 42,
+ "quality": "standard",
+ "cfgScale": 7.5,
+ "n": 2,
+ },
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "BACKGROUND_REMOVAL"
+ assert "imageGenerationConfig" not in body
+
+
+def test_transform_request_image_variation_includes_image_generation_config():
+ """Non-BACKGROUND_REMOVAL tasks may include imageGenerationConfig when params are set."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"x")
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="warm",
+ image=img,
+ image_edit_optional_request_params={"size": "1024x1024", "seed": 1},
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["taskType"] == "IMAGE_VARIATION"
+ assert "imageGenerationConfig" in body
+ assert body["imageGenerationConfig"]["width"] == 1024
+ assert body["imageGenerationConfig"]["height"] == 1024
+ assert body["imageGenerationConfig"]["seed"] == 1
+
+
+def test_map_openai_params_unknown_quality_not_silently_dropped():
+ """Non-Nova quality strings (e.g. OpenAI 'auto') must remain for downstream handling."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ mapped = config.map_openai_params(
+ cast(ImageEditOptionalRequestParams, {"quality": "auto"}),
+ model="amazon.nova-canvas-v1:0",
+ drop_params=False,
+ )
+ assert mapped.get("quality") == "auto"
+
+
+def test_transform_request_unknown_quality_reaches_image_generation_config():
+ """Unknown quality after map_openai_params is forwarded so callers are not silently ignored."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ img = io.BytesIO(b"x")
+ op = config.map_openai_params(
+ cast(ImageEditOptionalRequestParams, {"quality": "auto"}),
+ model="amazon.nova-canvas-v1:0",
+ drop_params=False,
+ )
+ body, _ = config.transform_image_edit_request(
+ model="amazon.nova-canvas-v1:0",
+ prompt="x",
+ image=img,
+ image_edit_optional_request_params=op,
+ litellm_params={}, # type: ignore[arg-type]
+ headers={},
+ )
+ assert body["imageGenerationConfig"]["quality"] == "auto"
+
+
+def test_is_nova_canvas_image_edit_model_uses_model_cost_flag(monkeypatch):
+ """Routing uses supports_nova_canvas_image_edit in model_cost, not a hardcoded name substring."""
+ fake_id = "amazon.custom-bedrock-image-edit-v99:0"
+ monkeypatch.setitem(
+ litellm.model_cost,
+ fake_id,
+ {
+ "litellm_provider": "bedrock",
+ "mode": "image_generation",
+ "supports_nova_canvas_image_edit": True,
+ },
+ )
+ assert (
+ BedrockAmazonNovaCanvasImageEditConfig._is_nova_canvas_image_edit_model(fake_id)
+ is True
+ )
+
+ monkeypatch.setitem(
+ litellm.model_cost,
+ "amazon.not-nova-canvas-v1:0",
+ {
+ "litellm_provider": "bedrock",
+ "mode": "image_generation",
+ },
+ )
+ assert (
+ BedrockAmazonNovaCanvasImageEditConfig._is_nova_canvas_image_edit_model(
+ "amazon.not-nova-canvas-v1:0"
+ )
+ is False
+ )
+
+ # Name-shaped ids do not route without supports_nova_canvas_image_edit (no substring heuristic).
+ monkeypatch.setitem(
+ litellm.model_cost,
+ "amazon.nova-canvas-v2:0",
+ {
+ "litellm_provider": "bedrock",
+ "mode": "image_generation",
+ },
+ )
+ assert (
+ BedrockAmazonNovaCanvasImageEditConfig._is_nova_canvas_image_edit_model(
+ "amazon.nova-canvas-v2:0"
+ )
+ is False
+ )
+
+
+def test_transform_response_to_openai_format():
+ """Response maps images[] to ImageResponse.data b64_json."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ resp = httpx.Response(
+ 200,
+ json={"images": ["YmFzZTY0X2E=", "YmFzZTY0X2I="]},
+ )
+ model_response = config.transform_image_edit_response(
+ model="amazon.nova-canvas-v1:0",
+ raw_response=resp,
+ logging_obj=None, # type: ignore[arg-type]
+ )
+ assert model_response.data is not None
+ assert len(model_response.data) == 2
+ assert model_response.data[0].b64_json == "YmFzZTY0X2E="
+
+
+def test_transform_response_non_200_raises():
+ """HTTP 4xx/5xx with JSON body surfaces a structured error."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ resp = httpx.Response(
+ 400,
+ json={"message": "ValidationException: invalid input"},
+ )
+ with pytest.raises(Exception, match="Nova Canvas image edit error"):
+ config.transform_image_edit_response(
+ model="amazon.nova-canvas-v1:0",
+ raw_response=resp,
+ logging_obj=None, # type: ignore[arg-type]
+ )
+
+
+def test_transform_response_errors_field_raises():
+ """Align with Bedrock Stability: top-level ``errors`` in body."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ resp = httpx.Response(
+ 200,
+ json={"errors": ["upstream failure"]},
+ )
+ with pytest.raises(Exception, match="Nova Canvas image edit error"):
+ config.transform_image_edit_response(
+ model="amazon.nova-canvas-v1:0",
+ raw_response=resp,
+ logging_obj=None, # type: ignore[arg-type]
+ )
+
+
+def test_transform_response_allows_errors_field_with_images():
+ """Do not treat ``errors`` as fatal when ``images`` is present."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ resp = httpx.Response(
+ 200,
+ json={"errors": ["non-fatal warning"], "images": ["YmFzZTY0X2E="]},
+ )
+ model_response = config.transform_image_edit_response(
+ model="amazon.nova-canvas-v1:0",
+ raw_response=resp,
+ logging_obj=None, # type: ignore[arg-type]
+ )
+ assert model_response.data is not None
+ assert len(model_response.data) == 1
+ assert model_response.data[0].b64_json == "YmFzZTY0X2E="
+
+
+def test_transform_response_message_or_error_field_raises():
+ """API-level error payload when there are no images (status 200)."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ resp = httpx.Response(
+ 200,
+ json={"message": "ValidationException: task rejected"},
+ )
+ with pytest.raises(Exception, match="Nova Canvas image edit error"):
+ config.transform_image_edit_response(
+ model="amazon.nova-canvas-v1:0",
+ raw_response=resp,
+ logging_obj=None, # type: ignore[arg-type]
+ )
+
+
+def test_transform_response_allows_informational_message_with_images():
+ """Do not treat ``message`` as fatal when ``images`` is present (SDK wrappers)."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ resp = httpx.Response(
+ 200,
+ json={
+ "message": "ok",
+ "images": ["YmFzZTY0X2E="],
+ },
+ )
+ model_response = config.transform_image_edit_response(
+ model="amazon.nova-canvas-v1:0",
+ raw_response=resp,
+ logging_obj=None, # type: ignore[arg-type]
+ )
+ assert model_response.data is not None
+ assert len(model_response.data) == 1
+ assert model_response.data[0].b64_json == "YmFzZTY0X2E="
+
+
+def test_transform_response_content_filtered_via_error_field():
+ """AWS Nova Canvas signals failures (e.g. content filter) via top-level ``error``, not ``finish_reasons``."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ resp = httpx.Response(
+ 200,
+ json={"images": [], "error": "CONTENT_FILTERED"},
+ )
+ with pytest.raises(Exception, match="Nova Canvas image edit error"):
+ config.transform_image_edit_response(
+ model="amazon.nova-canvas-v1:0",
+ raw_response=resp,
+ logging_obj=None, # type: ignore[arg-type]
+ )
+
+
+def test_transform_response_empty_images_without_error_raises():
+ """200 with empty ``images`` and no error fields must not return silent empty ImageResponse."""
+ config = BedrockAmazonNovaCanvasImageEditConfig()
+ resp = httpx.Response(200, json={"images": []})
+ with pytest.raises(Exception, match="returned no images"):
+ config.transform_image_edit_response(
+ model="amazon.nova-canvas-v1:0",
+ raw_response=resp,
+ logging_obj=None, # type: ignore[arg-type]
+ )
diff --git a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py
index f69f478278f..ea208007cd6 100644
--- a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py
+++ b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py
@@ -34,7 +34,9 @@ async def test_bedrock_sse_wrapper_encodes_dict_chunks():
_dummy_stream(),
litellm_logging_obj=LiteLLMLoggingObj(
model="bedrock/invoke/anthropic.claude-3-sonnet-20240229-v1:0",
- messages=[{"role": "user", "content": "Hello, can you tell me a short joke?"}],
+ messages=[
+ {"role": "user", "content": "Hello, can you tell me a short joke?"}
+ ],
stream=True,
call_type="chat",
start_time=datetime.now(),
@@ -58,6 +60,74 @@ async def test_bedrock_sse_wrapper_encodes_dict_chunks():
assert collected[1] == b"raw-bytes"
+async def test_bedrock_sse_wrapper_keeps_usage_in_message_start_and_message_delta():
+ """Regression test: usage should be available on both message_start and message_delta SSE events."""
+
+ cfg = AmazonAnthropicClaudeMessagesConfig()
+
+ async def _dummy_stream(): # type: ignore[return-type]
+ yield {
+ "type": "message_start",
+ "message": {
+ "id": "msg_123",
+ "type": "message",
+ "role": "assistant",
+ "content": [],
+ "usage": {
+ "input_tokens": 3,
+ "output_tokens": 1,
+ },
+ },
+ }
+ yield {
+ "type": "message_delta",
+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},
+ "usage": {
+ "input_tokens": 3,
+ "output_tokens": 8,
+ },
+ }
+ yield {
+ "type": "message_stop",
+ "usage": {
+ "input_tokens": 3,
+ "cache_creation_input_tokens": 1562,
+ "cache_read_input_tokens": 32392,
+ },
+ }
+
+ collected: list[bytes] = []
+ async for chunk in cfg.bedrock_sse_wrapper(
+ _dummy_stream(),
+ litellm_logging_obj=LiteLLMLoggingObj(
+ model="bedrock/invoke/anthropic.claude-3-sonnet-20240229-v1:0",
+ messages=[{"role": "user", "content": "Hello"}],
+ stream=True,
+ call_type="chat",
+ start_time=datetime.now(),
+ litellm_call_id="test_bedrock_sse_wrapper_keeps_usage_in_both_events",
+ function_id="test_bedrock_sse_wrapper_keeps_usage_in_both_events",
+ ),
+ request_body={},
+ ):
+ collected.append(chunk)
+
+ start_chunk = next(c for c in collected if b"event: message_start\n" in c)
+ delta_chunk = next(c for c in collected if b"event: message_delta\n" in c)
+
+ start_json = json.loads(start_chunk.decode("utf-8").split("data: ", 1)[1].strip())
+ delta_json = json.loads(delta_chunk.decode("utf-8").split("data: ", 1)[1].strip())
+
+ assert "usage" in start_json["message"]
+ assert start_json["message"]["usage"]["input_tokens"] == 3
+
+ assert "usage" in delta_json
+ assert delta_json["usage"]["cache_creation_input_tokens"] == 1562
+ assert delta_json["usage"]["cache_read_input_tokens"] == 32392
+ assert delta_json["usage"]["input_tokens"] == 3 + 1562 + 32392
+
+
def test_chunk_parser_usage_transformation():
"""Ensure Bedrock invocation metrics are transformed to Anthropic usage keys."""
@@ -96,12 +166,9 @@ def test_remove_ttl_from_cache_control():
{
"type": "text",
"text": "Hello",
- "cache_control": {
- "type": "ephemeral",
- "ttl": "1h"
- }
+ "cache_control": {"type": "ephemeral", "ttl": "1h"},
}
- ]
+ ],
}
]
}
@@ -122,20 +189,14 @@ def test_remove_ttl_from_cache_control():
{
"type": "text",
"text": "Hello",
- "cache_control": {
- "type": "ephemeral",
- "ttl": "1h"
- }
+ "cache_control": {"type": "ephemeral", "ttl": "1h"},
},
{
"type": "text",
"text": "World",
- "cache_control": {
- "type": "ephemeral",
- "ttl": "2h"
- }
- }
- ]
+ "cache_control": {"type": "ephemeral", "ttl": "2h"},
+ },
+ ],
}
]
}
@@ -156,11 +217,9 @@ def test_remove_ttl_from_cache_control():
{
"type": "text",
"text": "Hello",
- "cache_control": {
- "type": "ephemeral"
- }
+ "cache_control": {"type": "ephemeral"},
}
- ]
+ ],
}
]
}
@@ -232,6 +291,7 @@ def test_remove_custom_field_from_tools():
remove_custom_field_from_tools(request4)
assert request4["tools"] is None
+
def test_remove_scope_from_cache_control():
"""Ensure scope field is removed from cache_control for Bedrock (not supported)."""
@@ -303,9 +363,9 @@ def test_bedrock_messages_strips_output_config():
headers={},
)
- assert "output_config" not in result, (
- "output_config should be stripped — Bedrock Invoke rejects it"
- )
+ assert (
+ "output_config" not in result
+ ), "output_config should be stripped — Bedrock Invoke rejects it"
# Other params should be preserved
assert result.get("max_tokens") == 4096
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_model_armor.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_model_armor.py
index 97ca55073df..7bd87ed05d7 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_model_armor.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_model_armor.py
@@ -572,7 +572,7 @@ async def test_model_armor_streaming_block_yields_sse_error():
assert len(result_chunks) == 1
error_data = json.loads(result_chunks[0].removeprefix("data: "))
assert "error" in error_data
- assert error_data["error"]["code"] == 400
+ assert int(error_data["error"]["code"]) == 400
@pytest.mark.asyncio
diff --git a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py
index d269a9531fd..d35dbb87a1a 100644
--- a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py
+++ b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py
@@ -479,3 +479,67 @@ async def test_track_cost_callback_skips_for_falsy_model_and_no_slo(model_value)
)
mock_proxy_logging.failed_tracking_alert.assert_not_called()
+
+
+async def test_async_post_call_failure_hook_uses_actual_start_time():
+ """
+ Verify that failed requests record the actual request start time
+ instead of datetime.now(), so the spend log shows the real duration.
+
+ Previously both start_time and end_time were set to datetime.now()
+ at failure-logging time, resulting in duration=0 for all failures.
+ """
+ from datetime import timedelta
+
+ logger = _ProxyDBLogger()
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="test_api_key",
+ user_id="test_user_id",
+ team_id="test_team_id",
+ org_id="test_org_id",
+ end_user_id="test_end_user_id",
+ )
+
+ # Simulate a request that started 60 seconds ago
+ simulated_start = datetime.now() - timedelta(seconds=60)
+
+ mock_logging_obj = MagicMock()
+ mock_logging_obj.start_time = simulated_start
+ mock_logging_obj.model_call_details = {}
+ mock_logging_obj.litellm_trace_id = None
+
+ request_data = {
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "Hello"}],
+ "metadata": {},
+ "proxy_server_request": {},
+ "litellm_logging_obj": mock_logging_obj,
+ }
+
+ original_exception = Exception("Timeout error")
+
+ with patch(
+ "litellm.proxy.db.db_spend_update_writer.DBSpendUpdateWriter.update_database",
+ new_callable=AsyncMock,
+ ) as mock_update_database:
+ await logger.async_post_call_failure_hook(
+ request_data=request_data,
+ original_exception=original_exception,
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ mock_update_database.assert_called_once()
+ call_args = mock_update_database.call_args[1]
+
+ # start_time should be the simulated start, not datetime.now()
+ assert call_args["start_time"] == simulated_start
+
+ # end_time should be close to now (within a few seconds)
+ time_diff = (datetime.now() - call_args["end_time"]).total_seconds()
+ assert time_diff < 5, f"end_time should be close to now, was {time_diff}s ago"
+
+ # Duration should be approximately 60 seconds, not 0
+ duration = (call_args["end_time"] - call_args["start_time"]).total_seconds()
+ assert duration >= 55, f"Duration should be ~60s, got {duration}s"
diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
index 0ff276953c6..72092a97f5b 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py
@@ -33,6 +33,7 @@ from litellm.proxy.management_endpoints.key_management_endpoints import (
_check_org_key_limits,
_check_team_key_limits,
_common_key_generation_helper,
+ _enforce_upperbound_key_params,
_get_and_validate_existing_key,
_list_key_helper,
_persist_deleted_verification_tokens,
@@ -8435,3 +8436,146 @@ class TestKeyAliasSkipValidationOnUnchanged:
# None alias should always pass
_validate_key_alias_format(None)
+
+
+# --- Tests: _enforce_upperbound_key_params ---
+
+
+def test_enforce_upperbound_rejects_over_limit_on_generate():
+ """Test that key generation is rejected when values exceed upperbound."""
+ import litellm
+ from litellm.types.proxy.management_endpoints.ui_sso import (
+ LiteLLM_UpperboundKeyGenerateParams,
+ )
+
+ original = litellm.upperbound_key_generate_params
+ try:
+ litellm.upperbound_key_generate_params = LiteLLM_UpperboundKeyGenerateParams(
+ tpm_limit=1000, rpm_limit=100, max_budget=10.0
+ )
+ data = GenerateKeyRequest(tpm_limit=5000)
+ with pytest.raises(HTTPException) as exc_info:
+ _enforce_upperbound_key_params(data, fill_defaults=True)
+ assert exc_info.value.status_code == 400
+ assert "tpm_limit" in str(exc_info.value.detail)
+ finally:
+ litellm.upperbound_key_generate_params = original
+
+
+def test_enforce_upperbound_fills_defaults_on_generate():
+ """Test that None values are filled with upperbound defaults during generation."""
+ import litellm
+ from litellm.types.proxy.management_endpoints.ui_sso import (
+ LiteLLM_UpperboundKeyGenerateParams,
+ )
+
+ original = litellm.upperbound_key_generate_params
+ try:
+ litellm.upperbound_key_generate_params = LiteLLM_UpperboundKeyGenerateParams(
+ tpm_limit=1000, rpm_limit=100
+ )
+ data = GenerateKeyRequest() # tpm_limit=None, rpm_limit=None
+ _enforce_upperbound_key_params(data, fill_defaults=True)
+ assert data.tpm_limit == 1000
+ assert data.rpm_limit == 100
+ finally:
+ litellm.upperbound_key_generate_params = original
+
+
+def test_enforce_upperbound_skips_none_on_update():
+ """Test that None values are NOT filled during update (fill_defaults=False)."""
+ import litellm
+ from litellm.types.proxy.management_endpoints.ui_sso import (
+ LiteLLM_UpperboundKeyGenerateParams,
+ )
+
+ original = litellm.upperbound_key_generate_params
+ try:
+ litellm.upperbound_key_generate_params = LiteLLM_UpperboundKeyGenerateParams(
+ tpm_limit=1000, rpm_limit=100
+ )
+ data = UpdateKeyRequest(key="sk-test") # tpm_limit=None, rpm_limit=None
+ _enforce_upperbound_key_params(data, fill_defaults=False)
+ assert data.tpm_limit is None # should NOT be filled
+ assert data.rpm_limit is None # should NOT be filled
+ finally:
+ litellm.upperbound_key_generate_params = original
+
+
+def test_enforce_upperbound_rejects_over_limit_on_update():
+ """Test that key update is rejected when values exceed upperbound."""
+ import litellm
+ from litellm.types.proxy.management_endpoints.ui_sso import (
+ LiteLLM_UpperboundKeyGenerateParams,
+ )
+
+ original = litellm.upperbound_key_generate_params
+ try:
+ litellm.upperbound_key_generate_params = LiteLLM_UpperboundKeyGenerateParams(
+ tpm_limit=1000, rpm_limit=100, max_budget=10.0
+ )
+ data = UpdateKeyRequest(key="sk-test", tpm_limit=5000)
+ with pytest.raises(HTTPException) as exc_info:
+ _enforce_upperbound_key_params(data, fill_defaults=False)
+ assert exc_info.value.status_code == 400
+ assert "tpm_limit" in str(exc_info.value.detail)
+ finally:
+ litellm.upperbound_key_generate_params = original
+
+
+def test_enforce_upperbound_allows_within_limit_on_update():
+ """Test that key update passes when values are within upperbound."""
+ import litellm
+ from litellm.types.proxy.management_endpoints.ui_sso import (
+ LiteLLM_UpperboundKeyGenerateParams,
+ )
+
+ original = litellm.upperbound_key_generate_params
+ try:
+ litellm.upperbound_key_generate_params = LiteLLM_UpperboundKeyGenerateParams(
+ tpm_limit=1000, rpm_limit=100, max_budget=10.0
+ )
+ data = UpdateKeyRequest(key="sk-test", tpm_limit=500, rpm_limit=50, max_budget=5.0)
+ _enforce_upperbound_key_params(data, fill_defaults=False)
+ # Should not raise
+ assert data.tpm_limit == 500
+ assert data.rpm_limit == 50
+ assert data.max_budget == 5.0
+ finally:
+ litellm.upperbound_key_generate_params = original
+
+
+def test_enforce_upperbound_duration_over_limit():
+ """Test that duration exceeding upperbound is rejected."""
+ import litellm
+ from litellm.types.proxy.management_endpoints.ui_sso import (
+ LiteLLM_UpperboundKeyGenerateParams,
+ )
+
+ original = litellm.upperbound_key_generate_params
+ try:
+ litellm.upperbound_key_generate_params = LiteLLM_UpperboundKeyGenerateParams(
+ duration="7d"
+ )
+ data = UpdateKeyRequest(key="sk-test", duration="30d")
+ with pytest.raises(HTTPException) as exc_info:
+ _enforce_upperbound_key_params(data, fill_defaults=False)
+ assert exc_info.value.status_code == 400
+ assert "duration" in str(exc_info.value.detail)
+ finally:
+ litellm.upperbound_key_generate_params = original
+
+
+def test_enforce_upperbound_no_config_is_noop():
+ """Test that no enforcement happens when upperbound params are not configured."""
+ import litellm
+
+ original = litellm.upperbound_key_generate_params
+ try:
+ litellm.upperbound_key_generate_params = None
+ data = UpdateKeyRequest(key="sk-test", tpm_limit=999999)
+ _enforce_upperbound_key_params(data, fill_defaults=False)
+ # Should not raise — no enforcement configured
+ assert data.tpm_limit == 999999
+ finally:
+ litellm.upperbound_key_generate_params = original
diff --git a/tests/test_litellm/proxy/prompts/test_prompt_environment.py b/tests/test_litellm/proxy/prompts/test_prompt_environment.py
new file mode 100644
index 00000000000..ecd89afefbe
--- /dev/null
+++ b/tests/test_litellm/proxy/prompts/test_prompt_environment.py
@@ -0,0 +1,253 @@
+import json
+import pytest
+from unittest.mock import MagicMock
+from litellm.types.prompts.init_prompts import (
+ PromptInfo,
+ PromptSpec,
+ PromptLiteLLMParams,
+)
+
+
+def test_prompt_info_default_environment():
+ """PromptInfo should default environment to 'development'."""
+ info = PromptInfo(prompt_type="db")
+ assert info.environment == "development"
+
+
+def test_prompt_info_custom_environment():
+ """PromptInfo should accept a custom environment."""
+ info = PromptInfo(prompt_type="db", environment="production")
+ assert info.environment == "production"
+
+
+def test_prompt_spec_includes_environment_and_created_by():
+ """PromptSpec should carry environment and created_by fields."""
+ spec = PromptSpec(
+ prompt_id="test",
+ litellm_params=PromptLiteLLMParams(
+ prompt_id="test", prompt_integration="dotprompt"
+ ),
+ prompt_info=PromptInfo(prompt_type="db", environment="staging"),
+ environment="staging",
+ created_by="user-123",
+ )
+ assert spec.environment == "staging"
+ assert spec.created_by == "user-123"
+
+
+def test_prompt_spec_default_environment():
+ """PromptSpec environment should default to 'development'."""
+ spec = PromptSpec(
+ prompt_id="test",
+ litellm_params=PromptLiteLLMParams(
+ prompt_id="test", prompt_integration="dotprompt"
+ ),
+ prompt_info=PromptInfo(prompt_type="db"),
+ )
+ assert spec.environment == "development"
+ assert spec.created_by is None
+
+
+def test_create_versioned_prompt_spec_includes_environment():
+ """create_versioned_prompt_spec should populate environment and created_by from DB row."""
+ from litellm.proxy.prompts.prompt_endpoints import create_versioned_prompt_spec
+
+ mock_db_prompt = MagicMock()
+ mock_db_prompt.model_dump.return_value = {
+ "id": "uuid-123",
+ "prompt_id": "test_prompt",
+ "version": 2,
+ "environment": "staging",
+ "created_by": "user-456",
+ "litellm_params": json.dumps(
+ {
+ "prompt_id": "test_prompt",
+ "prompt_integration": "dotprompt",
+ }
+ ),
+ "prompt_info": json.dumps({"prompt_type": "db", "environment": "staging"}),
+ "created_at": None,
+ "updated_at": None,
+ }
+ spec = create_versioned_prompt_spec(mock_db_prompt)
+ assert spec.environment == "staging"
+ assert spec.created_by == "user-456"
+ assert spec.prompt_id == "test_prompt.v2"
+
+
+async def test_create_prompt_stores_environment_and_created_by():
+ """create_prompt should pass environment and created_by to the DB."""
+ from unittest.mock import AsyncMock, patch
+ from litellm.proxy._types import UserAPIKeyAuth, LitellmUserRoles
+ from litellm.proxy.prompts.prompt_endpoints import create_prompt, Prompt
+
+ mock_user_auth = UserAPIKeyAuth(
+ api_key="sk-1234",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ user_id="user-789",
+ )
+
+ mock_prisma_client = MagicMock()
+ mock_db_entry = MagicMock()
+ mock_db_entry.model_dump.return_value = {
+ "id": "uuid-1",
+ "prompt_id": "my_prompt",
+ "version": 1,
+ "environment": "staging",
+ "created_by": "user-789",
+ "litellm_params": json.dumps(
+ {
+ "prompt_id": "my_prompt",
+ "prompt_integration": "dotprompt",
+ }
+ ),
+ "prompt_info": json.dumps({"prompt_type": "db", "environment": "staging"}),
+ "created_at": None,
+ "updated_at": None,
+ }
+ mock_prisma_client.db.litellm_prompttable.create = AsyncMock(
+ return_value=mock_db_entry
+ )
+ mock_prisma_client.db.litellm_prompttable.find_many = AsyncMock(return_value=[])
+
+ request = Prompt(
+ prompt_id="my_prompt",
+ litellm_params=PromptLiteLLMParams(
+ prompt_id="my_prompt", prompt_integration="dotprompt"
+ ),
+ prompt_info=PromptInfo(prompt_type="db", environment="staging"),
+ )
+
+ with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
+ with patch(
+ "litellm.proxy.prompts.prompt_registry.IN_MEMORY_PROMPT_REGISTRY"
+ ) as mock_registry:
+ mock_registry.initialize_prompt.return_value = PromptSpec(
+ prompt_id="my_prompt.v1",
+ litellm_params=request.litellm_params,
+ prompt_info=request.prompt_info,
+ environment="staging",
+ created_by="user-789",
+ )
+ await create_prompt(request=request, user_api_key_dict=mock_user_auth)
+
+ create_call = mock_prisma_client.db.litellm_prompttable.create.call_args
+ data = create_call.kwargs["data"]
+ assert data["environment"] == "staging"
+ assert data["created_by"] == "user-789"
+
+
+async def test_update_prompt_stores_environment_and_created_by():
+ """update_prompt should pass environment and created_by to new version."""
+ from unittest.mock import AsyncMock, patch
+ from litellm.proxy._types import UserAPIKeyAuth, LitellmUserRoles
+ from litellm.proxy.prompts.prompt_endpoints import update_prompt, Prompt
+
+ mock_user_auth = UserAPIKeyAuth(
+ api_key="sk-1234",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ user_id="user-update",
+ )
+
+ mock_prisma_client = MagicMock()
+ mock_existing = MagicMock()
+ mock_existing.version = 1
+ mock_prisma_client.db.litellm_prompttable.find_many = AsyncMock(
+ return_value=[mock_existing]
+ )
+
+ mock_db_entry = MagicMock()
+ mock_db_entry.model_dump.return_value = {
+ "id": "uuid-2",
+ "prompt_id": "my_prompt",
+ "version": 2,
+ "environment": "production",
+ "created_by": "user-update",
+ "litellm_params": json.dumps(
+ {
+ "prompt_id": "my_prompt",
+ "prompt_integration": "dotprompt",
+ }
+ ),
+ "prompt_info": json.dumps({"prompt_type": "db", "environment": "production"}),
+ "created_at": None,
+ "updated_at": None,
+ }
+ mock_prisma_client.db.litellm_prompttable.create = AsyncMock(
+ return_value=mock_db_entry
+ )
+
+ request = Prompt(
+ prompt_id="my_prompt",
+ litellm_params=PromptLiteLLMParams(
+ prompt_id="my_prompt", prompt_integration="dotprompt"
+ ),
+ prompt_info=PromptInfo(prompt_type="db", environment="production"),
+ )
+
+ with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
+ with patch(
+ "litellm.proxy.prompts.prompt_registry.IN_MEMORY_PROMPT_REGISTRY"
+ ) as mock_registry:
+ mock_registry.get_prompt_by_id.return_value = PromptSpec(
+ prompt_id="my_prompt.v1",
+ litellm_params=request.litellm_params,
+ prompt_info=PromptInfo(prompt_type="db"),
+ )
+ mock_registry.initialize_prompt.return_value = PromptSpec(
+ prompt_id="my_prompt.v2",
+ litellm_params=request.litellm_params,
+ prompt_info=request.prompt_info,
+ environment="production",
+ created_by="user-update",
+ )
+ await update_prompt(
+ prompt_id="my_prompt", request=request, user_api_key_dict=mock_user_auth
+ )
+
+ create_call = mock_prisma_client.db.litellm_prompttable.create.call_args
+ data = create_call.kwargs["data"]
+ assert data["environment"] == "production"
+ assert data["created_by"] == "user-update"
+
+
+async def test_delete_prompt_scoped_to_environment():
+ """delete_prompt with environment param should scope deletion."""
+ from unittest.mock import AsyncMock, patch
+ from litellm.proxy._types import UserAPIKeyAuth, LitellmUserRoles
+ from litellm.proxy.prompts.prompt_endpoints import delete_prompt
+
+ mock_user_auth = UserAPIKeyAuth(
+ api_key="sk-1234",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_prompttable.delete_many = AsyncMock(return_value=None)
+
+ with patch(
+ "litellm.proxy.prompts.prompt_registry.IN_MEMORY_PROMPT_REGISTRY"
+ ) as mock_registry:
+ prompt_spec = PromptSpec(
+ prompt_id="test_prompt.v1",
+ litellm_params=PromptLiteLLMParams(
+ prompt_id="test_prompt", prompt_integration="dotprompt"
+ ),
+ prompt_info=PromptInfo(prompt_type="db"),
+ environment="staging",
+ )
+ mock_registry.get_prompt_by_id.return_value = prompt_spec
+
+ with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
+ await delete_prompt(
+ prompt_id="test_prompt",
+ user_api_key_dict=mock_user_auth,
+ environment="staging",
+ )
+
+ mock_prisma_client.db.litellm_prompttable.delete_many.assert_called_once_with(
+ where={"prompt_id": "test_prompt", "environment": "staging"}
+ )
diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py
index bdb38ab65f3..50dc3c6c6ec 100644
--- a/tests/test_litellm/test_utils.py
+++ b/tests/test_litellm/test_utils.py
@@ -752,6 +752,7 @@ def test_aaamodel_prices_and_context_window_json_is_valid():
"supports_file_search": {"type": "boolean"},
"supports_function_calling": {"type": "boolean"},
"supports_image_input": {"type": "boolean"},
+ "supports_nova_canvas_image_edit": {"type": "boolean"},
"supports_parallel_function_calling": {"type": "boolean"},
"supports_pdf_input": {"type": "boolean"},
"supports_prompt_caching": {"type": "boolean"},
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index 2e8518d00a6..a00441e703b 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -202,6 +202,7 @@ export interface Model {
interface PromptInfo {
prompt_type: string;
+ environment?: string;
}
export interface PromptSpec {
@@ -211,6 +212,8 @@ export interface PromptSpec {
created_at?: string;
updated_at?: string;
version?: number; // Explicit version number for version history
+ environment?: string;
+ created_by?: string;
}
export interface PromptTemplateBase {
@@ -222,6 +225,7 @@ export interface PromptTemplateBase {
interface PromptInfoResponse {
prompt_spec: PromptSpec;
raw_prompt_template: PromptTemplateBase | null;
+ environments?: string[];
}
export interface ListPromptsResponse {
@@ -6035,9 +6039,15 @@ export const estimateAttachmentImpactCall = async (
}
};
-export const getPromptsList = async (accessToken: string): Promise<ListPromptsResponse> => {
+export const getPromptsList = async (
+ accessToken: string,
+ environment?: string,
+): Promise<ListPromptsResponse> => {
try {
- const url = proxyBaseUrl ? `${proxyBaseUrl}/prompts/list` : `/prompts/list`;
+ let url = proxyBaseUrl ? `${proxyBaseUrl}/prompts/list` : `/prompts/list`;
+ if (environment) {
+ url += `?environment=${encodeURIComponent(environment)}`;
+ }
const response = await fetch(url, {
method: "GET",
headers: {
@@ -6061,9 +6071,12 @@ export const getPromptsList = async (accessToken: string): Promise<ListPromptsRe
}
};
-export const getPromptInfo = async (accessToken: string, promptId: string): Promise<PromptInfoResponse> => {
+export const getPromptInfo = async (accessToken: string, promptId: string, environment?: string): Promise<PromptInfoResponse> => {
try {
- const url = proxyBaseUrl ? `${proxyBaseUrl}/prompts/${promptId}/info` : `/prompts/${promptId}/info`;
+ let url = proxyBaseUrl ? `${proxyBaseUrl}/prompts/${promptId}/info` : `/prompts/${promptId}/info`;
+ if (environment) {
+ url += `?environment=${encodeURIComponent(environment)}`;
+ }
const response = await fetch(url, {
method: "GET",
headers: {
@@ -6087,9 +6100,12 @@ export const getPromptInfo = async (accessToken: string, promptId: string): Prom
}
};
-export const getPromptVersions = async (accessToken: string, promptId: string): Promise<ListPromptsResponse> => {
+export const getPromptVersions = async (accessToken: string, promptId: string, environment?: string): Promise<ListPromptsResponse> => {
try {
- const url = proxyBaseUrl ? `${proxyBaseUrl}/prompts/${promptId}/versions` : `/prompts/${promptId}/versions`;
+ let url = proxyBaseUrl ? `${proxyBaseUrl}/prompts/${promptId}/versions` : `/prompts/${promptId}/versions`;
+ if (environment) {
+ url += `?environment=${encodeURIComponent(environment)}`;
+ }
const response = await fetch(url, {
method: "GET",
headers: {
diff --git a/ui/litellm-dashboard/src/components/prompts.tsx b/ui/litellm-dashboard/src/components/prompts.tsx
index 24df7e78ab0..8e2e9c8b112 100644
--- a/ui/litellm-dashboard/src/components/prompts.tsx
+++ b/ui/litellm-dashboard/src/components/prompts.tsx
@@ -1,7 +1,7 @@
import React, { useState, useEffect } from "react";
import { Button } from "@tremor/react";
-import { Modal } from "antd";
+import { Modal, Select } from "antd";
import { getPromptsList, PromptSpec, ListPromptsResponse, deletePromptCall } from "./networking";
import PromptTable from "./prompts/prompt_table";
import PromptInfoView from "./prompts/prompt_info";
@@ -18,6 +18,7 @@ interface PromptsProps {
const PromptsPanel: React.FC<PromptsProps> = ({ accessToken, userRole }) => {
const [promptsList, setPromptsList] = useState<PromptSpec[]>([]);
const [isLoading, setIsLoading] = useState(false);
+ const [selectedEnvironment, setSelectedEnvironment] = useState<string | undefined>(undefined);
const [selectedPromptId, setSelectedPromptId] = useState<string | null>(null);
const [isAddModalVisible, setIsAddModalVisible] = useState(false);
const [showEditorView, setShowEditorView] = useState(false);
@@ -34,7 +35,7 @@ const PromptsPanel: React.FC<PromptsProps> = ({ accessToken, userRole }) => {
setIsLoading(true);
try {
- const response: ListPromptsResponse = await getPromptsList(accessToken);
+ const response: ListPromptsResponse = await getPromptsList(accessToken, selectedEnvironment);
console.log(`prompts: ${JSON.stringify(response)}`);
setPromptsList(response.prompts);
} catch (error) {
@@ -46,7 +47,7 @@ const PromptsPanel: React.FC<PromptsProps> = ({ accessToken, userRole }) => {
useEffect(() => {
fetchPrompts();
- }, [accessToken]);
+ }, [accessToken, selectedEnvironment]);
const handlePromptClick = (promptId: string) => {
setSelectedPromptId(promptId);
@@ -135,13 +136,25 @@ const PromptsPanel: React.FC<PromptsProps> = ({ accessToken, userRole }) => {
<>
<div className="flex justify-between items-center mb-4">
<div className="flex gap-2">
- <Button onClick={handleAddPrompt} disabled={!accessToken}>
- + Add New Prompt
- </Button>
+ <Button onClick={handleAddPrompt} disabled={!accessToken}>
+ + Add New Prompt
+ </Button>
<Button onClick={handleAddPromptFromFile} disabled={!accessToken} variant="secondary">
Upload .prompt File
</Button>
</div>
+ <Select
+ placeholder="All Environments"
+ allowClear
+ value={selectedEnvironment}
+ onChange={(value) => setSelectedEnvironment(value)}
+ style={{ width: 180 }}
+ options={[
+ { label: "Development", value: "development" },
+ { label: "Staging", value: "staging" },
+ { label: "Production", value: "production" },
+ ]}
+ />
</div>
<PromptTable
diff --git a/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/PromptEditorHeader.tsx b/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/PromptEditorHeader.tsx
index 8863c98f4ad..0211a60ab4c 100644
--- a/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/PromptEditorHeader.tsx
+++ b/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/PromptEditorHeader.tsx
@@ -1,6 +1,6 @@
import React from "react";
import { Button as TremorButton } from "@tremor/react";
-import { Input } from "antd";
+import { Input, Select } from "antd";
import { ArrowLeftIcon, SaveIcon, ClockIcon } from "lucide-react";
import PromptCodeSnippets from "./PromptCodeSnippets";
@@ -20,6 +20,8 @@ interface PromptEditorHeaderProps {
PROXY_BASE_URL?: string;
LITELLM_UI_API_DOC_BASE_URL?: string | null;
};
+ environment: string;
+ onEnvironmentChange: (env: string) => void;
}
const PromptEditorHeader: React.FC<PromptEditorHeaderProps> = ({
@@ -35,6 +37,8 @@ const PromptEditorHeader: React.FC<PromptEditorHeaderProps> = ({
promptVariables = {},
accessToken,
proxySettings,
+ environment,
+ onEnvironmentChange,
}) => {
return (
<div className="bg-white border-b border-gray-200 px-6 py-3 flex items-center justify-between">
@@ -53,6 +57,17 @@ const PromptEditorHeader: React.FC<PromptEditorHeaderProps> = ({
{version}
</span>
)}
+ <Select
+ value={environment}
+ onChange={onEnvironmentChange}
+ style={{ width: 140 }}
+ size="small"
+ options={[
+ { label: "Development", value: "development" },
+ { label: "Staging", value: "staging" },
+ { label: "Production", value: "production" },
+ ]}
+ />
<span className="px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded">Draft</span>
<span className="text-xs text-gray-400">Unsaved changes</span>
</div>
diff --git a/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/index.tsx b/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/index.tsx
index b17808df12e..ea49a4b87f4 100644
--- a/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/index.tsx
+++ b/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/index.tsx
@@ -1,7 +1,7 @@
import React, { useState } from "react";
import ToolModal from "../tool_modal";
import NotificationsManager from "../../molecules/notifications_manager";
-import { createPromptCall, updatePromptCall } from "../../networking";
+import { createPromptCall, updatePromptCall, getPromptInfo } from "../../networking";
import { PromptType, PromptEditorViewProps, Tool } from "./types";
import { convertToDotPrompt, parseExistingPrompt } from "./utils";
import PromptEditorHeader from "./PromptEditorHeader";
@@ -39,6 +39,7 @@ const PromptEditorView: React.FC<PromptEditorViewProps> = ({ onClose, onSuccess,
content: "Enter task specifics. Use {{template_variables}} for dynamic inputs",
},
],
+ environment: "development",
};
};
@@ -208,6 +209,7 @@ const PromptEditorView: React.FC<PromptEditorViewProps> = ({ onClose, onSuccess,
},
prompt_info: {
prompt_type: "db",
+ environment: prompt.environment,
},
};
@@ -273,6 +275,23 @@ const PromptEditorView: React.FC<PromptEditorViewProps> = ({ onClose, onSuccess,
promptModel={prompt.model}
promptVariables={extractTemplateVariables()}
accessToken={accessToken}
+ environment={prompt.environment}
+ onEnvironmentChange={async (env) => {
+ setPrompt({ ...prompt, environment: env });
+ if (editMode && accessToken && initialPromptData?.prompt_spec?.prompt_id) {
+ try {
+ const response = await getPromptInfo(accessToken, initialPromptData.prompt_spec.prompt_id, env);
+ if (response?.prompt_spec) {
+ const loadedPrompt = parseExistingPrompt(response);
+ setPrompt({ ...loadedPrompt, environment: env });
+ const versionNum = response.prompt_spec.version || 1;
+ setActiveVersionId(`${response.prompt_spec.prompt_id}.v${versionNum}`);
+ }
+ } catch {
+ // No version in this environment yet — keep current content, just change env
+ }
+ }
+ }}
/>
<div className="flex-1 flex overflow-hidden">
diff --git a/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/types.ts b/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/types.ts
index 4953c9b9437..37e73d0169b 100644
--- a/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/types.ts
+++ b/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/types.ts
@@ -20,6 +20,7 @@ export interface PromptType {
tools: Tool[];
developerMessage: string;
messages: Message[];
+ environment: string;
}
export interface PromptEditorViewProps {
diff --git a/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/utils.ts b/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/utils.ts
index 523470e34d0..a8dd7f60eb1 100644
--- a/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/utils.ts
+++ b/ui/litellm-dashboard/src/components/prompts/prompt_editor_view/utils.ts
@@ -246,6 +246,7 @@ export const parseExistingPrompt = (apiResponse: any): PromptType => {
parsedBody.messages.length > 0
? parsedBody.messages
: [{ role: "user", content: "Enter task specifics. Use {{template_variables}} for dynamic inputs" }],
+ environment: apiResponse?.prompt_spec?.environment || apiResponse?.prompt_spec?.prompt_info?.environment || "development",
};
};
diff --git a/ui/litellm-dashboard/src/components/prompts/prompt_info.tsx b/ui/litellm-dashboard/src/components/prompts/prompt_info.tsx
index dec0baa9505..ccc3560b849 100644
--- a/ui/litellm-dashboard/src/components/prompts/prompt_info.tsx
+++ b/ui/litellm-dashboard/src/components/prompts/prompt_info.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from "react";
+import React, { useState, useEffect, useRef } from "react";
import {
Card,
Title,
@@ -11,19 +11,25 @@ import {
TabList,
TabPanel,
TabPanels,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeaderCell,
+ TableRow,
} from "@tremor/react";
import { Button, Modal } from "antd";
import { ArrowLeftIcon, TrashIcon, PencilIcon } from "@heroicons/react/outline";
-import { getPromptInfo, PromptSpec, PromptTemplateBase, deletePromptCall } from "@/components/networking";
+import { getPromptInfo, getPromptVersions, PromptSpec, PromptTemplateBase, deletePromptCall } from "@/components/networking";
import { copyToClipboard as utilCopyToClipboard } from "@/utils/dataUtils";
import { CheckIcon, CopyIcon } from "lucide-react";
import NotificationsManager from "../molecules/notifications_manager";
import PromptCodeSnippets from "./prompt_editor_view/PromptCodeSnippets";
-import {
- extractModel,
- extractTemplateVariables,
- getBasePromptId,
- getCurrentVersion
+import {
+ extractModel,
+ extractTemplateVariables,
+ getBasePromptId,
+ getCurrentVersion
} from "./prompt_utils";
export interface PromptInfoProps {
@@ -44,14 +50,31 @@ const PromptInfoView: React.FC<PromptInfoProps> = ({ promptId, onClose, accessTo
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
- const fetchPromptInfo = async () => {
+ // Environment and version state
+ const [environments, setEnvironments] = useState<string[]>([]);
+ const [selectedEnv, setSelectedEnv] = useState<string | null>(null);
+ const [versionHistory, setVersionHistory] = useState<PromptSpec[]>([]);
+ const [selectedVersion, setSelectedVersion] = useState<number | null>(null);
+ const [loadingVersions, setLoadingVersions] = useState(false);
+
+ // Initial fetch — no environment filter, gets default + all environments list
+ const fetchPromptInfo = async (environment?: string) => {
try {
setLoading(true);
if (!accessToken) return;
- const response = await getPromptInfo(accessToken, promptId);
+ const response = await getPromptInfo(accessToken, promptId, environment);
setPromptData(response.prompt_spec);
setPromptTemplate(response.raw_prompt_template);
- setRawApiResponse(response); // Store the raw response for the Raw JSON tab
+ setRawApiResponse(response);
+
+ // Set environments from response
+ if (response.environments && response.environments.length > 0) {
+ setEnvironments(response.environments);
+ if (!selectedEnv) {
+ setSelectedEnv(response.prompt_spec.environment || response.environments[0]);
+ }
+ }
+ setSelectedVersion(response.prompt_spec.version || null);
} catch (error) {
NotificationsManager.fromBackend("Failed to load prompt information");
console.error("Error fetching prompt info:", error);
@@ -60,11 +83,46 @@ const PromptInfoView: React.FC<PromptInfoProps> = ({ promptId, onClose, accessTo
}
};
+ // Fetch version history for selected environment
+ const fetchVersionHistory = async (env: string) => {
+ if (!accessToken) return;
+ setLoadingVersions(true);
+ try {
+ const response = await getPromptVersions(accessToken, promptId, env);
+ setVersionHistory(response.prompts || []);
+ } catch {
+ setVersionHistory([]);
+ } finally {
+ setLoadingVersions(false);
+ }
+ };
+
+ const isInitialMount = useRef(true);
+
useEffect(() => {
+ setSelectedEnv(null);
+ setEnvironments([]);
+ setVersionHistory([]);
fetchPromptInfo();
}, [promptId, accessToken]);
- if (loading) {
+ // When environment changes (user clicks tab), re-fetch — skip initial mount
+ useEffect(() => {
+ if (isInitialMount.current) {
+ isInitialMount.current = false;
+ // Still fetch version history on initial mount once selectedEnv is set
+ if (selectedEnv && accessToken) {
+ fetchVersionHistory(selectedEnv);
+ }
+ return;
+ }
+ if (selectedEnv && accessToken) {
+ fetchPromptInfo(selectedEnv);
+ fetchVersionHistory(selectedEnv);
+ }
+ }, [selectedEnv]);
+
+ if (loading && !promptData) {
return <div className="p-4">Loading...</div>;
}
@@ -72,7 +130,6 @@ const PromptInfoView: React.FC<PromptInfoProps> = ({ promptId, onClose, accessTo
return <div className="p-4">Prompt not found</div>;
}
- // Format date helper function
const formatDate = (dateString?: string) => {
if (!dateString) return "-";
const date = new Date(dateString);
@@ -95,13 +152,12 @@ const PromptInfoView: React.FC<PromptInfoProps> = ({ promptId, onClose, accessTo
const handleDeleteConfirm = async () => {
if (!accessToken || !promptData) return;
-
setIsDeleting(true);
try {
await deletePromptCall(accessToken, basePromptId);
NotificationsManager.success(`Prompt "${basePromptId}" deleted successfully`);
- onDelete?.(); // Call the callback to refresh the parent component
- onClose(); // Close the info view
+ onDelete?.();
+ onClose();
} catch (error) {
console.error("Error deleting prompt:", error);
NotificationsManager.fromBackend("Failed to delete prompt");
@@ -115,10 +171,27 @@ const PromptInfoView: React.FC<PromptInfoProps> = ({ promptId, onClose, accessTo
setShowDeleteConfirm(false);
};
- // Use utility functions to extract prompt data
+ const handleVersionClick = async (version: PromptSpec) => {
+ if (!accessToken || !selectedEnv) return;
+ // Fetch specific version's info
+ const versionNum = version.version || 1;
+ setSelectedVersion(versionNum);
+ try {
+ const versionedId = `${promptId}.v${versionNum}`;
+ const response = await getPromptInfo(accessToken, versionedId, selectedEnv);
+ setPromptData(response.prompt_spec);
+ setPromptTemplate(response.raw_prompt_template);
+ setRawApiResponse(response);
+ } catch {
+ NotificationsManager.fromBackend(`Failed to load version v${versionNum}`);
+ }
+ };
+
const promptModel = promptData ? extractModel(promptData) || "gpt-4o" : "gpt-4o";
const basePromptId = getBasePromptId(promptData);
const currentVersion = getCurrentVersion(promptData);
+ const latestVersion = versionHistory.length > 0 ? Math.max(...versionHistory.map(v => v.version || 1)) : null;
+ const isViewingOldVersion = latestVersion !== null && selectedVersion !== null && selectedVersion < latestVersion;
return (
<div className="p-4">
@@ -174,64 +247,174 @@ const PromptInfoView: React.FC<PromptInfoProps> = ({ promptId, onClose, accessTo
</div>
</div>
+ {/* Environment Tabs */}
+ {environments.length > 0 && (
+ <div className="flex gap-2 mb-4">
+ {[...environments].sort((a, b) => {
+ const order: Record<string, number> = { development: 0, staging: 1, production: 2 };
+ return (order[a] ?? 99) - (order[b] ?? 99);
+ }).map((env) => (
+ <button
+ key={env}
+ onClick={() => {
+ setSelectedEnv(env);
+ setSelectedVersion(null);
+ }}
+ className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
+ selectedEnv === env
+ ? env === "production"
+ ? "bg-red-100 text-red-800 border-2 border-red-300"
+ : env === "staging"
+ ? "bg-yellow-100 text-yellow-800 border-2 border-yellow-300"
+ : "bg-green-100 text-green-800 border-2 border-green-300"
+ : "bg-gray-100 text-gray-600 border-2 border-transparent hover:bg-gray-200"
+ }`}
+ >
+ {env}
+ {versionHistory.length > 0 && selectedEnv === env && (
+ <span className="ml-1 text-xs opacity-75">
+ (v{latestVersion})
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {/* Old version banner */}
+ {isViewingOldVersion && (
+ <div className="mb-4 p-3 bg-amber-50 border border-amber-200 rounded-lg flex items-center justify-between">
+ <Text className="text-amber-800">
+ Viewing v{selectedVersion} — not the latest version (v{latestVersion})
+ </Text>
+ <TremorButton
+ variant="light"
+ size="xs"
+ onClick={() => {
+ const latest = versionHistory.find(v => v.version === latestVersion);
+ if (latest) handleVersionClick(latest);
+ }}
+ >
+ Go to latest
+ </TremorButton>
+ </div>
+ )}
+
<TabGroup>
<TabList className="mb-4">
<Tab key="overview">Overview</Tab>
{promptTemplate ? <Tab key="prompt-template">Prompt Template</Tab> : <></>}
- {isAdmin ? <Tab key="details">Details</Tab> : <></>}
<Tab key="raw-json">Raw JSON</Tab>
</TabList>
<TabPanels>
{/* Overview Panel */}
<TabPanel>
- <Grid numItems={1} numItemsSm={2} numItemsLg={3} className="gap-6">
+ <Grid numItems={1} numItemsSm={2} numItemsLg={4} className="gap-4">
<Card>
- <Text>Prompt ID</Text>
+ <Text>Version</Text>
<div className="mt-2">
- <Title className="font-mono text-sm">{basePromptId}</Title>
+ <Title>{currentVersion}</Title>
+ <Badge color="blue" className="mt-1">v{currentVersion}</Badge>
</div>
</Card>
<Card>
- <Text>Version</Text>
+ <Text>Prompt Type</Text>
<div className="mt-2">
- <Title>{currentVersion}</Title>
- <Badge color="blue" className="mt-1">
- v{currentVersion}
- </Badge>
+ <Title>{promptData.prompt_info?.prompt_type || "-"}</Title>
</div>
</Card>
<Card>
- <Text>Prompt Type</Text>
+ <Text>Created By</Text>
<div className="mt-2">
- <Title>{promptData.prompt_info?.prompt_type || "-"}</Title>
- <Badge color="blue" className="mt-1">
- {promptData.prompt_info?.prompt_type || "Unknown"}
- </Badge>
+ <Title className="text-sm">{promptData.created_by || "-"}</Title>
</div>
</Card>
<Card>
<Text>Created At</Text>
<div className="mt-2">
- <Title>{formatDate(promptData.created_at)}</Title>
- <Text>Last Updated: {formatDate(promptData.updated_at)}</Text>
+ <Title className="text-sm">{formatDate(promptData.created_at)}</Title>
+ <Text className="text-xs">Updated: {formatDate(promptData.updated_at)}</Text>
</div>
</Card>
</Grid>
- {promptData.litellm_params && Object.keys(promptData.litellm_params).length > 0 && (
- <Card className="mt-6">
- <Text className="font-medium">LiteLLM Parameters</Text>
- <div className="mt-2 p-3 bg-gray-50 rounded-md">
- <pre className="text-xs text-gray-800 whitespace-pre-wrap">
- {JSON.stringify(promptData.litellm_params, null, 2)}
- </pre>
- </div>
- </Card>
- )}
+ {/* Version History Table */}
+ <Card className="mt-6">
+ <Title className="mb-3">Version History — {selectedEnv}</Title>
+ {loadingVersions ? (
+ <Text>Loading versions...</Text>
+ ) : versionHistory.length > 0 ? (
+ <Table>
+ <TableHead>
+ <TableRow>
+ <TableHeaderCell>Version</TableHeaderCell>
+ <TableHeaderCell>Created By</TableHeaderCell>
+ <TableHeaderCell>Date</TableHeaderCell>
+ <TableHeaderCell>Actions</TableHeaderCell>
+ </TableRow>
+ </TableHead>
+ <TableBody>
+ {versionHistory.map((v) => {
+ const vNum = v.version || 1;
+ const isSelected = vNum === selectedVersion;
+ const isLatest = vNum === latestVersion;
+ return (
+ <TableRow
+ key={vNum}
+ className={`cursor-pointer hover:bg-blue-50 transition-colors ${
+ isSelected ? "bg-blue-50" : ""
+ }`}
+ onClick={() => handleVersionClick(v)}
+ >
+ <TableCell>
+ <span className={isSelected ? "font-bold" : ""}>
+ v{vNum}
+ </span>
+ {isLatest && (
+ <Badge color="blue" className="ml-2" size="xs">latest</Badge>
+ )}
+ </TableCell>
+ <TableCell>
+ <span className="text-sm">{v.created_by || "-"}</span>
+ </TableCell>
+ <TableCell>
+ <span className="text-sm">{formatDate(v.created_at)}</span>
+ </TableCell>
+ <TableCell>
+ <TremorButton
+ icon={PencilIcon}
+ variant="light"
+ size="xs"
+ onClick={(e) => {
+ e.stopPropagation();
+ // Build a response-like object for the editor
+ const editData = {
+ prompt_spec: {
+ ...v,
+ prompt_id: basePromptId,
+ environment: selectedEnv,
+ },
+ raw_prompt_template: isSelected ? promptTemplate : null,
+ };
+ onEdit?.(editData);
+ }}
+ >
+ Edit
+ </TremorButton>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ ) : (
+ <Text className="text-gray-400">No versions found in {selectedEnv}</Text>
+ )}
+ </Card>
</TabPanel>
{/* Prompt Template Panel */}
@@ -283,54 +466,6 @@ const PromptInfoView: React.FC<PromptInfoProps> = ({ promptId, onClose, accessTo
</TabPanel>
)}
- {/* Details Panel (only for admins) */}
- {isAdmin && (
- <TabPanel>
- <Card>
- <Title className="mb-4">Prompt Details</Title>
- <div className="space-y-4">
- <div>
- <Text className="font-medium">Prompt ID</Text>
- <div className="font-mono text-sm bg-gray-50 p-2 rounded">{basePromptId}</div>
- </div>
-
- <div>
- <Text className="font-medium">Prompt Type</Text>
- <div>{promptData.prompt_info?.prompt_type || "-"}</div>
- </div>
-
- <div>
- <Text className="font-medium">Created At</Text>
- <div>{formatDate(promptData.created_at)}</div>
- </div>
-
- <div>
- <Text className="font-medium">Last Updated</Text>
- <div>{formatDate(promptData.updated_at)}</div>
- </div>
-
- <div>
- <Text className="font-medium">LiteLLM Parameters</Text>
- <div className="mt-2 p-3 bg-gray-50 rounded-md border">
- <pre className="text-xs text-gray-800 whitespace-pre-wrap overflow-auto max-h-96">
- {JSON.stringify(promptData.litellm_params, null, 2)}
- </pre>
- </div>
- </div>
-
- <div>
- <Text className="font-medium">Prompt Info</Text>
- <div className="mt-2 p-3 bg-gray-50 rounded-md border">
- <pre className="text-xs text-gray-800 whitespace-pre-wrap">
- {JSON.stringify(promptData.prompt_info, null, 2)}
- </pre>
- </div>
- </div>
- </div>
- </Card>
- </TabPanel>
- )}
-
{/* Raw JSON Panel */}
<TabPanel>
<Card>
diff --git a/ui/litellm-dashboard/src/components/prompts/prompt_table.tsx b/ui/litellm-dashboard/src/components/prompts/prompt_table.tsx
index ee2f2baa193..18bb35d4888 100644
--- a/ui/litellm-dashboard/src/components/prompts/prompt_table.tsx
+++ b/ui/litellm-dashboard/src/components/prompts/prompt_table.tsx
@@ -184,6 +184,36 @@ const PromptTable: React.FC<PromptTableProps> = ({
);
},
},
+ {
+ header: "Environment",
+ accessorKey: "environment",
+ cell: ({ row }) => {
+ const prompt = row.original;
+ const env = prompt.environment || "development";
+ const colorMap: Record<string, string> = {
+ production: "text-red-600 bg-red-50",
+ staging: "text-yellow-600 bg-yellow-50",
+ development: "text-green-600 bg-green-50",
+ };
+ return (
+ <span className={`text-xs px-2 py-0.5 rounded ${colorMap[env] || "text-gray-600 bg-gray-50"}`}>
+ {env}
+ </span>
+ );
+ },
+ },
+ {
+ header: "Created By",
+ accessorKey: "created_by",
+ cell: ({ row }) => {
+ const prompt = row.original;
+ return (
+ <span className="text-xs text-gray-600">
+ {prompt.created_by || "-"}
+ </span>
+ );
+ },
+ },
{
header: "Type",
accessorKey: "prompt_info.prompt_type",