Support Chatbot: Combining Doc Retrieval and Order Lookups
Machine LearningModel answerLast updated
Design a shopping-support assistant that answers product questions from a document index and checks order data through safe, typed tools, covering routing, guardrails, sampling and evaluation.
Scenario
An online retailer wants a conversational support assistant built on a large language model. Customers will use it for two kinds of requests:
- Product questions (specs, compatibility, care instructions, return policy), answered from a searchable collection of product documents using retrieval-augmented generation.
- Order questions (status, tracking, history), answered by querying the company's internal relational order database.
Design the assistant end to end.
What to cover
- Routing. How does the assistant decide whether to search the documents, query the order database, or do both in one turn?
- Tool definitions. How would you describe the database-lookup capability to the model so that it calls it correctly and consistently? Sketch the argument schema and the tables behind it.
- Safety. How do you stop the assistant from taking actions it should not (for example deleting or altering orders), and from exposing personal data that may be present in the document collection?
- Sampling temperature. How does the temperature setting affect behavior in this use case, and what would you choose?
- Evaluation. How would you measure answer accuracy and the quality of tool usage?
Expected output
- A walkthrough of the request path from the customer's message to the final reply.
- A proposed interface or data model for the tools.
- A short evaluation plan.
- Trade-offs and failure modes you would watch for.
Hints
Hint 1
Treat document search as one more tool next to the order lookup, so the model picks among tools in a single decision, and mixed questions ("is the item I ordered last week dishwasher-safe?") can chain two calls.
Hint 2
Do not let the model write SQL or pass a user identifier. Expose narrow typed functions with enums, patterns and bounds, and let the server inject the authenticated user from the session.
Hint 3
Separate reading from writing: give the model read-only tools plus 'propose' actions that need out-of-band confirmation, and put business-rule checks in a policy layer outside the model.
Hint 4
For evaluation, score the tool choice, the arguments and the final grounded answer separately, using a labeled conversation set, then track the same signals online.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope
Functional: answer product questions from documents; look up status, tracking and history for the authenticated customer; optionally allow limited writes (such as cancelling an unshipped order) only after explicit confirmation; hand off to a human when confidence is low or the customer asks.
Non-functional: low latency (for example time to first token under about 2 s), no fabricated order facts, zero cross-customer data access, no personal data in replies.
Rough scale (assumed): 1M conversations/day, about 5 turns, about 2 model calls per turn, so roughly 10M calls/day, about 115/s average and several hundred/s at peak. A catalogue of 5M products at about 10 chunks each gives about 50M chunks. At 768 dimensions in float32 that is around 150 GB of vectors, so plan for quantization or sharding.
2. Request flow
- Gateway: authenticates the customer, builds a server-side session (user id, locale), applies rate limits.
- Input guard: detects injection attempts and redacts sensitive strings typed by the user (card numbers, national IDs) before logging or model use.
- Orchestrator loop (reason, act, observe): the model sees the system prompt, history and tool schemas, and on each step emits either a tool call or a final answer. Cap the loop at about 5 steps.
- Tool executor: validates arguments against the schema, injects session identity, checks policy, runs the call, returns structured JSON.
- Output guard: scans for personal data and checks grounding (every order number, date or price in the reply must appear in a tool result).
- Response: streamed to the customer; the whole trace is stored for audit and evaluation.
3. Routing between documents and database
Model document search as a tool (search_product_docs) beside get_orders. Native function calling then makes one unified decision and naturally handles mixed intents: fetch the order, read the SKU, then search documents for that SKU.
Optional optimization: a small classifier handles clear-cut cases (plain "where is my order", greetings) without the large model, saving a hop on a sizable share of traffic. The system prompt states two hard rules: order facts come only from order tools; product facts come only from retrieved passages, cited by document id. If neither source supports an answer, say so or escalate.
4. Tool schema
Never let the model produce raw SQL. Offer typed functions that run parameterized queries.
from enum import Enum
from pydantic import BaseModel, Field
class Status(str, Enum):
ANY = "any"; PROCESSING = "processing"; SHIPPED = "shipped"; DELIVERED = "delivered"
class GetOrdersArgs(BaseModel):
"""Look up the signed-in customer's orders: status, tracking, history."""
order_id: str | None = Field(None, pattern=r"^\d{10}$")
status: Status = Status.ANY
limit: int = Field(5, ge=1, le=20)
class SearchDocsArgs(BaseModel):
"""Search product specs, guides and policies."""
query: str = Field(..., max_length=300)
sku: str | None = None
class ProposeCancelArgs(BaseModel):
"""Request cancellation of an unshipped order. Needs customer confirmation."""
order_id: str = Field(..., pattern=r"^\d{10}$")
reason: str = Field(..., max_length=200)
Reliability techniques:
- Strict or constrained decoding, enums instead of free text, regex patterns, bounded integers.
- No user id argument. The executor takes it from the session, so the model cannot even express "show someone else's orders".
- Descriptions that say when to use and when not to use each tool, with a short example.
- On validation failure, return a structured error and allow one self-correction attempt.
Backing tables: orders(order_id, user_id, status, created_at, total), order_items(order_id, sku, qty), shipments(order_id, carrier, tracking, eta), doc_chunks(chunk_id, sku, doc_type, text, embedding, acl, version).
5. Safety and guardrails
Unauthorized actions
- Least privilege: read tools use a read-only database role with row-level security keyed by user id. Delete tools simply do not exist.
- Writes go through a separate service with its own authorization; the model can only call
propose_*tools, and the customer confirms outside the model. - A policy engine outside the model enforces business rules (order not shipped, inside cancellation window) before anything executes.
Personal data in the document index
- Scrub at ingestion (pattern matching plus entity recognition) and exclude sources such as tickets or reviews containing personal details. Prevention here beats filtering later.
- Apply access-control filters at retrieval so internal-only documents never reach customer sessions.
- Run a final detector on the output to redact or block.
Prompt injection: wrap retrieved text and tool output in delimited data blocks and tell the model never to follow instructions inside them. Because tools are narrow and writes need confirmation, a successful injection has a small blast radius.
6. Temperature
- Tool choice and arguments: 0 to 0.2. Randomness directly produces wrong tools, malformed ids and invented parameters; low values also make runs reproducible for debugging and tests.
- Final phrasing: about 0.2 to 0.3. Higher values increase the risk of invented dates or policies and add little value in support.
- Use higher values only offline, for example to generate diverse paraphrases for test sets.
Temperature 0 is not a guarantee of determinism and does not repair a weak prompt; schema constraints and grounding checks matter more.
7. Evaluation
Offline, on a labeled set of a few thousand conversations
- Routing/tool selection: precision and recall per tool, plus rate of unnecessary calls.
- Argument accuracy: exact match on ids, enums and filters; schema-validation failure rate.
- Retrieval: recall@k and MRR against labeled relevant chunks.
- Answer quality: groundedness (claims supported by tool output or passages), correctness, and refusal behavior, scored by rubric-based LLM judges calibrated against human labels.
- Safety suite: adversarial cases (cross-user requests, "cancel everything", injection in documents, personal data bait); target zero violations.
Online
- Task resolution and escalation rate, thumbs feedback, latency percentiles, tool error rates, cost per conversation.
- Shadow or A/B rollouts for prompt and model changes, with a regression gate on the offline suite.
8. Trade-offs and common mistakes
- Hard-coded keyword routing breaks on mixed questions; model-driven tool choice with a cheap fast path is a better balance.
- Letting the model supply the user id or SQL is the most common serious flaw.
- Relying on the prompt alone for safety; enforce in code and permissions.
- Skipping grounding checks, which lets plausible but invented tracking details through.
- Unbounded loops: cap steps, set timeouts, and fall back to a human handoff.
- Stale documents: version chunks and re-index on catalogue changes.