An AI extraction service might return a quote with start and end offsets so an application can highlight the source. Even when those offsets look plausible, the result may point to the wrong text. Define what the offsets count, then retrieve the claimed bytes yourself. This adapter uses an application-defined contract of UTF-8 bytes and an exclusive end. It makes no assumption that any model provider natively returns byte offsets.
Prerequisites and offline example
Use Python 3.12. Save this as span.py in UTF-8. The tuples stand in for parsed fields from a model response. The document is the exact stored source, not a reconstruction from normalized or reformatted text.
def evidence(document, start, end, quote):
document.decode("utf-8")
if type(start) is not int or type(end) is not int:
raise ValueError("offsets must be integers")
if not 0 <= start < end <= len(document):
raise ValueError("invalid span")
snippet = document[start:end].decode("utf-8")
if snippet != quote:
raise ValueError("quote does not match source bytes")
return snippet
source = "Café closes at 5".encode("utf-8")
assert evidence(source, 5, 12, " closes") == " closes"
for fixture in [(0, 4, "Caf"), (5, 12, " opens"),
(-1, 5, "Café"), (False, 5, "Café")]:
try:
evidence(source, *fixture)
except ValueError:
continue
raise AssertionError(f"accepted {fixture!r}")
print(evidence(source, 0, 5, "Café"))Run python3 span.py. Expected output:
CaféWhy the bytes matter
The first three letters each take one byte and é takes two. An end offset of four cuts that final character in half. Strict decoding rejects the slice instead of returning a replacement character. A negative start is rejected before indexing because Python would otherwise interpret it relative to the end. Likewise, False must not silently become byte zero. Checking an exact quote after decoding catches a different failure, where both boundaries are valid but the text at those boundaries differs from what the model reported.
When integrating this check, bind the document ID to a specific revision before looking up the bytes. Encoding, newline conversion, trimming and Unicode normalization can all move offsets or change equality. If valid-looking citations fail for accented text or emoji, verify that the producer and consumer agree on bytes rather than Unicode code points or UTF-16 units. For a service validating many citations in one document, validate the complete UTF-8 input once at ingestion rather than decoding it again on each call.
A successful check establishes that the quotation occupies those bytes. It does not establish that the quote supports the surrounding claim or that the source is authorized for display. Keep those checks separate. Return the verified snippet instead of trusting the original field, and apply output escaping for the eventual display format.
Reference: Python 3.12 codecs and UTF-8 documentation. More Python tutorials and AI tutorials.