citeformer 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. citeformer/__init__.py +78 -0
  2. citeformer/_version.py +8 -0
  3. citeformer/backends/__init__.py +28 -0
  4. citeformer/backends/anthropic.py +249 -0
  5. citeformer/backends/base.py +91 -0
  6. citeformer/backends/hf.py +285 -0
  7. citeformer/backends/llamacpp.py +171 -0
  8. citeformer/backends/mock.py +89 -0
  9. citeformer/backends/openai.py +333 -0
  10. citeformer/backends/vllm.py +133 -0
  11. citeformer/citeformer.py +338 -0
  12. citeformer/cli/__init__.py +9 -0
  13. citeformer/cli/app.py +165 -0
  14. citeformer/core.py +382 -0
  15. citeformer/csl.py +311 -0
  16. citeformer/grammar/__init__.py +31 -0
  17. citeformer/grammar/builder.py +221 -0
  18. citeformer/integrations/__init__.py +19 -0
  19. citeformer/integrations/langchain.py +176 -0
  20. citeformer/integrations/llamaindex.py +198 -0
  21. citeformer/metadata/__init__.py +39 -0
  22. citeformer/metadata/arxiv.py +143 -0
  23. citeformer/metadata/bibtex.py +431 -0
  24. citeformer/metadata/cache.py +38 -0
  25. citeformer/metadata/crossref.py +94 -0
  26. citeformer/metadata/pdf.py +111 -0
  27. citeformer/metadata/url.py +151 -0
  28. citeformer/metadata/zotero.py +116 -0
  29. citeformer/prompts.py +143 -0
  30. citeformer/py.typed +0 -0
  31. citeformer/render/__init__.py +39 -0
  32. citeformer/render/csl.py +96 -0
  33. citeformer/render/formatters/__init__.py +95 -0
  34. citeformer/render/formatters/_base.py +236 -0
  35. citeformer/render/formatters/apa.py +257 -0
  36. citeformer/render/formatters/chicago.py +236 -0
  37. citeformer/render/formatters/ieee.py +227 -0
  38. citeformer/render/formatters/mla.py +215 -0
  39. citeformer/render/formatters/nature.py +197 -0
  40. citeformer/render/formatters/vancouver.py +212 -0
  41. citeformer/render/styles.py +41 -0
  42. citeformer/verify/__init__.py +48 -0
  43. citeformer/verify/coverage.py +96 -0
  44. citeformer/verify/entailment.py +84 -0
  45. citeformer/verify/existence.py +59 -0
  46. citeformer/verify/nli.py +376 -0
  47. citeformer/verify/report.py +127 -0
  48. citeformer/verify/sentences.py +177 -0
  49. citeformer/verify/verifier.py +138 -0
  50. citeformer-0.1.0.dist-info/METADATA +342 -0
  51. citeformer-0.1.0.dist-info/RECORD +54 -0
  52. citeformer-0.1.0.dist-info/WHEEL +4 -0
  53. citeformer-0.1.0.dist-info/entry_points.txt +2 -0
  54. citeformer-0.1.0.dist-info/licenses/LICENSE +201 -0
citeformer/__init__.py ADDED
@@ -0,0 +1,78 @@
1
+ """citeformer — a bulletproof way to generate verifiably cited text from language models.
2
+
3
+ The public API surface:
4
+
5
+ - `Citeformer` — the orchestrator. Wrap a `Backend`, call `generate()`.
6
+ - Types: `Source`, `Citation`, `Reference`, `GenerationResult`, `Policy`.
7
+ - Verification: `VerificationReport`, `CitationSupport`.
8
+ - Backends: `Backend` (ABC) and `MockBackend` live here. Concrete backends
9
+ live on submodules that you import only if you install their extras:
10
+ ``citeformer.backends.hf.HFBackend``,
11
+ ``citeformer.backends.llamacpp.LlamaCppBackend``,
12
+ ``citeformer.backends.vllm.VLLMBackend``.
13
+ - Prompt helper: `build_rag_prompt` — assembles the canonical RAG prompt.
14
+ - Metadata helpers: `fetch_crossref`, `fetch_arxiv`, `extract_pdf`, `extract_url`.
15
+
16
+ See https://citeformer.readthedocs.io for documentation.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from citeformer._version import __version__
22
+ from citeformer.backends import Backend, MockBackend
23
+ from citeformer.citeformer import Citeformer, StreamingResult, deduplicate_adjacent_cites
24
+ from citeformer.core import (
25
+ Citation,
26
+ GenerationResult,
27
+ MarkerStyle,
28
+ Policy,
29
+ Reference,
30
+ Source,
31
+ )
32
+ from citeformer.csl import (
33
+ CSLValidationError,
34
+ ValidationReport,
35
+ validate_csl_json,
36
+ validate_source_metadata,
37
+ )
38
+ from citeformer.metadata import (
39
+ extract_pdf,
40
+ extract_url,
41
+ fetch_arxiv,
42
+ fetch_crossref,
43
+ load_bibtex,
44
+ load_zotero_csl,
45
+ )
46
+ from citeformer.prompts import build_rag_prompt
47
+ from citeformer.render import bundled_style_names, render_references
48
+ from citeformer.verify import CitationSupport, VerificationReport
49
+
50
+ __all__ = [
51
+ "Backend",
52
+ "CSLValidationError",
53
+ "Citation",
54
+ "CitationSupport",
55
+ "Citeformer",
56
+ "GenerationResult",
57
+ "MarkerStyle",
58
+ "MockBackend",
59
+ "Policy",
60
+ "Reference",
61
+ "Source",
62
+ "StreamingResult",
63
+ "ValidationReport",
64
+ "VerificationReport",
65
+ "__version__",
66
+ "build_rag_prompt",
67
+ "bundled_style_names",
68
+ "deduplicate_adjacent_cites",
69
+ "extract_pdf",
70
+ "extract_url",
71
+ "fetch_arxiv",
72
+ "fetch_crossref",
73
+ "load_bibtex",
74
+ "load_zotero_csl",
75
+ "render_references",
76
+ "validate_csl_json",
77
+ "validate_source_metadata",
78
+ ]
citeformer/_version.py ADDED
@@ -0,0 +1,8 @@
1
+ """Single source of truth for the citeformer package version.
2
+
3
+ Hatch reads this at build time (`[tool.hatch.version] path = ...` in pyproject.toml).
4
+ The release workflow bumps this value; never hand-edit it outside a `/bump` slash-command
5
+ or the `release-bump` skill ceremony.
6
+ """
7
+
8
+ __version__ = "0.1.0"
@@ -0,0 +1,28 @@
1
+ """Backend implementations for citeformer.
2
+
3
+ Each backend adapts a model runtime to the common `Backend` ABC (see `base.py`).
4
+ Only the `Backend` ABC and `MockBackend` are re-exported here because they
5
+ have no optional-extra dependencies. Import the real backends directly from
6
+ their submodules — they each require the matching extra:
7
+
8
+ **Local backends (logit-layer enforcement):**
9
+
10
+ - ``citeformer.backends.hf.HFBackend`` needs ``pip install citeformer[hf]``.
11
+ - ``citeformer.backends.llamacpp.LlamaCppBackend`` needs ``[llamacpp]``.
12
+ - ``citeformer.backends.vllm.VLLMBackend`` needs ``[vllm]`` (Linux/CUDA only).
13
+
14
+ **API backends (schema-layer or provider-native enforcement):**
15
+
16
+ - ``citeformer.backends.openai.OpenAIBackend`` needs ``[openai]``.
17
+ Enforces via OpenAI Structured Outputs ``strict=true`` JSON schema.
18
+ - ``citeformer.backends.anthropic.AnthropicBackend`` needs ``[anthropic]``.
19
+ Adapter over Anthropic's native Citations API — enforcement is
20
+ provider-side.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from citeformer.backends.base import Backend
26
+ from citeformer.backends.mock import MockBackend
27
+
28
+ __all__ = ["Backend", "MockBackend"]
@@ -0,0 +1,249 @@
1
+ """Anthropic backend — adapter over Anthropic's native Citations API.
2
+
3
+ Anthropic's Messages API has first-class Citations support (launched
4
+ Jan 2025): pass documents as `{"type": "document", ..., "citations": {"enabled": true}}`
5
+ and every assistant-side text block is decorated with an optional
6
+ ``citations`` array referencing the document index + character span.
7
+
8
+ This backend is an **adapter**, not an enforcement layer. Claude's own
9
+ system ensures the returned citation references point at a document that
10
+ was actually provided — so fabricating a reference is a provider-side
11
+ impossibility. We translate Anthropic's native shape back into citeformer's
12
+ :class:`~citeformer.core.Citation` / :class:`~citeformer.core.Reference`
13
+ types so downstream code can mix Anthropic output with local-backend output
14
+ in the same pipeline.
15
+
16
+ Because the enforcement is native, ``marker_style`` is advisory on this
17
+ backend — we render Claude's citations in the chosen shape for consistency
18
+ with the rest of citeformer, but the provider itself doesn't know about
19
+ marker styles; it emits a structured citation block per assertion.
20
+
21
+ Requires the ``anthropic`` extra: ``pip install citeformer[anthropic]``.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import logging
27
+ from collections.abc import Iterator
28
+ from typing import Any
29
+
30
+ from citeformer.backends.base import Backend
31
+ from citeformer.core import MarkerStyle, Policy, Source
32
+
33
+ _LOG = logging.getLogger(__name__)
34
+
35
+ _DEFAULT_MAX_TOKENS = 1024
36
+ _DEFAULT_MODEL = "claude-sonnet-4-6"
37
+
38
+
39
+ class AnthropicBackend(Backend):
40
+ """Anthropic Messages API backend with native citation support.
41
+
42
+ Attributes:
43
+ model: Anthropic model id (e.g. ``"claude-sonnet-4-6"``).
44
+ client: The ``anthropic.Anthropic`` client.
45
+ """
46
+
47
+ model: str
48
+ client: Any
49
+
50
+ def __init__(
51
+ self,
52
+ model: str = _DEFAULT_MODEL,
53
+ *,
54
+ client: Any | None = None,
55
+ **client_kwargs: Any,
56
+ ) -> None:
57
+ """Construct an Anthropic backend.
58
+
59
+ Args:
60
+ model: Anthropic model id supporting Citations (any 3.5+ or
61
+ Claude 4 family).
62
+ client: Pre-built ``anthropic.Anthropic`` client. If ``None``,
63
+ one is constructed from the environment (picks up
64
+ ``ANTHROPIC_API_KEY``).
65
+ **client_kwargs: Forwarded to ``Anthropic()`` when ``client`` is
66
+ ``None``.
67
+ """
68
+ try:
69
+ from anthropic import Anthropic
70
+ except ImportError as e:
71
+ raise ImportError(
72
+ "AnthropicBackend requires the `anthropic` extra. "
73
+ "Install with `pip install citeformer[anthropic]`."
74
+ ) from e
75
+
76
+ self.model = model
77
+ self.client = client if client is not None else Anthropic(**client_kwargs)
78
+
79
+ def generate(
80
+ self,
81
+ prompt: str,
82
+ sources: list[Source],
83
+ policy: Policy,
84
+ **options: Any,
85
+ ) -> str:
86
+ """Call Messages API with citations enabled; flatten to marker-decorated text.
87
+
88
+ Args:
89
+ prompt: User prompt.
90
+ sources: Sources in scope. Each becomes one document block.
91
+ policy: Citation policy — threaded into the system prompt so
92
+ Claude sees the caller's enforcement intent. The provider
93
+ itself doesn't have a typed policy, so we rely on the
94
+ system prompt to shape behaviour.
95
+ **options: ``max_tokens`` (default 1024), ``system_prompt``
96
+ (optional extra system content), ``marker_style`` (default
97
+ BRACKET — advisory, used to render citation markers).
98
+
99
+ Returns:
100
+ Flattened text carrying the configured marker style for every
101
+ assertion Claude cited.
102
+
103
+ Raises:
104
+ ValueError: If ``sources`` is empty.
105
+ """
106
+ if len(sources) < 1:
107
+ raise ValueError("AnthropicBackend requires at least 1 source")
108
+
109
+ max_tokens = int(options.get("max_tokens", _DEFAULT_MAX_TOKENS))
110
+ marker_style = options.get("marker_style", MarkerStyle.BRACKET)
111
+ system_prompt = _build_system_prompt(policy, options.get("system_prompt"))
112
+
113
+ documents = [
114
+ {
115
+ "type": "document",
116
+ "source": {
117
+ "type": "text",
118
+ "media_type": "text/plain",
119
+ "data": src.content or str(src.metadata.get("title", f"Source {i}")),
120
+ },
121
+ "title": str(src.metadata.get("title", f"Source {i}")),
122
+ "citations": {"enabled": True},
123
+ }
124
+ for i, src in enumerate(sources, start=1)
125
+ ]
126
+
127
+ message: Any = self.client.messages.create(
128
+ model=self.model,
129
+ max_tokens=max_tokens,
130
+ system=system_prompt,
131
+ messages=[
132
+ {
133
+ "role": "user",
134
+ "content": [
135
+ *documents,
136
+ {"type": "text", "text": prompt},
137
+ ],
138
+ }
139
+ ],
140
+ )
141
+ return _flatten_blocks(message.content, marker_style=marker_style)
142
+
143
+ def stream(
144
+ self,
145
+ prompt: str,
146
+ sources: list[Source],
147
+ policy: Policy,
148
+ **options: Any,
149
+ ) -> Iterator[str]:
150
+ """Yield the flattened response in sentence-sized chunks.
151
+
152
+ Anthropic's streaming surface is block-oriented; we take the simpler
153
+ path of calling :meth:`generate` once and slicing the result on
154
+ punctuation so downstream chunk consumers still see progression.
155
+ """
156
+ text = self.generate(prompt=prompt, sources=sources, policy=policy, **options)
157
+ buf: list[str] = []
158
+ for char in text:
159
+ buf.append(char)
160
+ if char in ".!?" and buf:
161
+ yield "".join(buf) + " "
162
+ buf = []
163
+ if buf:
164
+ yield "".join(buf)
165
+
166
+
167
+ def _build_system_prompt(policy: Policy, extra: str | None) -> str:
168
+ """Assemble the system prompt that nudges Claude to the right citation density."""
169
+ parts: list[str] = []
170
+ if extra:
171
+ parts.append(extra)
172
+ if policy is Policy.REQUIRED:
173
+ parts.append(
174
+ "Cite EVERY assertion in your response. Every sentence must "
175
+ "reference at least one provided document."
176
+ )
177
+ elif policy is Policy.QUOTES_ONLY:
178
+ parts.append(
179
+ "Cite any direct quotation from the provided documents. Paraphrases may be uncited."
180
+ )
181
+ else:
182
+ parts.append(
183
+ "Cite assertions that depend on specific information from the "
184
+ "provided documents. Avoid citing restatements of the user's "
185
+ "question."
186
+ )
187
+ return "\n\n".join(parts) if parts else "Cite your sources."
188
+
189
+
190
+ def _flatten_blocks(content: Any, *, marker_style: MarkerStyle) -> str:
191
+ """Fold Anthropic's block list back into plain text with inline markers.
192
+
193
+ The Messages API returns ``content`` as a list of blocks. Text blocks
194
+ (``block.type == 'text'``) may carry a ``citations`` list; each entry
195
+ has ``document_index`` (0-indexed into the order we supplied
196
+ documents). We emit a marker (``[N]`` / ``(N)`` / ``{N}`` / ``^N`` per
197
+ marker_style) for each citation at the *end* of the referenced text
198
+ block, remapping document_index → 1-indexed cite id.
199
+ """
200
+ open_char, close_char = _delimiters_for(marker_style)
201
+ parts: list[str] = []
202
+ for block in content or []:
203
+ block_type = getattr(block, "type", None) or (
204
+ block.get("type") if isinstance(block, dict) else None
205
+ )
206
+ if block_type != "text":
207
+ continue
208
+ text = str(
209
+ getattr(block, "text", None) or (block.get("text") if isinstance(block, dict) else "")
210
+ )
211
+ citations = (
212
+ getattr(block, "citations", None)
213
+ or (block.get("citations") if isinstance(block, dict) else None)
214
+ or []
215
+ )
216
+ seen: set[int] = set()
217
+ marker_suffix: list[str] = []
218
+ for cite in citations:
219
+ doc_index = (
220
+ getattr(cite, "document_index", None)
221
+ if not isinstance(cite, dict)
222
+ else cite.get("document_index")
223
+ )
224
+ if doc_index is None:
225
+ continue
226
+ cid = int(doc_index) + 1 # Anthropic is 0-indexed; we're 1-indexed
227
+ if cid not in seen:
228
+ seen.add(cid)
229
+ marker_suffix.append(f"{open_char}{cid}{close_char}")
230
+ joined = text.rstrip()
231
+ if marker_suffix:
232
+ suffix = " ".join(marker_suffix)
233
+ # If the text ends in sentence punctuation, put markers before it.
234
+ if joined and joined[-1] in ".!?":
235
+ parts.append(f"{joined[:-1]} {suffix}{joined[-1]}")
236
+ else:
237
+ parts.append(f"{joined} {suffix}")
238
+ else:
239
+ parts.append(joined)
240
+ return " ".join(parts).strip()
241
+
242
+
243
+ def _delimiters_for(style: MarkerStyle) -> tuple[str, str]:
244
+ return {
245
+ MarkerStyle.BRACKET: ("[", "]"),
246
+ MarkerStyle.PAREN: ("(", ")"),
247
+ MarkerStyle.CURLY: ("{", "}"),
248
+ MarkerStyle.CARET: ("^", ""),
249
+ }[style]
@@ -0,0 +1,91 @@
1
+ """Abstract backend interface.
2
+
3
+ Every concrete backend (`HFBackend`, `VLLMBackend`, `LlamaCppBackend`, `MockBackend`)
4
+ implements this ABC. The orchestration layer (`Citeformer`) is backend-agnostic and
5
+ delegates generation via this interface, keeping grammar-building and decoding logic
6
+ scoped to the backend that cares about them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from abc import ABC, abstractmethod
12
+ from collections.abc import Iterator
13
+ from typing import Any
14
+
15
+ from citeformer.core import Policy, Source
16
+
17
+
18
+ class Backend(ABC):
19
+ """Abstract backend for citeformer.
20
+
21
+ Subclasses implement `generate()` against a specific model runtime (HF transformers,
22
+ vLLM, llama.cpp, plus the `MockBackend`). Constrained-decoding grammar construction
23
+ is the backend's responsibility — each runtime has a different native format
24
+ (XGrammar object, GBNF string, etc.), so the shared `grammar/builder.py` module
25
+ emits a backend-agnostic intermediate representation that each backend converts as
26
+ needed.
27
+
28
+ Subclasses may optionally override `stream()` to yield chunks as the model decodes
29
+ them. The default implementation falls back to `generate()` and emits the full
30
+ text as a single chunk — any backend works with `Citeformer.stream()`, but only
31
+ overriding backends deliver true token-by-token behavior.
32
+ """
33
+
34
+ @abstractmethod
35
+ def generate(
36
+ self,
37
+ prompt: str,
38
+ sources: list[Source],
39
+ policy: Policy,
40
+ **options: Any,
41
+ ) -> str:
42
+ """Generate text with citation markers constrained to the given sources.
43
+
44
+ The returned string contains inline `[N]` markers where `N` is a 1-indexed
45
+ position into `sources`. On grammar-level-enforcing backends (HF, vLLM,
46
+ llama.cpp via their constrained-decoding integration) emitting an `[N]` for
47
+ `N > len(sources)` is token-impossible; `MockBackend` in tests just respects
48
+ the contract by construction.
49
+
50
+ Args:
51
+ prompt: User prompt. The orchestration layer is responsible for
52
+ constructing a retrieval-augmented prompt (stitching in source
53
+ snippets); this method receives the final prompt string.
54
+ sources: Sources in scope; position determines citation index.
55
+ policy: Citation enforcement policy.
56
+ **options: Backend-specific decoding options (e.g. `max_tokens`,
57
+ `temperature`, `seed`). Unknown options are silently ignored.
58
+
59
+ Returns:
60
+ The generated text with inline markers. References are not part of the
61
+ backend output — the orchestration layer renders them separately.
62
+ """
63
+
64
+ def stream(
65
+ self,
66
+ prompt: str,
67
+ sources: list[Source],
68
+ policy: Policy,
69
+ **options: Any,
70
+ ) -> Iterator[str]:
71
+ """Yield generation output as a stream of text chunks.
72
+
73
+ The default implementation is not a true stream: it calls `generate()` and
74
+ yields the full text as a single chunk. Backends that can produce
75
+ token-by-token output (HF, llama.cpp) should override this to yield chunks
76
+ as they're decoded — the grammar constraints apply to every yielded chunk
77
+ exactly as in `generate()`.
78
+
79
+ Args:
80
+ prompt: See `generate()`.
81
+ sources: See `generate()`.
82
+ policy: See `generate()`.
83
+ **options: See `generate()`. Most backends also accept streaming-specific
84
+ hints here (e.g. XGrammar's LogitsProcessor is already stateful, so
85
+ no extra plumbing is needed).
86
+
87
+ Yields:
88
+ Text chunks in the order they're produced. Joining all yielded chunks
89
+ reconstructs what `generate()` would have returned.
90
+ """
91
+ yield self.generate(prompt=prompt, sources=sources, policy=policy, **options)