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
[Fix] Watsonx - Apply correct prompt templates for openai/gpt-oss model family (#15341)
Ishaan Jaff1c56a0d8561c
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.pyindex 95daa40ca8e..d2cad0abd93 100644--- a/litellm/litellm_core_utils/prompt_templates/factory.py+++ b/litellm/litellm_core_utils/prompt_templates/factory.py@@ -2,7 +2,6 @@ import copyimport jsonimport mimetypesimport re-from litellm._uuid import uuidimport xml.etree.ElementTree as ETfrom enum import Enumfrom typing import Any, List, Optional, Tuple, cast, overload@@ -13,6 +12,7 @@ import litellmimport litellm.typesimport litellm.types.llmsfrom litellm import verbose_logger+from litellm._uuid import uuidfrom litellm.llms.custom_httpx.http_handler import HTTPHandler, get_async_httpx_clientfrom litellm.types.files import get_file_extension_from_mime_typefrom litellm.types.llms.anthropic import *@@ -364,62 +364,20 @@ def phind_codellama_pt(messages):return prompt-def hf_chat_template( # noqa: PLR0915- model: str, messages: list, chat_template: Optional[Any] = None-):- # Define Jinja2 environment- env = ImmutableSandboxedEnvironment()-- def raise_exception(message):- raise Exception(f"Error message - {message}")-- # Create a template object from the template text- env.globals["raise_exception"] = raise_exception-- ## get the tokenizer config from huggingface- bos_token = ""- eos_token = ""- if chat_template is None:-- def _get_tokenizer_config(hf_model_name):- try:- url = f"https://huggingface.co/{hf_model_name}/raw/main/tokenizer_config.json"- # Make a GET request to fetch the JSON data- client = HTTPHandler(concurrent_limit=1)-- response = client.get(url)- except Exception as e:- raise e- if response.status_code == 200:- # Parse the JSON data- tokenizer_config = json.loads(response.content)- return {"status": "success", "tokenizer": tokenizer_config}- else:- return {"status": "failure"}-- if model in litellm.known_tokenizer_config:- tokenizer_config = litellm.known_tokenizer_config[model]- else:- tokenizer_config = _get_tokenizer_config(model)- litellm.known_tokenizer_config.update({model: tokenizer_config})-- if (- tokenizer_config["status"] == "failure"- or "chat_template" not in tokenizer_config["tokenizer"]- ):- raise Exception("No chat template found")- ## read the bos token, eos token and chat template from the json- tokenizer_config = tokenizer_config["tokenizer"] # type: ignore-- bos_token = tokenizer_config["bos_token"] # type: ignore- if bos_token is not None and not isinstance(bos_token, str):- if isinstance(bos_token, dict):- bos_token = bos_token.get("content", None)- eos_token = tokenizer_config["eos_token"] # type: ignore- if eos_token is not None and not isinstance(eos_token, str):- if isinstance(eos_token, dict):- eos_token = eos_token.get("content", None)- chat_template = tokenizer_config["chat_template"] # type: ignore+def _render_chat_template(env, chat_template: str, bos_token: str, eos_token: str, messages: list) -> str:+ """+ Shared template rendering logic for both sync and async hf_chat_template++ Args:+ env: Jinja2 environment+ chat_template: Chat template string+ bos_token: Beginning of sequence token+ eos_token: End of sequence token+ messages: Messages to render++ Returns:+ Rendered template string+ """try:template = env.from_string(chat_template) # type: ignoreexcept Exception as e:@@ -434,7 +392,6 @@ def hf_chat_template( # noqa: PLR0915bos_token="<bos>",)return True-# This will be raised if Jinja attempts to render the system message and it can'texcept Exception:return False@@ -468,7 +425,7 @@ def hf_chat_template( # noqa: PLR0915)except Exception as e:if "Conversation roles must alternate user/assistant" in str(e):- # reformat messages to ensure user/assistant are alternating, if there's either 2 consecutive 'user' messages or 2 consecutive 'assistant' message, add a blank 'user' or 'assistant' message to ensure compatibility+ # reformat messages to ensure user/assistant are alternatingnew_messages = []for i in range(len(reformatted_messages) - 1):new_messages.append(reformatted_messages[i])@@ -494,6 +451,188 @@ def hf_chat_template( # noqa: PLR0915) # don't use verbose_logger.exception, if exception is raised+async def _afetch_and_extract_template(+ model: str, chat_template: Optional[Any], get_config_fn, get_template_fn+) -> Tuple[str, str, str]:+ """+ Async version: Fetch template and tokens from HuggingFace.++ Returns: (chat_template, bos_token, eos_token)+ """+ from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (+ _extract_token_value,+ )++ bos_token = ""+ eos_token = ""++ if chat_template is None:+ # Fetch or retrieve cached tokenizer config+ if model in litellm.known_tokenizer_config:+ tokenizer_config = litellm.known_tokenizer_config[model]+ else:+ tokenizer_config = await get_config_fn(hf_model_name=model)+ litellm.known_tokenizer_config.update({model: tokenizer_config})++ # Try to get chat template from tokenizer_config.json first+ if (+ tokenizer_config.get("status") == "success"+ and "tokenizer" in tokenizer_config+ and isinstance(tokenizer_config["tokenizer"], dict)+ and "chat_template" in tokenizer_config["tokenizer"]+ ):+ tokenizer_data: dict = tokenizer_config["tokenizer"] # type: ignore+ bos_token = _extract_token_value(+ token_value=tokenizer_data.get("bos_token")+ )+ eos_token = _extract_token_value(+ token_value=tokenizer_data.get("eos_token")+ )+ chat_template = tokenizer_data["chat_template"]+ else:+ # Fallback: Try to fetch chat template from separate .jinja file+ template_result = await get_template_fn(hf_model_name=model)+ if template_result.get("status") == "success":+ chat_template = template_result["chat_template"]+ # Still try to get tokens from tokenizer_config if available+ if (+ tokenizer_config.get("status") == "success"+ and "tokenizer" in tokenizer_config+ and isinstance(tokenizer_config["tokenizer"], dict)+ ):+ tokenizer_data: dict = tokenizer_config["tokenizer"] # type: ignore+ bos_token = _extract_token_value(+ token_value=tokenizer_data.get("bos_token")+ )+ eos_token = _extract_token_value(+ token_value=tokenizer_data.get("eos_token")+ )+ else:+ raise Exception("No chat template found")++ return chat_template, bos_token, eos_token # type: ignore+++def _fetch_and_extract_template(+ model: str, chat_template: Optional[Any], get_config_fn, get_template_fn+) -> Tuple[str, str, str]:+ """+ Sync version: Fetch template and tokens from HuggingFace.++ Returns: (chat_template, bos_token, eos_token)+ """+ from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (+ _extract_token_value,+ )++ bos_token = ""+ eos_token = ""++ if chat_template is None:+ # Fetch or retrieve cached tokenizer config+ if model in litellm.known_tokenizer_config:+ tokenizer_config = litellm.known_tokenizer_config[model]+ else:+ tokenizer_config = get_config_fn(hf_model_name=model)+ litellm.known_tokenizer_config.update({model: tokenizer_config})++ # Try to get chat template from tokenizer_config.json first+ if (+ tokenizer_config.get("status") == "success"+ and "tokenizer" in tokenizer_config+ and isinstance(tokenizer_config["tokenizer"], dict)+ and "chat_template" in tokenizer_config["tokenizer"]+ ):+ tokenizer_data: dict = tokenizer_config["tokenizer"] # type: ignore+ bos_token = _extract_token_value(+ token_value=tokenizer_data.get("bos_token")+ )+ eos_token = _extract_token_value(+ token_value=tokenizer_data.get("eos_token")+ )+ chat_template = tokenizer_data["chat_template"]+ else:+ # Fallback: Try to fetch chat template from separate .jinja file+ template_result = get_template_fn(hf_model_name=model)+ if template_result.get("status") == "success":+ chat_template = template_result["chat_template"]+ # Still try to get tokens from tokenizer_config if available+ if (+ tokenizer_config.get("status") == "success"+ and "tokenizer" in tokenizer_config+ and isinstance(tokenizer_config["tokenizer"], dict)+ ):+ tokenizer_data: dict = tokenizer_config["tokenizer"] # type: ignore+ bos_token = _extract_token_value(+ token_value=tokenizer_data.get("bos_token")+ )+ eos_token = _extract_token_value(+ token_value=tokenizer_data.get("eos_token")+ )+ else:+ raise Exception("No chat template found")++ return chat_template, bos_token, eos_token # type: ignore+++async def ahf_chat_template(+ model: str, messages: list, chat_template: Optional[Any] = None+):+ """HuggingFace chat template (async version)"""+ from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (+ _aget_chat_template_file,+ _aget_tokenizer_config,+ strftime_now,+ )++ env = ImmutableSandboxedEnvironment()+ env.globals["raise_exception"] = lambda msg: Exception(f"Error message - {msg}")+ env.globals["strftime_now"] = strftime_now++ template, bos_token, eos_token = await _afetch_and_extract_template(+ model=model,+ chat_template=chat_template,+ get_config_fn=_aget_tokenizer_config,+ get_template_fn=_aget_chat_template_file,+ )+ return _render_chat_template(+ env=env,+ chat_template=template,+ bos_token=bos_token,+ eos_token=eos_token,+ messages=messages,+ )+++def hf_chat_template(+ model: str, messages: list, chat_template: Optional[Any] = None+):+ """HuggingFace chat template (sync version)"""+ from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (+ _get_chat_template_file,+ _get_tokenizer_config,+ strftime_now,+ )++ env = ImmutableSandboxedEnvironment()+ env.globals["raise_exception"] = lambda msg: Exception(f"Error message - {msg}")+ env.globals["strftime_now"] = strftime_now++ template, bos_token, eos_token = _fetch_and_extract_template(+ model=model,+ chat_template=chat_template,+ get_config_fn=_get_tokenizer_config,+ get_template_fn=_get_chat_template_file,+ )+ return _render_chat_template(+ env=env,+ chat_template=template,+ bos_token=bos_token,+ eos_token=eos_token,+ messages=messages,+ )++def deepseek_r1_pt(messages):return hf_chat_template(model="deepseek-r1/deepseek-r1-7b-instruct", messages=messages@@ -4031,33 +4170,9 @@ def prompt_factory(elif custom_llm_provider == "azure_text":return azure_text_pt(messages=messages)elif custom_llm_provider == "watsonx":- if "granite" in model and "chat" in model:- # granite-13b-chat-v1 and granite-13b-chat-v2 use a specific prompt template- return ibm_granite_pt(messages=messages)- elif "ibm-mistral" in model and "instruct" in model:- # models like ibm-mistral/mixtral-8x7b-instruct-v01-q use the mistral instruct prompt template- return mistral_instruct_pt(messages=messages)- elif "meta-llama/llama-3" in model and "instruct" in model:- # https://llama.meta.com/docs/model-cards-and-prompt-formats/meta-llama-3/- return custom_prompt(- role_dict={- "system": {- "pre_message": "<|start_header_id|>system<|end_header_id|>\n",- "post_message": "<|eot_id|>",- },- "user": {- "pre_message": "<|start_header_id|>user<|end_header_id|>\n",- "post_message": "<|eot_id|>",- },- "assistant": {- "pre_message": "<|start_header_id|>assistant<|end_header_id|>\n",- "post_message": "<|eot_id|>",- },- },- messages=messages,- initial_prompt_value="<|begin_of_text|>",- final_prompt_value="<|start_header_id|>assistant<|end_header_id|>\n",- )+ from litellm.llms.watsonx.chat.transformation import IBMWatsonXChatConfig+ return IBMWatsonXChatConfig.apply_prompt_template(model=model, messages=messages)+try:if "meta-llama/llama-2" in model and "chat" in model:return llama_2_chat_pt(messages=messages)diff --git a/litellm/litellm_core_utils/prompt_templates/huggingface_template_handler.py b/litellm/litellm_core_utils/prompt_templates/huggingface_template_handler.pynew file mode 100644index 00000000000..9305d5bbfc1--- /dev/null+++ b/litellm/litellm_core_utils/prompt_templates/huggingface_template_handler.py@@ -0,0 +1,139 @@+import json+from datetime import datetime+from typing import Any, Dict, Union++from litellm.llms.custom_httpx.http_handler import (+ _get_httpx_client,+ get_async_httpx_client,+)+from litellm.types.llms.custom_http import httpxSpecialProvider+++def strftime_now(fmt: str) -> str:+ """+ Custom function for templates that need current date/time formatting (e.g., gpt-oss)++ Args:+ fmt: Format string for datetime.now().strftime()++ Returns:+ Formatted string+ """+ return datetime.now().strftime(fmt)+++def _get_tokenizer_config(hf_model_name: str) -> Dict[str, Any]:+ """+ Fetch tokenizer_config.json from HuggingFace (sync)++ Args:+ hf_model_name: HuggingFace model name (e.g., 'openai/gpt-oss-120b')++ Returns:+ Dict with 'status' and optionally 'tokenizer' keys+ """+ try:+ url = f"https://huggingface.co/{hf_model_name}/raw/main/tokenizer_config.json"+ client = _get_httpx_client()+ response = client.get(url=url)+ except Exception as e:+ raise e+ if response.status_code == 200:+ tokenizer_config = json.loads(response.content)+ return {"status": "success", "tokenizer": tokenizer_config}+ else:+ return {"status": "failure"}+++async def _aget_tokenizer_config(hf_model_name: str) -> Dict[str, Any]:+ """+ Fetch tokenizer_config.json from HuggingFace (async)++ Args:+ hf_model_name: HuggingFace model name (e.g., 'openai/gpt-oss-120b')++ Returns:+ Dict with 'status' and optionally 'tokenizer' keys+ """+ try:+ url = f"https://huggingface.co/{hf_model_name}/raw/main/tokenizer_config.json"+ client = get_async_httpx_client(+ llm_provider=httpxSpecialProvider.PromptFactory,+ )+ response = await client.get(url=url)+ except Exception as e:+ raise e+ if response.status_code == 200:+ tokenizer_config = json.loads(response.content)+ return {"status": "success", "tokenizer": tokenizer_config}+ else:+ return {"status": "failure"}+++def _get_chat_template_file(hf_model_name: str) -> Dict[str, Any]:+ """+ Fetch chat template from separate .jinja file (sync)++ Args:+ hf_model_name: HuggingFace model name (e.g., 'openai/gpt-oss-120b')++ Returns:+ Dict with 'status' and optionally 'chat_template' keys+ """+ template_filenames = ["chat_template.jinja", "chat_template.jinja2"]+ client = _get_httpx_client()++ for filename in template_filenames:+ try:+ url = f"https://huggingface.co/{hf_model_name}/raw/main/{filename}"+ response = client.get(url=url)+ if response.status_code == 200:+ return {"status": "success", "chat_template": response.content.decode("utf-8")}+ except Exception:+ continue++ return {"status": "failure"}+++async def _aget_chat_template_file(hf_model_name: str) -> Dict[str, Any]:+ """+ Fetch chat template from separate .jinja file (async)++ Args:+ hf_model_name: HuggingFace model name (e.g., 'openai/gpt-oss-120b')++ Returns:+ Dict with 'status' and optionally 'chat_template' keys+ """+ template_filenames = ["chat_template.jinja", "chat_template.jinja2"]+ client = get_async_httpx_client(+ llm_provider=httpxSpecialProvider.PromptFactory,+ )++ for filename in template_filenames:+ try:+ url = f"https://huggingface.co/{hf_model_name}/raw/main/{filename}"+ response = await client.get(url=url)+ if response.status_code == 200:+ return {"status": "success", "chat_template": response.content.decode("utf-8")}+ except Exception:+ continue++ return {"status": "failure"}+++def _extract_token_value(token_value: Union[None, str, Dict[str, Any]]) -> str:+ """+ Extract token string from various formats (string, dict, etc.)++ Args:+ token_value: Token value in various formats (None, str, or dict with 'content' key)++ Returns:+ Extracted token string+ """+ if token_value is None or isinstance(token_value, str):+ return token_value or ""+ if isinstance(token_value, dict):+ return token_value.get("content", "")+ return ""\ No newline at end of filediff --git a/litellm/llms/watsonx/chat/transformation.py b/litellm/llms/watsonx/chat/transformation.pyindex 6b0dd5a39ae..2c096cafced 100644--- a/litellm/llms/watsonx/chat/transformation.py+++ b/litellm/llms/watsonx/chat/transformation.py@@ -4,10 +4,14 @@ Translation from OpenAI's `/chat/completions` endpoint to IBM WatsonX's `/text/cDocs: https://cloud.ibm.com/apidocs/watsonx-ai#text-chat"""-from typing import List, Optional, Tuple, Union+from typing import Dict, List, Optional, Tuple, Unionfrom litellm.secret_managers.main import get_secret_str-from litellm.types.llms.watsonx import WatsonXAIEndpoint, WatsonXAPIParams+from litellm.types.llms.watsonx import (+ WatsonXAIEndpoint,+ WatsonXAPIParams,+ WatsonXModelPattern,+)from ....utils import _remove_additional_properties, _remove_strict_from_schemafrom ...openai.chat.gpt_transformation import OpenAIGPTConfig@@ -120,3 +124,95 @@ class IBMWatsonXChatConfig(IBMWatsonXMixin, OpenAIGPTConfig):None if model.startswith("deployment/") else api_params["project_id"])return payload++ @staticmethod+ def _apply_prompt_template_core(model: str, messages: List[Dict[str, str]], hf_template_fn) -> Optional[str]:+ """Core logic for applying prompt templates"""+ from litellm.litellm_core_utils.prompt_templates.factory import (+ custom_prompt,+ ibm_granite_pt,+ mistral_instruct_pt,+ )++ if WatsonXModelPattern.GRANITE_CHAT.value in model:+ return ibm_granite_pt(messages=messages)+ elif WatsonXModelPattern.IBM_MISTRAL.value in model:+ return mistral_instruct_pt(messages=messages)+ elif WatsonXModelPattern.GPT_OSS.value in model:+ hf_model = model.split("watsonx/")[-1] if "watsonx/" in model else model+ try:+ return hf_template_fn(model=hf_model, messages=messages)+ except Exception:+ pass+ elif WatsonXModelPattern.LLAMA3_INSTRUCT.value in model:+ return custom_prompt(+ role_dict={+ "system": {"pre_message": "<|start_header_id|>system<|end_header_id|>\n", "post_message": "<|eot_id|>"},+ "user": {"pre_message": "<|start_header_id|>user<|end_header_id|>\n", "post_message": "<|eot_id|>"},+ "assistant": {"pre_message": "<|start_header_id|>assistant<|end_header_id|>\n", "post_message": "<|eot_id|>"},+ },+ messages=messages,+ initial_prompt_value="<|begin_of_text|>",+ final_prompt_value="<|start_header_id|>assistant<|end_header_id|>\n",+ )+ return None++ @staticmethod+ async def aapply_prompt_template(model: str, messages: List[Dict[str, str]]) -> Optional[str]:+ """Apply prompt template (async version)"""+ import litellm+ from litellm.litellm_core_utils.prompt_templates.factory import (+ ahf_chat_template,+ custom_prompt,+ hf_chat_template,+ ibm_granite_pt,+ mistral_instruct_pt,+ )++ if WatsonXModelPattern.GRANITE_CHAT.value in model:+ return ibm_granite_pt(messages=messages)+ elif WatsonXModelPattern.IBM_MISTRAL.value in model:+ return mistral_instruct_pt(messages=messages)+ elif WatsonXModelPattern.GPT_OSS.value in model:+ hf_model = model.split("watsonx/")[-1] if "watsonx/" in model else model+ try:+ # Use sync if cached, async if not+ if hf_model in litellm.known_tokenizer_config:+ return hf_chat_template(model=hf_model, messages=messages)+ else:+ return await ahf_chat_template(model=hf_model, messages=messages)+ except Exception:+ pass+ elif WatsonXModelPattern.LLAMA3_INSTRUCT.value in model:+ return custom_prompt(+ role_dict={+ "system": {+ "pre_message": "<|start_header_id|>system<|end_header_id|>\n",+ "post_message": "<|eot_id|>",+ },+ "user": {+ "pre_message": "<|start_header_id|>user<|end_header_id|>\n",+ "post_message": "<|eot_id|>",+ },+ "assistant": {+ "pre_message": "<|start_header_id|>assistant<|end_header_id|>\n",+ "post_message": "<|eot_id|>",+ },+ },+ messages=messages,+ initial_prompt_value="<|begin_of_text|>",+ final_prompt_value="<|start_header_id|>assistant<|end_header_id|>\n",+ )+ return None++ @staticmethod+ def apply_prompt_template(model: str, messages: List[Dict[str, str]]) -> Optional[str]:+ """Apply prompt template (sync version)"""+ from litellm.litellm_core_utils.prompt_templates.factory import (+ hf_chat_template,+ )++ return IBMWatsonXChatConfig._apply_prompt_template_core(+ model=model, messages=messages, hf_template_fn=hf_chat_template+ )+diff --git a/litellm/llms/watsonx/common_utils.py b/litellm/llms/watsonx/common_utils.pyindex c756be6d458..58b33097cbd 100644--- a/litellm/llms/watsonx/common_utils.py+++ b/litellm/llms/watsonx/common_utils.py@@ -131,34 +131,102 @@ def _get_api_params()-def convert_watsonx_messages_to_prompt(+async def _aconvert_watsonx_messages_core(model: str,messages: List[AllMessageValues],provider: str,custom_prompt_dict: Dict,+ apply_template_fn,) -> str:+ """Async core logic for converting watsonx messages to prompt"""+ from litellm.types.llms.watsonx import WatsonXModelPattern+# handle anthropic prompts and amazon titan promptsif model in custom_prompt_dict:- # check if the model has a registered custom promptmodel_prompt_dict = custom_prompt_dict[model]- prompt = ptf.custom_prompt(+ return ptf.custom_prompt(messages=messages,- role_dict=model_prompt_dict.get(- "role_dict", model_prompt_dict.get("roles")- ),+ role_dict=model_prompt_dict.get("role_dict", model_prompt_dict.get("roles")),initial_prompt_value=model_prompt_dict.get("initial_prompt_value", ""),final_prompt_value=model_prompt_dict.get("final_prompt_value", ""),bos_token=model_prompt_dict.get("bos_token", ""),eos_token=model_prompt_dict.get("eos_token", ""),)- return prompt- elif provider == "ibm-mistralai":- prompt = ptf.mistral_instruct_pt(messages=messages)+ elif provider == WatsonXModelPattern.IBM_MISTRALAI.value:+ return ptf.mistral_instruct_pt(messages=messages)else:- prompt: str = ptf.prompt_factory( # type: ignore+ # Try applying specific template first+ result = await apply_template_fn(model=model, messages=messages)+ if result:+ return result+ # Fallback to default+ return ptf.prompt_factory(model=model, messages=messages, custom_llm_provider="watsonx"+ ) # type: ignore+++def _convert_watsonx_messages_core(+ model: str,+ messages: List[AllMessageValues],+ provider: str,+ custom_prompt_dict: Dict,+ apply_template_fn,+) -> str:+ """Sync core logic for converting watsonx messages to prompt"""+ from litellm.types.llms.watsonx import WatsonXModelPattern++ # handle anthropic prompts and amazon titan prompts+ if model in custom_prompt_dict:+ model_prompt_dict = custom_prompt_dict[model]+ return ptf.custom_prompt(+ messages=messages,+ role_dict=model_prompt_dict.get("role_dict", model_prompt_dict.get("roles")),+ initial_prompt_value=model_prompt_dict.get("initial_prompt_value", ""),+ final_prompt_value=model_prompt_dict.get("final_prompt_value", ""),+ bos_token=model_prompt_dict.get("bos_token", ""),+ eos_token=model_prompt_dict.get("eos_token", ""),)- return prompt+ elif provider == WatsonXModelPattern.IBM_MISTRALAI.value:+ return ptf.mistral_instruct_pt(messages=messages)+ else:+ # Try applying specific template first+ result = apply_template_fn(model=model, messages=messages)+ if result:+ return result+ # Fallback to default+ return ptf.prompt_factory(+ model=model, messages=messages, custom_llm_provider="watsonx"+ ) # type: ignore+++async def aconvert_watsonx_messages_to_prompt(+ model: str, messages: List[AllMessageValues], provider: str, custom_prompt_dict: Dict+) -> str:+ """Async version of convert_watsonx_messages_to_prompt"""+ from litellm.llms.watsonx.chat.transformation import IBMWatsonXChatConfig++ return await _aconvert_watsonx_messages_core(+ model=model,+ messages=messages,+ provider=provider,+ custom_prompt_dict=custom_prompt_dict,+ apply_template_fn=IBMWatsonXChatConfig.aapply_prompt_template,+ )+++def convert_watsonx_messages_to_prompt(+ model: str, messages: List[AllMessageValues], provider: str, custom_prompt_dict: Dict+) -> str:+ """Sync version of convert_watsonx_messages_to_prompt"""+ from litellm.llms.watsonx.chat.transformation import IBMWatsonXChatConfig++ return _convert_watsonx_messages_core(+ model=model,+ messages=messages,+ provider=provider,+ custom_prompt_dict=custom_prompt_dict,+ apply_template_fn=IBMWatsonXChatConfig.apply_prompt_template,+ )# Mixin class for shared IBM Watson X functionalitydiff --git a/litellm/llms/watsonx/completion/transformation.py b/litellm/llms/watsonx/completion/transformation.pyindex a0b9735a990..3c1229ecd2b 100644--- a/litellm/llms/watsonx/completion/transformation.py+++ b/litellm/llms/watsonx/completion/transformation.py@@ -228,39 +228,35 @@ class IBMWatsonXAIConfig(IBMWatsonXMixin, BaseConfig):"us-south",]- def transform_request(- self,- model: str,- messages: List[AllMessageValues],- optional_params: Dict,- litellm_params: Dict,- headers: Dict,- ) -> Dict:- provider = model.split("/")[0]- prompt = convert_watsonx_messages_to_prompt(- model=model,- messages=messages,- provider=provider,- custom_prompt_dict={},- )+ def _build_request_payload(self, model: str, prompt: str, optional_params: Dict) -> Dict:+ """Shared logic to build request payload"""extra_body_params = optional_params.pop("extra_body", {})optional_params.update(extra_body_params)watsonx_api_params = _get_api_params(params=optional_params)-- watsonx_auth_payload = self._prepare_payload(- model=model,- api_params=watsonx_api_params,- )-- # init the payload to the text generation call- payload = {+ watsonx_auth_payload = self._prepare_payload(model=model, api_params=watsonx_api_params)++ return {"input": prompt,"moderations": optional_params.pop("moderations", {}),"parameters": optional_params,**watsonx_auth_payload,}- return payload+ async def atransform_request(self, model: str, messages: List[AllMessageValues], optional_params: Dict, litellm_params: Dict, headers: Dict) -> Dict:+ """Async version of transform_request"""+ from litellm.llms.watsonx.common_utils import (+ aconvert_watsonx_messages_to_prompt,+ )++ provider = model.split("/")[0]+ prompt = await aconvert_watsonx_messages_to_prompt(model=model, messages=messages, provider=provider, custom_prompt_dict={})+ return self._build_request_payload(model=model, prompt=prompt, optional_params=optional_params)++ def transform_request(self, model: str, messages: List[AllMessageValues], optional_params: Dict, litellm_params: Dict, headers: Dict) -> Dict:+ """Sync version of transform_request"""+ provider = model.split("/")[0]+ prompt = convert_watsonx_messages_to_prompt(model=model, messages=messages, provider=provider, custom_prompt_dict={})+ return self._build_request_payload(model=model, prompt=prompt, optional_params=optional_params)def transform_response(self,diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex bdfc4fd020b..29a65887747 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -13303,8 +13303,7 @@"supported_endpoints": ["/v1/images/generations","/v1/images/edits"- ],- "supports_vision": true+ ]},"gpt-realtime": {"cache_creation_input_audio_token_cost": 4e-07,diff --git a/litellm/types/llms/watsonx.py b/litellm/types/llms/watsonx.pyindex 426ca8a7d25..4eb2f2531a0 100644--- a/litellm/types/llms/watsonx.py+++ b/litellm/types/llms/watsonx.py@@ -32,3 +32,12 @@ class WatsonXAIEndpoint(str, Enum):EMBEDDINGS = "/ml/v1/text/embeddings"PROMPTS = "/ml/v1/prompts"AVAILABLE_MODELS = "/ml/v1/foundation_model_specs"+++class WatsonXModelPattern(str, Enum):+ """Model identifier patterns for WatsonX models"""+ GRANITE_CHAT = "granite-chat"+ IBM_MISTRAL = "ibm-mistral"+ IBM_MISTRALAI = "ibm-mistralai"+ GPT_OSS = "openai/gpt-oss"+ LLAMA3_INSTRUCT = "meta-llama/llama-3-instruct"diff --git a/tests/test_litellm/llms/watsonx/test_watsonx.py b/tests/test_litellm/llms/watsonx/test_watsonx.pyindex 13ca6ad8e6c..b76d7e8a2be 100644--- a/tests/test_litellm/llms/watsonx/test_watsonx.py+++ b/tests/test_litellm/llms/watsonx/test_watsonx.py@@ -5,12 +5,14 @@ import syssys.path.insert(0, os.path.abspath("../..")) # Adds the parent directory to the system path+from typing import Optional+from unittest.mock import Mock, patch++import pytest+import litellmfrom litellm import completionfrom litellm.llms.custom_httpx.http_handler import HTTPHandler-from unittest.mock import patch, Mock-import pytest-from typing import Optional@pytest.fixture@@ -203,3 +205,143 @@ def test_watsonx_completion_regular_model_includes_model_id(assert json_data["model_id"] == "regular-model" # Provider prefix is stripped# Ensure project_id is also included for regular modelsassert "project_id" in json_data+++async def test_watsonx_gpt_oss_prompt_transformation(monkeypatch):+ """+ Test that gpt-oss-120b model transforms messages to proper format instead of simple concatenation.++ This test starts from litellm.acompletion and verifies what gets sent in the final POST request body.+ Input messages should be transformed using the HuggingFace chat template from openai/gpt-oss-120b,+ not just concatenated as "You are chatgpt Hi there".+ """+ monkeypatch.setenv("WATSONX_PROJECT_ID", "test-project-id")+ monkeypatch.setenv("WATSONX_API_BASE", "https://test-api.watsonx.ai")++ # Test with gpt-oss model using watsonx_text provider (text generation endpoint)+ model = "watsonx_text/openai/gpt-oss-120b"++ # Input messages+ messages = [+ {"role": "system", "content": "You are chatgpt"},+ {"role": "user", "content": "Hi there"}+ ]++ # Mock the HTTP client+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler++ client = AsyncHTTPHandler()++ # Mock the token call+ mock_token_response = Mock()+ mock_token_response.json.return_value = {+ "access_token": "mock_access_token",+ "expires_in": 3600,+ }+ mock_token_response.raise_for_status = Mock()++ # Mock the completion call+ mock_completion_response = Mock()+ mock_completion_response.status_code = 200+ mock_completion_response.json.return_value = {+ "results": [{+ "generated_text": "Hello! How can I help you?",+ "generated_token_count": 10,+ "input_token_count": 5+ }],+ "model_id": "openai/gpt-oss-120b"+ }++ with patch.object(client, "post") as mock_post, patch.object(+ litellm.module_level_client, "post", return_value=mock_token_response+ ):+ # Set the mock to return the completion response+ mock_post.return_value = mock_completion_response++ try:+ # Call acompletion with messages+ await litellm.acompletion(+ model=model,+ messages=messages,+ api_key="test_api_key",+ client=client,+ )+ except Exception as e:+ # May fail due to incomplete mocking, but we should have captured the request+ print(f"Exception (may be expected): {e}")++ # Verify the POST was called+ assert mock_post.call_count >= 1, f"POST should have been called at least once, got {mock_post.call_count}"++ # Get the request body from the first call+ call_args = mock_post.call_args+ json_data = json.loads(call_args.kwargs["data"])++ print(f"\n{'='*80}")+ print(f"Input messages to litellm.acompletion:")+ print(json.dumps(messages, indent=2))+ print(f"\n{'='*80}")+ print(f"Final POST request body:")+ print(json.dumps(json_data, indent=2))+ print(f"{'='*80}\n")++ # Verify the transformed input is in the request+ assert "input" in json_data, "Request should have 'input' field"+ transformed_prompt = json_data["input"]++ print(f"Transformed prompt: {repr(transformed_prompt)}")+ print(f"Prompt length: {len(transformed_prompt)}")++ # Verify it's NOT simple concatenation+ simple_concat = "You are chatgpt Hi there"+ assert transformed_prompt != simple_concat, (+ f"Prompt should not be simple concatenation.\n"+ f"Expected: Chat template with <|start|> tags\n"+ f"Got: {transformed_prompt}"+ )++ # Verify it contains proper chat template formatting+ assert "<|start|>" in transformed_prompt, "Prompt should contain <|start|> tag"+ assert "<|message|>" in transformed_prompt, "Prompt should contain <|message|> tag"+ assert "<|end|>" in transformed_prompt, "Prompt should contain <|end|> tag"+ assert "You are chatgpt" in transformed_prompt, "Prompt should contain system message content"+ assert "Hi there" in transformed_prompt, "Prompt should contain user message content"+++async def test_watsonx_gpt_oss_uses_async_http_handler():+ """+ Test that verifies async HTTP client is used when fetching HuggingFace templates.+ """+ from unittest.mock import AsyncMock, MagicMock, patch++ from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import (+ _aget_chat_template_file,+ )++ # Mock the async HTTP client+ mock_async_client = MagicMock()+ mock_get = AsyncMock()+ mock_async_client.get = mock_get++ # Create mock response for chat template file+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.content = b"test template content"+ mock_get.return_value = mock_response++ # Test the async function directly+ with patch("litellm.litellm_core_utils.prompt_templates.huggingface_template_handler.get_async_httpx_client", return_value=mock_async_client):+ result = await _aget_chat_template_file(hf_model_name="test/model")++ # Verify async HTTP client was called+ assert mock_get.called, "Async HTTP client's get method should be called"+ assert mock_get.await_count > 0, "Async HTTP client's get should be awaited"++ # Verify it was called with HuggingFace URL+ call_args = mock_get.call_args+ assert call_args is not None, "get should have been called with arguments"+ called_url = call_args.kwargs.get("url", "")+ assert "huggingface.co/test/model" in called_url, f"Should call HuggingFace API for test/model, got: {called_url}"+ assert result["status"] == "success", "Should return success status"