The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Agent Builder - support new experimental agent builder, to ensure agents pass compliance checks (#21817)
Krish Dholakia9fc6fd647c1e
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex a994db85b11..97f36a9b00f 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -98,6 +98,7 @@ _custom_logger_compatible_callbacks_literal = Literal["openmeter","logfire","literalai",+ "litellm_agent","dynamic_rate_limiter","dynamic_rate_limiter_v3","langsmith",diff --git a/litellm/integrations/litellm_agent/__init__.py b/litellm/integrations/litellm_agent/__init__.pynew file mode 100644index 00000000000..f09434080ed--- /dev/null+++ b/litellm/integrations/litellm_agent/__init__.py@@ -0,0 +1,5 @@+"""LiteLLM Agent integration - model name resolver for litellm_agent/ prefix."""++from .litellm_agent_model_resolver import LiteLLMAgentModelResolver++__all__ = ["LiteLLMAgentModelResolver"]diff --git a/litellm/integrations/litellm_agent/litellm_agent_model_resolver.py b/litellm/integrations/litellm_agent/litellm_agent_model_resolver.pynew file mode 100644index 00000000000..85d209da5b1--- /dev/null+++ b/litellm/integrations/litellm_agent/litellm_agent_model_resolver.py@@ -0,0 +1,79 @@+"""+Hook for LiteLLM that strips the litellm_agent/ prefix from model names.++When model is litellm_agent/gpt-3.5-turbo, this hook replaces it with gpt-3.5-turbo+before the completion call, similar to langfuse/model resolution.+"""++from typing import Dict, List, Optional, Tuple++from litellm.integrations.custom_logger import CustomLogger+from litellm.types.llms.openai import AllMessageValues+from litellm.types.prompts.init_prompts import PromptSpec+from litellm.types.utils import StandardCallbackDynamicParams++LITELLM_AGENT_PREFIX = "litellm_agent/"+++class LiteLLMAgentModelResolver(CustomLogger):+ """+ CustomLogger that strips litellm_agent/ prefix from model names.++ Enables model configs like litellm_agent/gpt-3.5-turbo to resolve to gpt-3.5-turbo.+ """++ def get_chat_completion_prompt(+ self,+ model: str,+ messages: List[AllMessageValues],+ non_default_params: dict,+ prompt_id: Optional[str],+ prompt_variables: Optional[dict],+ dynamic_callback_params: StandardCallbackDynamicParams,+ prompt_spec: Optional[PromptSpec] = None,+ prompt_label: Optional[str] = None,+ prompt_version: Optional[int] = None,+ ignore_prompt_manager_model: Optional[bool] = False,+ ignore_prompt_manager_optional_params: Optional[bool] = False,+ ) -> Tuple[str, List[AllMessageValues], dict]:+ """+ Strip litellm_agent/ prefix from model name.++ Returns:+ (resolved_model, messages, non_default_params)+ """+ if ignore_prompt_manager_model:+ return model, messages, non_default_params+ resolved_model = model.replace(LITELLM_AGENT_PREFIX, "", 1)+ return resolved_model, messages, non_default_params++ async def async_get_chat_completion_prompt(+ self,+ model: str,+ messages: List[AllMessageValues],+ non_default_params: dict,+ prompt_id: Optional[str],+ prompt_variables: Optional[dict],+ dynamic_callback_params: StandardCallbackDynamicParams,+ litellm_logging_obj: object,+ prompt_spec: Optional[PromptSpec] = None,+ tools: Optional[List[Dict]] = None,+ prompt_label: Optional[str] = None,+ prompt_version: Optional[int] = None,+ ignore_prompt_manager_model: Optional[bool] = False,+ ignore_prompt_manager_optional_params: Optional[bool] = False,+ ) -> Tuple[str, List[AllMessageValues], dict]:+ """Async delegate to get_chat_completion_prompt."""+ return self.get_chat_completion_prompt(+ model=model,+ messages=messages,+ non_default_params=non_default_params,+ prompt_id=prompt_id,+ prompt_variables=prompt_variables,+ dynamic_callback_params=dynamic_callback_params,+ prompt_spec=prompt_spec,+ prompt_label=prompt_label,+ prompt_version=prompt_version,+ ignore_prompt_manager_model=ignore_prompt_manager_model,+ ignore_prompt_manager_optional_params=ignore_prompt_manager_optional_params,+ )diff --git a/litellm/litellm_core_utils/custom_logger_registry.py b/litellm/litellm_core_utils/custom_logger_registry.pyindex a3c25ab65e9..fc73701ea9d 100644--- a/litellm/litellm_core_utils/custom_logger_registry.py+++ b/litellm/litellm_core_utils/custom_logger_registry.py@@ -18,11 +18,11 @@ from litellm.integrations.azure_storage.azure_storage import AzureBlobStorageLogfrom litellm.integrations.bitbucket import BitBucketPromptManagerfrom litellm.integrations.braintrust_logging import BraintrustLoggerfrom litellm.integrations.cloudzero.cloudzero import CloudZeroLogger-from litellm.integrations.focus.focus_logger import FocusLoggerfrom litellm.integrations.datadog.datadog import DataDogLoggerfrom litellm.integrations.datadog.datadog_llm_obs import DataDogLLMObsLoggerfrom litellm.integrations.deepeval import DeepEvalLoggerfrom litellm.integrations.dotprompt import DotpromptManager+from litellm.integrations.focus.focus_logger import FocusLoggerfrom litellm.integrations.galileo import GalileoObservefrom litellm.integrations.gcs_bucket.gcs_bucket import GCSBucketLoggerfrom litellm.integrations.gcs_pubsub.pub_sub import GcsPubSubLogger@@ -33,6 +33,7 @@ from litellm.integrations.langfuse.langfuse_prompt_management import (LangfusePromptManagement,)from litellm.integrations.langsmith import LangsmithLogger+from litellm.integrations.litellm_agent import LiteLLMAgentModelResolverfrom litellm.integrations.literal_ai import LiteralAILoggerfrom litellm.integrations.mlflow import MlflowLoggerfrom litellm.integrations.openmeter import OpenMeterLogger@@ -61,6 +62,7 @@ class CustomLoggerRegistry:"galileo": GalileoObserve,"langsmith": LangsmithLogger,"literalai": LiteralAILogger,+ "litellm_agent": LiteLLMAgentModelResolver,"prometheus": PrometheusLogger,"datadog": DataDogLogger,"datadog_llm_observability": DataDogLLMObsLogger,diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 56a22af3c29..5a67b89816b 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -147,6 +147,7 @@ from ..integrations.langfuse.langfuse import LangFuseLoggerfrom ..integrations.langfuse.langfuse_handler import LangFuseHandlerfrom ..integrations.langfuse.langfuse_prompt_management import LangfusePromptManagementfrom ..integrations.langsmith import LangsmithLogger+from ..integrations.litellm_agent import LiteLLMAgentModelResolverfrom ..integrations.literal_ai import LiteralAILoggerfrom ..integrations.logfire_logger import LogfireLevel, LogfireLoggerfrom ..integrations.lunary import LunaryLogger@@ -587,6 +588,11 @@ class Logging(LiteLLMLoggingBaseClass):if prompt_id:return True+ # Check if model uses litellm_agent prefix (model replacement without prompt_id)+ model = non_default_params.get("model", "")+ if isinstance(model, str) and model.startswith("litellm_agent/"):+ return True+if self._should_run_prompt_management_hooks_without_prompt_id(non_default_params=non_default_params,tools=tools,@@ -3629,6 +3635,14 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915_literalai_logger = LiteralAILogger()_in_memory_loggers.append(_literalai_logger)return _literalai_logger # type: ignore+ elif logging_integration == "litellm_agent":+ for callback in _in_memory_loggers:+ if isinstance(callback, LiteLLMAgentModelResolver):+ return callback # type: ignore++ _litellm_agent_resolver = LiteLLMAgentModelResolver()+ _in_memory_loggers.append(_litellm_agent_resolver)+ return _litellm_agent_resolver # type: ignoreelif logging_integration == "prometheus":PrometheusLogger = _get_cached_prometheus_logger()@@ -4183,6 +4197,10 @@ def get_custom_logger_compatible_class( # noqa: PLR0915for callback in _in_memory_loggers:if isinstance(callback, LiteralAILogger):return callback+ elif logging_integration == "litellm_agent":+ for callback in _in_memory_loggers:+ if isinstance(callback, LiteLLMAgentModelResolver):+ return callbackelif logging_integration == "prometheus":PrometheusLogger = _get_cached_prometheus_logger()for callback in _in_memory_loggers:diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.pyindex cdddee4e54e..b1d571343cf 100644--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py@@ -452,7 +452,7 @@ def update_responses_input_with_model_file_ids(For managed files (unified file IDs), uses model_file_id_mapping if provided,otherwise decodes the base64-encoded unified file ID and extracts the llm_output_file_id directly.-+Args:input: The responses API input parametermodel_id: The model ID to use for looking up provider-specific file IDs@@ -488,9 +488,13 @@ def update_responses_input_with_model_file_ids(file_id = content_item.get("file_id")if file_id:provider_file_id = file_id # Default to original-+# Check if we have a mapping for this file ID- if model_file_id_mapping and model_id and file_id in model_file_id_mapping:+ if (+ model_file_id_mapping+ and model_id+ and file_id in model_file_id_mapping+ ):# Use the model-specific file ID from mappingprovider_file_id = (model_file_id_mapping.get(file_id, {}).get(model_id)@@ -501,15 +505,19 @@ def update_responses_input_with_model_file_ids(updated_content.append(updated_content_item)else:# Check if this is a base64-encoded unified file ID without mapping- is_unified_file_id = _is_base64_encoded_unified_file_id(file_id)+ is_unified_file_id = _is_base64_encoded_unified_file_id(+ file_id+ )if is_unified_file_id:# Fallback: decode unified file ID- unified_file_id = convert_b64_uid_to_unified_uid(file_id)+ unified_file_id = convert_b64_uid_to_unified_uid(+ file_id+ )if "llm_output_file_id," in unified_file_id:provider_file_id = unified_file_id.split("llm_output_file_id,")[1].split(";")[0]-+updated_content_item = content_item.copy()updated_content_item["file_id"] = provider_file_idupdated_content.append(updated_content_item)@@ -534,9 +542,9 @@ def update_responses_tools_with_model_file_ids() -> Optional[List[Dict[str, Any]]]:"""Updates responses API tools with provider-specific file IDs.-+Handles code_interpreter tools with container.file_ids.-+Args:tools: The responses API tools parametermodel_id: The model ID to use for looking up provider-specific file IDs@@ -545,18 +553,18 @@ def update_responses_tools_with_model_file_ids("""if not tools or not isinstance(tools, list):return tools-+if not model_file_id_mapping or not model_id:return tools-+updated_tools = []for tool in tools:if not isinstance(tool, dict):updated_tools.append(tool)continue-+updated_tool = tool.copy()-+# Handle code_interpreter with container file_idsif tool.get("type") == "code_interpreter":container = tool.get("container")@@ -578,14 +586,14 @@ def update_responses_tools_with_model_file_ids(updated_file_ids.append(file_id)else:updated_file_ids.append(file_id)-+# Update the tool with new file IDsupdated_container = container.copy()updated_container["file_ids"] = updated_file_idsupdated_tool["container"] = updated_container-+updated_tools.append(updated_tool)-+return updated_tools@@ -1104,6 +1112,45 @@ def set_last_user_message(return messages+def add_system_prompt_to_messages(+ messages: List[AllMessageValues],+ system_prompt: str,+ merge_with_first_system: bool = False,+) -> List[AllMessageValues]:+ """+ Add a system prompt to the messages list.++ Args:+ messages: List of chat completion messages+ system_prompt: The system prompt content to add. If empty or None, returns messages unchanged.+ merge_with_first_system: If True and the first message is already a system message,+ prepends the new prompt to that message's content. If False, adds a new system+ message at the beginning.++ Returns:+ New list of messages with the system prompt added+ """+ if not system_prompt:+ return list(messages)++ if merge_with_first_system and messages and messages[0].get("role") == "system":+ first = dict(messages[0])+ existing_content = first.get("content", "")+ if isinstance(existing_content, str):+ merged_content = f"{system_prompt.strip()}\n\n{existing_content}"+ elif isinstance(existing_content, list):+ merged_content = [{"type": "text", "text": system_prompt.strip()}] + list(+ existing_content+ )+ else:+ merged_content = [{"type": "text", "text": system_prompt.strip()}]+ first["content"] = merged_content+ return [cast(AllMessageValues, first)] + list(messages[1:])++ system_message: AllMessageValues = {"role": "system", "content": system_prompt}+ return [system_message, *messages]++def convert_prefix_message_to_non_prefix_messages(messages: List[AllMessageValues],) -> List[AllMessageValues]:diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.pyindex 0f613ceb504..fe57046f808 100644--- a/litellm/llms/anthropic/chat/transformation.py+++ b/litellm/llms/anthropic/chat/transformation.py@@ -46,6 +46,7 @@ from litellm.types.llms.openai import (ChatCompletionToolCallChunk,ChatCompletionToolCallFunctionChunk,ChatCompletionToolParam,+ OpenAIChatCompletionFinishReason,OpenAIMcpServerTool,OpenAIWebSearchOptions,)@@ -54,10 +55,7 @@ from litellm.types.utils import (CompletionTokensDetailsWrapper,)from litellm.types.utils import Message as LitellmMessage-from litellm.types.utils import (- PromptTokensDetailsWrapper,- ServerToolUse,-)+from litellm.types.utils import PromptTokensDetailsWrapper, ServerToolUsefrom litellm.utils import (ModelResponse,Usage,@@ -251,10 +249,14 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):# All numeric/string/array constraints not supported by Anthropicunsupported_fields = {- "maxItems", "minItems", # array constraints- "minimum", "maximum", # numeric constraints- "exclusiveMinimum", "exclusiveMaximum", # numeric constraints- "minLength", "maxLength", # string constraints+ "maxItems",+ "minItems", # array constraints+ "minimum",+ "maximum", # numeric constraints+ "exclusiveMinimum",+ "exclusiveMaximum", # numeric constraints+ "minLength",+ "maxLength", # string constraints}# Build description additions from removed constraints@@ -844,7 +846,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):@staticmethoddef map_openai_context_management_to_anthropic(- context_management: Union[List[Dict[str, Any]], Dict[str, Any]]+ context_management: Union[List[Dict[str, Any]], Dict[str, Any]],) -> Optional[Dict[str, Any]]:"""OpenAI format: [{"type": "compaction", "compact_threshold": 200000}]@@ -876,19 +878,22 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):entry_type = entry.get("type")if entry_type == "compaction":- anthropic_edit: Dict[str, Any] = {- "type": "compact_20260112"- }+ anthropic_edit: Dict[str, Any] = {"type": "compact_20260112"}compact_threshold = entry.get("compact_threshold")# Rewrite to 'trigger' with correct nesting if threshold exists- if compact_threshold is not None and isinstance(compact_threshold, (int, float)):+ if compact_threshold is not None and isinstance(+ compact_threshold, (int, float)+ ):anthropic_edit["trigger"] = {"type": "input_tokens",- "value": int(compact_threshold)+ "value": int(compact_threshold),}# Map any other keys by passthrough except handled onesfor k in entry:- if k not in {"type", "compact_threshold"}: # only passthrough other keys+ if k not in {+ "type",+ "compact_threshold",+ }: # only passthrough other keysanthropic_edit[k] = entry[k]anthropic_edits.append(anthropic_edit)@@ -911,10 +916,14 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):for param, value in non_default_params.items():if param == "max_tokens":- optional_params["max_tokens"] = value- if param == "max_completion_tokens":- optional_params["max_tokens"] = value- if param == "tools":+ optional_params["max_tokens"] = (+ value if isinstance(value, int) else max(1, int(round(value)))+ )+ elif param == "max_completion_tokens":+ optional_params["max_tokens"] = (+ value if isinstance(value, int) else max(1, int(round(value)))+ )+ elif param == "tools":# check if optional params already has toolsanthropic_tools, mcp_servers = self._map_tools(value)optional_params = self._add_tools_to_optional_params(@@ -922,7 +931,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):)if mcp_servers:optional_params["mcp_servers"] = mcp_servers- if param == "tool_choice" or param == "parallel_tool_calls":+ elif param == "tool_choice" or param == "parallel_tool_calls":_tool_choice: Optional[AnthropicMessagesToolChoice] = (self._map_tool_choice(tool_choice=non_default_params.get("tool_choice"),@@ -932,17 +941,19 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):if _tool_choice is not None:optional_params["tool_choice"] = _tool_choice- if param == "stream" and value is True:+ elif param == "stream" and value is True:optional_params["stream"] = value- if param == "stop" and (isinstance(value, str) or isinstance(value, list)):+ elif param == "stop" and (+ isinstance(value, str) or isinstance(value, list)+ ):_value = self._map_stop_sequences(value)if _value is not None:optional_params["stop_sequences"] = _value- if param == "temperature":+ elif param == "temperature":optional_params["temperature"] = value- if param == "top_p":+ elif param == "top_p":optional_params["top_p"] = value- if param == "response_format" and isinstance(value, dict):+ elif param == "response_format" and isinstance(value, dict):if any(substring in modelfor substring in {@@ -982,14 +993,14 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):optional_params=optional_params, tools=[_tool])optional_params["json_mode"] = True- if (+ elif (param == "user"and value is not Noneand isinstance(value, str)and _valid_user_id(value) # anthropic fails on emails):optional_params["metadata"] = {"user_id": value}- if param == "thinking":+ elif param == "thinking":optional_params["thinking"] = valueelif param == "reasoning_effort" and isinstance(value, str):optional_params["thinking"] = AnthropicConfig._map_reasoning_effort(@@ -1007,9 +1018,13 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):elif param == "context_management":# Supports both OpenAI list format and Anthropic dict formatif isinstance(value, (list, dict)):- anthropic_context_management = self.map_openai_context_management_to_anthropic(value)+ anthropic_context_management = (+ self.map_openai_context_management_to_anthropic(value)+ )if anthropic_context_management is not None:- optional_params["context_management"] = anthropic_context_management+ optional_params["context_management"] = (+ anthropic_context_management+ )elif param == "speed" and isinstance(value, str):# Pass through Anthropic-specific speed parameter for fast modeoptional_params["speed"] = value@@ -1071,7 +1086,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):if not system_message_block["content"]:continue# Skip system messages containing x-anthropic-billing-header metadata- if system_message_block["content"].startswith("x-anthropic-billing-header:"):+ if system_message_block["content"].startswith(+ "x-anthropic-billing-header:"+ ):continueanthropic_system_message_content = AnthropicSystemMessageContent(type="text",@@ -1091,7 +1108,11 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):if _content.get("type") == "text" and not text_value:continue# Skip system messages containing x-anthropic-billing-header metadata- if _content.get("type") == "text" and text_value and text_value.startswith("x-anthropic-billing-header:"):+ if (+ _content.get("type") == "text"+ and text_value+ and text_value.startswith("x-anthropic-billing-header:")+ ):continueanthropic_system_message_content = (AnthropicSystemMessageContent(@@ -1201,7 +1222,8 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):# Add context management header if any other edits/entries existif has_other:self._ensure_beta_header(- headers, ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value+ headers,+ ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value,)def update_headers_with_optional_anthropic_beta(@@ -1227,7 +1249,8 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):ANTHROPIC_HOSTED_TOOLS.MEMORY.value):self._ensure_beta_header(- headers, ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value+ headers,+ ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value,)if optional_params.get("context_management") is not None:self._ensure_context_management_beta_header(@@ -1491,7 +1514,16 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):if thinking_content is not None:reasoning_content += thinking_content- return text_content, citations, thinking_blocks, reasoning_content, tool_calls, web_search_results, tool_results, compaction_blocks+ return (+ text_content,+ citations,+ thinking_blocks,+ reasoning_content,+ tool_calls,+ web_search_results,+ tool_results,+ compaction_blocks,+ )def calculate_usage(self,@@ -1576,7 +1608,11 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):)completion_token_details = CompletionTokensDetailsWrapper(reasoning_tokens=reasoning_tokens if reasoning_tokens > 0 else 0,- text_tokens=completion_tokens - reasoning_tokens if reasoning_tokens > 0 else completion_tokens,+ text_tokens=(+ completion_tokens - reasoning_tokens+ if reasoning_tokens > 0+ else completion_tokens+ ),)total_tokens = prompt_tokens + completion_tokens@@ -1696,8 +1732,9 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):"content"] # allow user to access raw anthropic tool calling response- model_response.choices[0].finish_reason = map_finish_reason(- completion_response["stop_reason"]+ model_response.choices[0].finish_reason = cast(+ OpenAIChatCompletionFinishReason,+ map_finish_reason(completion_response["stop_reason"]),)## CALCULATING USAGEdiff --git a/litellm/main.py b/litellm/main.pyindex 356ca7ecf13..52e7475169e 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -159,6 +159,7 @@ from .litellm_core_utils.fallback_utils import (completion_with_fallbacks,)from .litellm_core_utils.prompt_templates.common_utils import (+ add_system_prompt_to_messages,get_completion_messages,update_messages_with_model_file_ids,)@@ -599,7 +600,7 @@ async def acompletion( # noqa: PLR0915# Add the context to the functionctx = contextvars.copy_context()func_with_context = partial(ctx.run, func)-+init_response = await loop.run_in_executor(None, func_with_context)if isinstance(init_response, dict) or isinstance(init_response, ModelResponse@@ -939,7 +940,7 @@ def responses_api_bridge_check(model = model.replace("responses/", "")mode = "responses"model_info["mode"] = mode-+if web_search_options is not None and custom_llm_provider == "xai":model_info["mode"] = "responses"model = model.replace("responses/", "")@@ -1108,9 +1109,7 @@ def completion( # type: ignore # noqa: PLR0915skip_mcp_handler = kwargs.pop("_skip_mcp_handler", False)if not skip_mcp_handler and tools:- from litellm.responses.mcp.chat_completions_handler import (- acompletion_with_mcp,- )+ from litellm.responses.mcp.chat_completions_handler import acompletion_with_mcpfrom litellm.responses.mcp.litellm_proxy_mcp_handler import (LiteLLM_Proxy_MCP_Handler,)@@ -1245,6 +1244,7 @@ def completion( # type: ignore # noqa: PLR0915### PROMPT MANAGEMENT ###prompt_id = cast(Optional[str], kwargs.get("prompt_id", None))prompt_variables = cast(Optional[dict], kwargs.get("prompt_variables", None))+ litellm_system_prompt = kwargs.get("litellm_system_prompt", None)### COPY MESSAGES ### - related issue https://github.com/BerriAI/litellm/discussions/4489messages = get_completion_messages(messages=messages,@@ -1276,6 +1276,14 @@ def completion( # type: ignore # noqa: PLR0915prompt_version=kwargs.get("prompt_version", None),)+ ### LITELLM SYSTEM PROMPT ###+ if litellm_system_prompt:+ messages = add_system_prompt_to_messages(+ messages=messages,+ system_prompt=litellm_system_prompt,+ merge_with_first_system=True,+ )+try:if base_url is not None:api_base = base_url@@ -1558,7 +1566,9 @@ def completion( # type: ignore # noqa: PLR0915## RESPONSES API BRIDGE LOGIC ## - check if model has 'mode: responses' in litellm.model_cost mapmodel_info, model = responses_api_bridge_check(- model=model, custom_llm_provider=custom_llm_provider, web_search_options=web_search_options+ model=model,+ custom_llm_provider=custom_llm_provider,+ web_search_options=web_search_options,)if model_info.get("mode") == "responses":@@ -2209,17 +2219,19 @@ def completion( # type: ignore # noqa: PLR0915elif custom_llm_provider == "a2a":# A2A (Agent-to-Agent) Protocol# Resolve agent configuration from registry if model format is "a2a/<agent-name>"- api_base, api_key, headers = litellm.A2AConfig.resolve_agent_config_from_registry(- model=model,- api_base=api_base,- api_key=api_key,- headers=headers,- optional_params=optional_params,+ api_base, api_key, headers = (+ litellm.A2AConfig.resolve_agent_config_from_registry(+ model=model,+ api_base=api_base,+ api_key=api_key,+ headers=headers,+ optional_params=optional_params,+ ))-+# Fall back to environment variables and defaultsapi_base = api_base or litellm.api_base or get_secret_str("A2A_API_BASE")-+if api_base is None:raise Exception("api_base is required for A2A provider. "@@ -4783,7 +4795,10 @@ def embedding( # noqa: PLR0915or custom_llm_provider == "together_ai"or custom_llm_provider == "nvidia_nim"or custom_llm_provider == "litellm_proxy"- or (model in litellm.open_ai_embedding_models and custom_llm_provider is None)+ or (+ model in litellm.open_ai_embedding_models+ and custom_llm_provider is None+ )):api_base = (api_base@@ -7239,7 +7254,11 @@ def stream_chunk_builder( # noqa: PLR0915continuechoice = chunk["choices"][0]- delta_obj = choice.get("delta", {}) if isinstance(choice, dict) else getattr(choice, "delta", {})+ delta_obj = (+ choice.get("delta", {})+ if isinstance(choice, dict)+ else getattr(choice, "delta", {})+ )if isinstance(delta_obj, dict):delta = delta_objelif hasattr(delta_obj, "model_dump"):@@ -7266,7 +7285,9 @@ def stream_chunk_builder( # noqa: PLR0915if is_simple_text_stream:if simple_content_parts:- response["choices"][0]["message"]["content"] = "".join(simple_content_parts)+ response["choices"][0]["message"]["content"] = "".join(+ simple_content_parts+ )completion_output = get_content_from_model_response(response)usage = processor.calculate_usage(chunks=chunks,@@ -7291,7 +7312,9 @@ def stream_chunk_builder( # noqa: PLR0915if litellm.include_cost_in_streaming_usage and logging_obj is not None:setattr(- usage, "cost", logging_obj._response_cost_calculator(result=response)+ usage,+ "cost",+ logging_obj._response_cost_calculator(result=response),)return response@@ -7504,6 +7527,7 @@ def __getattr__(name: str) -> Any:# before loading tiktoken, ensuring the local cache is used# instead of downloading from the internetfrom litellm._lazy_imports import _get_default_encoding+_encoding = _get_default_encoding()# Cache it in the module's __dict__ for subsequent accessesimport sysdiff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex c4b6a4fa099..813a4fb3a6e 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -16,6 +16,10 @@ model_list:- model_name: gpt-5-minilitellm_params:model: openai/gpt-5-mini+ - model_name: custom_litellm_model+ litellm_params:+ model: litellm_agent/claude-sonnet-4-5-20250929+ litellm_system_prompt: "Be a helpful assistant."guardrails:diff --git a/litellm/router.py b/litellm/router.pyindex c6409ce1680..ac2862da689 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -163,11 +163,7 @@ from litellm.types.utils import ()from litellm.types.utils import ModelInfofrom litellm.types.utils import ModelInfo as ModelMapInfo-from litellm.types.utils import (- ModelResponseStream,- StandardLoggingPayload,- Usage,-)+from litellm.types.utils import ModelResponseStream, StandardLoggingPayload, Usagefrom litellm.utils import (CustomStreamWrapper,EmbeddingResponse,@@ -1996,12 +1992,11 @@ class Router:When both have tools, concatenate them (deployment tools first, then request tools).tool_choice: use request value if provided, else deployment's."""- dep_params = deployment.get("litellm_params", {}) or {}- dep_params = (- dep_params.model_dump(exclude_none=True)- if hasattr(dep_params, "model_dump")- else dep_params- )+ dep_params_raw = deployment.get("litellm_params", {}) or {}+ if isinstance(dep_params_raw, dict):+ dep_params = dep_params_raw+ else:+ dep_params = dep_params_raw.model_dump(exclude_none=True)dep_tools = dep_params.get("tools") or []req_tools = kwargs.get("tools") or []if dep_tools or req_tools:@@ -2573,6 +2568,12 @@ class Router:litellm_model = data.get("model", None)+ # litellm_agent/ prefix only strips the model name, no prompt_id needed+ is_litellm_agent_model = (+ isinstance(litellm_model, str)+ and litellm_model.startswith("litellm_agent/")+ )+prompt_id = kwargs.get("prompt_id") or prompt_management_deployment["litellm_params"].get("prompt_id", None)@@ -2585,7 +2586,9 @@ class Router:"litellm_params"].get("prompt_label", None)- if prompt_id is None or not isinstance(prompt_id, str):+ if not is_litellm_agent_model and (+ prompt_id is None or not isinstance(prompt_id, str)+ ):raise ValueError(f"Prompt ID is not set or not a string. Got={prompt_id}, type={type(prompt_id)}")diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 9228b25b03e..ac795ba57cb 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -2917,8 +2917,9 @@ all_litellm_params = ("api_key","api_version","prompt_id",- "provider_specific_header","prompt_variables",+ "litellm_system_prompt",+ "provider_specific_header","prompt_version","api_base","force_timeout",diff --git a/tests/test_litellm/integrations/litellm_agent/test_litellm_agent_model_resolver.py b/tests/test_litellm/integrations/litellm_agent/test_litellm_agent_model_resolver.pynew file mode 100644index 00000000000..c91da9a4b89--- /dev/null+++ b/tests/test_litellm/integrations/litellm_agent/test_litellm_agent_model_resolver.py@@ -0,0 +1,81 @@+"""Unit tests for LiteLLMAgentModelResolver - litellm_agent/ prefix model resolution."""++from unittest.mock import MagicMock++import pytest++from litellm.integrations.litellm_agent import LiteLLMAgentModelResolver+++class TestLiteLLMAgentModelResolver:+ def test_get_chat_completion_prompt_strips_prefix(self):+ """Verify get_chat_completion_prompt strips litellm_agent/ prefix from model."""+ resolver = LiteLLMAgentModelResolver()+ messages = [{"role": "user", "content": "Hello"}]++ resolved_model, out_messages, out_params = resolver.get_chat_completion_prompt(+ model="litellm_agent/gpt-3.5-turbo",+ messages=messages,+ non_default_params={},+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ )++ assert resolved_model == "gpt-3.5-turbo"+ assert out_messages == messages+ assert out_params == {}++ def test_get_chat_completion_prompt_preserves_rest_of_model(self):+ """Verify model name after prefix is preserved (e.g. openai/gpt-3.5-turbo)."""+ resolver = LiteLLMAgentModelResolver()+ messages = [{"role": "user", "content": "Test"}]++ resolved_model, _, _ = resolver.get_chat_completion_prompt(+ model="litellm_agent/openai/gpt-3.5-turbo",+ messages=messages,+ non_default_params={},+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ )++ assert resolved_model == "openai/gpt-3.5-turbo"++ def test_get_chat_completion_prompt_respects_ignore_prompt_manager_model(self):+ """Verify model is unchanged when ignore_prompt_manager_model is True."""+ resolver = LiteLLMAgentModelResolver()+ messages = [{"role": "user", "content": "Hello"}]++ resolved_model, _, _ = resolver.get_chat_completion_prompt(+ model="litellm_agent/gpt-3.5-turbo",+ messages=messages,+ non_default_params={},+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ ignore_prompt_manager_model=True,+ )++ assert resolved_model == "litellm_agent/gpt-3.5-turbo"++ @pytest.mark.asyncio+ async def test_async_get_chat_completion_prompt_strips_prefix(self):+ """Verify async_get_chat_completion_prompt strips prefix."""+ resolver = LiteLLMAgentModelResolver()+ messages = [{"role": "user", "content": "Hello"}]++ resolved_model, out_messages, _ = (+ await resolver.async_get_chat_completion_prompt(+ model="litellm_agent/gpt-3.5-turbo",+ messages=messages,+ non_default_params={},+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ litellm_logging_obj=MagicMock(),+ )+ )++ assert resolved_model == "gpt-3.5-turbo"+ assert out_messages == messagesdiff --git a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.pyindex f566f91841d..81fe56640b8 100644--- a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py+++ b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py@@ -10,6 +10,7 @@ sys.path.insert() # Adds the parent directory to the system pathfrom litellm.litellm_core_utils.prompt_templates.common_utils import (+ add_system_prompt_to_messages,get_format_from_file_id,handle_any_messages_to_chat_completion_str_messages_conversion,split_concatenated_json_objects,@@ -128,6 +129,60 @@ def test_handle_any_messages_to_chat_completion_str_messages_conversion_complex(assert result[0]["input"] == json.dumps(message)+def test_add_system_prompt_to_messages_prepend():+ """Adds system prompt at beginning when no system message exists."""+ messages = [+ {"role": "user", "content": "Hello"},+ {"role": "assistant", "content": "Hi there"},+ ]+ result = add_system_prompt_to_messages(messages, "You are a helpful assistant.")+ assert result == [+ {"role": "system", "content": "You are a helpful assistant."},+ {"role": "user", "content": "Hello"},+ {"role": "assistant", "content": "Hi there"},+ ]+++def test_add_system_prompt_to_messages_empty_prompt_unchanged():+ """Returns messages unchanged when system_prompt is empty."""+ messages = [{"role": "user", "content": "Hello"}]+ assert add_system_prompt_to_messages(messages, "") == messages+ assert add_system_prompt_to_messages(messages, None) == messages+++def test_add_system_prompt_to_messages_merge_with_first_system():+ """Merges new prompt into first system message when merge_with_first_system=True."""+ messages = [+ {"role": "system", "content": "Existing system prompt."},+ {"role": "user", "content": "Hello"},+ ]+ result = add_system_prompt_to_messages(+ messages, "You are helpful.", merge_with_first_system=True+ )+ assert result == [+ {"role": "system", "content": "You are helpful.\n\nExisting system prompt."},+ {"role": "user", "content": "Hello"},+ ]+++def test_add_system_prompt_to_messages_merge_with_first_system_adds_new_when_no_system():+ """When merge_with_first_system=True but no system message, adds new one at start."""+ messages = [{"role": "user", "content": "Hello"}]+ result = add_system_prompt_to_messages(+ messages, "You are helpful.", merge_with_first_system=True+ )+ assert result == [+ {"role": "system", "content": "You are helpful."},+ {"role": "user", "content": "Hello"},+ ]+++def test_add_system_prompt_to_messages_empty_list():+ """Adds system prompt to empty messages list."""+ result = add_system_prompt_to_messages([], "You are helpful.")+ assert result == [{"role": "system", "content": "You are helpful."}]++def test_convert_prefix_message_to_non_prefix_messages():from litellm.litellm_core_utils.prompt_templates.common_utils import (convert_prefix_message_to_non_prefix_messages,diff --git a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.pyindex 5d7a02f90d8..40ecfdd3050 100644--- a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py+++ b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py@@ -2924,3 +2924,23 @@ def test_fast_mode_parameter_mapping():assert "speed" in resultassert result["speed"] == "fast"+++def test_map_openai_params_max_tokens_normalized_to_int():+ """+ Test that map_openai_params normalizes max_tokens to an integer (e.g. 0.7 -> 1).+ """+ config = AnthropicConfig()++ non_default_params = {"max_tokens": 0.7}+ optional_params = {}++ result = config.map_openai_params(+ non_default_params=non_default_params,+ optional_params=optional_params,+ model="claude-3-5-sonnet-20241022",+ drop_params=False,+ )++ assert "max_tokens" in result+ assert result["max_tokens"] == 1diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/page.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/page.tsxindex 375529f5175..555930a576c 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/page.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/page.tsx@@ -1,6 +1,7 @@"use client";import { useState, useEffect } from "react";+import AgentBuilderView from "@/components/playground/chat_ui/AgentBuilderView";import ChatUI from "@/components/playground/chat_ui/ChatUI";import CompareUI from "@/components/playground/compareUI/CompareUI";import ComplianceUI from "@/components/playground/complianceUI/ComplianceUI";@@ -39,6 +40,7 @@ export default function PlaygroundPage() {<Tab>Chat</Tab><Tab>Compare</Tab><Tab>Compliance</Tab>+ <Tab>Agent Builder (Experimental)</Tab></TabList><TabPanels className="h-full"><TabPanel className="h-full">@@ -57,6 +59,17 @@ export default function PlaygroundPage() {<TabPanel className="h-full"><ComplianceUI accessToken={accessToken} disabledPersonalKeyCreation={disabledPersonalKeyCreation} /></TabPanel>+ <TabPanel className="h-full">+ <AgentBuilderView+ accessToken={accessToken}+ token={token}+ userID={userId}+ userRole={userRole}+ disabledPersonalKeyCreation={disabledPersonalKeyCreation}+ proxySettings={proxySettings}+ customProxyBaseUrl={proxySettings?.LITELLM_UI_API_DOC_BASE_URL ?? proxySettings?.PROXY_BASE_URL}+ />+ </TabPanel></TabPanels></TabGroup>);diff --git a/ui/litellm-dashboard/src/components/playground/chat_ui/AgentBuilderView.tsx b/ui/litellm-dashboard/src/components/playground/chat_ui/AgentBuilderView.tsxnew file mode 100644index 00000000000..10719b7ff4f--- /dev/null+++ b/ui/litellm-dashboard/src/components/playground/chat_ui/AgentBuilderView.tsx@@ -0,0 +1,379 @@+"use client";++import { CommentOutlined, ExperimentOutlined, PlusOutlined, RobotOutlined, SaveOutlined } from "@ant-design/icons";+import { Button, Input, Select, Spin, Tabs } from "antd";+import React, { useCallback, useEffect, useState } from "react";+import NotificationsManager from "../../molecules/notifications_manager";+import { modelCreateCall } from "../../networking";+import { AgentModel, fetchAvailableAgentModels } from "../llm_calls/fetch_agents";+import { fetchAvailableModels, ModelGroup } from "../llm_calls/fetch_models";+import ComplianceUI from "../complianceUI/ComplianceUI";+import ChatUI from "./ChatUI";++const { TextArea } = Input;++export interface AgentBuilderViewProps {+ accessToken: string | null;+ token: string | null;+ userID: string | null;+ userRole: string | null;+ disabledPersonalKeyCreation?: boolean;+ proxySettings?: {+ PROXY_BASE_URL?: string;+ LITELLM_UI_API_DOC_BASE_URL?: string | null;+ };+ apiKey?: string;+ customProxyBaseUrl?: string;+}++const NEW_AGENT_ID = "__new__";++export default function AgentBuilderView({+ accessToken,+ token,+ userID,+ userRole,+ disabledPersonalKeyCreation = false,+ proxySettings,+ apiKey,+ customProxyBaseUrl,+}: AgentBuilderViewProps) {+ const [agentModels, setAgentModels] = useState<AgentModel[]>([]);+ const [modelGroups, setModelGroups] = useState<ModelGroup[]>([]);+ const [loadingAgents, setLoadingAgents] = useState(true);+ const [selectedId, setSelectedId] = useState<string | null>(null);+ const [activeTab, setActiveTab] = useState<"configure" | "chat" | "test">("configure");++ // Draft for new agent+ const [draftName, setDraftName] = useState("");+ const [draftSystemPrompt, setDraftSystemPrompt] = useState("");+ const [draftUnderlyingModel, setDraftUnderlyingModel] = useState<string | undefined>(undefined);+ const [draftTemperature, setDraftTemperature] = useState(0.7);+ const [draftMaxTokens, setDraftMaxTokens] = useState(4096);++ const [saving, setSaving] = useState(false);++ const effectiveApiKey = apiKey || accessToken || "";+ const selectedAgent = selectedId === NEW_AGENT_ID ? null : agentModels.find((a) => a.model_name === selectedId) ?? null;+ const isNewAgent = selectedId === NEW_AGENT_ID;++ const loadAgents = useCallback(async () => {+ if (!accessToken || !userID || !userRole) return;+ setLoadingAgents(true);+ try {+ const list = await fetchAvailableAgentModels(accessToken, userID, userRole);+ setAgentModels(list);+ if (!selectedId || (selectedId !== NEW_AGENT_ID && !list.some((a) => a.model_name === selectedId))) {+ setSelectedId(list.length > 0 ? list[0].model_name : null);+ }+ } catch (e) {+ console.error(e);+ NotificationsManager.fromBackend("Failed to load agents");+ } finally {+ setLoadingAgents(false);+ }+ }, [accessToken, userID, userRole]);++ const loadModels = useCallback(async () => {+ if (!effectiveApiKey) return;+ try {+ const models = await fetchAvailableModels(effectiveApiKey);+ setModelGroups(models);+ if (!draftUnderlyingModel && models.length > 0) {+ setDraftUnderlyingModel(models[0].model_group);+ }+ } catch (e) {+ console.error(e);+ }+ }, [effectiveApiKey]);++ useEffect(() => {+ loadAgents();+ }, [loadAgents]);++ useEffect(() => {+ loadModels();+ }, [loadModels]);++ const handleAddAgent = () => {+ setSelectedId(NEW_AGENT_ID);+ setDraftName("");+ setDraftSystemPrompt("You are a helpful assistant.");+ setDraftUnderlyingModel(modelGroups[0]?.model_group);+ setDraftTemperature(0.7);+ setDraftMaxTokens(4096);+ setActiveTab("configure");+ };++ const handleSaveAgent = async () => {+ if (!accessToken || !draftName?.trim() || !draftUnderlyingModel) {+ NotificationsManager.fromBackend("Name and underlying model are required");+ return;+ }+ setSaving(true);+ try {+ await modelCreateCall(accessToken, {+ model_name: draftName.trim(),+ litellm_params: {+ model: `litellm_agent/${draftUnderlyingModel}`,+ litellm_system_prompt: draftSystemPrompt.trim() || undefined,+ temperature: draftTemperature,+ max_tokens: draftMaxTokens,+ },+ model_info: {},+ });+ const newName = draftName.trim();+ await loadAgents();+ setSelectedId(newName);+ setActiveTab("chat");+ } catch (e) {+ NotificationsManager.fromBackend("Failed to save agent");+ } finally {+ setSaving(false);+ }+ };++ if (!accessToken || !userID || !userRole) {+ return (+ <div className="flex h-full items-center justify-center p-8 text-gray-500">+ Sign in to use Agent Builder.+ </div>+ );+ }++ return (+ <div className="flex h-full flex-col bg-white text-gray-900">+ <div className="flex flex-shrink-0 flex-col border-b border-gray-200">+ <div className="flex h-12 items-center justify-between px-4">+ <span className="text-sm font-medium text-gray-900">Agent Builder</span>+ {isNewAgent ? (+ <Button+ type="primary"+ icon={<SaveOutlined />}+ onClick={handleSaveAgent}+ loading={saving}+ disabled={!draftName?.trim() || !draftUnderlyingModel}+ >+ Save Agent+ </Button>+ ) : (+ <span className="text-xs text-gray-500">Build Agents that pass your compliance requirements.</span>+ )}+ </div>+ <div className="flex items-center gap-2 border-t border-amber-200 bg-amber-50 px-4 py-2 text-xs text-amber-800">+ <ExperimentOutlined className="flex-shrink-0 text-amber-600" />+ <span>+ Agent Builder is experimental and may change or be removed without notice.+ </span>+ </div>+ </div>++ <div className="flex flex-1 overflow-hidden">+ {/* Roster */}+ <div className="w-60 flex-shrink-0 border-r border-gray-200 bg-white flex flex-col">+ <div className="flex items-center justify-between border-b border-gray-200 p-3">+ <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">Agents</span>+ <Button type="text" size="small" icon={<PlusOutlined />} onClick={handleAddAgent} aria-label="Add agent" />+ </div>+ <div className="flex-1 overflow-y-auto p-2">+ {loadingAgents ? (+ <div className="flex justify-center py-4">+ <Spin size="small" />+ </div>+ ) : (+ <>+ {agentModels.map((agent) => (+ <button+ key={agent.model_name}+ type="button"+ onClick={() => setSelectedId(agent.model_name)}+ className={`mb-1 w-full rounded-md border-l-2 px-3 py-2 text-left text-sm transition-colors ${+ selectedId === agent.model_name+ ? "border-blue-500 bg-blue-50 text-blue-800"+ : "border-transparent hover:bg-gray-50"+ }`}+ >+ <div className="font-medium truncate">{agent.model_name}</div>+ <div className="text-[10px] text-gray-500 truncate">litellm_agent</div>+ </button>+ ))}+ <button+ type="button"+ onClick={handleAddAgent}+ className="mb-1 w-full rounded-md border border-dashed border-gray-300 px-3 py-2 text-left text-sm text-gray-500 hover:border-blue-400 hover:bg-blue-50/50 hover:text-gray-700"+ >+ <PlusOutlined className="mr-1" /> New agent+ </button>+ </>+ )}+ </div>+ </div>++ {/* Main content */}+ <div className="flex flex-1 flex-col overflow-hidden">+ {selectedId === null && !isNewAgent && agentModels.length === 0 && !loadingAgents && (+ <div className="flex flex-1 items-center justify-center p-8 text-gray-500">+ No agents yet. Add an agent to get started.+ </div>+ )}+ {(selectedId !== null || isNewAgent) && (+ <>+ <Tabs+ activeKey={activeTab}+ onChange={(k) => setActiveTab(k as "configure" | "chat" | "test")}+ className="flex-1 overflow-hidden [&_.ant-tabs-content]:h-full [&_.ant-tabs-tabpane]:h-full [&_.ant-tabs-nav]:pl-4"+ items={[+ {+ key: "configure",+ label: (+ <span>+ <RobotOutlined className="mr-1" /> Configure+ </span>+ ),+ children: (+ <div className="h-full overflow-y-auto p-6">+ {isNewAgent ? (+ <div className="mx-auto max-w-xl space-y-4">+ <div>+ <label className="mb-1 block text-sm font-medium text-gray-700">Agent name</label>+ <Input+ value={draftName}+ onChange={(e) => setDraftName(e.target.value)}+ placeholder="My Agent"+ />+ </div>+ <div>+ <label className="mb-1 block text-sm font-medium text-gray-700">System prompt</label>+ <TextArea+ value={draftSystemPrompt}+ onChange={(e) => setDraftSystemPrompt(e.target.value)}+ placeholder="You are a helpful assistant..."+ rows={6}+ />+ </div>+ <div>+ <label className="mb-1 block text-sm font-medium text-gray-700">Underlying LLM</label>+ <Select+ value={draftUnderlyingModel}+ onChange={setDraftUnderlyingModel}+ className="w-full"+ options={modelGroups.map((m) => ({ value: m.model_group, label: m.model_group }))}+ placeholder="Select model"+ />+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div>+ <label className="mb-1 block text-sm font-medium text-gray-700">Temperature</label>+ <Input+ type="number"+ min={0}+ max={2}+ step={0.1}+ value={draftTemperature}+ onChange={(e) => setDraftTemperature(Number(e.target.value))}+ />+ </div>+ <div>+ <label className="mb-1 block text-sm font-medium text-gray-700">Max tokens</label>+ <Input+ type="number"+ min={1}+ value={draftMaxTokens}+ onChange={(e) => setDraftMaxTokens(Number(e.target.value))}+ />+ </div>+ </div>+ </div>+ ) : selectedAgent ? (+ <div className="mx-auto max-w-xl space-y-4">+ <div>+ <label className="mb-1 block text-sm font-medium text-gray-700">Name</label>+ <div className="rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm">+ {selectedAgent.model_name}+ </div>+ </div>+ <div>+ <label className="mb-1 block text-sm font-medium text-gray-700">System prompt</label>+ <div className="rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm whitespace-pre-wrap">+ {selectedAgent.litellm_params?.litellm_system_prompt || "(none)"}+ </div>+ </div>+ <div>+ <label className="mb-1 block text-sm font-medium text-gray-700">Underlying model</label>+ <div className="rounded border border-gray-200 bg-gray-50 px-3 py-2 text-sm font-mono">+ {selectedAgent.litellm_params?.model ?? ""}+ </div>+ </div>+ <Button type="primary" icon={<CommentOutlined />} onClick={() => setActiveTab("chat")}>+ Test in Chat+ </Button>+ </div>+ ) : null}+ </div>+ ),+ },+ {+ key: "chat",+ label: (+ <span>+ <CommentOutlined className="mr-1" /> Chat+ </span>+ ),+ disabled: isNewAgent,+ children: (+ <div className="flex h-full flex-col min-h-0">+ {selectedAgent ? (+ <ChatUI+ key={selectedAgent.model_name}+ simplified+ fixedModel={selectedAgent.model_name}+ accessToken={accessToken}+ token={token}+ userRole={userRole}+ userID={userID}+ disabledPersonalKeyCreation={disabledPersonalKeyCreation}+ proxySettings={proxySettings}+ />+ ) : (+ <div className="flex flex-1 items-center justify-center text-gray-500">+ Save an agent first to test in Chat.+ </div>+ )}+ </div>+ ),+ },+ {+ key: "test",+ label: (+ <span>+ <ExperimentOutlined className="mr-1" /> Batch Test+ </span>+ ),+ disabled: isNewAgent,+ children: (+ <div className="flex h-full flex-col min-h-0">+ {selectedAgent ? (+ <ComplianceUI+ accessToken={accessToken}+ disabledPersonalKeyCreation={disabledPersonalKeyCreation}+ backendMode="chat_completions"+ fixedModel={selectedAgent.model_name}+ proxySettings={proxySettings}+ />+ ) : (+ <div className="flex flex-1 items-center justify-center text-gray-500">+ Select an agent to run batch tests.+ </div>+ )}+ </div>+ ),+ },+ ]}+ />+ </>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx b/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsxindex 7e50ca6b95a..4a47cc00b20 100644--- a/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx+++ b/ui/litellm-dashboard/src/components/playground/chat_ui/ChatUI.tsx@@ -84,6 +84,10 @@ interface ChatUIProps {PROXY_BASE_URL?: string;LITELLM_UI_API_DOC_BASE_URL?: string | null;};+ /** When true, hide configuration sidebar and use fixedModel only (e.g. embedded in Agent Builder). */+ simplified?: boolean;+ /** When simplified is true, use this as the model and do not show model selector. */+ fixedModel?: string;}const MCP_SUPPORTED_ENDPOINTS = new Set<EndpointType>([@@ -99,6 +103,8 @@ const ChatUI: React.FC<ChatUIProps> = ({userID,disabledPersonalKeyCreation,proxySettings,+ simplified = false,+ fixedModel,}) => {const [mcpServers, setMCPServers] = useState<MCPServer[]>([]);const [selectedMCPServers, setSelectedMCPServers] = useState<string[]>(() => {@@ -140,6 +146,7 @@ const ChatUI: React.FC<ChatUIProps> = ({);const [inputMessage, setInputMessage] = useState("");const [chatHistory, setChatHistory] = useState<MessageType[]>(() => {+ if (simplified) return [];try {const saved = sessionStorage.getItem("chatHistory");return saved ? JSON.parse(saved) : [];@@ -148,7 +155,7 @@ const ChatUI: React.FC<ChatUIProps> = ({return [];}});- const [selectedModel, setSelectedModel] = useState<string | undefined>(undefined);+ const [selectedModel, setSelectedModel] = useState<string | undefined>(simplified ? fixedModel : undefined);const [showCustomModelInput, setShowCustomModelInput] = useState<boolean>(false);const [modelInfo, setModelInfo] = useState<ModelGroup[]>([]);const [agentInfo, setAgentInfo] = useState<Agent[]>([]);@@ -252,6 +259,14 @@ const ChatUI: React.FC<ChatUIProps> = ({}};+ // When simplified, keep selectedModel and endpointType in sync with fixedModel / chat-only+ useEffect(() => {+ if (simplified && fixedModel) {+ setSelectedModel(fixedModel);+ setEndpointType(EndpointType.CHAT);+ }+ }, [simplified, fixedModel]);+// Fetch tools for a specific serverconst loadServerTools = async (serverId: string) => {const userApiKey = apiKeySource === "session" ? accessToken : apiKey;@@ -312,6 +327,7 @@ const ChatUI: React.FC<ChatUIProps> = ({]);useEffect(() => {+ if (simplified) return; // Do not persist chat history in simplified (embedded) modeconst handler = setTimeout(() => {sessionStorage.setItem("chatHistory", JSON.stringify(chatHistory));}, 500); // Debounce by 500ms@@ -319,7 +335,7 @@ const ChatUI: React.FC<ChatUIProps> = ({return () => {clearTimeout(handler);};- }, [chatHistory]);+ }, [chatHistory, simplified]);useEffect(() => {sessionStorage.setItem("apiKeySource", JSON.stringify(apiKeySource));@@ -334,10 +350,12 @@ const ChatUI: React.FC<ChatUIProps> = ({sessionStorage.setItem("selectedVoice", selectedVoice);sessionStorage.removeItem("selectedMCPTools"); // Clean up old key- if (selectedModel) {- sessionStorage.setItem("selectedModel", selectedModel);- } else {- sessionStorage.removeItem("selectedModel");+ if (!simplified) {+ if (selectedModel) {+ sessionStorage.setItem("selectedModel", selectedModel);+ } else {+ sessionStorage.removeItem("selectedModel");+ }}if (messageTraceId) {sessionStorage.setItem("messageTraceId", messageTraceId);@@ -352,6 +370,7 @@ const ChatUI: React.FC<ChatUIProps> = ({sessionStorage.setItem("useApiSessionManagement", JSON.stringify(useApiSessionManagement));// Note: codeInterpreterEnabled and selectedContainerId are persisted by useCodeInterpreter hook}, [+ simplified,apiKeySource,apiKey,selectedModel,@@ -375,7 +394,7 @@ const ChatUI: React.FC<ChatUIProps> = ({return;}- // Fetch model info and set the default selected model+ // Fetch model info and set the default selected model (skip in simplified mode; we use fixedModel)const loadModels = async () => {try {if (!userApiKey) {@@ -400,9 +419,11 @@ const ChatUI: React.FC<ChatUIProps> = ({}};- loadModels();+ if (!simplified) {+ loadModels();+ }loadMCPServers();- }, [accessToken, userID, userRole, apiKeySource, apiKey, token]);+ }, [accessToken, userID, userRole, apiKeySource, apiKey, token, simplified]);// Load tools when MCP direct mode has a server selecteduseEffect(() => {@@ -868,7 +889,7 @@ const ChatUI: React.FC<ChatUIProps> = ({return;}- const effectiveApiKey = apiKeySource === "session" ? accessToken : apiKey;+ const effectiveApiKey = simplified ? accessToken : apiKeySource === "session" ? accessToken : apiKey;if (!effectiveApiKey) {NotificationsManager.fromBackend("Please provide a Virtual Key or select Current UI Session");@@ -959,6 +980,10 @@ const ChatUI: React.FC<ChatUIProps> = ({newUserMessage,];+ const requestProxyBaseUrl =+ simplified && proxySettings+ ? (proxySettings.LITELLM_UI_API_DOC_BASE_URL ?? proxySettings.PROXY_BASE_URL ?? undefined)+ : (customProxyBaseUrl || undefined);await makeOpenAIChatCompletionRequest(apiChatHistory,(chunk, model) => updateTextUI("assistant", chunk, model),@@ -979,7 +1004,7 @@ const ChatUI: React.FC<ChatUIProps> = ({useAdvancedParams ? temperature : undefined,useAdvancedParams ? maxTokens : undefined,updateTotalLatency,- customProxyBaseUrl || undefined,+ requestProxyBaseUrl,mcpServers,mcpServerToolRestrictions,handleMCPEvent,@@ -1207,9 +1232,11 @@ const ChatUI: React.FC<ChatUIProps> = ({handleRemoveResponsesImage(); // Clear any uploaded images for responseshandleRemoveChatImage(); // Clear any uploaded images for chat completionshandleRemoveAudio(); // Clear any uploaded audio for transcription- sessionStorage.removeItem("chatHistory");- sessionStorage.removeItem("messageTraceId");- sessionStorage.removeItem("responsesSessionId");+ if (!simplified) {+ sessionStorage.removeItem("chatHistory");+ sessionStorage.removeItem("messageTraceId");+ sessionStorage.removeItem("responsesSessionId");+ }NotificationsManager.success("Chat history cleared.");};@@ -1246,10 +1273,11 @@ const ChatUI: React.FC<ChatUIProps> = ({const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;return (- <div className="w-full p-4 pb-0 bg-white">- <Card className="w-full rounded-xl shadow-md overflow-hidden">- <div className="flex h-[80vh] w-full gap-4">- {/* Left Sidebar with Controls */}+ <div className={`w-full bg-white ${simplified ? "h-full flex flex-col" : "p-4 pb-0"}`}>+ <Card className={`w-full rounded-xl shadow-md overflow-hidden ${simplified ? "h-full flex flex-col" : ""}`}>+ <div className={`flex w-full gap-4 ${simplified ? "h-full" : "h-[80vh]"}`}>+ {/* Left Sidebar with Controls - hidden in simplified mode */}+ {!simplified && (<div className="w-1/4 p-4 bg-gray-50 overflow-y-auto"><Title className="text-xl font-semibold mb-6 mt-2">Configurations</Title><div className="space-y-4">@@ -1794,11 +1822,12 @@ const ChatUI: React.FC<ChatUIProps> = ({)}</div></div>+ )}{/* Main Chat Area */}- <div className="w-3/4 flex flex-col bg-white">+ <div className={`flex flex-col bg-white ${simplified ? "flex-1 w-full" : "w-3/4"}`}><div className="p-4 border-b border-gray-200 flex justify-between items-center">- <Title className="text-xl font-semibold mb-0">Test Key</Title>+ <Title className="text-xl font-semibold mb-0">{simplified ? "Chat" : "Test Key"}</Title><div className="flex gap-2"><TremorButtononClick={clearChatHistory}@@ -1807,6 +1836,7 @@ const ChatUI: React.FC<ChatUIProps> = ({>Clear Chat</TremorButton>+ {!simplified && (<TremorButtononClick={() => setIsGetCodeModalVisible(true)}className="bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300"@@ -1814,6 +1844,7 @@ const ChatUI: React.FC<ChatUIProps> = ({>Get Code</TremorButton>+ )}</div></div><div className="flex-1 overflow-auto p-4 pb-0">diff --git a/ui/litellm-dashboard/src/components/playground/complianceUI/ComplianceUI.tsx b/ui/litellm-dashboard/src/components/playground/complianceUI/ComplianceUI.tsxindex efc5fb2ee42..7bec4b4534e 100644--- a/ui/litellm-dashboard/src/components/playground/complianceUI/ComplianceUI.tsx+++ b/ui/litellm-dashboard/src/components/playground/complianceUI/ComplianceUI.tsx@@ -11,6 +11,7 @@ import {getPoliciesList,testPoliciesAndGuardrails,} from "@/components/networking";+import { makeOpenAIChatCompletionRequest } from "../llm_calls/chat_completion";import {AlertTriangle,BarChart3,@@ -110,11 +111,23 @@ interface GuardrailOption {interface ComplianceUIProps {accessToken: string | null;disabledPersonalKeyCreation?: boolean;+ /** When "chat_completions", use /chat/completions with fixedModel instead of test_policies_and_guardrails. */+ backendMode?: "policies" | "chat_completions";+ /** Required when backendMode is "chat_completions"; model name for chat completions (e.g. selected agent). */+ fixedModel?: string;+ /** Used when backendMode is "chat_completions" for the request base URL. */+ proxySettings?: {+ PROXY_BASE_URL?: string;+ LITELLM_UI_API_DOC_BASE_URL?: string | null;+ };}export default function ComplianceUI({accessToken,disabledPersonalKeyCreation,+ backendMode = "policies",+ fixedModel,+ proxySettings,}: ComplianceUIProps) {const frameworks = getFrameworks();@@ -432,6 +445,9 @@ export default function ComplianceUI({if (csvInputRef.current) csvInputRef.current.value = "";};+ const requestProxyBaseUrl =+ proxySettings?.LITELLM_UI_API_DOC_BASE_URL ?? proxySettings?.PROXY_BASE_URL ?? undefined;+const runQuickTest = useCallback(async () => {if (!quickTestInput.trim() || !accessToken) return;const text = quickTestInput.trim();@@ -445,44 +461,82 @@ export default function ComplianceUI({setQuickTestInput("");setIsQuickTesting(true);try {- const { inputs, guardrail_errors = [] } = await testPoliciesAndGuardrails(- accessToken,- {- policy_names:- selectedPolicies.length > 0 ? selectedPolicies : undefined,- guardrail_names:- selectedGuardrails.length > 0 ? selectedGuardrails : undefined,- inputs: { texts: [text] },- request_data: {},- input_type: "request",- }- );- const result: "blocked" | "allowed" =- guardrail_errors.length > 0 ? "blocked" : "allowed";- const triggeredBy =- guardrail_errors.length > 0- ? guardrail_errors- .map((e) => `${e.guardrail_name}: ${e.message}`)- .join("; ")- : undefined;- const returnedText =- Array.isArray(inputs?.texts) && inputs.texts.length > 0- ? inputs.texts[0]- : undefined;- const displayText =- result === "blocked"- ? `Blocked — ${triggeredBy ?? "content filter"}`- : "Allowed — no policy or guardrail violations detected.";- const sysMsg: QuickTestMessage = {- id: `msg-${Date.now()}-sys`,- type: "system",- text: displayText,- result,- triggeredBy,- returnedText,- timestamp: new Date(),- };- setQuickTestMessages((prev) => [...prev, sysMsg]);+ if (backendMode === "chat_completions" && fixedModel) {+ let fullResponse = "";+ await makeOpenAIChatCompletionRequest(+ [{ role: "user", content: text }],+ (chunk: string) => {+ fullResponse += chunk;+ },+ fixedModel,+ accessToken,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined, // vector_store_ids (param 11)+ selectedGuardrails.length > 0 ? selectedGuardrails : undefined,+ selectedPolicies.length > 0 ? selectedPolicies : undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ requestProxyBaseUrl,+ undefined+ );+ const sysMsg: QuickTestMessage = {+ id: `msg-${Date.now()}-sys`,+ type: "system",+ text: "Allowed — model response received.",+ result: "allowed",+ returnedText: fullResponse,+ timestamp: new Date(),+ };+ setQuickTestMessages((prev) => [...prev, sysMsg]);+ } else {+ const { inputs, guardrail_errors = [] } = await testPoliciesAndGuardrails(+ accessToken,+ {+ policy_names:+ selectedPolicies.length > 0 ? selectedPolicies : undefined,+ guardrail_names:+ selectedGuardrails.length > 0 ? selectedGuardrails : undefined,+ inputs: { texts: [text] },+ request_data: {},+ input_type: "request",+ }+ );+ const result: "blocked" | "allowed" =+ guardrail_errors.length > 0 ? "blocked" : "allowed";+ const triggeredBy =+ guardrail_errors.length > 0+ ? guardrail_errors+ .map((e) => `${e.guardrail_name}: ${e.message}`)+ .join("; ")+ : undefined;+ const returnedText =+ Array.isArray(inputs?.texts) && inputs.texts.length > 0+ ? inputs.texts[0]+ : undefined;+ const displayText =+ result === "blocked"+ ? `Blocked — ${triggeredBy ?? "content filter"}`+ : "Allowed — no policy or guardrail violations detected.";+ const sysMsg: QuickTestMessage = {+ id: `msg-${Date.now()}-sys`,+ type: "system",+ text: displayText,+ result,+ triggeredBy,+ returnedText,+ timestamp: new Date(),+ };+ setQuickTestMessages((prev) => [...prev, sysMsg]);+ }} catch (err) {const errorMessage = err instanceof Error ? err.message : String(err);const sysMsg: QuickTestMessage = {@@ -502,6 +556,9 @@ export default function ComplianceUI({quickTestInput,selectedPolicies,selectedGuardrails,+ backendMode,+ fixedModel,+ requestProxyBaseUrl,]);const handleQuickTestKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {@@ -533,45 +590,99 @@ export default function ComplianceUI({}));setTestResults(pendingResults);try {- const inputsList = allTexts.map((text) => ({ texts: [text] }));- const response = await testPoliciesAndGuardrails(accessToken, {- policy_names:- selectedPolicies.length > 0 ? selectedPolicies : undefined,- guardrail_names:+ if (backendMode === "chat_completions" && fixedModel) {+ const newResults = [...pendingResults];+ for (let index = 0; index < selected.length; index++) {+ const row = pendingResults[index];+ const prompt = allTexts[index];+ let responseText = "";+ try {+ await makeOpenAIChatCompletionRequest(+ [{ role: "user", content: prompt }],+ (chunk: string) => {+ responseText += chunk;+ },+ fixedModel,+ accessToken,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,selectedGuardrails.length > 0 ? selectedGuardrails : undefined,- inputs_list: inputsList,- request_data: {},- input_type: "request",- });- const results = response.results ?? [];- setTestResults(- pendingResults.map((row, index) => {- const item = results[index];- const guardrail_errors = item?.guardrail_errors ?? [];- const actualResult: "blocked" | "allowed" =- guardrail_errors.length > 0 ? "blocked" : "allowed";- const triggeredBy =- guardrail_errors.length > 0- ? guardrail_errors- .map((e) => `${e.guardrail_name}: ${e.message}`)- .join("; ")- : undefined;- const returnedText =- Array.isArray(item?.inputs?.texts) && item.inputs.texts.length > 0- ? item.inputs.texts[0]- : undefined;- return {- ...row,- actualResult,- isMatch:- (row.expectedResult === "fail" && actualResult === "blocked") ||- (row.expectedResult === "pass" && actualResult === "allowed"),- triggeredBy,- returnedText,- status: "complete" as const,- };- })- );+ selectedPolicies.length > 0 ? selectedPolicies : undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ requestProxyBaseUrl,+ undefined+ );+ const actualResult: "blocked" | "allowed" = "allowed";+ newResults[index] = {+ ...row,+ actualResult,+ returnedText: responseText,+ isMatch: row.expectedResult === "pass",+ status: "complete" as const,+ };+ } catch (err) {+ const errorMessage = err instanceof Error ? err.message : String(err);+ newResults[index] = {+ ...row,+ actualResult: "blocked" as const,+ isMatch: false,+ triggeredBy: errorMessage,+ status: "complete" as const,+ };+ }+ setTestResults([...newResults]);+ }+ } else {+ const inputsList = allTexts.map((text) => ({ texts: [text] }));+ const response = await testPoliciesAndGuardrails(accessToken, {+ policy_names:+ selectedPolicies.length > 0 ? selectedPolicies : undefined,+ guardrail_names:+ selectedGuardrails.length > 0 ? selectedGuardrails : undefined,+ inputs_list: inputsList,+ request_data: {},+ input_type: "request",+ });+ const results = response.results ?? [];+ setTestResults(+ pendingResults.map((row, index) => {+ const item = results[index];+ const guardrail_errors = item?.guardrail_errors ?? [];+ const actualResult: "blocked" | "allowed" =+ guardrail_errors.length > 0 ? "blocked" : "allowed";+ const triggeredBy =+ guardrail_errors.length > 0+ ? guardrail_errors+ .map((e) => `${e.guardrail_name}: ${e.message}`)+ .join("; ")+ : undefined;+ const returnedText =+ Array.isArray(item?.inputs?.texts) && item.inputs.texts.length > 0+ ? item.inputs.texts[0]+ : undefined;+ return {+ ...row,+ actualResult,+ isMatch:+ (row.expectedResult === "fail" && actualResult === "blocked") ||+ (row.expectedResult === "pass" && actualResult === "allowed"),+ triggeredBy,+ returnedText,+ status: "complete" as const,+ };+ })+ );+ }} catch (err) {const errorMessage = err instanceof Error ? err.message : String(err);setTestResults(@@ -591,6 +702,9 @@ export default function ComplianceUI({selectedPolicies,selectedGuardrails,allFrameworks,+ backendMode,+ fixedModel,+ requestProxyBaseUrl,]);const completedResults = testResults.filter((r) => r.status === "complete");diff --git a/ui/litellm-dashboard/src/components/playground/llm_calls/fetch_agents.tsx b/ui/litellm-dashboard/src/components/playground/llm_calls/fetch_agents.tsxindex f0f283c5252..cc57976c1aa 100644--- a/ui/litellm-dashboard/src/components/playground/llm_calls/fetch_agents.tsx+++ b/ui/litellm-dashboard/src/components/playground/llm_calls/fetch_agents.tsx@@ -1,6 +1,6 @@// fetch_agents.tsx-import { getProxyBaseUrl, getGlobalLitellmHeaderName } from "../../networking";+import { getProxyBaseUrl, getGlobalLitellmHeaderName, modelInfoCall } from "../../networking";export interface Agent {agent_id: string;@@ -13,6 +13,17 @@ export interface Agent {};}+/** Agent model from /model/info where litellm_params.model starts with "litellm_agent/" */+export interface AgentModel {+ model_name: string;+ litellm_params: {+ model: string;+ litellm_system_prompt?: string;+ [key: string]: unknown;+ };+ model_info?: Record<string, unknown> | null;+}+/*** Fetches available A2A agents from /v1/agents endpoint.*/@@ -53,3 +64,43 @@ export const fetchAvailableAgents = async (throw error;}};++/**+ * Fetches available litellm_agent models from /v2/model/info.+ * Filters for models where litellm_params.model starts with "litellm_agent/".+ */+export const fetchAvailableAgentModels = async (+ accessToken: string,+ userID: string,+ userRole: string,+ customBaseUrl?: string,+): Promise<AgentModel[]> => {+ try {+ const size = 200;+ const response = await modelInfoCall(accessToken, userID, userRole, 1, size);+ const data = response?.data ?? [];+ const list = Array.isArray(data) ? data : [];++ const agentModels: AgentModel[] = list+ .filter(+ (m: { litellm_params?: { model?: string } }) =>+ typeof m?.litellm_params?.model === "string" &&+ m.litellm_params.model.startsWith("litellm_agent/"),+ )+ .map((m: any) => ({+ model_name: m.model_name ?? m.model_group ?? "",+ litellm_params: {+ ...m.litellm_params,+ model: m.litellm_params.model,+ litellm_system_prompt: m.litellm_params?.litellm_system_prompt,+ },+ model_info: m.model_info ?? null,+ }));++ agentModels.sort((a, b) => a.model_name.localeCompare(b.model_name));+ return agentModels;+ } catch (error) {+ console.error("Error fetching agent models:", error);+ throw error;+ }+};