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(sap provider layer): enable response-format for anthropic models and improve compatibility for GPT models via LangChain (#22804)
Guilherme Segantinie335dd70f899
diff --git a/litellm/llms/sap/chat/handler.py b/litellm/llms/sap/chat/handler.pyindex c24cf3d279f..1390b2a4785 100755--- a/litellm/llms/sap/chat/handler.py+++ b/litellm/llms/sap/chat/handler.py@@ -181,7 +181,7 @@ class AsyncSAPStreamIterator:def __init__(self,- response:AsyncIterator,+ response: AsyncIterator,event_prefix: str = "data: ",final_msg: str = "[DONE]",):diff --git a/litellm/llms/sap/chat/models.py b/litellm/llms/sap/chat/models.pyindex d8039ff5618..1b09ce9a756 100644--- a/litellm/llms/sap/chat/models.py+++ b/litellm/llms/sap/chat/models.py@@ -45,9 +45,21 @@ class FunctionObj(BaseModel):class FunctionTool(BaseModel):description: str = ""name: str- parameters: dict = {}+ parameters: dict = {"type": "object", "properties": {}}strict: bool = False+ @field_validator("parameters", mode="before")+ @classmethod+ def ensure_object_type(cls, v: dict) -> dict:+ """Ensure parameters has type='object' as required by SAP Orchestration Service."""+ if not v:+ return {"type": "object", "properties": {}}+ if "type" not in v:+ v = {"type": "object", **v}+ if "properties" not in v:+ v["properties"] = {}+ return v+class ChatCompletionTool(BaseModel):type_: Literal["function"] = Field(default="function", alias="type")diff --git a/litellm/llms/sap/chat/transformation.py b/litellm/llms/sap/chat/transformation.pyindex 2b1573bf4ed..a019ba1767a 100755--- a/litellm/llms/sap/chat/transformation.py+++ b/litellm/llms/sap/chat/transformation.py@@ -157,9 +157,9 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig):"response_format","timeout",]+ # Remove response_format for providers that don't support it on SAP GenAI Hubif (- model.startswith('anthropic')- or model.startswith("amazon")+ model.startswith("amazon")or model.startswith("cohere")or model.startswith("alephalpha")or model == "gpt-4"@@ -169,6 +169,7 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig):params.remove("tool_choice")return params+def validate_environment(self,headers: dict,@@ -203,8 +204,18 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig):litellm_params: dict,headers: dict,) -> dict:+ # Filter out parameters that are not valid model params for SAP Orchestration API+ # - tools, model_version, deployment_url: handled separately+ excluded_params = {"tools", "model_version", "deployment_url"}++ # Filter strict for GPT models only - SAP AI Core doesn't accept it as a model param+ # LangChain agents pass strict=true at top level, which fails for GPT models+ # Anthropic models accept strict, so preserve it for them+ if model.startswith("gpt"):+ excluded_params.add("strict")+model_params = {- k: v for k, v in optional_params.items() if k not in {"tools", "model_version", "deployment_url"}+ k: v for k, v in optional_params.items() if k not in excluded_params}model_version = optional_params.pop("model_version", "latest")@@ -286,7 +297,37 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig):original_response=raw_response.text,additional_args={"complete_input_dict": request_data},)- return ModelResponse.model_validate(raw_response.json()["final_result"])+ response = ModelResponse.model_validate(raw_response.json()["final_result"])++ # Strip markdown code blocks if JSON response_format was used with Anthropic models+ # SAP GenAI Hub with Anthropic models sometimes wraps JSON in ```json ... ```+ # based on prompt phrasing. GPT/Gemini models don't exhibit this behavior,+ # so we gate the stripping to avoid accidentally modifying valid responses.+ response_format = optional_params.get("response_format", {})+ if response_format.get("type") in ("json_object", "json_schema"):+ if model.startswith("anthropic"):+ response = self._strip_markdown_json(response)++ return response++ def _strip_markdown_json(self, response: ModelResponse) -> ModelResponse:+ """Strip markdown code block wrapper from JSON content if present.++ SAP GenAI Hub with Anthropic models sometimes returns JSON wrapped in+ markdown code blocks (```json ... ```) depending on prompt phrasing.+ This method strips that wrapper to ensure consistent JSON output.+ """+ import re++ for choice in response.choices or []:+ if choice.message and choice.message.content:+ content = choice.message.content.strip()+ # Match ```json ... ``` or ``` ... ```+ match = re.match(r'^```(?:json)?\s*\n?(.*?)\n?```$', content, re.DOTALL)+ if match:+ choice.message.content = match.group(1).strip()++ return responsedef get_model_response_iterator(self,@@ -295,6 +336,6 @@ class GenAIHubOrchestrationConfig(OpenAIGPTConfig):json_mode: Optional[bool] = False,):if sync_stream:- return SAPStreamIterator(response=streaming_response) # type: ignore+ return SAPStreamIterator(response=streaming_response) # type: ignoreelse:- return AsyncSAPStreamIterator(response=streaming_response) # type: ignore+ return AsyncSAPStreamIterator(response=streaming_response) # type: ignorediff --git a/tests/test_litellm/llms/sap/chat/test_sap_langchain_strict_param.py b/tests/test_litellm/llms/sap/chat/test_sap_langchain_strict_param.pynew file mode 100644index 00000000000..63bbbeae354--- /dev/null+++ b/tests/test_litellm/llms/sap/chat/test_sap_langchain_strict_param.py@@ -0,0 +1,424 @@+"""+Test that LangChain's strict parameter is handled correctly for SAP GenAI Hub.++LangChain agents automatically set strict=true when using response_format with+json_schema. This parameter gets passed at the top level of optional_params,+but SAP AI Core Orchestration API does not accept it as a model parameter for+GPT models (returns 400 error).++These tests verify that:+1. The strict parameter is filtered from model_params+2. The strict parameter inside response_format.json_schema is preserved+3. The fix works for both GPT and Anthropic models+"""++import pytest+from unittest.mock import MagicMock, patch, AsyncMock++from litellm.llms.sap.chat.transformation import GenAIHubOrchestrationConfig+++class TestLangChainAgentCompatibility:+ """Test compatibility with LangChain agent's strict parameter behavior."""++ def test_langchain_create_react_agent_style_params(self):+ """Simulate LangChain's create_react_agent with response_format schema.++ LangChain's create_react_agent passes parameters like:+ {+ "response_format": {+ "type": "json_schema",+ "json_schema": {+ "name": "AgentResponse",+ "strict": true,+ "schema": {...}+ }+ },+ "strict": true, # Also passed at top level+ "temperature": 0+ }+ """+ config = GenAIHubOrchestrationConfig()++ # Simulate LangChain agent parameters+ langchain_params = {+ "response_format": {+ "type": "json_schema",+ "json_schema": {+ "name": "AgentResponse",+ "strict": True,+ "schema": {+ "type": "object",+ "properties": {+ "thought": {"type": "string"},+ "action": {"type": "string"},+ "action_input": {"type": "string"}+ },+ "required": ["thought", "action", "action_input"]+ }+ }+ },+ "strict": True, # LangChain adds this at top level+ "temperature": 0+ }++ request = config.transform_request(+ model="gpt-4o",+ messages=[{"role": "user", "content": "What is 2+2?"}],+ optional_params=langchain_params,+ litellm_params={},+ headers={},+ )++ # Verify strict is NOT in model.params (would cause 400 error)+ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params, "strict should be filtered from model.params"++ # Verify other params are preserved+ assert model_params.get("temperature") == 0++ # Verify strict inside json_schema IS preserved+ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]+ assert prompt_config["response_format"]["json_schema"]["strict"] is True++ def test_langchain_structured_output_style_params(self):+ """Simulate LangChain's with_structured_output() method.++ When using model.with_structured_output(Schema), LangChain passes:+ {+ "response_format": {+ "type": "json_schema",+ "json_schema": {"name": "Schema", "strict": true, "schema": {...}}+ },+ "strict": true+ }+ """+ config = GenAIHubOrchestrationConfig()++ # Pydantic-style schema from LangChain+ structured_output_params = {+ "response_format": {+ "type": "json_schema",+ "json_schema": {+ "name": "SearchQuery",+ "strict": True,+ "schema": {+ "type": "object",+ "properties": {+ "query": {"type": "string", "description": "Search query"},+ "max_results": {"type": "integer", "default": 10}+ },+ "required": ["query"]+ }+ }+ },+ "strict": True,+ "max_tokens": 1000+ }++ request = config.transform_request(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "Search for Python tutorials"}],+ optional_params=structured_output_params,+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params+ assert model_params.get("max_tokens") == 1000++ def test_langchain_tool_calling_agent_params(self):+ """Simulate LangChain tool calling agent with strict mode.++ Tool calling agents may pass strict for both tools and response_format.+ """+ config = GenAIHubOrchestrationConfig()++ tool_agent_params = {+ "tools": [{+ "type": "function",+ "function": {+ "name": "search_web",+ "description": "Search the web for information",+ "parameters": {+ "type": "object",+ "properties": {+ "query": {"type": "string"}+ },+ "required": ["query"]+ },+ "strict": True # Tool-level strict+ }+ }],+ "response_format": {+ "type": "json_schema",+ "json_schema": {+ "name": "ToolResponse",+ "strict": True,+ "schema": {+ "type": "object",+ "properties": {"result": {"type": "string"}}+ }+ }+ },+ "strict": True, # Top-level strict from LangChain+ "tool_choice": "auto"+ }++ request = config.transform_request(+ model="gpt-4o",+ messages=[{"role": "user", "content": "Search for weather"}],+ optional_params=tool_agent_params,+ litellm_params={},+ headers={},+ )++ # Top-level strict should be filtered+ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params++ # Tools should be included+ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]+ assert "tools" in prompt_config+ assert len(prompt_config["tools"]) == 1++ # Tool's strict parameter should be preserved (it's inside the tool definition)+ assert prompt_config["tools"][0]["function"]["strict"] is True++ def test_gpt4_model_with_langchain_strict(self):+ """Test that gpt-4 (which doesn't support response_format) handles strict gracefully."""+ config = GenAIHubOrchestrationConfig()++ # Even if LangChain passes strict, it should be filtered+ request = config.transform_request(+ model="gpt-4",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={"strict": True, "temperature": 0.5},+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params+ assert model_params.get("temperature") == 0.5++ def test_anthropic_model_preserves_strict(self):+ """Test Anthropic models preserve top-level strict (SAP API accepts it for Anthropic)."""+ config = GenAIHubOrchestrationConfig()++ langchain_params = {+ "response_format": {+ "type": "json_schema",+ "json_schema": {+ "name": "Response",+ "strict": True,+ "schema": {"type": "object", "properties": {"answer": {"type": "string"}}}+ }+ },+ "strict": True,+ "max_tokens": 2000+ }++ request = config.transform_request(+ model="anthropic--claude-3-5-sonnet",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params=langchain_params,+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ # Anthropic models CAN have strict in model.params (SAP API accepts it)+ assert model_params.get("strict") is True+ assert model_params.get("max_tokens") == 2000++ # json_schema strict should also be preserved+ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]+ assert prompt_config["response_format"]["json_schema"]["strict"] is True+++class TestLangChainRequestPayloadStructure:+ """Test the final request payload structure matches SAP API expectations."""++ def test_request_payload_structure_without_strict_in_params(self):+ """Verify the complete request structure is correct for SAP Orchestration API."""+ config = GenAIHubOrchestrationConfig()++ request = config.transform_request(+ model="gpt-4o",+ messages=[+ {"role": "system", "content": "You are a helpful assistant."},+ {"role": "user", "content": "What is 2+2?"}+ ],+ optional_params={+ "strict": True,+ "temperature": 0.7,+ "max_tokens": 500,+ "response_format": {+ "type": "json_schema",+ "json_schema": {+ "name": "MathAnswer",+ "strict": True,+ "schema": {+ "type": "object",+ "properties": {"answer": {"type": "integer"}},+ "required": ["answer"]+ }+ }+ }+ },+ litellm_params={},+ headers={},+ )++ # Verify overall structure+ assert "config" in request+ assert "modules" in request["config"]+ assert "prompt_templating" in request["config"]["modules"]++ prompt_templating = request["config"]["modules"]["prompt_templating"]++ # Verify model section+ assert "model" in prompt_templating+ assert prompt_templating["model"]["name"] == "gpt-4o"+ assert "params" in prompt_templating["model"]++ model_params = prompt_templating["model"]["params"]+ # These should be in params+ assert model_params["temperature"] == 0.7+ assert model_params["max_tokens"] == 500+ # strict should NOT be in params+ assert "strict" not in model_params++ # Verify prompt section+ assert "prompt" in prompt_templating+ prompt = prompt_templating["prompt"]++ # response_format should be in prompt, not in model.params+ assert "response_format" in prompt+ assert prompt["response_format"]["type"] == "json_schema"+ assert prompt["response_format"]["json_schema"]["strict"] is True++ def test_no_strict_anywhere_in_model_params_section(self):+ """Ensure strict never appears in model.params regardless of input."""+ config = GenAIHubOrchestrationConfig()++ # Try various ways strict might be passed+ test_cases = [+ {"strict": True},+ {"strict": False},+ {"strict": True, "temperature": 0},+ {"response_format": {"type": "json_object"}, "strict": True},+ ]++ for params in test_cases:+ request = config.transform_request(+ model="gpt-4o",+ messages=[{"role": "user", "content": "Test"}],+ optional_params=params.copy(),+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params, f"strict leaked into model.params with input: {params}"+++class TestEdgeCases:+ """Test edge cases and boundary conditions."""++ def test_strict_false_also_filtered(self):+ """Even strict=false should be filtered (it's not a valid model param)."""+ config = GenAIHubOrchestrationConfig()++ request = config.transform_request(+ model="gpt-4o",+ messages=[{"role": "user", "content": "Test"}],+ optional_params={"strict": False, "temperature": 0.5},+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params++ def test_empty_optional_params(self):+ """Should work with empty optional_params."""+ config = GenAIHubOrchestrationConfig()++ request = config.transform_request(+ model="gpt-4o",+ messages=[{"role": "user", "content": "Test"}],+ optional_params={},+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params++ def test_only_strict_in_params(self):+ """Should work when strict is the only param."""+ config = GenAIHubOrchestrationConfig()++ request = config.transform_request(+ model="gpt-4o",+ messages=[{"role": "user", "content": "Test"}],+ optional_params={"strict": True},+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params+ # model_params might be empty or have other defaults, but no strict++ def test_gpt_models_filter_strict(self):+ """Verify strict is filtered for all GPT model variants."""+ config = GenAIHubOrchestrationConfig()++ gpt_models = [+ "gpt-4o",+ "gpt-4o-mini",+ "gpt-4-turbo",+ "gpt-4",+ "gpt-3.5-turbo",+ ]++ for model in gpt_models:+ request = config.transform_request(+ model=model,+ messages=[{"role": "user", "content": "Test"}],+ optional_params={"strict": True, "temperature": 0.5},+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params, f"strict should be filtered for GPT model: {model}"+ assert model_params.get("temperature") == 0.5, f"temperature missing for model: {model}"++ def test_non_gpt_models_preserve_strict(self):+ """Verify strict is preserved for non-GPT models (Anthropic, Gemini, Mistral, etc.)."""+ config = GenAIHubOrchestrationConfig()++ non_gpt_models = [+ "anthropic--claude-3-5-sonnet",+ "anthropic--claude-3-opus",+ "gemini-1.5-pro",+ "mistral-large",+ ]++ for model in non_gpt_models:+ request = config.transform_request(+ model=model,+ messages=[{"role": "user", "content": "Test"}],+ optional_params={"strict": True, "temperature": 0.5},+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert model_params.get("strict") is True, f"strict should be preserved for non-GPT model: {model}"+ assert model_params.get("temperature") == 0.5, f"temperature missing for model: {model}"diff --git a/tests/test_litellm/llms/sap/chat/test_sap_response_format.py b/tests/test_litellm/llms/sap/chat/test_sap_response_format.pynew file mode 100644index 00000000000..71c61bfc219--- /dev/null+++ b/tests/test_litellm/llms/sap/chat/test_sap_response_format.py@@ -0,0 +1,1048 @@+"""+Test SAP response_format support for various models.++SAP GenAI Hub natively supports response_format for Anthropic models,+so no tool-based conversion is needed. This test verifies that response_format+is correctly passed through to the API for supported models.+"""++import pytest++from litellm.llms.sap.chat.transformation import GenAIHubOrchestrationConfig+++class TestResponseFormatSupport:+ """Test response_format is supported for appropriate models."""++ def test_anthropic_model_supports_response_format(self):+ """Anthropic models should support response_format param (native SAP support)."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("anthropic--claude-3-5-sonnet")+ assert "response_format" in params++ def test_anthropic_claude_4_supports_response_format(self):+ """Claude 4 models should support response_format param."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("anthropic--claude-4.5-sonnet")+ assert "response_format" in params++ def test_cohere_model_does_not_support_response_format(self):+ """Cohere models should not support response_format param."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("cohere--command-r")+ assert "response_format" not in params++ def test_amazon_model_does_not_support_response_format(self):+ """Amazon models should not support response_format."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("amazon--nova-pro")+ assert "response_format" not in params++ def test_alephalpha_model_does_not_support_response_format(self):+ """AlephAlpha models should not support response_format param."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("alephalpha--luminous")+ assert "response_format" not in params++ def test_gpt4_exact_does_not_support_response_format(self):+ """gpt-4 (exact match) should not support response_format param."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("gpt-4")+ assert "response_format" not in params++ def test_gpt4o_supports_response_format(self):+ """gpt-4o should support response_format (native support)."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("gpt-4o")+ assert "response_format" in params++ def test_gemini_supports_response_format(self):+ """Gemini models should support response_format (native support)."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("gemini-1.5-pro")+ assert "response_format" in params+++class TestTransformRequestWithResponseFormat:+ """Test transform_request handles response_format correctly."""++ def test_transform_request_includes_json_schema_response_format(self):+ """transform_request should include response_format with json_schema type."""+ config = GenAIHubOrchestrationConfig()+ response_format = {+ "type": "json_schema",+ "json_schema": {+ "name": "test",+ "schema": {+ "type": "object",+ "properties": {"result": {"type": "string"}},+ "required": ["result"]+ }+ }+ }++ request = config.transform_request(+ model="anthropic--claude-3-5-sonnet",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={"response_format": response_format},+ litellm_params={},+ headers={},+ )++ # Verify response_format is in the request+ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]+ assert "response_format" in prompt_config+ assert prompt_config["response_format"]["type"] == "json_schema"++ def test_transform_request_includes_json_object_response_format(self):+ """transform_request should include response_format with json_object type."""+ config = GenAIHubOrchestrationConfig()+ response_format = {"type": "json_object"}++ request = config.transform_request(+ model="anthropic--claude-3-5-sonnet",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={"response_format": response_format},+ litellm_params={},+ headers={},+ )++ # Verify response_format is in the request+ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]+ assert "response_format" in prompt_config+ assert prompt_config["response_format"]["type"] == "json_object"++ def test_transform_request_without_response_format(self):+ """transform_request should work without response_format."""+ config = GenAIHubOrchestrationConfig()++ request = config.transform_request(+ model="anthropic--claude-3-5-sonnet",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={},+ litellm_params={},+ headers={},+ )++ # Verify response_format is NOT in the request+ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]+ assert "response_format" not in prompt_config++ def test_transform_request_with_tools_and_response_format(self):+ """transform_request should include both tools and response_format."""+ config = GenAIHubOrchestrationConfig()++ user_tools = [{+ "type": "function",+ "function": {+ "name": "search_web",+ "description": "Search the web",+ "parameters": {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"]+ }+ }+ }]++ response_format = {+ "type": "json_schema",+ "json_schema": {+ "name": "result",+ "schema": {+ "type": "object",+ "properties": {"answer": {"type": "string"}}+ }+ }+ }++ request = config.transform_request(+ model="anthropic--claude-3-5-sonnet",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={"tools": user_tools, "response_format": response_format},+ litellm_params={},+ headers={},+ )++ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]++ # Both should be present+ assert "tools" in prompt_config+ assert "response_format" in prompt_config+ assert len(prompt_config["tools"]) == 1+ assert prompt_config["tools"][0]["function"]["name"] == "search_web"+++class TestStreamIterators:+ """Test streaming iterators work without json_mode."""++ def test_sync_stream_iterator_basic(self):+ """SAPStreamIterator should work without json_mode parameter."""+ from litellm.llms.sap.chat.handler import SAPStreamIterator++ iterator = SAPStreamIterator(response=iter([]))+ assert iterator._done is False++ def test_async_stream_iterator_basic(self):+ """AsyncSAPStreamIterator should work without json_mode parameter."""+ from litellm.llms.sap.chat.handler import AsyncSAPStreamIterator++ async def async_gen():+ yield ""++ iterator = AsyncSAPStreamIterator(response=async_gen())+ assert iterator._done is False++ def test_get_model_response_iterator_sync(self):+ """get_model_response_iterator should return sync iterator."""+ config = GenAIHubOrchestrationConfig()++ iterator = config.get_model_response_iterator(+ streaming_response=iter([]),+ sync_stream=True,+ )++ from litellm.llms.sap.chat.handler import SAPStreamIterator+ assert isinstance(iterator, SAPStreamIterator)++ def test_get_model_response_iterator_async(self):+ """get_model_response_iterator should return async iterator."""+ config = GenAIHubOrchestrationConfig()++ async def async_gen():+ yield ""++ iterator = config.get_model_response_iterator(+ streaming_response=async_gen(),+ sync_stream=False,+ )++ from litellm.llms.sap.chat.handler import AsyncSAPStreamIterator+ assert isinstance(iterator, AsyncSAPStreamIterator)+++class TestNestedSchema:+ """Test that complex nested schemas are preserved correctly."""++ def test_nested_schema_preserved(self):+ """Complex nested schemas should be preserved in the request."""+ config = GenAIHubOrchestrationConfig()+ nested_schema = {+ "type": "object",+ "properties": {+ "user": {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "addresses": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "street": {"type": "string"},+ "city": {"type": "string"}+ }+ }+ }+ }+ }+ }+ }++ response_format = {+ "type": "json_schema",+ "json_schema": {+ "name": "nested",+ "schema": nested_schema+ }+ }++ request = config.transform_request(+ model="anthropic--claude-3-5-sonnet",+ messages=[{"role": "user", "content": "Test"}],+ optional_params={"response_format": response_format},+ litellm_params={},+ headers={},+ )++ # Verify the nested schema is preserved+ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]+ assert "response_format" in prompt_config+ assert prompt_config["response_format"]["json_schema"]["schema"] == nested_schema+++class TestTransformResponseWithResponseFormat:+ """Test transform_response handles response_format correctly."""++ def test_transform_response_strips_markdown_for_json_schema(self):+ """transform_response should strip markdown when response_format.type=json_schema."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()++ # Create mock raw_response+ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"result": "success"}\n```'},+ "finish_reason": "stop"+ }],+ "model": "anthropic--claude-3-5-sonnet"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ # Create mock logging_obj+ logging_obj = MagicMock()++ response_format = {+ "type": "json_schema",+ "json_schema": {"name": "test", "schema": {"type": "object"}}+ }++ result = config.transform_response(+ model="anthropic--claude-3-5-sonnet",+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={"response_format": response_format},+ litellm_params={},+ encoding=None,+ )++ assert result.choices[0].message.content == '{"result": "success"}'++ def test_transform_response_strips_markdown_for_json_object(self):+ """transform_response should strip markdown when response_format.type=json_object."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"answer": 42}\n```'},+ "finish_reason": "stop"+ }],+ "model": "anthropic--claude-3-5-sonnet"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ logging_obj = MagicMock()++ result = config.transform_response(+ model="anthropic--claude-3-5-sonnet",+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={"response_format": {"type": "json_object"}},+ litellm_params={},+ encoding=None,+ )++ assert result.choices[0].message.content == '{"answer": 42}'++ def test_transform_response_no_strip_for_text_type(self):+ """transform_response should NOT strip markdown when response_format.type=text."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"data": "keep me"}\n```'},+ "finish_reason": "stop"+ }],+ "model": "anthropic--claude-3-5-sonnet"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ logging_obj = MagicMock()++ result = config.transform_response(+ model="anthropic--claude-3-5-sonnet",+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={"response_format": {"type": "text"}},+ litellm_params={},+ encoding=None,+ )++ # Content should remain unchanged for text type+ assert result.choices[0].message.content == '```json\n{"data": "keep me"}\n```'++ def test_transform_response_no_strip_without_response_format(self):+ """transform_response should NOT strip markdown when no response_format provided."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"preserve": true}\n```'},+ "finish_reason": "stop"+ }],+ "model": "anthropic--claude-3-5-sonnet"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ logging_obj = MagicMock()++ result = config.transform_response(+ model="anthropic--claude-3-5-sonnet",+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={}, # No response_format+ litellm_params={},+ encoding=None,+ )++ # Content should remain unchanged when no response_format+ assert result.choices[0].message.content == '```json\n{"preserve": true}\n```'+++class TestMarkdownStripping:+ """Test markdown code block stripping for JSON responses."""++ def test_strip_markdown_json_wrapper(self):+ """Should strip ```json ... ``` wrapper from content."""+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()+ response = ModelResponse(+ id="test",+ choices=[Choices(+ index=0,+ message=Message(role="assistant", content='```json\n{"answer": 4}\n```'),+ finish_reason="stop"+ )],+ model="test"+ )++ result = config._strip_markdown_json(response)+ assert result.choices[0].message.content == '{"answer": 4}'++ def test_strip_plain_markdown_wrapper(self):+ """Should strip ``` ... ``` wrapper (without json label)."""+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()+ response = ModelResponse(+ id="test",+ choices=[Choices(+ index=0,+ message=Message(role="assistant", content='```\n{"answer": 4}\n```'),+ finish_reason="stop"+ )],+ model="test"+ )++ result = config._strip_markdown_json(response)+ assert result.choices[0].message.content == '{"answer": 4}'++ def test_no_strip_when_no_markdown(self):+ """Should not modify content without markdown wrapper."""+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()+ response = ModelResponse(+ id="test",+ choices=[Choices(+ index=0,+ message=Message(role="assistant", content='{"answer": 4}'),+ finish_reason="stop"+ )],+ model="test"+ )++ result = config._strip_markdown_json(response)+ assert result.choices[0].message.content == '{"answer": 4}'++ def test_strip_only_for_json_response_format(self):+ """Should only strip for json_object or json_schema types, not text."""+ config = GenAIHubOrchestrationConfig()++ # json_schema type should trigger stripping+ assert config.get_supported_openai_params("anthropic--claude-3-5-sonnet")+ # The actual stripping is tested in transform_response, which checks type++ def test_strip_multiple_choices(self):+ """Should strip markdown from all choices, not just the first."""+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()+ response = ModelResponse(+ id="test",+ choices=[+ Choices(+ index=0,+ message=Message(role="assistant", content='```json\n{"choice": 0}\n```'),+ finish_reason="stop"+ ),+ Choices(+ index=1,+ message=Message(role="assistant", content='```json\n{"choice": 1}\n```'),+ finish_reason="stop"+ ),+ Choices(+ index=2,+ message=Message(role="assistant", content='```\n{"choice": 2}\n```'),+ finish_reason="stop"+ ),+ ],+ model="test"+ )++ result = config._strip_markdown_json(response)+ assert result.choices[0].message.content == '{"choice": 0}'+ assert result.choices[1].message.content == '{"choice": 1}'+ assert result.choices[2].message.content == '{"choice": 2}'++ def test_strip_with_whitespace_variations(self):+ """Should handle various whitespace patterns around JSON."""+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()++ # Test with extra spaces and different newline styles+ test_cases = [+ ('```json\n{"a":1}\n```', '{"a":1}'), # Standard+ ('```json\n {"a":1} \n```', '{"a":1}'), # Extra spaces inside+ (' ```json\n{"a":1}\n``` ', '{"a":1}'), # Extra spaces outside (stripped by .strip())+ ('```json\n\n{"a":1}\n\n```', '{"a":1}'), # Extra newlines+ ]++ for input_content, expected in test_cases:+ response = ModelResponse(+ id="test",+ choices=[Choices(+ index=0,+ message=Message(role="assistant", content=input_content),+ finish_reason="stop"+ )],+ model="test"+ )++ result = config._strip_markdown_json(response)+ assert result.choices[0].message.content == expected, f"Failed for input: {repr(input_content)}"++ def test_no_strip_partial_markdown(self):+ """Should not corrupt content with incomplete markdown (only opening ```)."""+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()++ # Only opening backticks - should be preserved+ response = ModelResponse(+ id="test",+ choices=[Choices(+ index=0,+ message=Message(role="assistant", content='```json\n{"incomplete": true}'),+ finish_reason="stop"+ )],+ model="test"+ )++ result = config._strip_markdown_json(response)+ # Should remain unchanged since there's no closing ```+ assert result.choices[0].message.content == '```json\n{"incomplete": true}'++ def test_preserve_markdown_in_json_value(self):+ """Should preserve markdown code blocks inside JSON string values."""+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()++ # JSON with markdown inside a string value - only outer wrapper should be stripped+ content_with_nested = '```json\n{"code": "```python\\nprint(1)\\n```"}\n```'+ response = ModelResponse(+ id="test",+ choices=[Choices(+ index=0,+ message=Message(role="assistant", content=content_with_nested),+ finish_reason="stop"+ )],+ model="test"+ )++ result = config._strip_markdown_json(response)+ # Only the outer wrapper should be stripped, inner markdown preserved+ assert result.choices[0].message.content == '{"code": "```python\\nprint(1)\\n```"}'+++class TestResponseFormatErrorHandling:+ """Test error handling in response_format processing."""++ def test_empty_content_handling(self):+ """_strip_markdown_json should handle None/empty content gracefully."""+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()++ # Test with None content+ response_none = ModelResponse(+ id="test",+ choices=[Choices(+ index=0,+ message=Message(role="assistant", content=None),+ finish_reason="stop"+ )],+ model="test"+ )++ result = config._strip_markdown_json(response_none)+ assert result.choices[0].message.content is None++ # Test with empty string content+ response_empty = ModelResponse(+ id="test",+ choices=[Choices(+ index=0,+ message=Message(role="assistant", content=""),+ finish_reason="stop"+ )],+ model="test"+ )++ result = config._strip_markdown_json(response_empty)+ assert result.choices[0].message.content == ""++ def test_response_format_with_no_choices(self):+ """_strip_markdown_json should handle response with empty choices."""+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ # Empty choices list+ response = ModelResponse(+ id="test",+ choices=[],+ model="test"+ )++ # Should not raise an error+ result = config._strip_markdown_json(response)+ assert result.choices == []++ def test_response_format_with_message_no_content(self):+ """_strip_markdown_json should handle choice with message but no content."""+ from litellm.types.utils import ModelResponse, Choices, Message++ config = GenAIHubOrchestrationConfig()++ # Choice with message but content is None+ response = ModelResponse(+ id="test",+ choices=[Choices(+ index=0,+ message=Message(role="assistant", content=None),+ finish_reason="stop"+ )],+ model="test"+ )++ # Should not raise an error and content should remain None+ result = config._strip_markdown_json(response)+ assert result.choices[0].message.content is None+++class TestStrictParameterFiltering:+ """Test that strict parameter is filtered from model_params.++ LangChain agents pass strict=true at the top level of optional_params,+ but SAP AI Core Orchestration API does not accept it as a model parameter+ for GPT models. The strict parameter should only exist inside+ response_format.json_schema, not as a top-level model param.+ """++ def test_strict_param_filtered_from_model_params(self):+ """strict should be filtered out and not appear in model.params."""+ config = GenAIHubOrchestrationConfig()++ request = config.transform_request(+ model="gpt-4o",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={"strict": True, "temperature": 0.7},+ litellm_params={},+ headers={},+ )++ # strict should NOT be in model.params+ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params+ # Other params should still be there+ assert model_params.get("temperature") == 0.7++ def test_strict_preserved_inside_response_format_json_schema(self):+ """strict inside response_format.json_schema should be preserved."""+ config = GenAIHubOrchestrationConfig()++ response_format = {+ "type": "json_schema",+ "json_schema": {+ "name": "test_schema",+ "strict": True, # This is the correct location for strict+ "schema": {+ "type": "object",+ "properties": {"result": {"type": "string"}},+ "required": ["result"]+ }+ }+ }++ request = config.transform_request(+ model="gpt-4o",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={"response_format": response_format},+ litellm_params={},+ headers={},+ )++ # strict should be preserved inside json_schema+ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]+ assert prompt_config["response_format"]["json_schema"]["strict"] is True++ def test_langchain_style_strict_filtered_with_response_format(self):+ """LangChain sends strict at top level AND inside json_schema - only top level filtered."""+ config = GenAIHubOrchestrationConfig()++ # LangChain sends both top-level strict AND inside json_schema+ response_format = {+ "type": "json_schema",+ "json_schema": {+ "name": "agent_response",+ "strict": True,+ "schema": {+ "type": "object",+ "properties": {"answer": {"type": "string"}}+ }+ }+ }++ request = config.transform_request(+ model="gpt-4o",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={+ "strict": True, # Top-level strict from LangChain - should be filtered+ "response_format": response_format,+ "temperature": 0.5+ },+ litellm_params={},+ headers={},+ )++ # Top-level strict should NOT be in model.params+ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ assert "strict" not in model_params+ assert model_params.get("temperature") == 0.5++ # strict inside json_schema should be preserved+ prompt_config = request["config"]["modules"]["prompt_templating"]["prompt"]+ assert prompt_config["response_format"]["json_schema"]["strict"] is True++ def test_strict_preserved_for_anthropic_models(self):+ """strict should be preserved for Anthropic models (SAP API accepts it)."""+ config = GenAIHubOrchestrationConfig()++ request = config.transform_request(+ model="anthropic--claude-3-5-sonnet",+ messages=[{"role": "user", "content": "Hello"}],+ optional_params={"strict": True, "max_tokens": 1000},+ litellm_params={},+ headers={},+ )++ model_params = request["config"]["modules"]["prompt_templating"]["model"]["params"]+ # Anthropic models CAN have strict in model.params (SAP API accepts it)+ assert model_params.get("strict") is True+ assert model_params.get("max_tokens") == 1000+++class TestModelVariantSupport:+ """Test response_format support for various model variants."""++ def test_gpt4_turbo_supports_response_format(self):+ """gpt-4-turbo should support response_format (native support)."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("gpt-4-turbo")+ assert "response_format" in params++ def test_mistral_model_support(self):+ """Mistral models should support response_format (native support)."""+ config = GenAIHubOrchestrationConfig()+ params = config.get_supported_openai_params("mistral-large")+ assert "response_format" in params+++class TestMarkdownStrippingModelGating:+ """Test that markdown stripping is only applied to Anthropic models.++ The markdown stripping behavior is specific to Anthropic models on SAP GenAI Hub.+ GPT/Gemini models don't exhibit this behavior, so stripping should be gated+ to avoid accidentally modifying valid responses.+ """++ def test_gpt_model_no_markdown_strip_json_schema(self):+ """GPT models should NOT have markdown stripped for json_schema response_format."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ # GPT response with markdown-wrapped JSON+ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"result": "success"}\n```'},+ "finish_reason": "stop"+ }],+ "model": "gpt-4o"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ logging_obj = MagicMock()++ response_format = {+ "type": "json_schema",+ "json_schema": {"name": "test", "schema": {"type": "object"}}+ }++ result = config.transform_response(+ model="gpt-4o", # GPT model - should NOT strip+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={"response_format": response_format},+ litellm_params={},+ encoding=None,+ )++ # Markdown should NOT be stripped for GPT models+ assert result.choices[0].message.content == '```json\n{"result": "success"}\n```'++ def test_gpt_model_no_markdown_strip_json_object(self):+ """GPT models should NOT have markdown stripped for json_object response_format."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"answer": 42}\n```'},+ "finish_reason": "stop"+ }],+ "model": "gpt-4o"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ logging_obj = MagicMock()++ result = config.transform_response(+ model="gpt-4o", # GPT model - should NOT strip+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={"response_format": {"type": "json_object"}},+ litellm_params={},+ encoding=None,+ )++ # Markdown should NOT be stripped for GPT models+ assert result.choices[0].message.content == '```json\n{"answer": 42}\n```'++ def test_gemini_model_no_markdown_strip(self):+ """Gemini models should NOT have markdown stripped."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"data": "gemini"}\n```'},+ "finish_reason": "stop"+ }],+ "model": "gemini-1.5-pro"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ logging_obj = MagicMock()++ result = config.transform_response(+ model="gemini-1.5-pro", # Gemini model - should NOT strip+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={"response_format": {"type": "json_object"}},+ litellm_params={},+ encoding=None,+ )++ # Markdown should NOT be stripped for Gemini models+ assert result.choices[0].message.content == '```json\n{"data": "gemini"}\n```'++ def test_mistral_model_no_markdown_strip(self):+ """Mistral models should NOT have markdown stripped."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"model": "mistral"}\n```'},+ "finish_reason": "stop"+ }],+ "model": "mistral-large"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ logging_obj = MagicMock()++ result = config.transform_response(+ model="mistral-large", # Mistral model - should NOT strip+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={"response_format": {"type": "json_schema", "json_schema": {"name": "test", "schema": {}}}},+ litellm_params={},+ encoding=None,+ )++ # Markdown should NOT be stripped for Mistral models+ assert result.choices[0].message.content == '```json\n{"model": "mistral"}\n```'++ def test_anthropic_model_still_strips_markdown(self):+ """Anthropic models should still have markdown stripped (existing behavior)."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"result": "anthropic"}\n```'},+ "finish_reason": "stop"+ }],+ "model": "anthropic--claude-3-5-sonnet"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ logging_obj = MagicMock()++ result = config.transform_response(+ model="anthropic--claude-3-5-sonnet", # Anthropic - SHOULD strip+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={"response_format": {"type": "json_schema", "json_schema": {"name": "test", "schema": {}}}},+ litellm_params={},+ encoding=None,+ )++ # Markdown SHOULD be stripped for Anthropic models+ assert result.choices[0].message.content == '{"result": "anthropic"}'++ def test_anthropic_claude_4_strips_markdown(self):+ """Claude 4 models should have markdown stripped."""+ from unittest.mock import MagicMock+ from litellm.types.utils import ModelResponse++ config = GenAIHubOrchestrationConfig()++ raw_response = MagicMock()+ raw_response.json.return_value = {+ "final_result": {+ "id": "test-id",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": '```json\n{"model": "claude-4"}\n```'},+ "finish_reason": "stop"+ }],+ "model": "anthropic--claude-4.5-sonnet"+ }+ }+ raw_response.text = '{"final_result": {...}}'++ logging_obj = MagicMock()++ result = config.transform_response(+ model="anthropic--claude-4.5-sonnet", # Claude 4 Anthropic - SHOULD strip+ raw_response=raw_response,+ model_response=ModelResponse(id="test", model="test"),+ logging_obj=logging_obj,+ request_data={},+ messages=[{"role": "user", "content": "test"}],+ optional_params={"response_format": {"type": "json_object"}},+ litellm_params={},+ encoding=None,+ )++ # Markdown SHOULD be stripped for Anthropic models+ assert result.choices[0].message.content == '{"model": "claude-4"}'diff --git a/tests/test_litellm/llms/sap/chat/test_sap_tool_parameters.py b/tests/test_litellm/llms/sap/chat/test_sap_tool_parameters.pynew file mode 100644index 00000000000..792d2f3fe6b--- /dev/null+++ b/tests/test_litellm/llms/sap/chat/test_sap_tool_parameters.py@@ -0,0 +1,160 @@+"""+Test SAP Tool Parameters Validation++This test ensures that tools passed to the SAP Orchestration Service+have `parameters.type` set to 'object' as required by the SAP API.++Issue: SAP GenAI Hub Orchestration Service rejects tools with:+"tools.0.custom.input_schema.type: Input should be 'object'"+"""++import pytest++from litellm.llms.sap.chat.models import FunctionTool, ChatCompletionTool+++class TestFunctionToolParametersValidation:+ """Test that FunctionTool ensures parameters has type='object'."""++ def test_should_add_type_object_when_parameters_empty(self):+ """Empty parameters should get type='object' and properties={}."""+ tool = FunctionTool(name="test_tool", parameters={})++ assert tool.parameters.get("type") == "object"+ assert "properties" in tool.parameters++ def test_should_add_type_object_when_parameters_missing_type(self):+ """Parameters without type should get type='object' added."""+ tool = FunctionTool(+ name="test_tool",+ parameters={"properties": {"query": {"type": "string"}}}+ )++ assert tool.parameters.get("type") == "object"+ assert tool.parameters.get("properties") == {"query": {"type": "string"}}++ def test_should_preserve_existing_type_object(self):+ """Parameters with type='object' should be preserved."""+ tool = FunctionTool(+ name="test_tool",+ parameters={+ "type": "object",+ "properties": {"query": {"type": "string"}}+ }+ )++ assert tool.parameters.get("type") == "object"+ assert tool.parameters.get("properties") == {"query": {"type": "string"}}++ def test_should_add_properties_when_missing(self):+ """Parameters without properties should get properties={} added."""+ tool = FunctionTool(+ name="test_tool",+ parameters={"type": "object"}+ )++ assert tool.parameters.get("type") == "object"+ assert "properties" in tool.parameters++ def test_should_preserve_additional_schema_properties(self):+ """Additional JSON schema properties should be preserved."""+ tool = FunctionTool(+ name="test_tool",+ parameters={+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ "additionalProperties": False+ }+ )++ assert tool.parameters.get("type") == "object"+ assert tool.parameters.get("required") == ["query"]+ assert tool.parameters.get("additionalProperties") is False+++class TestChatCompletionToolValidation:+ """Test that ChatCompletionTool correctly validates nested FunctionTool."""++ def test_should_validate_empty_parameters_in_function(self):+ """ChatCompletionTool with empty parameters should get type='object'."""+ tool_dict = {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web",+ "parameters": {}+ }+ }+ completion_tool = ChatCompletionTool(**tool_dict)++ assert completion_tool.function.parameters.get("type") == "object"+ assert "properties" in completion_tool.function.parameters++ def test_should_validate_missing_type_in_function_parameters(self):+ """ChatCompletionTool function parameters without type should get type='object'."""+ tool_dict = {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web",+ "parameters": {+ "properties": {+ "query": {"type": "string", "description": "Search query"}+ }+ }+ }+ }+ completion_tool = ChatCompletionTool(**tool_dict)++ assert completion_tool.function.parameters.get("type") == "object"+++class TestToolTransformationIntegration:+ """Test the full tool transformation flow similar to SAP transformation.py."""++ def test_should_transform_openai_format_tool_correctly(self):+ """Simulate transformation.py tool validation flow."""+ from litellm.llms.sap.chat.transformation import validate_dict++ # OpenAI format tool with empty parameters (common case that was failing)+ openai_tool = {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Perform a web search"+ }+ }++ validated_tool = validate_dict(openai_tool, ChatCompletionTool)++ # After validation, parameters should have type='object'+ assert validated_tool["function"]["parameters"]["type"] == "object"+ assert "properties" in validated_tool["function"]["parameters"]++ def test_should_transform_tool_with_existing_parameters(self):+ """Tool with parameters should preserve them while ensuring type='object'."""+ from litellm.llms.sap.chat.transformation import validate_dict++ openai_tool = {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Get weather for a location",+ "parameters": {+ "properties": {+ "location": {+ "type": "string",+ "description": "City name"+ }+ },+ "required": ["location"]+ }+ }+ }++ validated_tool = validate_dict(openai_tool, ChatCompletionTool)++ assert validated_tool["function"]["parameters"]["type"] == "object"+ assert "location" in validated_tool["function"]["parameters"]["properties"]+ assert validated_tool["function"]["parameters"]["required"] == ["location"]