A shopper types "show me the Samsung S25". The AI assistant replies "Sure, here are the Samsung S25 details". Then it shows the price, the storage and the photos of an iPhone 16. Nothing crashed. The tool call was valid JSON. The ID in the call was a real product ID. It was only the wrong one.
This post explains why this happens, and why "use structured outputs" does not fix it. Then it shows a small backend fix: give the model short references such as P1 and P2, and keep the real IDs on the server. The shop example is a made-up scenario, not a real incident. The logs come from running the code shown.
The setup
The backend searches the catalog and puts the results in the model's context:
[
{ "uuid": "a8f2-123", "name": "iPhone 16" },
{ "uuid": "b9d3-456", "name": "Samsung S25" },
{ "uuid": "c7e4-789", "name": "OnePlus 13" }
]The model also has one tool, getProductDetails, which takes a productId. The user asks for the Samsung S25. The model understands the request. Then it writes this tool call:
{
"name": "getProductDetails",
"input": { "productId": "a8f2-123" }
}That is the iPhone's ID. The backend finds the row, returns the iPhone, and the model describes it as the Samsung. The short IDs here are for reading. Real UUIDs are 36 characters long, which gives the model more characters to get wrong.
Why this is dangerous
- No check fails. The JSON is valid. The ID exists. The database returns a row. Every log line looks normal.
- The answer sounds right. The model says "Samsung S25" in its text, so the user trusts the iPhone's price.
- Read tools are the easy case. The same mistake in
addToCart,cancelOrderorrefundchanges real data for the wrong record.
The model writes the ID, it does not look it up
UUIDs are not the cause. The cause is this: the model never copies a value from a row. It generates the tool arguments one token at a time, the same way it generates a sentence. Nothing in that process links the string it writes to the row it meant.
A random ID gives the model nothing to hold on to. "Samsung S25" has meaning. b9d3-456 does not. So the model can make several kinds of mistakes:
- It takes the ID from the row next to the right one.
- It changes one or two characters inside a long ID.
- It uses an ID from an earlier search in the same chat.
- It writes an ID that looks right but does not exist.
The last one is the safe case, because the lookup fails. The other three return a real record.
Structured output checks the shape, not the choice
Strict mode and structured outputs are useful. OpenAI's Structured Outputs guide says the feature "ensures the model will always generate responses that adhere to your supplied JSON Schema." Anthropic has the same feature for tools, called strict tool use.
But a schema says what a valid value looks like. It cannot say which value the user meant. "a8f2-123" is a valid string. It also passes a UUID format check.
You can go further and put every allowed ID in an enum. Then the model cannot invent an ID. But it can still pick the wrong item from the list. An enum turns "any string" into "one of these three". It does not turn it into "the right one of these three".
Fix 1: select by index
Number the list and ask the model for a position instead of an ID:
{ "name": "getProductDetails", "input": { "index": 1 } }A small number is much easier to get right than a long random string. But an index only means something next to the exact list it came from. The backend must give the model the same list, in the same order, that it later reads from. That is often not true:
An index breaks when:
- the user sorts or filters the list,
- the backend loads page 2, so index 0 now means another product (the same problem as in offset pagination),
- a new search runs in a later turn, and the model mixes the old list with the new one,
- two lists are in the context at once, such as "products" and "accessories".
Use an index only when one list stays fixed for the whole task, and the server keeps that exact list.
Fix 2: short references that the server owns
This is the fix to use in most cases. The backend never sends UUIDs to the model. It sends a short reference for each product, such as P1, P2 and P3. It stores what each reference points to, for this conversation only. When the model calls a tool with P2, the server looks up P2, checks it, and only then reads the database.
The model now sees this instead of the raw list:
P1 · iPhone 16
P2 · Samsung S25
P3 · OnePlus 13And the tool takes a reference, plus the name the model thinks it belongs to:
{
"name": "getProductDetails",
"description": "Get details for one product that was shown to the user. Pass the ref shown next to the product, such as P2, and the product name exactly as shown. Never pass a UUID.",
"input_schema": {
"type": "object",
"properties": {
"ref": { "type": "string", "pattern": "^P[0-9]+$" },
"expectedName": { "type": "string", "description": "The product name shown next to the ref" }
},
"required": ["ref", "expectedName"],
"additionalProperties": false
}
}Why add expectedName? The model knows the right name, even when it writes the wrong reference. So the server can compare the two. If the model sends P1 with "Samsung S25", the server knows that something is wrong before it reads any data.
The resolver
// refs.ts: the model sees P1, P2, P3. Only the server knows the real UUIDs.
import { randomUUID } from "node:crypto";
type Product = { uuid: string; name: string; ownerTenant: string };
type RefEntry = { uuid: string; name: string; sessionId: string; resultSetId: string; expiresAt: number };
type Session = { id: string; userId: string; tenant: string };
export class ToolError extends Error {
code: string;
constructor(code: string, message: string) { super(message); this.code = code; }
}
const TTL_MS = 15 * 60 * 1000;
const refs = new Map<string, RefEntry>(); // key: `${sessionId}:${ref}`. Use Redis with a TTL in production.
const counters = new Map<string, number>(); // per session, so P numbers are never reused
// Call this every time the backend shows products to the model.
export function issueRefs(session: Session, products: Product[]) {
const resultSetId = randomUUID();
return products.map((p) => {
const n = (counters.get(session.id) ?? 0) + 1;
counters.set(session.id, n);
const ref = `P${n}`;
refs.set(`${session.id}:${ref}`, {
uuid: p.uuid, name: p.name, sessionId: session.id, resultSetId, expiresAt: Date.now() + TTL_MS,
});
return { ref, name: p.name }; // no UUID goes to the model
});
}
// Call this when the model calls a tool with a ref.
export async function resolveRef(
session: Session,
ref: string,
expectedName: string,
loadProduct: (uuid: string) => Promise<Product | undefined>,
): Promise<Product> {
if (!/^P\d+$/.test(ref)) throw new ToolError("BAD_REF", `"${ref}" is not a product reference`);
const entry = refs.get(`${session.id}:${ref}`); // the key includes the session: another session's P2 is not found
if (!entry) throw new ToolError("UNKNOWN_REF", `${ref} was not shown in this conversation`);
if (Date.now() > entry.expiresAt) throw new ToolError("EXPIRED_REF", `${ref} expired. Search again`);
if (normalize(entry.name) !== normalize(expectedName)) {
throw new ToolError("NAME_MISMATCH", `${ref} is "${entry.name}", not "${expectedName}"`);
}
const product = await loadProduct(entry.uuid);
if (!product || product.ownerTenant !== session.tenant) { // the ref is not a permission: check again
throw new ToolError("FORBIDDEN", `${ref} is not available`);
}
return product;
}
const normalize = (s: string) => s.toLowerCase().replace(/\s+/g, " ").trim();What the code does, in plain steps:
issueRefs()runs every time the backend shows products to the model. It gives each product the next free number in this session, stores the UUID on the server, and returns onlyrefandname.- The counter never resets inside a session. So
P2always means the same product for the whole conversation, even after a new search. resolveRef()runs when the model calls a tool. It checks the format, looks up the ref inside this session only, checks the expiry and compares the names.- Only then does it read the database, and it checks access again on the real row. A ref only says "this product was shown". It does not say "this user may still see it".
Here is a run with five calls: one right, four wrong.
shown to the model: [
{ ref: 'P1', name: 'iPhone 16' },
{ ref: 'P2', name: 'Samsung S25' },
{ ref: 'P3', name: 'OnePlus 13' }
]
right ref : ok -> b9d3-456 (Samsung S25)
wrong ref : NAME_MISMATCH - P1 is "iPhone 16", not "Samsung S25"
invented ref : UNKNOWN_REF - P9 was not shown in this conversation
raw uuid : BAD_REF - "b9d3-456" is not a product reference
other session : UNKNOWN_REF - P2 was not shown in this conversationThe wrong ref from the opening story now fails with a clear error. It does not return the iPhone.
Send the error back to the model
Do not hide a failed lookup, and never fall back to "the closest product". Return the error as the tool result, so the model can correct itself or ask the user. The Claude API has an is_error flag for this in tool results:
async function handleGetProductDetails(session: Session, call: { id: string; input: { ref: string; expectedName: string } }) {
try {
const product = await resolveRef(session, call.input.ref, call.input.expectedName, loadProduct);
return { type: "tool_result", tool_use_id: call.id, content: JSON.stringify(await getDetails(product.uuid)) };
} catch (e) {
if (!(e instanceof ToolError)) throw e; // a real bug: let it fail loudly
return { type: "tool_result", tool_use_id: call.id, is_error: true, content: `${e.code}: ${e.message}` };
}
}The error NAME_MISMATCH: P1 is "iPhone 16", not "Samsung S25" tells the model what went wrong. It can then call the tool again with P2. Count these errors per tool. A rising count tells you that a prompt or a list format confuses the model.
Four details that matter
- Stale references. Old refs keep their meaning, because numbers are never reused. They expire after
TTL_MS. When a ref expires, the error tells the model to search again. Use theresultSetIdif a tool must only accept refs from the latest search. - Another user's reference. The session is part of the lookup key, so a ref from another chat is not found. This matters because changing an ID in a request is the classic Broken Object Level Authorization attack (OWASP API1:2023). OWASP says to "check if the logged-in user has access to perform the requested action on the record". Do this in every function that uses client input to read a record. A tool argument is client input.
- Two products with the same name. "iPhone 16" can mean 128 GB or 256 GB, or two sellers. A name check cannot tell them apart. So show the model a name that is unique in the list, such as
P4 · iPhone 16 · 128 GB · Black. Then compare against that full line. If the user's words fit two items, the model should ask, not pick. - Write tools. For
addToCartorrefund, resolve the ref the same way, and then show the user the resolved name before you write. The model can still choose the wrong product with a correct ref.
Fix 3: let the backend search
Another option is to keep IDs away from the model completely. The model sends words, and the server finds the product:
// findProduct: a sketch. The model sends a query, the server picks the row.
async function findProduct(session: Session, query: string) {
const hits = await searchCatalog(session.tenant, query, { limit: 5 }); // full-text or vector search, filtered by tenant
if (hits.length === 0) return { status: "not_found" };
const clearWinner = hits.length === 1 || hits[0].score - hits[1].score > 0.1;
if (!clearWinner) return { status: "ambiguous", options: issueRefs(session, hits) }; // the model asks the user
return { status: "found", product: await getDetails(hits[0].uuid) };
}This works well when the user names a product that the model has not seen yet. The search can be exact, fuzzy or semantic (see vector search with HNSW). The risk moves to the search: "S25" and "S25 Ultra" can score almost the same. So the server needs a clear rule for "too close to call", and it returns refs for the model to ask about. The 0.1 above is only an example. Tune it on your own catalog.
| Approach | The model sends | A wrong pick returns | It breaks when | Use it when |
|---|---|---|---|---|
| Direct UUID | "b9d3-456" | Another real record, silently | The model changes or swaps a character | Avoid for anything the model chooses |
| Index | 1 | Another item, silently | The list is sorted, paged or replaced | One fixed list for one short task |
| Server refs | "P2" + name | A clear error, in most cases | You skip the session or access check | The default for chat and agents |
| Backend search | "Samsung S25" | "Ambiguous", if the rule is good | Two names score almost the same | The model has not seen the product yet |
In practice, many systems use the last two together. Search finds the candidates. Refs let the model point at one of them.
Four myths
| Myth | Reality |
|---|---|
| "Strict mode fixes it." | Strict mode makes the arguments match the schema. A wrong but valid ID matches the schema. |
| "An enum of IDs fixes it." | It stops invented IDs. The model can still choose the wrong value from the enum. |
| "UUIDs are the problem." | The problem is trusting text the model generated to name a record. A short ID can be wrong too. It is only wrong less often. |
| "A ref is a permission." | A ref says the product was shown. Check access on the real row at every call. |
The takeaway
- The model chooses. The server identifies. Let the model point at a short ref. Let the server turn it into a real ID.
- Treat tool arguments as user input. Check the format, the session, the expiry and the access, every time.
- Fail loudly, back to the model. A clear error that the model can read is better than a silent wrong answer.
Sources
- Anthropic Engineering: Writing effective tools for agents ("Returning meaningful context from your tools").
- OpenAI: Structured Outputs.
- Claude API docs: Strict tool use and Handle tool calls.
- OWASP API Security Top 10 (2023): API1:2023 Broken Object Level Authorization.