The LLM picked the wrong product. A user says: show me the Samsung S25. The AI replies: sure, here is the Samsung S25. But its tool call is getProductDetails with a8f2-123, which is valid JSON with no error. That ID belongs to the iPhone 16, so the user gets the wrong product.TODO(human): describe what this diagram shows The LLM Picked the Wrong Product User Show me the Samsung S25 AI Sure, here is the Samsung S25 getProductDetails("a8f2-123") valid JSON, no error wrong product iPhone 16

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.

Part 1The problemThe right product name, the wrong product ID

The setup

The backend searches the catalog and puts the results in the model's context:

JSON
[
  { "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:

JSON
{
  "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, cancelOrder or refund changes real data for the wrong record.
Part 2Why it happensA tool argument is generated text, not a lookup

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.

In the wild. Anthropic's guide to writing tools for agents says that "merely resolving arbitrary alphanumeric UUIDs to more semantically meaningful and interpretable language (or even a 0-indexed ID scheme) significantly improves Claude's precision in retrieval tasks by reducing hallucinations."

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".

The rule. Treat every tool argument as untrusted user input. The model wrote it, so it can be wrong in the same ways a typed form field can be wrong.
Part 3Three fixesAn index, a server-side reference, or a server-side search

Fix 1: select by index

Number the list and ask the model for a position instead of an ID:

JSON
{ "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:

Turn 1 shows a list: index 0 iPhone 16, index 1 Samsung S25, index 2 OnePlus 13. In turn 3 the user sorts by price, so the list is now: index 0 OnePlus 13, index 1 iPhone 16, index 2 Samsung S25. The model still means Samsung and sends index 1. The server reads the new list and returns the iPhone 16.TODO(human): describe what this diagram shows The same index, a different list Turn 1: search results 0 · iPhone 16 1 · Samsung S25 2 · OnePlus 13 user: "sort by price" model still sends: index 1 Turn 3: sorted by price 0 · OnePlus 13 1 · iPhone 16 2 · Samsung S25 the model meant Samsung S25, the server returns iPhone 16

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.

How the backend resolves a product reference. Seven steps in a row. User: Samsung S25 details? LLM: sees only P1, P2, P3. Tool Call: getProductDetails(P2). Reference Resolver, on the server: checks session, expiry, name and access. UUID Lookup: P2 to b9d3-456. Database: reads the real row. Product Details: Samsung S25. The Reference Resolver, UUID Lookup and Database run on the backend.TODO(human): describe what this diagram shows How the backend resolves a product reference Backend (server side) UserSamsung S25details?LLMsees onlyP1, P2, P3Tool CallgetProductDetails(P2)ReferenceResolverchecks session,expiry, name,accessUUIDLookupP2 →b9d3-456Databasereads thereal rowProductDetailsSamsung S25 The model only sees P1, P2, P3. The UUID never leaves the server.

The model now sees this instead of the raw list:

P1 · iPhone 16
P2 · Samsung S25
P3 · OnePlus 13

And the tool takes a reference, plus the name the model thinks it belongs to:

JSON
{
  "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

TypeScript
// 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 only ref and name.
  • The counter never resets inside a session. So P2 always 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 conversation

The 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:

TypeScript
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 the resultSetId if 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 addToCart or refund, 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.

Another option is to keep IDs away from the model completely. The model sends words, and the server finds the product:

TypeScript
// 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.

Part 4Which one to useCompare the four ways, and drop four myths
Two columns. Left, direct UUID selection: the LLM sees the UUIDs, sends a8f2-123, and the database returns the iPhone 16. Result: wrong product, no error. Right, backend reference mapping: the LLM sees P1, P2 and P3, sends P2 plus the name Samsung S25, and the server maps P2 to the UUID and checks access. Result: right product, or a clear error.TODO(human): describe what this diagram shows Direct UUID selection Backend reference mapping LLM sees the UUIDs LLM sends a8f2-123 Database returns iPhone 16 ✕ Wrong product, no error no check fails, and the answer sounds right LLM sees P1, P2, P3 LLM sends P2 + Samsung S25 Server maps P2 to the UUID and checks access ✓ Right product, or a clear error P1 + Samsung S25 → NAME_MISMATCH
ApproachThe model sendsA wrong pick returnsIt breaks whenUse it when
Direct UUID"b9d3-456"Another real record, silentlyThe model changes or swaps a characterAvoid for anything the model chooses
Index1Another item, silentlyThe list is sorted, paged or replacedOne fixed list for one short task
Server refs"P2" + nameA clear error, in most casesYou skip the session or access checkThe default for chat and agents
Backend search"Samsung S25""Ambiguous", if the rule is goodTwo names score almost the sameThe 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

MythReality
"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

  1. The model chooses. The server identifies. Let the model point at a short ref. Let the server turn it into a real ID.
  2. Treat tool arguments as user input. Check the format, the session, the expiry and the access, every time.
  3. Fail loudly, back to the model. A clear error that the model can read is better than a silent wrong answer.

Sources