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
Add OCI Cohere support with tool calling and streaming capabilities (#15365)
Sameer Kankute513925fd1250
diff --git a/docs/my-website/docs/providers/oci.md b/docs/my-website/docs/providers/oci.mdindex c11d64f4553..1f52fba04f3 100644--- a/docs/my-website/docs/providers/oci.md+++ b/docs/my-website/docs/providers/oci.md@@ -6,18 +6,27 @@ LiteLLM supports the following models for OCI on-demand GenAI API.Check the [OCI Models List](https://docs.oracle.com/en-us/iaas/Content/generative-ai/pretrained-models.htm) to see if the model is available for your region.+## Supported Models++### Meta Llama Models- `meta.llama-4-maverick-17b-128e-instruct-fp8`- `meta.llama-4-scout-17b-16e-instruct`- `meta.llama-3.3-70b-instruct`- `meta.llama-3.2-90b-vision-instruct`- `meta.llama-3.1-405b-instruct`+### xAI Grok Models- `xai.grok-4`- `xai.grok-3`- `xai.grok-3-fast`- `xai.grok-3-mini`- `xai.grok-3-mini-fast`+### Cohere Models+- `cohere.command-latest`+- `cohere.command-a-03-2025`+- `cohere.command-plus-latest`+## AuthenticationLiteLLM uses OCI signing key authentication. Follow the [official Oracle tutorial](https://docs.oracle.com/en-us/iaas/Content/API/Concepts/apisigningkey.htm) to create a signing key and obtain the following parameters:@@ -83,3 +92,24 @@ response = completion(for chunk in response:print(chunk["choices"][0]["delta"]["content"]) # same as openai format```++## Usage Examples by Model Type++### Using Cohere Models++```python+from litellm import completion++messages = [{"role": "user", "content": "Explain quantum computing"}]+response = completion(+ model="oci/cohere.command-latest",+ messages=messages,+ oci_region="us-chicago-1",+ oci_user=<your_oci_user>,+ oci_fingerprint=<your_oci_fingerprint>,+ oci_tenancy=<your_oci_tenancy>,+ oci_key=<string_with_content_of_oci_key>,+ oci_compartment_id=<oci_compartment_id>,+)+print(response)+```\ No newline at end of filediff --git a/litellm/llms/oci/chat/transformation.py b/litellm/llms/oci/chat/transformation.pyindex 18740052480..3ab827797c5 100644--- a/litellm/llms/oci/chat/transformation.py+++ b/litellm/llms/oci/chat/transformation.py@@ -19,6 +19,13 @@ from litellm.llms.custom_httpx.http_handler import ()from litellm.llms.oci.common_utils import OCIErrorfrom litellm.types.llms.oci import (+ CohereChatRequest,+ CohereMessage,+ CohereChatResult,+ CohereParameterDefinition,+ CohereStreamChunk,+ CohereTool,+ CohereToolCall,OCIChatRequestPayload,OCICompletionPayload,OCICompletionResponse,@@ -37,13 +44,13 @@ from litellm.types.llms.openai import AllMessageValuesfrom litellm.types.utils import (Delta,LlmProviders,+ ModelResponse,ModelResponseStream,StreamingChoices,)from litellm.utils import (ChatCompletionMessageToolCall,CustomStreamWrapper,- ModelResponse,Usage,)@@ -170,13 +177,16 @@ class OCIChatConfig(BaseConfig):"web_search_options": False,}+ # Cohere and Gemini use the same parameter mapping as GENERIC+ self.openai_to_oci_cohere_param_map = self.openai_to_oci_generic_param_map.copy()+def get_supported_openai_params(self, model: str) -> List[str]:supported_params = []vendor = get_vendor_from_model(model)if vendor == OCIVendors.COHERE:- raise ValueError(- "Cohere models are not yet supported in the litellm OCI chat completion endpoint. Use the Cohere API directly."- )+ open_ai_to_oci_param_map = self.openai_to_oci_cohere_param_map+ open_ai_to_oci_param_map.pop("tool_choice")+ open_ai_to_oci_param_map.pop("max_retries")else:open_ai_to_oci_param_map = self.openai_to_oci_generic_param_mapfor key, value in open_ai_to_oci_param_map.items():@@ -195,9 +205,7 @@ class OCIChatConfig(BaseConfig):adapted_params = {}vendor = get_vendor_from_model(model)if vendor == OCIVendors.COHERE:- raise ValueError(- "Cohere models are not yet supported in the litellm OCI chat completion endpoint. Use the Cohere API directly."- )+ open_ai_to_oci_param_map = self.openai_to_oci_cohere_param_mapelse:open_ai_to_oci_param_map = self.openai_to_oci_generic_param_map@@ -416,21 +424,130 @@ class OCIChatConfig(BaseConfig):def _get_optional_params(self, vendor: OCIVendors, optional_params: dict) -> Dict:selected_params = {}if vendor == OCIVendors.COHERE:- raise ValueError(- "Cohere models are not yet supported in the litellm OCI chat completion endpoint. Use the Cohere API directly."- )+ open_ai_to_oci_param_map = self.openai_to_oci_cohere_param_map+ # remove tool_choice from the map+ open_ai_to_oci_param_map.pop("tool_choice")+ # Add default values for Cohere API+ selected_params = {+ "maxTokens": 600,+ "temperature": 1,+ "topK": 0,+ "topP": 0.75,+ "frequencyPenalty": 0+ }else:open_ai_to_oci_param_map = self.openai_to_oci_generic_param_map- for value in open_ai_to_oci_param_map.values():- if value in optional_params:- selected_params[value] = optional_params[value]+ # Map OpenAI params to OCI params+ for openai_key, oci_key in open_ai_to_oci_param_map.items():+ if oci_key and openai_key in optional_params:+ selected_params[oci_key] = optional_params[openai_key] # type: ignore[index]++ # Also check for already-mapped OCI params (for backward compatibility)+ for oci_value in open_ai_to_oci_param_map.values():+ if oci_value and oci_value in optional_params and oci_value not in selected_params:+ selected_params[oci_value] = optional_params[oci_value] # type: ignore[index]+if "tools" in selected_params:- selected_params["tools"] = adapt_tool_definition_to_oci_standard(- selected_params["tools"], vendor- )+ if vendor == OCIVendors.COHERE:+ selected_params["tools"] = self.adapt_tool_definitions_to_cohere_standard( # type: ignore[assignment]+ selected_params["tools"] # type: ignore[arg-type]+ )+ else:+ selected_params["tools"] = adapt_tool_definition_to_oci_standard( # type: ignore[assignment]+ selected_params["tools"], vendor # type: ignore[arg-type]+ )return selected_params+ def adapt_messages_to_cohere_standard(self, messages: List[AllMessageValues]) -> List[CohereMessage]:+ """Build chat history for Cohere models."""+ chat_history = []+ for msg in messages[:-1]: # All messages except the last one+ role = msg.get("role")+ content = msg.get("content")++ if isinstance(content, list):+ # Extract text from content array+ text_content = ""+ for content_item in content:+ if isinstance(content_item, dict) and content_item.get("type") == "text":+ text_content += content_item.get("text", "")+ content = text_content++ # Ensure content is a string+ if not isinstance(content, str):+ content = str(content) if content is not None else ""++ # Handle tool calls+ tool_calls: Optional[List[CohereToolCall]] = None+ if role == "assistant" and "tool_calls" in msg and msg.get("tool_calls"): # type: ignore[union-attr,typeddict-item]+ tool_calls = []+ for tool_call in msg["tool_calls"]: # type: ignore[union-attr,typeddict-item]+ # Parse arguments if they're a JSON string+ raw_arguments: Any = tool_call.get("function", {}).get("arguments", {})+ if isinstance(raw_arguments, str):+ try:+ arguments: Dict[str, Any] = json.loads(raw_arguments)+ except json.JSONDecodeError:+ arguments = {}+ else:+ arguments = raw_arguments++ tool_calls.append(CohereToolCall(+ name=str(tool_call.get("function", {}).get("name", "")),+ parameters=arguments+ ))++ if role == "user":+ chat_history.append(CohereMessage(role="USER", message=content))+ elif role == "assistant":+ chat_history.append(CohereMessage(role="CHATBOT", message=content, toolCalls=tool_calls))+ elif role == "tool":+ # Tool messages need special handling+ chat_history.append(CohereMessage(+ role="TOOL",+ message=content,+ toolCalls=None # Tool messages don't have tool calls+ ))++ return chat_history++ def adapt_tool_definitions_to_cohere_standard(self, tools: List[Dict[str, Any]]) -> List[CohereTool]:+ """Adapt tool definitions to Cohere format."""+ cohere_tools = []+ for tool in tools:+ function_def = tool.get("function", {})+ parameters = function_def.get("parameters", {}).get("properties", {})+ required = function_def.get("parameters", {}).get("required", [])++ parameter_definitions = {}+ for param_name, param_schema in parameters.items():+ parameter_definitions[param_name] = CohereParameterDefinition(+ description=param_schema.get("description", ""),+ type=param_schema.get("type", "string"),+ isRequired=param_name in required+ )++ cohere_tools.append(CohereTool(+ name=function_def.get("name", ""),+ description=function_def.get("description", ""),+ parameterDefinitions=parameter_definitions+ ))++ return cohere_tools++ def _extract_text_content(self, content: Any) -> str:+ """Extract text content from message content."""+ if isinstance(content, str):+ return content+ elif isinstance(content, list):+ text_content = ""+ for content_item in content:+ if isinstance(content_item, dict) and content_item.get("type") == "text":+ text_content += content_item.get("text", "")+ return text_content+ return str(content)+def transform_request(self,model: str,@@ -445,28 +562,47 @@ class OCIChatConfig(BaseConfig):vendor = get_vendor_from_model(model)- if vendor == OCIVendors.COHERE:+ oci_serving_mode = optional_params.get("oci_serving_mode", "ON_DEMAND")+ if oci_serving_mode not in ["ON_DEMAND", "DEDICATED"]:raise Exception(- "Cohere models are not yet supported in the litellm OCI chat completion endpoint. Use the Cohere API directly."+ "kwarg `oci_serving_mode` must be either 'ON_DEMAND' or 'DEDICATED'")- else:- oci_serving_mode = optional_params.get("oci_serving_mode", "ON_DEMAND")- if oci_serving_mode not in ["ON_DEMAND", "DEDICATED"]:- raise Exception(- "kwarg `oci_serving_mode` must be either 'ON_DEMAND' or 'DEDICATED'"- )- if oci_serving_mode == "DEDICATED":- servingMode = OCIServingMode(- servingType="DEDICATED",- endpointId=model,- )- else:- servingMode = OCIServingMode(- servingType="ON_DEMAND",- modelId=model,- )+ if oci_serving_mode == "DEDICATED":+ servingMode = OCIServingMode(+ servingType="DEDICATED",+ endpointId=model,+ )+ else:+ servingMode = OCIServingMode(+ servingType="ON_DEMAND",+ modelId=model,+ )+ # Build request based on vendor type+ if vendor == OCIVendors.COHERE:+ # For Cohere, we need to use the specific Cohere format+ # Extract the last user message as the main message+ user_messages = [msg for msg in messages if msg.get("role") == "user"]+ if not user_messages:+ raise Exception("No user message found for Cohere model")+++ # Create Cohere-specific chat request+ chat_request = CohereChatRequest(+ apiFormat="COHERE",+ message=self._extract_text_content(user_messages[-1]["content"]),+ chatHistory=self.adapt_messages_to_cohere_standard(messages),+ **self._get_optional_params(OCIVendors.COHERE, optional_params)+ )++ data = OCICompletionPayload(+ compartmentId=oci_compartment_id,+ servingMode=servingMode,+ chatRequest=chat_request+ )+ else:+ # Use generic format for other vendorsdata = OCICompletionPayload(compartmentId=oci_compartment_id,servingMode=servingMode,@@ -479,6 +615,111 @@ class OCIChatConfig(BaseConfig):return data.model_dump(exclude_none=True)+ def _handle_cohere_response(+ self,+ json_response: dict,+ model: str,+ model_response: ModelResponse+ ) -> ModelResponse:+ """Handle Cohere-specific response format."""+ cohere_response = CohereChatResult(**json_response)+ # Cohere response format (uses camelCase)+ model_id = model++ # Set basic response info+ model_response.model = model_id+ model_response.created = int(datetime.datetime.now().timestamp())++ # Extract the response text+ response_text = cohere_response.chatResponse.text+ oci_finish_reason = cohere_response.chatResponse.finishReason++ # Map finish reason+ if oci_finish_reason == "COMPLETE":+ finish_reason = "stop"+ elif oci_finish_reason == "MAX_TOKENS":+ finish_reason = "length"+ else:+ finish_reason = "stop"++ # Handle tool calls+ tool_calls: Optional[List[Dict[str, Any]]] = None+ if cohere_response.chatResponse.toolCalls:+ tool_calls = []+ for tool_call in cohere_response.chatResponse.toolCalls:+ tool_calls.append({+ "id": f"call_{len(tool_calls)}", # Generate a simple ID+ "type": "function",+ "function": {+ "name": tool_call.name,+ "arguments": json.dumps(tool_call.parameters)+ }+ })++ # Create choice+ from litellm.types.utils import Choices+ choice = Choices(+ index=0,+ message={+ "role": "assistant",+ "content": response_text,+ "tool_calls": tool_calls+ },+ finish_reason=finish_reason+ )+ model_response.choices = [choice]++ # Extract usage info+ usage_info = cohere_response.chatResponse.usage+ from litellm.types.utils import Usage+ model_response.usage = Usage( # type: ignore[attr-defined]+ prompt_tokens=usage_info.promptTokens, # type: ignore[union-attr]+ completion_tokens=usage_info.completionTokens, # type: ignore[union-attr]+ total_tokens=usage_info.totalTokens # type: ignore[union-attr]+ )++ return model_response++ def _handle_generic_response(+ self,+ json: dict,+ model: str,+ model_response: ModelResponse,+ raw_response: httpx.Response+ ) -> ModelResponse:+ """Handle generic OCI response format."""+ try:+ completion_response = OCICompletionResponse(**json)+ except TypeError as e:+ raise OCIError(+ message=f"Response cannot be casted to OCICompletionResponse: {str(e)}",+ status_code=raw_response.status_code,+ )++ iso_str = completion_response.chatResponse.timeCreated+ dt = datetime.datetime.fromisoformat(iso_str.replace("Z", "+00:00"))+ model_response.created = int(dt.timestamp())++ model_response.model = completion_response.modelId++ message = model_response.choices[0].message # type: ignore+ response_message = completion_response.chatResponse.choices[0].message+ if response_message.content and response_message.content[0].type == "TEXT":+ message.content = response_message.content[0].text+ if response_message.toolCalls:+ message.tool_calls = adapt_tools_to_openai_standard(+ response_message.toolCalls+ )++ usage = Usage(+ prompt_tokens=completion_response.chatResponse.usage.promptTokens,+ completion_tokens=completion_response.chatResponse.usage.completionTokens,+ total_tokens=completion_response.chatResponse.usage.totalTokens,+ )+ model_response.usage = usage # type: ignore++ return model_response+def transform_response(self,model: str,@@ -509,46 +750,13 @@ class OCIChatConfig(BaseConfig):status_code=raw_response.status_code,)- try:- completion_response = OCICompletionResponse(**json)- except TypeError as e:- raise OCIError(- message=f"Response cannot be casted to OCICompletionResponse: {str(e)}",- status_code=raw_response.status_code,- )-vendor = get_vendor_from_model(model)++ # Handle response based on vendor typeif vendor == OCIVendors.COHERE:- raise ValueError(- "Cohere models are not yet supported in the litellm OCI chat completion endpoint. Use the Cohere API directly."- )- else:- iso_str = completion_response.chatResponse.timeCreated- dt = datetime.datetime.fromisoformat(iso_str.replace("Z", "+00:00"))- model_response.created = int(dt.timestamp())-- model_response.model = completion_response.modelId-- message = model_response.choices[0].message # type: ignore- if vendor == OCIVendors.COHERE:- raise ValueError(- "Cohere models are not yet supported in the litellm OCI chat completion endpoint. Use the Cohere API directly."- )+ model_response = self._handle_cohere_response(json, model, model_response)else:- response_message = completion_response.chatResponse.choices[0].message- if response_message.content and response_message.content[0].type == "TEXT":- message.content = response_message.content[0].text- if response_message.toolCalls:- message.tool_calls = adapt_tools_to_openai_standard(- response_message.toolCalls- )-- usage = Usage(- prompt_tokens=completion_response.chatResponse.usage.promptTokens,- completion_tokens=completion_response.chatResponse.usage.completionTokens,- total_tokens=completion_response.chatResponse.usage.totalTokens,- )- model_response.usage = usage # type: ignore+ model_response = self._handle_generic_response(json, model, model_response, raw_response)model_response._hidden_params["additional_headers"] = raw_response.headers@@ -818,26 +1026,21 @@ def adapt_messages_to_generic_oci_standard(def adapt_tool_definition_to_oci_standard(tools: List[Dict], vendor: OCIVendors):new_tools = []- if vendor == OCIVendors.COHERE:- raise ValueError(- "Cohere models are not yet supported in the litellm OCI chat completion endpoint. Use the Cohere API directly."- )- else:- for tool in tools:- if tool["type"] != "function":- raise Exception("OCI only supports function tools")+ for tool in tools:+ if tool["type"] != "function":+ raise Exception("OCI only supports function tools")- tool_function = tool.get("function")- if not isinstance(tool_function, dict):- raise Exception("Prop `function` is not a dictionary")+ tool_function = tool.get("function")+ if not isinstance(tool_function, dict):+ raise Exception("Prop `function` is not a dictionary")- new_tool = OCIToolDefinition(- type="FUNCTION",- name=tool_function.get("name"),- description=tool_function.get("description", ""),- parameters=tool_function.get("parameters", {}),- )- new_tools.append(new_tool)+ new_tool = OCIToolDefinition(+ type="FUNCTION",+ name=tool_function.get("name"),+ description=tool_function.get("description", ""),+ parameters=tool_function.get("parameters", {}),+ )+ new_tools.append(new_tool)return new_tools@@ -877,6 +1080,58 @@ class OCIStreamWrapper(CustomStreamWrapper):if not chunk.startswith("data:"):raise ValueError(f"Chunk does not start with 'data:': {chunk}")dict_chunk = json.loads(chunk[5:]) # Remove 'data: ' prefix and parse JSON++ # Check if this is a Cohere stream chunk+ if "apiFormat" in dict_chunk and dict_chunk.get("apiFormat") == "COHERE":+ return self._handle_cohere_stream_chunk(dict_chunk)+ else:+ return self._handle_generic_stream_chunk(dict_chunk)++ def _handle_cohere_stream_chunk(self, dict_chunk: dict):+ """Handle Cohere-specific streaming chunks."""+ try:+ typed_chunk = CohereStreamChunk(**dict_chunk)+ except TypeError as e:+ raise ValueError(f"Chunk cannot be casted to CohereStreamChunk: {str(e)}")++ if typed_chunk.index is None:+ typed_chunk.index = 0++ # Extract text content+ text = typed_chunk.text or ""++ # Map finish reason to standard format+ finish_reason = typed_chunk.finishReason+ if finish_reason == "COMPLETE":+ finish_reason = "stop"+ elif finish_reason == "MAX_TOKENS":+ finish_reason = "length"+ elif finish_reason is None:+ finish_reason = None+ else:+ finish_reason = "stop"++ # For Cohere, we don't have tool calls in the streaming format+ tool_calls = None++ return ModelResponseStream(+ choices=[+ StreamingChoices(+ index=typed_chunk.index if typed_chunk.index else 0,+ delta=Delta(+ content=text,+ tool_calls=tool_calls,+ provider_specific_fields=None,+ thinking_blocks=None,+ reasoning_content=None,+ ),+ finish_reason=finish_reason,+ )+ ]+ )++ def _handle_generic_stream_chunk(self, dict_chunk: dict):+ """Handle generic OCI streaming chunks."""try:typed_chunk = OCIStreamChunk(**dict_chunk)except TypeError as e:diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 6d49d6e7e2d..499a16f967f 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -16633,6 +16633,42 @@"supports_function_calling": true,"supports_response_schema": false},+ "oci/cohere.command-latest": {+ "input_cost_per_token": 1.56e-06,+ "litellm_provider": "oci",+ "max_input_tokens": 128000,+ "max_output_tokens": 4000,+ "max_tokens": 128000,+ "mode": "chat",+ "output_cost_per_token": 1.56e-06,+ "source": "https://www.oracle.com/cloud/ai/generative-ai/pricing/",+ "supports_function_calling": true,+ "supports_response_schema": false+ },+ "oci/cohere.command-a-03-2025": {+ "input_cost_per_token": 1.56e-06,+ "litellm_provider": "oci",+ "max_input_tokens": 256000,+ "max_output_tokens": 4000,+ "max_tokens": 256000,+ "mode": "chat",+ "output_cost_per_token": 1.56e-06,+ "source": "https://www.oracle.com/cloud/ai/generative-ai/pricing/",+ "supports_function_calling": true,+ "supports_response_schema": false+ },+ "oci/cohere.command-plus-latest": {+ "input_cost_per_token": 1.56e-06,+ "litellm_provider": "oci",+ "max_input_tokens": 128000,+ "max_output_tokens": 4000,+ "max_tokens": 128000,+ "mode": "chat",+ "output_cost_per_token": 1.56e-06,+ "source": "https://www.oracle.com/cloud/ai/generative-ai/pricing/",+ "supports_function_calling": true,+ "supports_response_schema": false+ },"ollama/codegeex4": {"input_cost_per_token": 0.0,"litellm_provider": "ollama",diff --git a/litellm/types/llms/oci.py b/litellm/types/llms/oci.pyindex 56fd61ad7e6..b9a82cc8b73 100644--- a/litellm/types/llms/oci.py+++ b/litellm/types/llms/oci.py@@ -15,6 +15,7 @@ class OCIVendors(Enum):"""COHERE = "COHERE"+ GEMINI = "GEMINI"GENERIC = "GENERIC"@@ -108,7 +109,7 @@ class OCICompletionPayload(BaseModel):compartmentId: strservingMode: OCIServingMode- chatRequest: OCIChatRequestPayload+ chatRequest: Union[OCIChatRequestPayload, CohereChatRequest]# --- API Response Models (Non-streaming) ---@@ -181,3 +182,191 @@ class OCIStreamChunk(BaseModel):message: Optional[OCIStreamDelta] = Nonepad: Optional[str] = Noneindex: Optional[int] = None+++# --- Cohere-Specific Models ---++class CohereStreamChunk(BaseModel):+ """Model for a single SSE event chunk from OCI Cohere API."""++ apiFormat: str+ text: Optional[str] = None+ chatHistory: Optional[List[CohereMessage]] = None+ finishReason: Optional[str] = None+ pad: Optional[str] = None+ index: Optional[int] = None++class CohereMessage(BaseModel):+ """Base model for Cohere messages."""++ role: str+ message: str+ toolCalls: Optional[List[CohereToolCall]] = None+++class CohereUserMessage(CohereMessage):+ """User message in Cohere chat."""++ role: Literal["USER"] = "USER"+++class CohereChatBotMessage(CohereMessage):+ """Chatbot message in Cohere chat."""++ role: Literal["CHATBOT"] = "CHATBOT"+++class CohereSystemMessage(CohereMessage):+ """System message in Cohere chat."""++ role: Literal["SYSTEM"] = "SYSTEM"+++class CohereToolMessage(CohereMessage):+ """Tool message in Cohere chat."""++ role: Literal["TOOL"] = "TOOL"+ toolCallId: str+++class CohereParameterDefinition(BaseModel):+ """Parameter definition for Cohere tools."""++ description: str+ type: str+ isRequired: bool = False+++class CohereTool(BaseModel):+ """Tool definition for Cohere."""++ name: str+ description: str+ parameterDefinitions: Dict[str, CohereParameterDefinition]+++class CohereToolCall(BaseModel):+ """Tool call made by Cohere model."""++ name: str+ parameters: Dict[str, Any]+++class CohereToolResult(BaseModel):+ """Result of a tool call."""++ callId: str+ result: str+++class CohereResponseFormat(BaseModel):+ """Response format for Cohere."""++ type: str+++class CohereResponseTextFormat(CohereResponseFormat):+ """Text response format for Cohere."""++ type: Literal["text"] = "text"++++class CohereChatRequest(BaseModel):+ """Cohere chat request model."""++ # Required fields+ message: str+ apiFormat: Literal["COHERE"] = "COHERE"++ # Optional fields+ chatHistory: Optional[List[CohereMessage]] = None+ maxTokens: Optional[int] = None+ temperature: Optional[float] = None+ topP: Optional[float] = None+ topK: Optional[int] = None+ frequencyPenalty: Optional[float] = None+ presencePenalty: Optional[float] = None+ stopSequences: Optional[List[str]] = None+ seed: Optional[int] = None+ tools: Optional[List[CohereTool]] = None+ toolChoice: Optional[Union[str, Dict[str, Any]]] = None+ responseFormat: Optional[CohereResponseFormat] = None+ preambleOverride: Optional[str] = None+ documents: Optional[List[Dict[str, Any]]] = None+ searchQueriesOnly: Optional[bool] = None+ searchEntryPoint: Optional[str] = None+ grounding: Optional[Dict[str, Any]] = None+ isEcho: Optional[bool] = None+ isSearchQueriesOnly: Optional[bool] = None+ isRawPrompting: Optional[bool] = None+ isForceSingleStep: Optional[bool] = None+ promptTruncation: Optional[str] = None+ safetyMode: Optional[str] = None+ citationQuality: Optional[str] = None+ maxInputTokens: Optional[int] = None+ isStream: Optional[bool] = None+ streamOptions: Optional[Dict[str, Any]] = None+++class CohereUsage(BaseModel):+ """Usage information for Cohere response."""++ promptTokens: int+ completionTokens: int+ totalTokens: int+ promptTokensDetails: Optional[Dict[str, Any]] = None+ completionTokensDetails: Optional[Dict[str, Any]] = None+++class CohereCitation(BaseModel):+ """Citation in Cohere response."""++ start: int+ end: int+ text: str+ document_ids: List[str]+++class CohereSearchQuery(BaseModel):+ """Search query generated by Cohere."""++ text: str+ generation_id: str+++class CohereChatResponse(BaseModel):+ """Cohere chat response model."""++ # Required fields+ text: str+ apiFormat: Literal["COHERE"] = "COHERE"+ finishReason: Literal["COMPLETE", "ERROR_TOXIC", "ERROR_LIMIT", "ERROR", "USER_CANCEL", "MAX_TOKENS"]++ # Optional fields+ chatHistory: Optional[List[CohereMessage]] = None+ citations: Optional[List[CohereCitation]] = None+ documents: Optional[List[Dict[str, Any]]] = None+ errorMessage: Optional[str] = None+ isSearchRequired: Optional[bool] = None+ prompt: Optional[str] = None+ searchQueries: Optional[List[CohereSearchQuery]] = None+ toolCalls: Optional[List[CohereToolCall]] = None+ usage: Optional[CohereUsage] = None+++class CohereChatDetails(BaseModel):+ """Chat details for Cohere request."""++ compartmentId: str+ servingMode: OCIServingMode+ chatRequest: CohereChatRequest+++class CohereChatResult(BaseModel):+ """Complete Cohere chat result."""++ modelId: str+ modelVersion: str+ chatResponse: CohereChatResponse+diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 38cf9671686..826b9b8af57 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -16633,6 +16633,42 @@"supports_function_calling": true,"supports_response_schema": false},+ "oci/cohere.command-latest": {+ "input_cost_per_token": 1.56e-06,+ "litellm_provider": "oci",+ "max_input_tokens": 128000,+ "max_output_tokens": 4000,+ "max_tokens": 128000,+ "mode": "chat",+ "output_cost_per_token": 1.56e-06,+ "source": "https://www.oracle.com/cloud/ai/generative-ai/pricing/",+ "supports_function_calling": true,+ "supports_response_schema": false+ },+ "oci/cohere.command-a-03-2025": {+ "input_cost_per_token": 1.56e-06,+ "litellm_provider": "oci",+ "max_input_tokens": 256000,+ "max_output_tokens": 4000,+ "max_tokens": 256000,+ "mode": "chat",+ "output_cost_per_token": 1.56e-06,+ "source": "https://www.oracle.com/cloud/ai/generative-ai/pricing/",+ "supports_function_calling": true,+ "supports_response_schema": false+ },+ "oci/cohere.command-plus-latest": {+ "input_cost_per_token": 1.56e-06,+ "litellm_provider": "oci",+ "max_input_tokens": 128000,+ "max_output_tokens": 4000,+ "max_tokens": 128000,+ "mode": "chat",+ "output_cost_per_token": 1.56e-06,+ "source": "https://www.oracle.com/cloud/ai/generative-ai/pricing/",+ "supports_function_calling": true,+ "supports_response_schema": false+ },"ollama/codegeex4": {"input_cost_per_token": 0.0,"litellm_provider": "ollama",diff --git a/tests/test_litellm/llms/oci/chat/test_oci_cohere_tool_calls.py b/tests/test_litellm/llms/oci/chat/test_oci_cohere_tool_calls.pynew file mode 100644index 00000000000..abbb7e3e301--- /dev/null+++ b/tests/test_litellm/llms/oci/chat/test_oci_cohere_tool_calls.py@@ -0,0 +1,561 @@+import datetime+import httpx+import pytest+import json+from unittest.mock import patch, MagicMock++from litellm import ModelResponse+from litellm.llms.oci.chat.transformation import (+ OCIChatConfig,+ get_vendor_from_model,+ OCIStreamWrapper,+)+from litellm.types.llms.oci import OCIVendors++# Test constants+TEST_COMPARTMENT_ID = "ocid1.compartment.oc1..xxxxxx"+BASE_OCI_PARAMS = {+ "oci_region": "us-ashburn-1",+ "oci_user": "ocid1.user.oc1..xxxxxxEXAMPLExxxxxx",+ "oci_fingerprint": "4f:29:77:cc:b1:3e:55:ab:61:2a:de:47:f1:38:4c:90",+ "oci_tenancy": "ocid1.tenancy.oc1..xxxxxxEXAMPLExxxxxx",+ "oci_compartment_id": TEST_COMPARTMENT_ID,+ "oci_key_file": "/path/to/private_key.pem",+}+++class TestOCICohereToolCalls:+ """Test Cohere tool calling functionality"""++ def test_cohere_tool_definition_transformation(self):+ """Test that OpenAI tool definitions are correctly transformed to Cohere format"""+ config = OCIChatConfig()++ # OpenAI format tools+ openai_tools = [+ {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Get current weather for a location",+ "parameters": {+ "type": "object",+ "properties": {+ "location": {+ "type": "string",+ "description": "The city or location to get weather for"+ },+ "unit": {+ "type": "string",+ "description": "Temperature unit (celsius or fahrenheit)",+ "enum": ["celsius", "fahrenheit"]+ }+ },+ "required": ["location"]+ }+ }+ },+ {+ "type": "function",+ "function": {+ "name": "calculate",+ "description": "Perform mathematical calculations",+ "parameters": {+ "type": "object",+ "properties": {+ "expression": {+ "type": "string",+ "description": "Mathematical expression to evaluate"+ }+ },+ "required": ["expression"]+ }+ }+ }+ ]++ # Transform tools+ cohere_tools = config.adapt_tool_definitions_to_cohere_standard(openai_tools)++ # Verify transformation+ assert len(cohere_tools) == 2++ # Check first tool+ weather_tool = cohere_tools[0]+ assert weather_tool.name == "get_weather"+ assert weather_tool.description == "Get current weather for a location"+ assert "location" in weather_tool.parameterDefinitions+ assert "unit" in weather_tool.parameterDefinitions++ # Check location parameter+ location_param = weather_tool.parameterDefinitions["location"]+ assert location_param.description == "The city or location to get weather for"+ assert location_param.type == "string"+ assert location_param.isRequired == True++ # Check unit parameter+ unit_param = weather_tool.parameterDefinitions["unit"]+ assert unit_param.description == "Temperature unit (celsius or fahrenheit)"+ assert unit_param.type == "string"+ assert unit_param.isRequired == False++ # Check second tool+ calc_tool = cohere_tools[1]+ assert calc_tool.name == "calculate"+ assert calc_tool.description == "Perform mathematical calculations"+ assert "expression" in calc_tool.parameterDefinitions++ expression_param = calc_tool.parameterDefinitions["expression"]+ assert expression_param.description == "Mathematical expression to evaluate"+ assert expression_param.type == "string"+ assert expression_param.isRequired == True++ def test_cohere_request_with_tools(self):+ """Test request transformation for Cohere models with tools"""+ config = OCIChatConfig()+ messages = [{"role": "user", "content": "What's the weather like in Tokyo?"}]+ tools = [+ {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Get current weather for a location",+ "parameters": {+ "type": "object",+ "properties": {+ "location": {+ "type": "string",+ "description": "The city or location to get weather for"+ }+ },+ "required": ["location"]+ }+ }+ }+ ]+ optional_params = {+ "oci_compartment_id": TEST_COMPARTMENT_ID,+ "tools": tools,+ }++ transformed_request = config.transform_request(+ model="cohere.command-latest",+ messages=messages, # type: ignore+ optional_params=optional_params,+ litellm_params={},+ headers={},+ )++ # Verify basic structure+ assert transformed_request["compartmentId"] == TEST_COMPARTMENT_ID+ assert transformed_request["servingMode"]["servingType"] == "ON_DEMAND"+ assert transformed_request["servingMode"]["modelId"] == "cohere.command-latest"++ # Verify Cohere-specific structure+ chat_request = transformed_request["chatRequest"]+ assert chat_request["apiFormat"] == "COHERE"+ assert chat_request["message"] == "What's the weather like in Tokyo?"+ assert chat_request["chatHistory"] == []++ # Verify default parameters are included+ assert chat_request["maxTokens"] == 600+ assert chat_request["temperature"] == 1+ assert chat_request["topK"] == 0+ assert chat_request["topP"] == 0.75+ assert chat_request["frequencyPenalty"] == 0++ # Verify tools are transformed correctly+ assert "tools" in chat_request+ assert len(chat_request["tools"]) == 1+ tool = chat_request["tools"][0]+ assert tool["name"] == "get_weather"+ assert tool["description"] == "Get current weather for a location"+ assert "parameterDefinitions" in tool+ assert "location" in tool["parameterDefinitions"]++ def test_cohere_response_with_tool_calls(self):+ """Test response transformation for Cohere models with tool calls"""+ config = OCIChatConfig()++ # Mock Cohere response with tool calls+ mock_cohere_response = {+ "modelId": "cohere.command-latest",+ "modelVersion": "1.0",+ "chatResponse": {+ "apiFormat": "COHERE",+ "text": "I will look up the weather in Tokyo.",+ "finishReason": "COMPLETE",+ "toolCalls": [+ {+ "name": "get_weather",+ "parameters": {+ "location": "Tokyo"+ }+ }+ ],+ "usage": {+ "promptTokens": 26,+ "completionTokens": 22,+ "totalTokens": 48+ }+ }+ }++ response = httpx.Response(+ status_code=200,+ json=mock_cohere_response,+ headers={"Content-Type": "application/json"}+ )++ result = config.transform_response(+ model="cohere.command-latest",+ raw_response=response,+ model_response=ModelResponse(),+ logging_obj={}, # type: ignore+ request_data={},+ messages=[],+ optional_params={},+ litellm_params={},+ encoding={},+ )++ # Verify response structure+ assert isinstance(result, ModelResponse)+ assert result.model == "cohere.command-latest"+ assert result.choices[0].message.content == "I will look up the weather in Tokyo."++ # Verify tool calls are present+ assert result.choices[0].message.tool_calls is not None+ assert len(result.choices[0].message.tool_calls) == 1++ tool_call = result.choices[0].message.tool_calls[0]+ assert tool_call.id == "call_0"+ assert tool_call.type == "function"+ assert tool_call.function.name == "get_weather"+ assert tool_call.function.arguments == '{"location": "Tokyo"}'++ # Verify usage+ assert result.usage.prompt_tokens == 26+ assert result.usage.completion_tokens == 22+ assert result.usage.total_tokens == 48++ def test_cohere_chat_history_with_tool_calls(self):+ """Test chat history transformation with tool calls"""+ config = OCIChatConfig()++ messages = [+ {"role": "user", "content": "What's the weather like in Tokyo?"},+ {+ "role": "assistant",+ "content": "I will look up the weather in Tokyo.",+ "tool_calls": [+ {+ "id": "call_0",+ "type": "function",+ "function": {+ "name": "get_weather",+ "arguments": '{"location": "Tokyo"}'+ }+ }+ ]+ },+ {+ "role": "tool",+ "content": "The weather in Tokyo is 22°C with partly cloudy skies.",+ "tool_call_id": "call_0"+ }+ ]++ chat_history = config.adapt_messages_to_cohere_standard(messages)++ # Verify chat history structure (excludes last message)+ assert len(chat_history) == 2++ # Check user message+ user_msg = chat_history[0]+ assert user_msg.role == "USER"+ assert user_msg.message == "What's the weather like in Tokyo?"++ # Check assistant message with tool calls+ assistant_msg = chat_history[1]+ assert assistant_msg.role == "CHATBOT"+ assert assistant_msg.message == "I will look up the weather in Tokyo."+ assert assistant_msg.toolCalls is not None+ assert len(assistant_msg.toolCalls) == 1+ assert assistant_msg.toolCalls[0].name == "get_weather"+ # The parameters should be parsed as JSON+ assert assistant_msg.toolCalls[0].parameters == {"location": "Tokyo"}++ # Note: The tool message (last message) is excluded from chat history+ # This is the expected behavior for Cohere models++ def test_cohere_streaming_chunk_handling(self):+ """Test Cohere streaming chunk handling"""+ # Mock the required parameters+ mock_stream = MagicMock()+ mock_model = "cohere.command-latest"+ mock_logging = MagicMock()++ stream_wrapper = OCIStreamWrapper(+ completion_stream=mock_stream,+ model=mock_model,+ logging_obj=mock_logging+ )++ # Mock Cohere streaming chunk+ cohere_chunk = {+ "apiFormat": "COHERE",+ "text": "I will look up the weather",+ "index": 0+ }++ chunk_data = f"data: {json.dumps(cohere_chunk)}"+ result = stream_wrapper.chunk_creator(chunk_data)++ # Verify streaming chunk structure+ assert result.choices[0].delta.content == "I will look up the weather"+ assert result.choices[0].index == 0+ assert result.choices[0].finish_reason is None++ def test_cohere_streaming_finish_chunk(self):+ """Test Cohere streaming finish chunk handling"""+ # Mock the required parameters+ mock_stream = MagicMock()+ mock_model = "cohere.command-latest"+ mock_logging = MagicMock()++ stream_wrapper = OCIStreamWrapper(+ completion_stream=mock_stream,+ model=mock_model,+ logging_obj=mock_logging+ )++ # Mock Cohere finish chunk+ cohere_finish_chunk = {+ "apiFormat": "COHERE",+ "text": ".",+ "index": 0,+ "finishReason": "COMPLETE"+ }++ chunk_data = f"data: {json.dumps(cohere_finish_chunk)}"+ result = stream_wrapper.chunk_creator(chunk_data)++ # Verify finish chunk structure+ assert result.choices[0].delta.content == "."+ assert result.choices[0].index == 0+ assert result.choices[0].finish_reason == "stop" # COMPLETE is mapped to stop++ def test_cohere_parameter_mapping_excludes_tool_choice(self):+ """Test that tool_choice is excluded from Cohere parameter mapping"""+ config = OCIChatConfig()+ supported_params = config.get_supported_openai_params("cohere.command-latest")++ # Should support standard parameters+ assert "stream" in supported_params+ assert "max_tokens" in supported_params+ assert "temperature" in supported_params+ assert "tools" in supported_params+ assert "top_p" in supported_params++ # Should NOT support tool_choice (removed for Cohere)+ assert "tool_choice" not in supported_params++ def test_cohere_default_parameters(self):+ """Test that Cohere requests include required default parameters"""+ config = OCIChatConfig()+ messages = [{"role": "user", "content": "Hello"}]+ optional_params = {"oci_compartment_id": TEST_COMPARTMENT_ID}++ transformed_request = config.transform_request(+ model="cohere.command-latest",+ messages=messages, # type: ignore+ optional_params=optional_params,+ litellm_params={},+ headers={},+ )++ chat_request = transformed_request["chatRequest"]++ # Verify all required default parameters are present+ assert chat_request["maxTokens"] == 600+ assert chat_request["temperature"] == 1+ assert chat_request["topK"] == 0+ assert chat_request["topP"] == 0.75+ assert chat_request["frequencyPenalty"] == 0++ def test_cohere_parameter_override(self):+ """Test that user-provided parameters override defaults"""+ config = OCIChatConfig()+ messages = [{"role": "user", "content": "Hello"}]+ optional_params = {+ "oci_compartment_id": TEST_COMPARTMENT_ID,+ "temperature": 0.5,+ "max_tokens": 1000,+ }++ transformed_request = config.transform_request(+ model="cohere.command-latest",+ messages=messages, # type: ignore+ optional_params=optional_params,+ litellm_params={},+ headers={},+ )++ chat_request = transformed_request["chatRequest"]++ # Verify user parameters override defaults+ assert chat_request["temperature"] == 0.5+ assert chat_request["maxTokens"] == 1000++ # Verify other defaults are still present+ assert chat_request["topK"] == 0+ assert chat_request["topP"] == 0.75+ assert chat_request["frequencyPenalty"] == 0++ def test_cohere_vendor_detection(self):+ """Test that Cohere models are correctly identified"""+ assert get_vendor_from_model("cohere.command-latest") == OCIVendors.COHERE+ assert get_vendor_from_model("cohere.command-a-03-2025") == OCIVendors.COHERE+ assert get_vendor_from_model("cohere.command-plus-latest") == OCIVendors.COHERE+ assert get_vendor_from_model("cohere.command-r-plus-08-2024") == OCIVendors.COHERE+ assert get_vendor_from_model("cohere.command-r-08-2024") == OCIVendors.COHERE++ def test_cohere_error_handling_invalid_tool_format(self):+ """Test error handling for invalid tool format"""+ config = OCIChatConfig()++ # Invalid tool format (missing function key)+ invalid_tools = [+ {+ "type": "function",+ "name": "get_weather", # Missing "function" wrapper+ "description": "Get weather"+ }+ ]++ # The function should handle missing function key gracefully+ cohere_tools = config.adapt_tool_definitions_to_cohere_standard(invalid_tools)++ # Should create a tool with empty name and description+ assert len(cohere_tools) == 1+ assert cohere_tools[0].name == ""+ assert cohere_tools[0].description == ""++ def test_cohere_response_without_tool_calls(self):+ """Test response transformation without tool calls"""+ config = OCIChatConfig()++ mock_cohere_response = {+ "modelId": "cohere.command-latest",+ "modelVersion": "1.0",+ "chatResponse": {+ "apiFormat": "COHERE",+ "text": "Hello! How can I help you today?",+ "finishReason": "COMPLETE",+ "usage": {+ "promptTokens": 10,+ "completionTokens": 15,+ "totalTokens": 25+ }+ }+ }++ response = httpx.Response(+ status_code=200,+ json=mock_cohere_response,+ headers={"Content-Type": "application/json"}+ )++ result = config.transform_response(+ model="cohere.command-latest",+ raw_response=response,+ model_response=ModelResponse(),+ logging_obj={}, # type: ignore+ request_data={},+ messages=[],+ optional_params={},+ litellm_params={},+ encoding={},+ )++ # Verify response structure+ assert isinstance(result, ModelResponse)+ assert result.model == "cohere.command-latest"+ assert result.choices[0].message.content == "Hello! How can I help you today?"+ assert result.choices[0].message.tool_calls is None+ assert result.usage.prompt_tokens == 10+ assert result.usage.completion_tokens == 15+ assert result.usage.total_tokens == 25+++class TestOCICohereStreaming:+ """Test Cohere streaming functionality"""++ def _create_stream_wrapper(self):+ """Helper to create OCIStreamWrapper with required parameters"""+ mock_stream = MagicMock()+ mock_model = "cohere.command-latest"+ mock_logging = MagicMock()++ return OCIStreamWrapper(+ completion_stream=mock_stream,+ model=mock_model,+ logging_obj=mock_logging+ )++ def test_cohere_streaming_wrapper_initialization(self):+ """Test OCIStreamWrapper initialization"""+ stream_wrapper = self._create_stream_wrapper()++ assert hasattr(stream_wrapper, 'chunk_creator')+ assert hasattr(stream_wrapper, '_handle_cohere_stream_chunk')+ assert hasattr(stream_wrapper, '_handle_generic_stream_chunk')++ def test_cohere_streaming_chunk_parsing(self):+ """Test parsing of Cohere streaming chunks"""+ stream_wrapper = self._create_stream_wrapper()++ # Test valid Cohere chunk+ cohere_chunk = {+ "apiFormat": "COHERE",+ "text": "Hello",+ "index": 0+ }+ chunk_data = f"data: {json.dumps(cohere_chunk)}"++ result = stream_wrapper.chunk_creator(chunk_data)+ assert result.choices[0].delta.content == "Hello"+ assert result.choices[0].index == 0++ def test_cohere_streaming_invalid_chunk_format(self):+ """Test error handling for invalid chunk format"""+ stream_wrapper = self._create_stream_wrapper()++ # Test invalid chunk (not starting with "data:")+ with pytest.raises(ValueError, match="Chunk does not start with 'data:'"):+ stream_wrapper.chunk_creator("invalid chunk")++ def test_cohere_streaming_non_json_chunk(self):+ """Test error handling for non-JSON chunk"""+ stream_wrapper = self._create_stream_wrapper()++ # Test non-JSON chunk+ with pytest.raises(json.JSONDecodeError):+ stream_wrapper.chunk_creator("data: invalid json")++ def test_cohere_streaming_generic_chunk_fallback(self):+ """Test fallback to generic chunk handling for non-Cohere chunks"""+ stream_wrapper = self._create_stream_wrapper()++ # Test generic chunk (no apiFormat or different apiFormat)+ generic_chunk = {+ "apiFormat": "GEMINI",+ "text": "Hello from Gemini"+ }+ chunk_data = f"data: {json.dumps(generic_chunk)}"++ # This should fall back to generic handling+ result = stream_wrapper.chunk_creator(chunk_data)+ # The exact structure depends on the generic handler implementation+ assert hasattr(result, 'choices')