verbatim_core API Reference
Transformer
verbatim_core.transformer.Transformer
Turn a question and chunks into a cited answer, built from spans of the chunks.
The first spans fill the template of the answer, and every span gets one citation that points at it by chunk id and offsets. One transformer can serve concurrent calls: the settings of a call come in its config, and nothing is set on the transformer between calls.
Source code in packages/core/verbatim_core/transformer.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
config
property
The settings of a call that passes none: the config given, else the templates'.
__init__(extractor, templates, *, config=None)
Build a transformer from an extractor and the templates of the answers.
:param extractor: Extracts the spans of the chunks :param templates: The templates the answers are written with :param config: The settings of a call, unless the call passes its own. Without it, the templates' settings are the default. :raises ConfigurationError: If the config is not a TransformConfig, or asks for structured template mode
Source code in packages/core/verbatim_core/transformer.py
transform(question, chunks, *, config=None)
Write a cited answer to the question from the chunks.
:param question: The question :param chunks: Chunks with unique ids :param config: Replaces the transformer's default config for this call :return: The answer, with its citations, spans, usage and warnings :raises InvalidInputError: If two chunks share an id, or the config is of the wrong type or asks for structured template mode :raises UpstreamError: If a service the extractor calls fails :raises ConfigurationError: If a service rejects its key, model or quota
Source code in packages/core/verbatim_core/transformer.py
atransform(question, chunks, *, config=None)
async
Async version of transform.
Source code in packages/core/verbatim_core/transformer.py
stream(question, chunks, *, config=None)
Write the answer of transform as events: the spans, then the answer.
:raises InvalidInputError: When called, if the config is of the wrong type or asks for
structured template mode. The other errors of transform come from the iteration.
Source code in packages/core/verbatim_core/transformer.py
astream(question, chunks, *, config=None)
Async version of stream.
Source code in packages/core/verbatim_core/transformer.py
TransformConfig
verbatim_core.transformer.TransformConfig
Bases: BaseModel
Settings of a Transformer call.
Source code in packages/core/verbatim_core/_transform_config.py
VerbatimTransform
verbatim_core.transform.VerbatimTransform
RAG-agnostic verbatim transform over a Transformer (sync/async).
Context items become chunks with positional ids (ctx_0, ctx_1, ...), and the Transformer's
answer becomes a QueryResponse. The template manager's settings apply, with this transform's
number of displayed spans.
Source code in packages/core/verbatim_core/transform.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
__init__(llm_client=None, extractor=None, template_manager=None, max_display_spans=_DEFAULT_MAX_DISPLAY_SPANS, extraction_mode='auto', template_mode='contextual', span_match_mode='exact', fuzzy_threshold=0.8, extraction_prompt=None, system_prompt=None)
Build the transform from its parts, with defaults for the parts not given.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm_client
|
LLMClient | None
|
The client of the default extractor and template manager. Defaults to
|
None
|
extractor
|
SpanExtractor[Any] | None
|
The span extractor. Defaults to an |
None
|
template_manager
|
TemplateManager | None
|
The templates. Defaults to a |
None
|
max_display_spans
|
int
|
The number of spans shown in the answer. The rest are cited for reference only. |
_DEFAULT_MAX_DISPLAY_SPANS
|
extraction_mode
|
str
|
"batch", "individual" or "auto", for the default extractor. |
'auto'
|
template_mode
|
str
|
The template mode of the default template manager. |
'contextual'
|
span_match_mode
|
str
|
"exact" or "fuzzy", for the default extractor. |
'exact'
|
fuzzy_threshold
|
float
|
How closely, from 0 to 1, a quote must match the chunk text in fuzzy mode, for the default extractor. |
0.8
|
extraction_prompt
|
str | None
|
A Jinja2 prompt for the default extractor, instead of the bundled one. |
None
|
system_prompt
|
str | None
|
The system message of the default extractor, sent only with
|
None
|
Source code in packages/core/verbatim_core/transform.py
transform(question, context, answer=None)
Answer the question from the context items, with citations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The question to answer. |
required |
context
|
Iterable[dict[str, Any]]
|
Dicts with "content" or "text", and optionally "title", "source" and "metadata", or objects with a text attribute. |
required |
answer
|
str | None
|
Ignored. |
None
|
Returns:
| Type | Description |
|---|---|
QueryResponse
|
The cited answer. |
Raises:
| Type | Description |
|---|---|
InvalidInputError
|
If a context item has another shape. |
ConfigurationError
|
If the template manager is in structured mode. |
Source code in packages/core/verbatim_core/transform.py
transform_async(question, context, answer=None)
async
Async version of transform.
Source code in packages/core/verbatim_core/transform.py
LLMSpanExtractor
verbatim_core.extractors.LLMSpanExtractor
Bases: SpanExtractor[LLMExtractConfig]
Extract spans with an LLM that quotes the text of each chunk that answers the question.
Each quote is located in its chunk: the first exact occurrence, else in fuzzy match mode the
best fuzzy match, the earliest on a tie. A span's text is the chunk's text at the located
offsets, never the quote. A quote that can't be located is dropped and reported in the
result's warnings with the code quote_not_found. Every span has the score 1.0, "extracted
without a score".
A failed LLM call raises, and the whole extraction fails.
Source code in packages/core/verbatim_core/extractors.py
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 | |
__init__(llm_client=None, model=_UNSET, extraction_mode=_UNSET, max_display_spans=_UNSET, batch_size=_UNSET, span_match_mode=_UNSET, fuzzy_threshold=_UNSET, extraction_prompt=_UNSET, system_prompt=_UNSET, *, config=None)
Build an extractor over an LLM client.
:param llm_client: The client that makes the LLM calls :param config: The settings of a call, unless the call passes its own
The other arguments are deprecated. Without llm_client the extractor builds an
LLMClient(model). The settings from extraction_mode to system_prompt belong in
config, and max_display_spans is unused.
:raises ConfigurationError: If config is not an LLMExtractConfig, is passed
together with the deprecated settings, or a deprecated setting has an invalid value
Source code in packages/core/verbatim_core/extractors.py
extract(question, chunks, *, config=None)
Extract the spans of the chunks that are relevant to the question.
:param question: The query or question :param chunks: Chunks with unique ids :param config: Replaces the extractor's default config for this call :return: The spans, with the usage and warnings of the call :raises InvalidInputError: If two chunks share an id, or the config is of the wrong type :raises UpstreamError: If an LLM call fails or its reply can't be read :raises ConfigurationError: If the LLM service rejects the key, the model or the quota
Source code in packages/core/verbatim_core/extractors.py
aextract(question, chunks, *, config=None)
async
Async version of extract. It makes its LLM calls concurrently.
Source code in packages/core/verbatim_core/extractors.py
extract_spans(question, search_results)
Extract relevant spans from search results.
Unlike extract, it tolerates failed LLM calls. When a batch call fails, it retries the
chunks of the batch one by one, and a chunk whose call fails yields no spans.
:param question: The query or question :param search_results: List of search results to extract from :return: Dictionary mapping result text to list of relevant spans
Source code in packages/core/verbatim_core/extractors.py
extract_spans_async(question, search_results)
async
Async version of extract_spans.
Source code in packages/core/verbatim_core/extractors.py
SpanExtractor
verbatim_core.extractors.SpanExtractor
Bases: ABC, Generic[_ConfigT]
Base class for span extractors.
A subclass implements extract, and aextract when it has a native async path. Otherwise
aextract runs extract in a worker thread. The type argument is the subclass's config
class, as in SpanExtractor[LLMExtractConfig].
A subclass written against the old interface implements only extract_spans. It gets
extract and aextract from this class, which locate each span text in its chunk and warn
that the subclass should implement extract. A span text that can't be located is dropped
and reported in the result's warnings with the code span_text_not_found.
Of a subclass's methods, the one defined in the most specific class is the implementation. A
subclass of an extractor that overrides extract_spans, as subclasses written before 0.3.0
did, is called through it like a subclass that implements only extract_spans. A subclass
that overrides extract below a parent's aextract gets an aextract that runs its
extract in a worker thread. A call's LLM calls then run one after another: to keep the
parent's concurrent aextract, override aextract too, for example with
await super().aextract(...) and the same changes to its result as in extract.
Source code in packages/core/verbatim_core/extractors.py
__init_subclass__(**kwargs)
Check that the subclass implements extract or extract_spans, and route its calls.
Source code in packages/core/verbatim_core/extractors.py
extract(question, chunks, *, config=None)
Extract the spans of the chunks that are relevant to the question.
:param question: The query or question :param chunks: Chunks with unique ids :param config: Replaces the extractor's default config for this call :return: The spans, with the usage and warnings of the call :raises InvalidInputError: If two chunks share an id
Source code in packages/core/verbatim_core/extractors.py
aextract(question, chunks, *, config=None)
async
Async version of extract.
Source code in packages/core/verbatim_core/extractors.py
extract_spans(question, search_results)
Extract relevant spans from search results.
:param question: The query or question :param search_results: List of search results to extract from :return: Dictionary mapping result text to list of relevant spans
Source code in packages/core/verbatim_core/extractors.py
extract_spans_async(question, search_results)
async
Async version of extract_spans.
Source code in packages/core/verbatim_core/extractors.py
LLMClient
verbatim_core.llm_client.LLMClient
Centralized LLM interaction handler with async support.
Provides a unified interface for all OpenAI API calls used throughout the Verbatim RAG system, including span extraction and template generation.
Source code in packages/core/verbatim_core/llm_client.py
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 | |
__init__(model='gpt-4o-mini', temperature=0.7, api_base='https://api.openai.com/v1', api_key=None)
Initialize the LLM client.
:param model: The OpenAI model to use :param temperature: Default temperature for completions :param api_base: The base URL for the OpenAI API (can be used with custom models and with VLLM) :param api_key: Optional API key. Falls back to OPENAI_API_KEY when unset.
Source code in packages/core/verbatim_core/llm_client.py
complete(prompt, json_mode=False, temperature=None, system_prompt=None)
Complete text synchronously.
:param prompt: The prompt to send :param json_mode: Whether to request JSON output format :param temperature: Override default temperature :param system_prompt: Optional system message to prepend :return: The completion text :raises UpstreamError: If the call fails or the reply is empty :raises ConfigurationError: If the service rejects the key, the model or the quota
Source code in packages/core/verbatim_core/llm_client.py
complete_async(prompt, json_mode=False, temperature=None, system_prompt=None)
async
Asynchronous text completion. See complete.
Source code in packages/core/verbatim_core/llm_client.py
completion(prompt, *, json_mode=False, temperature=None, system_prompt=None)
Like complete, and also returns the model name and the token counts the provider sent.
Source code in packages/core/verbatim_core/llm_client.py
completion_async(prompt, *, json_mode=False, temperature=None, system_prompt=None)
async
Asynchronous version of completion.
Source code in packages/core/verbatim_core/llm_client.py
extract_spans(question, documents)
Specialized method for span extraction from documents.
:param question: The user's question :param documents: Dictionary mapping doc IDs to document text :return: Dictionary mapping doc IDs to lists of extracted spans
Source code in packages/core/verbatim_core/llm_client.py
extract_spans_async(question, documents)
async
Async span extraction from documents.
:param question: The user's question :param documents: Dictionary mapping doc IDs to document text :return: Dictionary mapping doc IDs to lists of extracted spans
Source code in packages/core/verbatim_core/llm_client.py
extract_structured(question, template, placeholders, documents)
Extract spans organized by template placeholders with document attribution.
:param question: The user's question :param template: Template with placeholders like [METHODOLOGY] :param placeholders: Dict mapping placeholder names to hints :param documents: List of document texts :return: Dict mapping placeholder names to lists of {text, doc} objects
Source code in packages/core/verbatim_core/llm_client.py
extract_structured_async(question, template, placeholders, documents)
async
Async version of structured extraction with document attribution.
:param question: The user's question :param template: Template with placeholders like [METHODOLOGY] :param placeholders: Dict mapping placeholder names to hints :param documents: List of document texts :return: Dict mapping placeholder names to lists of {text, doc} objects
Source code in packages/core/verbatim_core/llm_client.py
generate_template(question, spans, citation_count, use_per_fact=True, template_preview_chars=100, preserve_span_newlines=False, template_prompt=None, system_prompt=None)
Generate a contextual template for the given question and spans.
:param question: The user's question :param spans: List of spans that will fill the template :param citation_count: Number of citation-only spans :param use_per_fact: Whether to use per-span placeholders :param template_preview_chars: Max chars per span shown to the template LLM. None = no truncation. Default 100 reproduces pre-0.2.8 behaviour. :param preserve_span_newlines: Keep newlines in spans shown to the template LLM. Default False collapses them (pre-0.2.8 behaviour). :param template_prompt: Custom Jinja2 prompt string. Variables available: question, n_spans, citation_count, spans_block (per-fact) or span_preview (aggregate). None uses the bundled prompt. :param system_prompt: System message for the template-generation call. :return: Generated template string
Source code in packages/core/verbatim_core/llm_client.py
generate_template_async(question, spans, citation_count, use_per_fact=True, template_preview_chars=100, preserve_span_newlines=False, template_prompt=None, system_prompt=None)
async
Async template generation. See generate_template for parameter docs.
Source code in packages/core/verbatim_core/llm_client.py
template_completion(question, spans, citation_count, use_per_fact=True, template_preview_chars=100, preserve_span_newlines=False, template_prompt=None, system_prompt=None)
Like generate_template, but returns the completion and raises when the call fails.
:raises UpstreamError: If the call fails or the reply is empty :raises ConfigurationError: If the service rejects the key, the model or the quota
Source code in packages/core/verbatim_core/llm_client.py
template_completion_async(question, spans, citation_count, use_per_fact=True, template_preview_chars=100, preserve_span_newlines=False, template_prompt=None, system_prompt=None)
async
Async version of template_completion.
Source code in packages/core/verbatim_core/llm_client.py
extract_relevant_spans_batch(question, documents)
Extract spans for a batch of documents. Same as extract_spans.
extract_relevant_spans_batch_async(question, documents)
async
Extract spans for a batch of documents asynchronously. Same as extract_spans_async.
Source code in packages/core/verbatim_core/llm_client.py
extract_relevant_spans(question, document_text)
Extract spans from a single document.
Source code in packages/core/verbatim_core/llm_client.py
extract_relevant_spans_async(question, document_text)
async
Extract spans from a single document asynchronously.
Source code in packages/core/verbatim_core/llm_client.py
simple_complete(prompt)
simple_complete_async(prompt)
async
ResponseBuilder
verbatim_core.response_builder.ResponseBuilder
Builds structured query responses with highlights and citations.
Takes search results and extracted spans and creates a complete QueryResponse object with proper document highlighting and citation tracking.
Source code in packages/core/verbatim_core/response_builder.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
__init__()
build_response(question, answer, search_results, relevant_spans, display_span_count=None)
Build a complete QueryResponse from components.
:param question: The original question :param answer: The generated answer text :param search_results: List of search results from the index :param relevant_spans: Dict mapping document text to extracted spans :param display_span_count: Number of spans to display vs cite-only :return: Complete QueryResponse object
Source code in packages/core/verbatim_core/response_builder.py
build_from_answer(question, answer, chunks)
Build a QueryResponse from an answer and the chunks it was written from.
Each citation's span is highlighted at its offsets, without searching for its text. When it overlaps a span cited before it in the same chunk, the earlier one keeps the highlight, and the later one gets neither a highlight nor a citation in the response.
:param question: The original question :param answer: The answer, whose citations point at spans of the chunks :param chunks: The chunks the answer was written from, in the order of the documents :return: Complete QueryResponse object :raises InvalidInputError: If two chunks share an id, or a citation points outside them
Source code in packages/core/verbatim_core/response_builder.py
clean_answer(answer)
Clean up generated answer text.
Removes common formatting issues and artifacts from LLM generation.
:param answer: Raw answer text from generation :return: Cleaned answer text
Source code in packages/core/verbatim_core/response_builder.py
TemplateManager
verbatim_core.templates.manager.TemplateManager
Template manager with strategy pattern and mode selection.
Manages different template strategies and provides a unified interface for template generation and filling. Supports persistence of configuration across sessions.
Its settings, config, are the default settings of a Transformer built with it.
Source code in packages/core/verbatim_core/templates/manager.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 | |
current_mode
property
writable
The template mode of config.
citation_mode
property
writable
The citation mode of config.
__init__(llm_client=None, default_mode='static', rag_system=None)
Initialize template manager.
:param llm_client: Optional LLM client for contextual and random modes :param default_mode: Default template mode ("static", "contextual", "random", "question_specific", "structured") :param rag_system: Optional RAG system for structured mode
Source code in packages/core/verbatim_core/templates/manager.py
set_mode(mode)
Switch to a different template mode.
Deprecated: pass TransformConfig(template_mode=...) to the Transformer or its call.
:param mode: Template mode to switch to :return: True if mode was switched successfully
Source code in packages/core/verbatim_core/templates/manager.py
get_current_mode()
strategy(mode)
Return the strategy of a template mode, without switching to it.
:param mode: Template mode :return: The strategy, or None if the mode needs an LLM client the manager doesn't have :raises KeyError: If there is no such mode
Source code in packages/core/verbatim_core/templates/manager.py
get_available_modes()
Get list of available template modes.
:return: List of mode names that are available
Source code in packages/core/verbatim_core/templates/manager.py
process(question, display_spans, citation_spans)
Generate and fill a template in one operation.
:param question: The user's question :param display_spans: Spans to display with full text :param citation_spans: Spans for citation reference only :return: Completed response text
Source code in packages/core/verbatim_core/templates/manager.py
process_async(question, display_spans, citation_spans)
async
Async version of process for contextual templates.
:param question: The user's question :param display_spans: Spans to display with full text :param citation_spans: Spans for citation reference only :return: Completed response text
Source code in packages/core/verbatim_core/templates/manager.py
get_template(question='', spans=None, citation_count=0)
Generate a template without filling it.
:param question: The user's question :param spans: List of spans that will fill the template :param citation_count: Number of citation-only spans :return: Template string with placeholders
Source code in packages/core/verbatim_core/templates/manager.py
fill_template(template, display_spans, citation_spans)
Fill a template with content.
:param template: Template string with placeholders :param display_spans: Spans to display with full text :param citation_spans: Spans for citation reference only :return: Filled template
Source code in packages/core/verbatim_core/templates/manager.py
save(filepath)
Save all template configurations to file.
:param filepath: Path to save configuration
Source code in packages/core/verbatim_core/templates/manager.py
load(filepath)
Load template configurations from file.
:param filepath: Path to load configuration from :return: True if loaded successfully
Source code in packages/core/verbatim_core/templates/manager.py
info()
Get current template manager state information.
:return: Dictionary with current state info
Source code in packages/core/verbatim_core/templates/manager.py
use_static_mode(template=None)
Switch to static mode with optional custom template.
:param template: Optional custom template
Source code in packages/core/verbatim_core/templates/manager.py
use_contextual_mode(use_per_fact=True, template_preview_chars=100, preserve_span_newlines=False, template_prompt=None, system_prompt=None)
Switch to contextual mode with configuration.
:param use_per_fact: Whether to use per-span placeholders (≤8 spans). :param template_preview_chars: Max chars per span in the template-gen prompt. None = full span. Default 100 (pre-0.2.8 behaviour). :param preserve_span_newlines: Keep newlines in spans shown to the template LLM. :param template_prompt: Custom Jinja2 prompt string (see ContextualTemplate). :param system_prompt: System message for the template-generation call. :return: True if switched successfully
Source code in packages/core/verbatim_core/templates/manager.py
use_random_mode(templates=None)
Switch to random mode with optional template pool.
:param templates: Optional list of templates :return: True if switched successfully
Source code in packages/core/verbatim_core/templates/manager.py
generate_random_templates(count=10)
Generate diverse random templates if in random mode.
:param count: Number of templates to generate :return: True if generation was attempted
Source code in packages/core/verbatim_core/templates/manager.py
use_question_specific_mode(templates=None, *, embedder=None)
Switch to question-specific mode with optional template definitions.
:param templates: Optional list of template configs, each with a "template" and its
"examples": [{
"template": "Template with [RELEVANT_SENTENCES]",
"examples": ["Example question 1", "Example question 2"]
}]
:param embedder: A loaded embedding model, such as a SentenceTransformer, that embeds the
examples and questions. See QuestionSpecificTemplate.
:return: True if switched successfully
Source code in packages/core/verbatim_core/templates/manager.py
use_structured_mode(template=None, placeholder_mappings=None)
Switch to structured mode with semantic placeholders.
:param template: Template with semantic placeholders like [METHODOLOGY], [RESULTS] :param placeholder_mappings: Custom placeholder → query mappings :return: True if switched successfully
Example
manager.use_structured_mode( template="# Analysis\n## Method\n[METHODOLOGY]\n## Results\n[RESULTS]", placeholder_mappings={"THEIR_METHOD": "what method did the baseline use"} )
Source code in packages/core/verbatim_core/templates/manager.py
set_rag_system(rag_system)
Set the RAG system for modes that need it (structured).
:param rag_system: RAG system instance
Source code in packages/core/verbatim_core/templates/manager.py
process_structured_async(question, template=None, placeholder_mappings=None)
async
Run structured extraction, as a convenience helper.
Note: Prefer calling rag.query_async() directly after setting up structured mode. This method is kept for convenience.
Source code in packages/core/verbatim_core/templates/manager.py
set_citation_mode(mode)
Configure how citations are rendered inside filled templates ("inline" or "hidden").
Deprecated: pass TransformConfig(citation_mode=...) to the Transformer or its call.
Source code in packages/core/verbatim_core/templates/manager.py
set_citation_format(citation_format)
Configure citation marker format for all strategies.
Deprecated: pass TransformConfig(citation_format=...) to the Transformer or its call.
:param citation_format: str.format template with {number} and {span_id} variables. Default "[{number}]". Example: "[{span_id}]" renders "[cite1]" when span data includes {"span_id": "cite1"}. :raises ConfigurationError: If the format uses other variables
Source code in packages/core/verbatim_core/templates/manager.py
QuestionSpecificTemplate
verbatim_core.templates.question_specific.QuestionSpecificTemplate
Bases: TemplateStrategy
Question-specific template strategy using semantic similarity matching.
Maintains a list of (template, example_questions) pairs. When a query arrives, computes similarity to all examples and selects the template from the best-matching pair.
Example usage
templates = [ { "template": "Methodology: [RELEVANT_SENTENCES]", "examples": ["What methods were used?", "How was this done?"] }, { "template": "Key Findings: [RELEVANT_SENTENCES]", "examples": ["What were the results?", "What did they find?"] } ] strategy = QuestionSpecificTemplate.from_pretrained("all-MiniLM-L6-v2", templates=templates)
Source code in packages/core/verbatim_core/templates/question_specific.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | |
__init__(templates=None, model_name=_UNSET, device=_UNSET, citation_mode='inline', *, embedder=None)
Initialize question-specific template strategy.
:param templates: List of template definitions, each with 'template' and 'examples' keys
:param model_name: Deprecated. Load the embedder with from_pretrained(model_name).
:param device: Deprecated, with model_name.
:param embedder: A loaded embedding model with an encode(texts) method, such as a
SentenceTransformer. It embeds the template examples here and each question.
Source code in packages/core/verbatim_core/templates/question_specific.py
from_pretrained(model_name, device=None, *, templates=None, citation_mode='inline')
classmethod
Load a sentence-transformers embedding model and build the templates with it.
:param model_name: A sentence-transformers model id, or the path of a local model :param device: The device to run the model on. None lets sentence-transformers choose. :param templates: List of template definitions, each with 'template' and 'examples' keys :param citation_mode: "inline" or "hidden" :raises ConfigurationError: If sentence-transformers is not installed, or the model can't be loaded
Source code in packages/core/verbatim_core/templates/question_specific.py
set_citation_mode(citation_mode)
Set how the filled templates render citations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
citation_mode
|
str
|
"inline" or "hidden". |
required |
Source code in packages/core/verbatim_core/templates/question_specific.py
set_question_templates(templates)
Set templates with example questions.
:param templates: List of template configs, each with: - "template": Template string with [RELEVANT_SENTENCES] - "examples": List of example questions :raises ValueError: If template format is invalid
Source code in packages/core/verbatim_core/templates/question_specific.py
generate(question, spans, citation_count=0)
Generate template by finding best match for the question.
:param question: User's question :param spans: List of spans (not used for matching) :param citation_count: Number of citation spans (not used for matching) :return: Best matching template or default template
Source code in packages/core/verbatim_core/templates/question_specific.py
fill(template, display_spans, citation_spans)
Fill the template with actual span content.
:param template: Template string with placeholders :param display_spans: Spans to display with full text :param citation_spans: Spans for citation reference only :return: Filled template
Source code in packages/core/verbatim_core/templates/question_specific.py
save_state()
Save the current template configuration.
:return: Dictionary with template state
Source code in packages/core/verbatim_core/templates/question_specific.py
load_state(state)
Load template configuration from saved state.
:param state: Dictionary with template configuration
Source code in packages/core/verbatim_core/templates/question_specific.py
add_template(template, examples)
Add a new template to the list.
:param template: Template string with [RELEVANT_SENTENCES] :param examples: List of example questions for this template :raises ValueError: If template is invalid
Source code in packages/core/verbatim_core/templates/question_specific.py
remove_template(index)
Remove a template by index.
:param index: Index of template to remove :raises IndexError: If index is out of range
Source code in packages/core/verbatim_core/templates/question_specific.py
Models
verbatim_core.models
Pydantic models for verbatim_core (RAG-agnostic).
Highlight
Bases: BaseModel
A highlighted character span within a document.
Source code in packages/core/verbatim_core/models.py
validate_end_after_start()
Ensure the highlight ends after it starts.
Source code in packages/core/verbatim_core/models.py
DocumentWithHighlights
Bases: BaseModel
A document together with its highlighted spans.
Source code in packages/core/verbatim_core/models.py
Citation
Bases: BaseModel
A citation pointing to a highlight in a document.
Source code in packages/core/verbatim_core/models.py
StructuredAnswer
QueryResponse
Bases: BaseModel
Full response to a query.
Source code in packages/core/verbatim_core/models.py
StreamingResponseType
Shared types
verbatim_core.types
Types shared by the stateless interfaces of verbatim_core.
Where they live is provisional: they may move to a package shared with other libraries.
HasText
Chunk
Bases: BaseModel
A piece of source text with an id, the unit spans are extracted from.
Source code in packages/core/verbatim_core/types.py
validate_source_offsets_in_order()
Check that source_end doesn't precede source_start.
Source code in packages/core/verbatim_core/types.py
Span
Bases: BaseModel
A part of a text, given by offsets in Unicode code points.
The type is shared with other libraries, whose spans point into other texts. In this library
the text is always a chunk, and extractors return an ExtractedSpan.
Source code in packages/core/verbatim_core/types.py
validate_text_fits_offsets()
Check that end is after start and that text is exactly as long as the offsets say.
Source code in packages/core/verbatim_core/types.py
ExtractedSpan
Bases: Span
A span of a chunk, as an extractor returns it. Its offsets are relative to the chunk.
Source code in packages/core/verbatim_core/types.py
Usage
Bases: BaseModel
What one model or service did during a call.
Source code in packages/core/verbatim_core/types.py
ResultWarning
Bases: BaseModel
Something that made a result less complete without making it wrong.
Source code in packages/core/verbatim_core/types.py
Extraction
Bases: BaseModel
The spans an extractor found in a set of chunks.
Source code in packages/core/verbatim_core/types.py
AnswerCitation
Bases: BaseModel
A numbered citation in an answer. It points at its span by chunk id and offsets.
Source code in packages/core/verbatim_core/types.py
Answer
Bases: BaseModel
A cited answer, written from the spans extracted from a set of chunks.
Source code in packages/core/verbatim_core/types.py
Errors
verbatim_core.errors
Errors raised by verbatim_core and verbatim_rag.
VerbatimError
Bases: Exception
Base class of every error the library raises on purpose.
Source code in packages/core/verbatim_core/errors.py
__init__(message, *, code=None)
Create the error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
What the problem is and how to fix it. |
required |
code
|
str | None
|
A stable snake_case code, in place of the default code of the class. |
None
|
Source code in packages/core/verbatim_core/errors.py
__reduce__()
Keep the keyword attributes when the error crosses a process boundary.
InvalidInputError
Bases: VerbatimError, ValueError
The caller sent something wrong. Only a different input fixes it.
Source code in packages/core/verbatim_core/errors.py
__init__(message, *, code=None, param=None)
Create the error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
What the problem is and how to fix it. |
required |
code
|
str | None
|
A stable snake_case code, in place of the default code of the class. |
None
|
param
|
str | None
|
The argument that holds the bad value, for example |
None
|
Source code in packages/core/verbatim_core/errors.py
ConfigurationError
Bases: VerbatimError
The deployment is wrong. Only the operator can fix it.
Source code in packages/core/verbatim_core/errors.py
UpstreamError
Bases: VerbatimError
A service the library calls failed or did not answer in time.
Source code in packages/core/verbatim_core/errors.py
__init__(message, *, code=None, service='unknown', retryable=False, retry_after=None)
Create the error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
What the problem is and how to fix it. |
required |
code
|
str | None
|
A stable snake_case code, in place of the default code of the class. |
None
|
service
|
str
|
The service that failed, for example |
'unknown'
|
retryable
|
bool
|
Whether the same call may succeed when retried. |
False
|
retry_after
|
float | None
|
Seconds to wait before retrying, when the service said so. |
None
|
Source code in packages/core/verbatim_core/errors.py
Deprecation warning
verbatim_core._deprecation.VerbatimDeprecationWarning
UniversalDocument
verbatim_core.universal_document.UniversalDocument
dataclass
Minimal document with content, title, source and metadata.
Source code in packages/core/verbatim_core/universal_document.py
from_text(text, title='', source='', metadata=None)
classmethod
Create a document from raw text.
Source code in packages/core/verbatim_core/universal_document.py
from_dict(data)
classmethod
Create a document from a dict with content (or text).
Source code in packages/core/verbatim_core/universal_document.py
to_context()
Convert the document to a context dict.