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 OpenAI-compatible annotations support for Cohere v2 citations
Sameer Kankute192935120d0d
diff --git a/litellm/llms/cohere/chat/v2_transformation.py b/litellm/llms/cohere/chat/v2_transformation.pyindex 50426a0883b..8f6dde1967c 100644--- a/litellm/llms/cohere/chat/v2_transformation.py+++ b/litellm/llms/cohere/chat/v2_transformation.py@@ -6,7 +6,12 @@ import httpximport litellmfrom litellm.llms.base_llm.chat.transformation import BaseLLMExceptionfrom litellm.types.llms.cohere import CohereV2ChatResponse-from litellm.types.llms.openai import AllMessageValues, ChatCompletionToolCallChunk+from litellm.types.llms.openai import (+ AllMessageValues,+ ChatCompletionToolCallChunk,+ ChatCompletionAnnotation,+ ChatCompletionAnnotationURLCitation,+)from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfigfrom litellm.types.utils import ModelResponse, Usage@@ -207,9 +212,15 @@ class CohereV2ChatConfig(OpenAIGPTConfig):])- ## ADD CITATIONS- if "citations" in cohere_v2_chat_response:- setattr(model_response, "citations", cohere_v2_chat_response["citations"])+ ## ADD CITATIONS AS ANNOTATIONS+ annotations: Optional[List[ChatCompletionAnnotation]] = None+ citations = None++ if "message" in cohere_v2_chat_response and "citations" in cohere_v2_chat_response["message"]:+ citations = cohere_v2_chat_response["message"]["citations"]++ if citations:+ annotations = self._translate_citations_to_openai_annotations(citations)## Tool calling responsecohere_tools_response = cohere_v2_chat_response["message"].get("tool_calls", [])@@ -225,8 +236,13 @@ class CohereV2ChatConfig(OpenAIGPTConfig):_message = litellm.Message(tool_calls=tool_calls,content=None,+ annotations=annotations,)model_response.choices[0].message = _message # type: ignore+ else:+ if annotations:+ current_message = model_response.choices[0].message # type: ignore+ current_message.annotations = annotations## CALCULATING USAGE - use cohere `billed_units` for returning usagetoken_usage = cohere_v2_chat_response["usage"].get("tokens", {})@@ -276,3 +292,66 @@ class CohereV2ChatConfig(OpenAIGPTConfig):self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]) -> BaseLLMException:return CohereError(status_code=status_code, message=error_message)++ def _translate_citations_to_openai_annotations(self, citations: List[dict]) -> List[ChatCompletionAnnotation]:+ """+ Transform Cohere citations to OpenAI annotations format.++ Creates separate annotations for each source in a citation, allowing multiple+ annotations with the same start/end index if they reference different sources.++ Args:+ citations: List of Cohere citation objects with format:+ {+ "start": int,+ "end": int,+ "text": str,+ "sources": [+ {+ "type": "document",+ "document": {+ "title": str,+ "snippet": str,+ ...+ },+ "id": str+ }+ ]+ }++ Returns:+ List of OpenAI ChatCompletionAnnotation objects (one per source)+ """+ annotations: List[ChatCompletionAnnotation] = []++ for citation in citations:+ start_index = citation.get("start", 0)+ end_index = citation.get("end", 0)++ # Extract source information - loop through all sources+ sources = citation.get("sources", [])+ if not sources:+ continue++ # Create an annotation for each source+ for source in sources:+ if source.get("type") == "document" and "document" in source:+ document = source["document"]+ title = document.get("title", "")+ url = source.get("url") or f"source:{source.get('id', 'unknown')}"++ url_citation: ChatCompletionAnnotationURLCitation = {+ "start_index": start_index,+ "end_index": end_index,+ "title": title,+ "url": url,+ }++ annotation: ChatCompletionAnnotation = {+ "type": "url_citation",+ "url_citation": url_citation,+ }++ annotations.append(annotation)++ return annotations\ No newline at end of filediff --git a/tests/llm_translation/test_cohere.py b/tests/llm_translation/test_cohere.pyindex a47fc5443af..2d7e5da20d3 100644--- a/tests/llm_translation/test_cohere.py+++ b/tests/llm_translation/test_cohere.py@@ -638,8 +638,8 @@ def test_cohere_v2_tool_calling():@pytest.mark.parametrize("stream", [True, False])@pytest.mark.asyncio@pytest.mark.flaky(retries=3, delay=1)-async def test_cohere_v2_citations(stream):- """Test Cohere v2 citations functionality."""+async def test_cohere_v2_annotations(stream):+ """Test Cohere v2 annotations functionality (replaces citations)."""try:litellm.set_verbose = Truemessages = [@@ -649,14 +649,14 @@ async def test_cohere_v2_citations(stream):documents = [{"data": {- "title": "Test Document 1",- "snippet": "This is test content 1"+ "title": "Renewable Energy Benefits Document",+ "snippet": "Renewable energy sources like solar and wind power provide clean electricity while reducing greenhouse gas emissions and dependence on fossil fuels."}},{"data": {- "title": "Test Document 2",- "snippet": "This is test content 2"+ "title": "Environmental Impact Study",+ "snippet": "Studies show that renewable energy significantly reduces carbon footprint and helps combat climate change."}}]@@ -670,26 +670,47 @@ async def test_cohere_v2_citations(stream):)if stream:- # Test streaming with citations- citations_found = False+ # Test streaming with annotations+ annotations_found = Falseasync for chunk in response:- if hasattr(chunk, 'citations') and chunk.citations:- citations_found = True- print(f"Streaming citations: {chunk.citations}")+ # Check if chunk has a message with annotations+ if (hasattr(chunk, 'choices') and chunk.choices and+ len(chunk.choices) > 0 and+ hasattr(chunk.choices[0], 'message') and+ hasattr(chunk.choices[0].message, 'annotations') and+ chunk.choices[0].message.annotations):+ annotations_found = True+ print(f"Streaming annotations: {chunk.choices[0].message.annotations}")break- # Note: Citations might not appear in every chunk during streaming+ # Note: Annotations might not appear in every chunk during streamingelse:- # Test non-streaming with citations+ # Test non-streaming with annotationsassert response.choices is not Noneassert len(response.choices) > 0- # Check for citations in response- if hasattr(response, 'citations') and response.citations:- assert len(response.citations) > 0- print(f"Citations: {response.citations}")+ # Check for annotations in message+ message = response.choices[0].message+ if hasattr(message, 'annotations') and message.annotations:+ assert len(message.annotations) > 0+ print(f"Annotations found: {len(message.annotations)}")++ # Validate annotation structure+ for annotation in message.annotations:+ assert annotation.get('type') == 'url_citation', f"Expected type 'url_citation', got {annotation.get('type')}"+ assert 'url_citation' in annotation, "Missing url_citation field"+ url_citation = annotation['url_citation']+ assert 'start_index' in url_citation, "Missing start_index"+ assert 'end_index' in url_citation, "Missing end_index"+ assert 'title' in url_citation, "Missing title"+ assert 'url' in url_citation, "Missing url"++ print(f"First annotation: {message.annotations[0]}")else:- # Citations might not always be present depending on the response- print("No citations in this response")+ # Annotations might not always be present depending on the response+ print("No annotations in this response")++ # Ensure citations field is NOT present (removed backward compatibility)+ assert not hasattr(response, 'citations'), "Citations field should be removed - no backward compatibility"except litellm.ServiceUnavailableError:pass