Repository navigation
0.3.0 adds a stateless core. Extractors return spans with their chunk ids and offsets, and a
Transformer turns a question and chunks into an answer cited from the chunks' own text, with
the usage and warnings of the call. VerbatimRAG is built on a Transformer you pass in, takes
k per query, and streams with query_stream. Models and LLM clients are passed into
constructors, and the settings of a request are arguments of the call, so one instance can serve
concurrent requests. The 0.2 entry points keep working through 0.3.x and 0.4.x, warn with
VerbatimDeprecationWarning, and are removed in 0.5.0. The
migration guide maps each one to its
replacement.
Added
- Docker Compose development and demo stack: the FastAPI API and the Vite/React UI run
locally behind nginx, which proxies/api/same-origin, published on:8080by default
(FRONTEND_PORToverrides). Milvus Lite data persists on a named volume. Not a
production deployment — no TLS, authentication, tenancy, or scaling. docker/constraints.txt: a checked-in dependency lock used only by the container image;
the published ranges inpyproject.tomlare unchanged. Pinsmilvus-lite<3, whose 3.x
line rejects the vector-less metadata collectionLocalMilvusStorecreates.- Groundwork for the stateless core (#89), not yet used by the rest of the library.
verbatim_coreexports the result typesChunk,Span,ExtractedSpan,Usage,
ResultWarning,Extraction,AnswerCitationandAnswer, whose validation errors leave
out the input values so that customer text can't reach logs through them, and the errors
VerbatimError,InvalidInputError(also aValueError),ConfigurationErrorand
UpstreamError. Bothverbatim_coreandverbatim_ragexportVerbatimDeprecationWarning.
verbatim-core now liststyping_extensions>=4.5.0as a direct dependency. SpanExtractor.extract(question, chunks)andaextract, which return anExtraction: spans
with their chunk ids and offsets, plus the usage and warnings of the call (#90). A new
extractor implements onlyextractand getsextract_spansfrom the base class. An extractor
that implements onlyextract_spansgetsextractandaextract: each span text is located
in its chunk (the first exact occurrence, else the best fuzzy match), and texts that can't be
located are dropped and reported in the result's warnings with the codespan_text_not_found.
Of an extractor's methods, the one defined in the most specific class is the implementation: a
subclass of an extractor that overridesextract_spans, as subclasses written before 0.3.0
did, is called through itsextract_spanstoo, and a subclass that overridesextractbelow
a parent'saextractgets anaextractthat runs itsextractin a worker thread. Such a
subclass ofLLMSpanExtractormakes a call's LLM calls one after another, unless it overrides
aextracttoo.- The
verbatim_core.contentlogger. Log records that hold customer text, such as questions,
chunks and span texts, go only to this logger and only at DEBUG. Leave it at INFO to keep
customer text out of your logs whatever level the otherverbatim_coreloggers have. LLMSpanExtractor.extractandaextract(#91). Each quote of the LLM is located in its
chunk, and the span's text is the chunk's text at the located offsets. Every span has the
score 1.0, "extracted without a score". Quotes that can't be located are dropped and reported
in the result's warnings with the codequote_not_found. A failed LLM call raises, and the
whole extraction fails. The usage names the LLM, with the model version the LLM service
returned, and counts the chunks, characters, LLM calls and, where the service reports them,
tokens.aextractmakes its LLM calls concurrently. A client that replaces
LLMClient.complete, for example to call another provider, is still called that way, and its
usage then has no model version or tokens. So is a client that replacesextract_spans,
extract_relevant_spansor their batch and async versions, which the extractor called before
0.3.0. Acompletewithout asystem_promptparameter is called without one, unless a custom
prompt has a system prompt. An exception of such a client, other than the library's own errors,
is a failed LLM call: anUpstreamErrorwith the codeclient_failed, without the exception's
message, which stays in its__cause__.ExtractConfig, the base class of the extractors' settings, andLLMExtractConfig, the
settings ofLLMSpanExtractor:LLMSpanExtractor(llm_client, config=LLMExtractConfig(...)).
Aconfigpassed toextractreplaces the default for one call (#91).LLMClient.completionandcompletion_async, which return the text of a reply with the
model name and the token counts the LLM service sent (#91).ModelSpanExtractor.from_pretrained(model_id, device=None)and
SemanticHighlightExtractor.from_pretrained(...), which download and load a model or load it
from a local path (#92). They record the model's Hugging Face commit as the version the usage
of each extraction reports; for a local path, passmodel_version. They also load the
highlighter's tokenizer, which it used to load on the first extraction. Loading logs the event
model_loadedat INFO. The constructors take a loaded model and a config, and load nothing.extractandaextractonModelSpanExtractorandSemanticHighlightExtractor, whose spans
keep the offsets and probabilities the model computed (#92). Highlighter models give their
character spans with the span probability, the v1 sentence model the sentences of a chunk with
the sentence probability.SemanticHighlightExtractorlocates the sentences it highlights in
order, scored with the sentence probability, and turns token regions into offsets, scored with
the mean token probability. When a model examines only part of a chunk, the result has a
warning with the codechunk_truncated.aextractruns the model in a worker thread.ModelExtractConfigandSemanticHighlightConfig, the settings of the model extractors (#92).Transformer(extractor, templates, config=TransformConfig(...)), which writes a cited answer
from a question and chunks, without an index (#93).transformandatransformreturn an
Answer: its text, a citation for each span (its number, whether the answer shows the span or
cites it for reference only, and the span's chunk id and offsets), the spans, the usage of the
extractor and of the template LLM when one ran, and the warnings.streamandastreamyield a
spansevent once the spans are extracted and ananswerevent with the sameAnswer.
TransformConfigholds the settings of a call: the number of displayed spans, the template
mode, the citation mode and format, and a seed. Nothing is set on the transformer between
calls, so one transformer can serve concurrent calls. In random template mode it chooses the
template by a hash of the question, combined with the seed, so the same question gets the same
template. Structured template mode raises: it stays inVerbatimRAG. The template strategy
fills the answer with its own citation settings, asTemplateManager.processdid, unless the
call's config sets a citation mode or format: then the call fills with those and changes no
strategy. A strategy whose class defines its ownfillalways fills.- In a
Transformercall, a contextual template falls back to the fallback template only when
the LLM call fails with anUpstreamErroror the LLM sends an empty template, and the answer
then has the warningtemplate_fallback. A rejected API key, model or quota raises
ConfigurationError. Generated templates are logged only on theverbatim_core.content
logger. A client that replacesLLMClient.generate_templateis still called that way, and an
exception of its own is a failed LLM call, so the template falls back (#93). ResponseBuilder.build_from_answer, which builds today'sQueryResponsefrom anAnswer. It
highlights each cited span at its offsets, without searching for its text, and of two
overlapping spans keeps the first. A citation of a chunk it isn't given, or with offsets
outside its chunk, raisesInvalidInputError(#93).LLMClient.template_completionandtemplate_completion_async, which return the completion
of a template prompt and raise when the call fails, andTemplateStrategy.generate_result,
which returns a template with the usage and warnings of writing it (#93).TemplateManager.config, theTransformConfigthat the template manager's constructor
arguments describe. ATransformerbuilt without aconfiguses it as its default, and raises
ConfigurationErrorat the call while the template manager is in structured mode (#94).
TemplateManager.savealso saves the citation mode and format, andloadrestores them.VerbatimRAG(index, transformer=..., llm_client=None, intent_detector=None, reranker=None)
(#96).queryandquery_asynctakekand the other retrieval arguments per call, turn the
retrieved rows into chunks withSearchResult.to_chunk(), whose id is the row's id, and answer
with theTransformer. Nothing is set onVerbatimRAGby a call. Thellm_clientserves
structured template mode alone, which still answers without theTransformer.VerbatimRAG.query_stream(question, k=..., ...), an async generator with the retrieval
arguments ofquery(#97). It yields aDocumentsEventwith the retrieved chunks, a
SpansEventwith their spans and aResponseEventwith theQueryResponsethatquery
returns for the same input, and raises the errorsqueryraises. A question the intent
detector answers yields theResponseEventalone. The events are exported fromverbatim_rag.DocumentChunk, the new name of the ingestion recordverbatim_rag.document.Chunk(#96).QueryResponse.warnings: how an answer is degraded but still correct, asResultWarnings with
a code and a message, such asquote_not_found,chunk_truncated,template_fallbackand
reranker_fallback(#96).VerbatimRAG,VerbatimTransform,verbatim_enhance, the CLI and
the API server fill it; it was dropped before, so a response without warnings now has
"warnings": [].QuestionSpecificTemplate.from_pretrained(model_name, device=None, templates=...), and the
embedderargument ofQuestionSpecificTemplateandTemplateManager.use_question_specific_mode,
which take a loaded embedding model (#94). The template examples are embedded when the
templates are built, and each question with the same model, so no call loads a model.
from_pretrainedlogs the eventmodel_loadedat INFO.VerbatimDOC(rag, k=...), the number of chunks each query retrieves (#98). Without it,
VerbatimDOCretrievesrag.kchunks as before: 5, or the deprecatedVerbatimRAG(k=...).- The documentation has a migration page from each 0.2 entry point to its replacement, and a
reference of the error codes, result warning codes and log events the library emits (#99). - prek git hooks (
prek.toml): builtin file checks, Ruff
check/format anduv-lock/uv-exportrun on pre-commit; pytest, package build with
twine check, andpip-auditrun on pre-push.api/,frontend/anddocs/are excluded
for now. Install withuv tool install prek && prek install(seeCONTRIBUTING.md).
Changed
- One span gives one highlight and one citation: text that repeats in a chunk is highlighted and
cited once, where the extractor found it, instead of at every occurrence (ADR 0001). VerbatimRAG.query,query_asyncandquery_streamraise when an LLM call fails during
extraction, instead of answering from the remaining chunks (ADR 0006): anUpstreamErrorfor
a failed or unreadable reply, aConfigurationErrorfor a rejected API key, model or quota. So
doVerbatimTransform,verbatim_query,verbatim_enhanceandVerbatimDOC.- Random template mode gives the same question the same template, in every process, combined
withTransformConfig.seedwhen it is set, in aTransformercall and in
TemplateManager.process, instead of choosing at random (ADR 0005, #93, #94). - Contextual template mode without an LLM client warns with
VerbatimDeprecationWarningwhere
it printed a note, and uses the static template. - The steps of a call log at DEBUG instead of INFO or
print. Customer text, such as questions,
chunks, quotes and templates, is logged only on theverbatim_core.contentlogger, at DEBUG;
verbatim-rag logs none. - A context item of the wrong shape raises
InvalidInputError(codemissing_fieldor
invalid_value,paramsuch ascontext[3]orcontext[3].title) instead ofTypeErroror
ValueError, before any LLM call. This includes metadata that isn't a dict with string keys,
and a title or source that isn't a string.InvalidInputErroris aValueError, but
except TypeErrorno longer catches a context item that isn't a dict (#95). verbatim-ragnow requiresverbatim-core>=0.3.0,<0.4, the core's minor version: it uses a few
private names of the core, which the core keeps within a minor version.- A
SpanExtractorsubclass that implements neitherextractnorextract_spansraises
TypeErrorwhen it is defined, not when it is instantiated (#90). LLMClienttranslates the errors of the OpenAI client (#91). A rejected API key, model or
quota raisesConfigurationError. A timeout, a connection error, a rate limit, a server error
or a reply that can't be read raisesUpstreamError, which says whether a retry may help. The
OpenAI exception is the__cause__. An empty reply raisesUpstreamErrorinstead of
ValueError, and so does a reply without text, which returnedNone.LLMSpanExtractor.extract_spansraisesConfigurationErrorwhen the LLM service rejects the
API key, the model or the quota, instead of returning no spans. It still tolerates the other
failed calls, and now also counts a reply that isn't a JSON object of quote lists as one (#91).LLMSpanExtractorlogs quotes it can't locate in one WARNING record that counts them, without
their text, and its steps at DEBUG instead of INFO. The quotes go to the
verbatim_core.contentlogger at DEBUG (#91).- The settings of an
LLMSpanExtractorare in itsconfig. The attributesextraction_mode,
batch_size,span_match_mode,fuzzy_threshold,extraction_prompt,system_promptand
max_display_spansare gone (#91). - An unknown
extraction_mode, which acted likeindividual, raises:ConfigurationErrorfrom
LLMSpanExtractor, and pydantic'sValidationError, aValueError, fromVerbatimRAGand
VerbatimTransform(#91). - An error of a model extractor's model propagates, instead of giving its chunk no spans (#92).
SemanticHighlightExtractorruns its model on the device it is given, or the best available
one, where it ignoreddevice, and the model no longer draws progress bars (#92).- The model extractors raise
ConfigurationErrorinstead ofImportErrorwhen torch,
transformers or a package the model's code needs is missing (codemissing_dependency),
instead ofOSErrorwhen a model can't be downloaded or read (codemodel_not_loaded), and
instead ofValueErrorfor an invalidoutput_mode(#92). - The settings of the model extractors are in their
config. The attributesthreshold,
min_span_chars,merge_gap_chars,max_length,doc_stride,output_mode,language,
min_span_tokens,merge_gap,max_tokens,deviceandmodel_pathare gone (#92). - The template classes log instead of printing, and
QuestionSpecificTemplatelogs its steps at
DEBUG instead of INFO. When a template can't be written, the WARNING record has the event
fallback_usedand the warning codetemplate_fallback(#94). ContextualTemplate.generateandgenerate_async, for a client that replaces
generate_template, andRandomTemplate.generate_diverse_templatesfall back only when the
LLM call fails with anUpstreamError, which includes an exception of a client written before
0.3.0 (client_failed). A rejected API key, model or quota raisesConfigurationError(#94).QuestionSpecificTemplateraisesConfigurationError(codemissing_dependency) instead of
ImportErrorwhen sentence-transformers is missing, andConfigurationError(code
model_not_loaded) instead ofOSErrorwhen the model can't be loaded (#94).TemplateManager.loadraises these errors instead of logging them and going on, and raises
ConfigurationError(codemissing_embedder) for question-specific templates that were saved
with an embedder of their own when no embedder is given (#94). It still returnsFalsefor a
file that can't be read or isn't JSON.TemplateManager.set_citation_formatraisesConfigurationErrorfor a format with variables
other than{number}and{span_id}, instead of failing when a template is filled (#94).VerbatimTransformanswers with aTransformer(#95). verbatim-rag's copy is gone:
verbatim_rag.VerbatimTransformis verbatim-core's, which also accepts context items that are
objects with atextattribute.verbatim_enhance, theverbatim-enhanceCLI and the API
server's transform route use aTransformerdirectly; the route builds it once at startup and
logs no question or chunk text. The answers are today's, except:- A failed LLM call raises, from
VerbatimTransform,verbatim_query,verbatim_enhanceand
the CLI, and the API route answers 500, instead of an answer without the chunks the call
covered (ADR 0006). - A displayed span that a contextual template leaves out is cited as a reference.
- Context items with the same text each get their spans, instead of sharing one entry.
- A failed LLM call raises, from
VerbatimRAG.queryandquery_asyncanswer with aTransformer(#96). The answers are
today's, except:- A failed LLM call during extraction raises, instead of answering from the remaining chunks
(ADR 0006). - Retrieved rows with the same text each get their spans, instead of sharing one entry.
- Their steps log at DEBUG instead of printing.
- An extractor that implements only
extract_spansreceives the chunks, withid,textand
metadata, instead of the search results; one that readsscoreorenhanced_textneeds to
implementextract. The same holds forVerbatimTransform(#95).
- A failed LLM call during extraction raises, instead of answering from the remaining chunks
StreamingRAGand the API server's streaming route send the events of
VerbatimRAG.query_streamas the dicts they sent before (#97).num_docsand the other
retrieval arguments apply to the call:StreamingRAGno longer setskon theVerbatimRAG
it streams, so concurrent streams don't interfere. The events are today's, except:- The response of the
answerevent has thewarningsthatqueryreports. - An
errorevent has the error'scode, and itserroris the code, or the message of an
InvalidInputError, instead of the exception's text. An error that isn't aVerbatimError
has the codeinternal_error. The failure is logged once onverbatim_rag.streaming, with
its traceback. The traceback shows the messages ofVerbatimErrors only, since another
exception's message may quote the question or a chunk, and the route logs no question text. - A failed LLM call during extraction ends the stream with an
errorevent, instead of
answering from the remaining chunks (ADR 0006). - The
highlightsevent has the response's highlights: one per span, at its offsets
(ADR 0001). Retrieved rows with the same text each get their spans, instead of sharing one
entry. - In structured template mode the stream answers as
querydoes, withVerbatimRAG's
client, and sends noprogressorhighlightsevent. Before, it filled the structured
template from the extractor's spans.
- The response of the
- A reranker failure keeps the retrieval order only when its service fails (
UpstreamError), adds
the warningreranker_fallbackto the response, and logsfallback_usedon the
verbatim_rag.corelogger instead of the root logger. Other errors propagate.CohereReranker
andJinaRerankerraiseUpstreamErrorfor a failed call, andConfigurationErrorfor a
rejected API key or permission or an unknown model (#96). - Structured template mode without an LLM client raises
ConfigurationError(code
missing_llm_client) (#96). VerbatimDOCextracts withaextract, from the chunks of the retrieved rows (#98). An
extractor that implements onlyextract_spansstill works and warns. A query that fails makes
process,process_interactiveandstream_processraise its error, such as an
UpstreamErrorfor a failed LLM call (ADR 0006). Before, the document said "No relevant
information found." in its place.- CI now runs the prek hooks (
j178/prek-action) instead of separate Ruff, package-build and
pip-auditjobs; the Python 3.10–3.12 test matrix is unchanged. verbatim-corelint cleanup (#80): the package has its ownruff.toml, imports in
llm_clientmoved to module level, and out-of-scope rules are suppressed inline.
Deprecated
Each of these warns with VerbatimDeprecationWarning, a DeprecationWarning, and is removed in
0.5.0.
- Implementing only
extract_spansin aSpanExtractorsubclass, or overriding it in a
subclass of an extractor:extractandaextractwarn when they are called on it. Implement
extractinstead (#90). extract_spansandextract_spans_asyncwhere an extractor inherits them from
SpanExtractor. Useextractandaextract(#90).LLMSpanExtractor.extract_spansandextract_spans_async. Useextractandaextract(#91).LLMSpanExtractor()without anllm_client, which buildsLLMClient(model). Pass the client:
LLMSpanExtractor(LLMClient(model)). The argumentmodelnext to a client has no effect: the
client's model applies. The argumentmax_display_spanshas no effect either: pass it in
TransformConfig(max_display_spans=...)(#91).- The
LLMSpanExtractorargumentsextraction_mode,batch_size,span_match_mode,
fuzzy_threshold,extraction_promptandsystem_prompt. Pass them in
config=LLMExtractConfig(...)(#91). ModelSpanExtractor(model_path=...)andSemanticHighlightExtractor(model_name=...), and
both without a loaded model or with a model name, which load the model. Usefrom_pretrained
(#92).- The settings arguments of the model extractors. Pass them in
config=ModelExtractConfig(...)
orconfig=SemanticHighlightConfig(...), anddeviceandmax_tokenstofrom_pretrained.
TheModelSpanExtractorargumentextraction_modehas no effect and has no replacement, and
max_display_spansbelongs inTransformConfig(max_display_spans=...)(#92). - Contextual template mode without an LLM client. It warns where the template manager printed a
note. ATransformercall or its default config (#93) and
TemplateManager(default_mode="contextual")use the static template;set_modeand
use_contextual_modereturnFalseand keep the template mode (#94). Give the
TemplateManageranllm_client. TemplateManager.set_mode,set_citation_modeandset_citation_format, and assigning its
current_modeorcitation_mode. Pass the settings in aTransformConfigto theTransformer
or to its call. Until they are removed, they change the template manager'sconfig, the
default of everyTransformerbuilt with it and noconfigof its own.use_structured_mode
switches to structured mode without a warning (#94).TemplateManager.set_rag_system,StructuredTemplate.set_rag_systemand
StructuredTemplate.fill_async, through which the templates call back intoVerbatimRAG. Use
VerbatimRAG.query_async(#94).QuestionSpecificTemplate(model_name=..., device=...), and question-specific templates
without anembedder, which load an embedding model by name. Use
QuestionSpecificTemplate.from_pretrained(model_name)or passembedder(#94).VerbatimRAGwithout atransformer, and its argumentsmodel,k,template_manager,
extractor,max_display_spans,template_modeandextraction_mode. Pass aTransformer,
andktoquery(#96), or toVerbatimDOC(rag, k=...)(#98).- Assigning
VerbatimRAG.extractor,template_managerormax_display_spans. Pass a
Transformerwith the extractor, templates and config (#96). verbatim_rag.document.Chunk. UseDocumentChunk(#96).StreamingRAG,StreamingRAG.stream_queryandstream_query_sync. Use
VerbatimRAG.query_stream(#97).VerbatimTransform. UseTransformer, andResponseBuilder.build_from_answerfor a
QueryResponse(#95).verbatim_queryandverbatim_query_async. Retrieve with the provider, then call a
Transformer(#95).- The module
verbatim_rag.transform. Its names are verbatim-core's: import them from
verbatim_core, andSearchResultfromverbatim_rag.vector_stores(#95).
Fixed
- Concurrent calls on one
ModelSpanExtractororSemanticHighlightExtractortake turns in
the model and its tokenizer. Calls with different configs, andSemanticHighlightExtractor
in spans mode even with one config, failed withRuntimeError: Already borrowedfrom the
shared fast tokenizer. For calls in parallel, give each worker its own extractor. - The
verbatim-ragCLI'squeryandtemplatecommands, which failed with aTypeError
(#98).queryanswers with aTransformer:--max-display,--extraction-modeand
--contextual-templatesapply,--num-docsis thekof the query, and the citations are
counted as displayed or as references by their type.templatesaves the random templates
the LLM writes, andquery --templatesanswers with them. VerbatimRAG.queryandquery_asyncmark asdisplayexactly the citations whose spans
the answer shows, as the streaming path already did. They counted the retrieved chunks
instead, so with more chunks than shown spans, cited-only spans were marked as displayed,
and with fewer, shown spans were marked as references (#86). Structured mode is unchanged.LocalMilvusStoreno longer fails on Milvus Lite 3 and pymilvus 3. Its metadata collection
(<collection>_documents) now has a placeholder vector field, asCloudMilvusStorealready
does, because the 3.x line rejects collections without a vector field (#69).SearchResult.to_chunk()accepts row ids that are not strings, such as the integer ids of
a custom vector store, and passes them to the chunk as strings. A missing or empty id raises
InvalidInputError(#126).- The default
TemplateStrategy.generate_result_asyncruns the synchronous implementation in
a worker thread, so a question-specific template no longer blocks the event loop while it
embeds the question (#125).
Contributors
Thanks to @rezamuliawijaya for the fixes in #128 and #129.
Full changelog: v0.2.8...v0.3.0