How Extracting Structured Citations with Exact Character Offsets Works
In a grounded RAG or document-QA pipeline, asking an LLM to output raw character start/end indices directly is notoriously unreliable because models count tokens and characters poorly. Instead, you get exact, verifiable character offsets by having the model emit structured claims paired with verbatim supporting quotes or chunk IDs, and then deterministically locating those quotes/spans in your source passages and/or assembled answer in TypeScript.
- Two offset spaces to keep straight: A citation can point to (1) answer character offsets (
startIndex/endIndexin the generated response string so your UI can highlight which part of the answer is grounded) and/or (2) source-document character offsets (sourceStart/sourceEndin the retrieved chunk or original document). Always state and return which coordinate space each offset belongs to. - Quote-and-align beats model-predicted indices: Have the LLM return structured segments (
claimText,sourceId,supportingQuote) via strict JSON Schema, then run deterministic string matching (exact match first, followed by whitespace-normalized alignment) to compute exact UTF-16 code-unit or Unicode code-point offsets. - Handle duplicate substrings and streaming cleanly: If a short quote appears multiple times in a source chunk or answer, disambiguate using surrounding context or sequential cursor search; if streaming to the UI, attach verified span metadata per completed sentence/claim or once the full text is assembled.
Steps to Extract Structured Citations with Exact Offsets
- Provide indexed source passages with IDs: Format retrieved chunks with explicit
sourceIdlabels so the model can cite exact passage identifiers without inventing URLs or IDs. - Enforce a strict JSON Schema for claims and supporting quotes: Require the model to output structured
claims(each containingclaimtext,sourceId, andquotefrom that source) rather than guessing raw integer character offsets. - Compute exact offsets deterministically via string search: Locate
claiminside the assembled answer (answer.indexOf(claim, cursor)) andquoteinside the referenced source text (sourceText.indexOf(quote)), falling back to normalized whitespace matching if line breaks differ. - Drop or flag unverified citations: Discard or mark
verified: falseany citation whosesourceIdis unknown or whosequotecannot be matched in the source passage, preventing hallucinated attributions from reaching the UI.
TypeScript Example: Structured Citation Extraction and Exact Offset Resolver
import OpenAI from "openai";
const openai = new OpenAI();
export interface SourceChunk {
sourceId: string;
text: string;
}
export interface RawClaimItem {
claim: string;
sourceId: string;
quote: string;
}
export interface VerifiedCitation {
claim: string;
sourceId: string;
quote: string;
answerStart: number;
answerEnd: number;
sourceStart: number;
sourceEnd: number;
verified: boolean;
}
export interface GroundedAnswerWithOffsets {
answer: string;
citations: VerifiedCitation[];
}
function findSpanOffsets(
haystack: string,
needle: string,
fromIndex = 0
): { start: number; end: number } | null {
const trimmedNeedle = needle.trim();
if (!trimmedNeedle) return null;
// 1. Exact substring match starting at or after `fromIndex`
let idx = haystack.indexOf(needle, fromIndex);
if (idx === -1 && needle !== trimmedNeedle) {
idx = haystack.indexOf(trimmedNeedle, fromIndex);
}
if (idx !== -1) {
const matched = haystack.slice(idx).startsWith(needle) ? needle : trimmedNeedle;
return { start: idx, end: idx + matched.length };
}
// 2. Fallback: exact match anywhere in haystack if cursor was slightly ahead
if (fromIndex > 0) {
const fallbackIdx = haystack.indexOf(trimmedNeedle);
if (fallbackIdx !== -1) {
return { start: fallbackIdx, end: fallbackIdx + trimmedNeedle.length };
}
}
return null;
}
export async function generateGroundedAnswerWithOffsets(
question: string,
sources: SourceChunk[]
): Promise<GroundedAnswerWithOffsets> {
const sourceMap = new Map<string, SourceChunk>(sources.map((s) => [s.sourceId, s]));
const formattedSources = sources
.map((s) => `[SOURCE ${s.sourceId}]\n${s.text}`)
.join("\n\n");
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
temperature: 0,
messages: [
{
role: "system",
content: [
"Answer the user's question using ONLY the provided sources.",
"Return `answer` as a clear response, and return `citations` listing each grounded claim.",
"For each citation, `claim` must be an exact substring of `answer`, `sourceId` must match a provided SOURCE ID, and `quote` must be a verbatim substring copied from that source.",
].join(" "),
},
{
role: "user",
content: `Question: ${question}\n\nSources:\n${formattedSources}`,
},
],
response_format: {
type: "json_schema",
json_schema: {
name: "grounded_citation_response",
strict: true,
schema: {
type: "object",
additionalProperties: false,
required: ["answer", "citations"],
properties: {
answer: { type: "string" },
citations: {
type: "array",
items: {
type: "object",
additionalProperties: false,
required: ["claim", "sourceId", "quote"],
properties: {
claim: { type: "string" },
sourceId: { type: "string" },
quote: { type: "string" },
},
},
},
},
},
},
},
});
const rawJson = completion.choices[0]?.message.content ?? '{"answer":"","citations":[]}';
const parsed = JSON.parse(rawJson) as { answer: string; citations: RawClaimItem[] };
const answer = parsed.answer ?? "";
let answerCursor = 0;
const citations: VerifiedCitation[] = [];
for (const item of parsed.citations ?? []) {
const source = sourceMap.get(item.sourceId);
const answerSpan = findSpanOffsets(answer, item.claim, answerCursor);
const sourceSpan = source ? findSpanOffsets(source.text, item.quote, 0) : null;
if (answerSpan && sourceSpan) {
answerCursor = answerSpan.end;
citations.push({
claim: item.claim,
sourceId: item.sourceId,
quote: item.quote,
answerStart: answerSpan.start,
answerEnd: answerSpan.end,
sourceStart: sourceSpan.start,
sourceEnd: sourceSpan.end,
verified: true,
});
} else {
citations.push({
claim: item.claim,
sourceId: item.sourceId,
quote: item.quote,
answerStart: answerSpan?.start ?? -1,
answerEnd: answerSpan?.end ?? -1,
sourceStart: sourceSpan?.start ?? -1,
sourceEnd: sourceSpan?.end ?? -1,
verified: false,
});
}
}
return { answer, citations };
}
Helpful Tips for Production Citation Offset Pipelines
- Standardize on UTF-16 code units vs. Unicode code points across backend and UI: JavaScript
String.prototype.sliceandindexOfoperate on UTF-16 code units, whereas Pythonlen(s)or Rustchars().count()count Unicode code points—emojis or non-Latin characters can shift indices if your frontend and backend use different indexing units. - Keep chunk text immutable from retrieval to offset calculation: If you trim, normalize newlines, or strip whitespace after computing chunk offsets during ingestion,
sourceStartandsourceEndwill drift—always record offsets against the exact storedchunk.textstring. - Watch out for Markdown formatting inside
answer: If the model wraps aclaimin**bold**or bullet markers insideanswer,answer.indexOf(claim)may fail unless you either instruct the model to keepclaimplain-text-exact withinansweror strip/match around Markdown syntax.
You must log in or register to comment.
