-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Add Anthropic Citation API support #8721
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TomeHirata
wants to merge
13
commits into
stanfordnlp:main
Choose a base branch
from
TomeHirata:feat/citation-api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
06e3449
Add Anthropic citation support
TomeHirata 1c4a3a7
simplify
TomeHirata 4544996
fix field names
TomeHirata 60c8ff0
use recent model
TomeHirata b2fddf8
address comments
TomeHirata c001c7b
remove metadata
TomeHirata 5f3b762
fix test
TomeHirata 3deaa95
support citation streaming
TomeHirata acb0a5b
add supported text
TomeHirata 9e9279c
simplify
TomeHirata 86dcde3
error message
TomeHirata 8f46b3d
comment
TomeHirata 02e702e
fix nest
TomeHirata File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,10 @@ | ||
from dspy.adapters.types.audio import Audio | ||
from dspy.adapters.types.base_type import Type | ||
from dspy.adapters.types.citation import Citations | ||
from dspy.adapters.types.code import Code | ||
from dspy.adapters.types.document import Document | ||
from dspy.adapters.types.history import History | ||
from dspy.adapters.types.image import Image | ||
from dspy.adapters.types.tool import Tool, ToolCalls | ||
|
||
__all__ = ["History", "Image", "Audio", "Type", "Tool", "ToolCalls", "Code"] | ||
__all__ = ["History", "Image", "Audio", "Type", "Tool", "ToolCalls", "Code", "Citations", "Document"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,165 @@ | ||
from typing import Any | ||
|
||
import pydantic | ||
|
||
from dspy.adapters.types.base_type import Type | ||
|
||
|
||
class Citations(Type): | ||
"""Citations extracted from an LM response with source references. | ||
This type represents citations returned by language models that support | ||
citation extraction, particularly Anthropic's Citations API through LiteLLM. | ||
Citations include the quoted text and source information. | ||
Example: | ||
```python | ||
import dspy | ||
from dspy.signatures import Signature | ||
class AnswerWithSources(Signature): | ||
'''Answer questions using provided documents with citations.''' | ||
documents: list[dspy.Document] = dspy.InputField() | ||
question: str = dspy.InputField() | ||
answer: str = dspy.OutputField() | ||
citations: dspy.Citations = dspy.OutputField() | ||
# Create documents to provide as sources | ||
docs = [ | ||
dspy.Document( | ||
data="The Earth orbits the Sun in an elliptical path.", | ||
title="Basic Astronomy Facts" | ||
), | ||
dspy.Document( | ||
data="Water boils at 100°C at standard atmospheric pressure.", | ||
title="Physics Fundamentals", | ||
metadata={"author": "Dr. Smith", "year": 2023} | ||
) | ||
] | ||
# Use with a model that supports citations like Claude | ||
lm = dspy.LM("anthropic/claude-opus-4-1-20250805") | ||
predictor = dspy.Predict(AnswerWithSources, lm=lm) | ||
result = predictor(documents=docs, question="What temperature does water boil?") | ||
for citation in result.citations.citations: | ||
print(citation.format()) | ||
``` | ||
""" | ||
|
||
class Citation(Type): | ||
"""Individual citation with character location information.""" | ||
type: str = "char_location" | ||
cited_text: str | ||
document_index: int | ||
document_title: str | None = None | ||
start_char_index: int | ||
end_char_index: int | ||
supported_text: str | None = None | ||
|
||
def format(self) -> dict[str, Any]: | ||
"""Format citation as dictionary for LM consumption. | ||
Returns: | ||
A dictionary in the format expected by citation APIs. | ||
""" | ||
citation_dict = { | ||
"type": self.type, | ||
"cited_text": self.cited_text, | ||
"document_index": self.document_index, | ||
"start_char_index": self.start_char_index, | ||
"end_char_index": self.end_char_index | ||
} | ||
|
||
if self.document_title: | ||
citation_dict["document_title"] = self.document_title | ||
|
||
if self.supported_text: | ||
citation_dict["supported_text"] = self.supported_text | ||
|
||
return citation_dict | ||
|
||
citations: list[Citation] | ||
|
||
@classmethod | ||
def from_dict_list(cls, citations_dicts: list[dict[str, Any]]) -> "Citations": | ||
"""Convert a list of dictionaries to a Citations instance. | ||
Args: | ||
citations_dicts: A list of dictionaries, where each dictionary should have 'cited_text' key | ||
and 'document_index', 'start_char_index', 'end_char_index' keys. | ||
Returns: | ||
A Citations instance. | ||
Example: | ||
```python | ||
citations_dict = [ | ||
{ | ||
"cited_text": "The sky is blue", | ||
"document_index": 0, | ||
"document_title": "Weather Guide", | ||
"start_char_index": 0, | ||
"end_char_index": 15, | ||
"supported_text": "The sky was blue yesterday." | ||
} | ||
] | ||
citations = Citations.from_dict_list(citations_dict) | ||
``` | ||
""" | ||
citations = [cls.Citation(**item) for item in citations_dicts] | ||
return cls(citations=citations) | ||
|
||
@classmethod | ||
def description(cls) -> str: | ||
"""Description of the citations type for use in prompts.""" | ||
return ( | ||
"Citations with quoted text and source references. " | ||
"Include the exact text being cited and information about its source." | ||
) | ||
|
||
def format(self) -> list[dict[str, Any]]: | ||
"""Format citations as a list of dictionaries.""" | ||
return [citation.format() for citation in self.citations] | ||
|
||
@pydantic.model_validator(mode="before") | ||
@classmethod | ||
def validate_input(cls, data: Any): | ||
if isinstance(data, cls): | ||
return data | ||
|
||
# Handle case where data is a list of dicts with citation info | ||
if isinstance(data, list) and all( | ||
isinstance(item, dict) and "cited_text" in item for item in data | ||
): | ||
return {"citations": [cls.Citation(**item) for item in data]} | ||
|
||
# Handle case where data is a dict | ||
elif isinstance(data, dict): | ||
if "citations" in data: | ||
# Handle case where data is a dict with "citations" key | ||
citations_data = data["citations"] | ||
if isinstance(citations_data, list): | ||
return { | ||
"citations": [ | ||
cls.Citation(**item) if isinstance(item, dict) else item | ||
for item in citations_data | ||
] | ||
} | ||
elif "cited_text" in data: | ||
# Handle case where data is a single citation dict | ||
return {"citations": [cls.Citation(**data)]} | ||
|
||
raise ValueError(f"Received invalid value for `dspy.Citations`: {data}") | ||
|
||
def __iter__(self): | ||
"""Allow iteration over citations.""" | ||
return iter(self.citations) | ||
|
||
def __len__(self): | ||
"""Return the number of citations.""" | ||
return len(self.citations) | ||
|
||
def __getitem__(self, index): | ||
"""Allow indexing into citations.""" | ||
return self.citations[index] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
from typing import Any, Literal | ||
|
||
import pydantic | ||
|
||
from dspy.adapters.types.base_type import Type | ||
|
||
|
||
class Document(Type): | ||
"""A document type for providing content that can be cited by language models. | ||
|
||
This type represents documents that can be passed to language models for citation-enabled | ||
responses, particularly useful with Anthropic's Citations API. Documents include the content | ||
and metadata that helps the LM understand and reference the source material. | ||
|
||
Attributes: | ||
data: The text content of the document | ||
title: Optional title for the document (used in citations) | ||
media_type: MIME type of the document content (defaults to "text/plain") | ||
context: Optional context information about the document | ||
|
||
Example: | ||
```python | ||
import dspy | ||
from dspy.signatures import Signature | ||
|
||
class AnswerWithSources(Signature): | ||
'''Answer questions using provided documents with citations.''' | ||
documents: list[dspy.Document] = dspy.InputField() | ||
question: str = dspy.InputField() | ||
answer: str = dspy.OutputField() | ||
citations: dspy.Citations = dspy.OutputField() | ||
|
||
# Create documents | ||
docs = [ | ||
dspy.Document( | ||
data="The Earth orbits the Sun in an elliptical path.", | ||
title="Basic Astronomy Facts" | ||
), | ||
dspy.Document( | ||
data="Water boils at 100°C at standard atmospheric pressure.", | ||
title="Physics Fundamentals", | ||
) | ||
] | ||
|
||
# Use with a citation-supporting model | ||
lm = dspy.LM("anthropic/claude-opus-4-1-20250805") | ||
predictor = dspy.Predict(AnswerWithSources) | ||
result = predictor(documents=docs, question="What temperature does water boil?", lm=lm) | ||
print(result.citations) | ||
``` | ||
""" | ||
|
||
data: str | ||
title: str | None = None | ||
media_type: Literal["text/plain", "application/pdf"] = "text/plain" | ||
context: str | None = None | ||
|
||
def format(self) -> list[dict[str, Any]]: | ||
"""Format document for LM consumption. | ||
|
||
Returns: | ||
A list containing the document block in the format expected by citation-enabled language models. | ||
""" | ||
document_block = { | ||
"type": "document", | ||
"source": { | ||
"type": "text", | ||
"media_type": self.media_type, | ||
"data": self.data | ||
}, | ||
"citations": {"enabled": True} | ||
} | ||
|
||
if self.title: | ||
document_block["title"] = self.title | ||
|
||
if self.context: | ||
document_block["context"] = self.context | ||
|
||
return [document_block] | ||
|
||
|
||
|
||
@classmethod | ||
TomeHirata marked this conversation as resolved.
Show resolved
Hide resolved
|
||
def description(cls) -> str: | ||
"""Description of the document type for use in prompts.""" | ||
return ( | ||
"A document containing text content that can be referenced and cited. " | ||
"Include the full text content and optionally a title for proper referencing." | ||
) | ||
|
||
@pydantic.model_validator(mode="before") | ||
@classmethod | ||
def validate_input(cls, data: Any): | ||
if isinstance(data, cls): | ||
return data | ||
|
||
# Handle case where data is just a string (data only) | ||
if isinstance(data, str): | ||
return {"data": data} | ||
|
||
# Handle case where data is a dict | ||
elif isinstance(data, dict): | ||
return data | ||
|
||
raise ValueError(f"Received invalid value for `dspy.Document`: {data}") | ||
|
||
def __str__(self) -> str: | ||
"""String representation showing title and content length.""" | ||
title_part = f"'{self.title}': " if self.title else "" | ||
return f"Document({title_part}{len(self.data)} chars)" |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.