Skip to content

The agent engineering platform.

anthropic[patch]: always return content blocks if citations are generated (#29398)

ccurmeed797e17fbea
diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.py
index 36317fdd51..7085dc4b31 100644
--- a/libs/partners/anthropic/langchain_anthropic/chat_models.py
+++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py
@@ -764,7 +764,11 @@ class ChatAnthropic(BaseChatModel):
llm_output = {
k: v for k, v in data_dict.items() if k not in ("content", "role", "type")
}
- if len(content) == 1 and content[0]["type"] == "text":
+ if (
+ len(content) == 1
+ and content[0]["type"] == "text"
+ and "citations" not in content[0]
+ ):
msg = AIMessage(content=content[0]["text"])
elif any(block["type"] == "tool_use" for block in content):
tool_calls = extract_tool_calls(content)
diff --git a/libs/partners/anthropic/tests/integration_tests/test_chat_models.py b/libs/partners/anthropic/tests/integration_tests/test_chat_models.py
index 3da7bb94f9..ff1a56b7fc 100644
--- a/libs/partners/anthropic/tests/integration_tests/test_chat_models.py
+++ b/libs/partners/anthropic/tests/integration_tests/test_chat_models.py
@@ -622,3 +622,30 @@ def test_pdf_document_input() -> None:
assert isinstance(result, AIMessage)
assert isinstance(result.content, str)
assert len(result.content) > 0
+
+
+def test_citations() -> None:
+ llm = ChatAnthropic(model="claude-3-5-haiku-latest")
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "document",
+ "source": {
+ "type": "content",
+ "content": [
+ {"type": "text", "text": "The grass is green"},
+ {"type": "text", "text": "The sky is blue"},
+ ],
+ },
+ "citations": {"enabled": True},
+ },
+ {"type": "text", "text": "What color is the grass and sky?"},
+ ],
+ }
+ ]
+ response = llm.invoke(messages)
+ assert isinstance(response, AIMessage)
+ assert isinstance(response.content, list)
+ assert any("citations" in block for block in response.content)