How to Fix Gemini Citation Offsets in JavaScript
Change Cafe to Café in a test answer, and the source marker moves one space to the right. Add a coffee emoji and it lands inside the next word. The link still opens the right page. A test that checks the URL will happily pass both versions.
If you render inline citations from Gemini’s generateContent response in JavaScript, you can reproduce this bug without an API key. The response measures a claim’s position in bytes within one content part. JavaScript slices a string in UTF-16 code units. A short fixture can tell you whether those two systems disagree, whether your app selected the wrong part, or whether a formatting step changed the text underneath the citation.
Reproduce a citation that slips into the next claim
Imagine a travel assistant displaying the line below. The booking page supports the first sentence. A timetable supports the second. Put your finger where the booking link belongs before running the example.
Café ☕ is open. Doors close at six.
const answer = "Café ☕ is open. Doors close at six."; const claim = "Café ☕ is open."; const endByte = new TextEncoder().encode(claim).length; console.log(endByte, claim.length); // 18 15 console.log(answer.slice(0, endByte)); // Café ☕ is open. Do If you append a source badge to that slice, it splits “Doors” in two. The accent accounts for one extra byte, and the coffee symbol accounts for two. With plain ASCII, the same line of code produces the expected result. That explains how a renderer can pass a whole set of English demo questions and then fail on a customer’s street address.
A developer on Google’s forum described citations appearing on the following line. Another shared a workaround that searched for the quoted segment in the answer. That workaround suggests a second test. What happens when the exact phrase appears twice? The symptoms alone cannot establish which layer introduced the error in someone else’s app. Developer discussion of misplaced inline citations
Find the part that owns the citation
Start with one candidate from a saved response. Its content has a parts array. A grounding support can contain a segment locating a passage and groundingChunkIndices identifying sources in that candidate’s grounding metadata. Those arrays have different jobs. The third source can support a sentence in the first text part. A source can also appear beside several claims. Google’s Segment reference and GroundingSupport reference
| Field | Question it answers |
|---|---|
segment.partIndex | Which entry in the original content array owns this passage? |
segment.startIndex, segment.endIndex | Where does the passage begin and end in that part’s bytes? |
segment.text, when present | Which exact text should the extracted span contain? |
groundingChunkIndices | Which entries in this candidate’s grounding chunks support the passage? |
The start is inclusive and the end is exclusive. A span ending at byte eighteen includes the byte just before eighteen. Its marker belongs immediately after the span. Keep the original array order while resolving it. If your UI hides an introductory part or drops a non-text item before doing the lookup, every later part can have a different index in your display array.
Consider a response with “Summary” in one part and “Open.” in the next. A range starting at zero in the second part starts at the O. Flattening the response first puts that same zero at the S. All the characters are ASCII in this example. Fixing Unicode handling alone would still leave the wrong word highlighted.
Agree on what counts as a position
A person may see one letter where a string contains a base letter and a combining mark. A flag can look like one symbol while taking several code units. Counting visible characters with a grapheme splitter solves a layout problem. Here you need a translation between the provider’s byte positions and the positions accepted by your own string operations. ECMAScript string type
Record the unit in the variable name when the value crosses that boundary. A field named endByte invites a reviewer to check its use in slice. A field named end looks equally plausible in a byte buffer, a JavaScript string, and a text selection. The end of a sentence is a particularly hard place to notice a one-character mistake by eye.
Convert the byte offsets and check the passage
This small adapter builds a map once for a text part. It walks Unicode code points, counting the UTF-8 bytes and UTF-16 code units each one consumes. A byte in the middle of an encoded character has no entry. That gives the caller a way to reject a broken range without silently rounding it to the nearest letter.
function makeSpanReader(text) { const encoder = new TextEncoder(); const boundaries = new Map([[0, 0]]); let bytes = 0; let units = 0; for (const point of text) { bytes += encoder.encode(point).length; units += point.length; boundaries.set(bytes, units); } return function readSpan(segment) { const start = boundaries.get(segment.startIndex ?? 0); const end = boundaries.get(segment.endIndex); if (start === undefined || end === undefined || end <= start) { return null; } const quote = text.slice(start, end); if (segment.text !== undefined && segment.text !== quote) { return null; } return { start, end, quote }; }; } Use this on the original text string for a generateContent segment. In this adapter an omitted start means zero. A missing end leaves the span unresolved. The caller first selects the candidate, reads the original part at segment.partIndex ?? 0, and checks that it contains user-visible text. A missing segment, unavailable part, or reference to a hidden part stays out of the inline display.
For a multilingual support inbox, keep the original reply beside its translation. Resolve a Spanish claim against the provider’s Spanish text even if the reader has selected English. A translation can move the subject to the other end of the sentence or combine two sentences into one. Without an explicit alignment between the versions, put the source beside the original passage and make that passage available from the translated view.
Make the second occurrence pass
Suppose the answer compares two cafés. Each section ends with “Open.” Only the second café takes bookings. Searching the full string with indexOf("Open.") finds the first café and attaches a working booking link to the wrong business. Put the following test under the adapter and run both in Node. The positions are hand-counted so the test can catch a mistake in the mapping code itself.
const line = "Café ☕ Open. 🧭 Open."; const read = makeSpanReader(line); const target = read({ startIndex: 21, endIndex: 26, text: "Open." }); if (target?.start !== 16 || target?.end !== 21) { throw Error("Expected the second opening notice"); } if (read({ startIndex: 4, endIndex: 5 }) !== null) { throw Error("Accepted a start inside é"); } if (read({ startIndex: 21, endIndex: 26, text: "Shut." }) !== null) { throw Error("Accepted the wrong passage"); } Three checks do different work here. The first pins the marker to the correct occurrence. The second forces an invalid boundary through the reader. The third catches a valid pair of numbers applied to stale text. A snapshot containing two visible links might pass every time someone broke one of those behaviors.
Turn validated spans into source markers
Keep the text intact while you resolve the sources. For a web citation, look up each chunk index in the same candidate’s groundingChunks array. Check that the entry exists and carries a usable web URI before building a link. An adapter that understands only web sources can send other chunk types to their own renderer. Keep the original chunk index through this step. Filtering the array down to web links first can shift every subsequent lookup.
For a plain-text view, group valid references by the converted end position within each part. Walk those positions in ascending order. At each one, emit the original text from the previous end, then emit the source buttons for this end. Append the trailing text after the last marker. Two supports ending at the same point can share a button group. Deduplicate a repeated chunk index inside that group and retain it when a later sentence cites it again.
If a source survives but its span fails validation, a section labeled “Sources for this answer” can still give the reader a useful destination. Leave the precise claim unmarked. For a comparison of two cancellation policies, guessing could attach the flexible policy to the cheaper, nonrefundable ticket. Readers should be able to tell which level of attribution the interface actually has.
Handle Markdown and streamed answers
A Markdown parser can remove emphasis markers, join lines or turn a URL into link text. Byte positions from the raw **Open.** string do not describe the same positions in the rendered word. Use a parser that preserves source positions if you need inline badges in rich text. Check the parser’s position units on a fixture. Place the badge beside the containing link or code node if inserting it inside would create a nested control or break the formatting.
For streamed answers, let plain text appear as it arrives. Keep a copy of the original parts as your SDK assembles them. Resolve final supports against the completed candidate and attach the badges in a separate render step. If the framework hands you only one joined string and a list of URLs, preserve that source list. Restoring part-level data at the SDK boundary makes reliable inline placement possible later.
Build a fixture that catches the next regression
A good fixture is small enough that a reviewer can say exactly which word a link should follow. Save a synthetic candidate with two parts, two supports and two clearly named sources. Give each part the same ending. Reverse the order of the source chunks relative to the sentences. The test must fail if someone starts pairing the first sentence with the first URL by position.
| Change one thing | Expected result |
|---|---|
| Add an accent before the claim and update its byte range | The badge follows the same claim. |
| Put an emoji outside the basic multilingual plane before the claim | The mapped JavaScript end still selects the exact quote. |
| Place the same sentence in two parts | Only the designated part receives the marker. |
| Supply an end beyond the last byte | The sentence receives no inline marker. |
| Give one passage two valid source indices | Both sources appear at that passage. |
| Normalize decomposed text before applying the saved offsets | The fixture exposes the edit through a mismatch or invalid boundary. |
Test the mapping and the reader’s view separately. An adapter test can assert the exact substring and its start. A UI test can select the booking link by its accessible name, check the destination, then inspect the text immediately before the button. That last assertion catches layout code that moves every badge to the paragraph footer. Checking the list of URLs alone misses it.
Diagnose a report from production
Ask for the shortest shareable answer that demonstrates the shift. Replay a synthetic equivalent if the original contains customer data. Start by comparing the raw segment with the raw part. If they match after conversion, inspect each later transformation until the two strings diverge. A trim that drops a leading newline is enough. If they already disagree at the SDK boundary, capture the endpoint, SDK version, part index and range for a minimal report.
During rollout, count supports with a resolved inline marker, supports shown only in the source list, and supports with no usable source. Use the total number of supports as the denominator. Track responses that carry no supports separately. Otherwise a change in how often the model uses grounding can look like a sudden improvement in citation placement.
Once placement works, a second review can ask whether the linked page supports the claim. Give that reviewer the exact sentence and the source that a reader would open. The two checks catch different errors, and a saved example can serve both. A practical claim verification workflow
FAQ
Why do Gemini citation offsets work on English test data?
ASCII characters each occupy one UTF-8 byte and one UTF-16 code unit. Those positions line up by coincidence. A curly apostrophe in an English answer can expose the mismatch just as easily as an accented place name.
Does inserting citations from the end fix shifted indices?
Descending order preserves earlier positions as you insert new text later in the string. It still requires correct positions in the original string. Convert and validate the offsets first, even if the final output is a Markdown export.
Can I use the quoted text to find the source position?
Use a supplied quote to verify the selected range. A search can return several identical matches. “Available on request” might appear in every row of a comparison. The part and position tell you which row the provider associated with the source.
What if the grounding metadata omits the quote?
A valid pair of byte boundaries still yields a slice from the original part. You lose the independent equality check. Keep fixtures with known passages for that response shape, and distinguish cases with verified quotes when investigating a rendering bug.
Should I request another model response when a marker moves?
Replay the saved candidate through the renderer first. If the same input produces the same misplaced marker, you can debug the mapping locally. A fresh response changes the wording, the sources and the positions at once, making the original symptom harder to isolate.
Can I reuse this adapter with other Gemini endpoints?
Check the contract for the exact endpoint and SDK field you consume. This example targets generateContent grounding segments. For another annotation type, establish its offset unit, owning text block and end convention with a known fixture before sending its positions to a shared renderer.
原文:https://www.a8q9.cn/en/article/how-to-fix-gemini-citation-offsets-in-javascript-d6974e.html