Analyst Bot: RAG for Knowledge + Code for Exact Calculations

Cover image for article 1213

The author built a demo assistant for a fictional cleaning company called “Fresh Meter”. The bot sits in the website chat and in Telegram, answers questions from the knowledge base (RAG), computes preliminary pricing from the price list, and assembles a service request for a manager. The key problem: the LLM hallucinates prices and links. The solution is a hybrid architecture: RAG for semantic search + Python code for exact calculations and link verification.

Architecture: RAG + Code Verification

The user request pipeline:

  1. Intent classification — a BERT classifier determines: FAQ / price calculation / request intake / handoff to a manager.
  2. RAG search — vector search over the knowledge base (Qdrant + bge-m3, top-5 chunks). The context is passed to the LLM to phrase the answer.
  3. Code execution — if the intent is “price calculation”, the LLM generates Python code with parameters taken from the context, the code runs in a sandbox (gVisor), and the result is inserted into the answer.
  4. Link verification — every URL in the answer is checked with a HEAD request, and broken links are replaced with “link outdated”.
  5. Response synthesis — the LLM assembles the final answer from the RAG context + the code result + the verified links.

Example Intents and User Phrasings

IntentUser phrasingsBot action
FAQ“Are you open on weekends?”, “What does a deep clean include?”Answer based on RAG context from the knowledge base
Price calculation“How much to clean a 2-room apartment with windows?”, “Price for sofa dry cleaning”The LLM generates calculation code, the sandbox computes from the price list
Request intake“I want to book for Saturday by 10 am”, “Schedule a home visit”A form: address, date, phone, field validation
Handoff to a manager“I need a human, not a bot”, “Can I get a discount for regular cleaning?”A ticket in the CRM and a notification to the manager

The classifier is a cheap BERT (110M parameters, 8 ms on CPU), not a prompt: a prompt on every request would cost 200+ tokens and add 300-400 ms of latency.

Why the Hybrid Beats Pure RAG

Pure RAG + LLM hallucinates on numbers: “a 3-room apartment cleaning costs 5,000 rubles” (while the price list says 7,500). Python code takes the current prices from the DB/JSON and computes exactly. The division of labor: the LLM is responsible for language understanding and answer structure, the code — for exact facts.

End-to-End Example: From Question to an Answer with a Price

Question: “How much would it cost to clean a three-room apartment and wash four windows?” The path of the request:

  1. Classifier: intent = calc_price, confidence 0.94.
  2. RAG pulls the service card and the coefficient rule (windows are counted per unit).
  3. The LLM generates the code:
def calc_price(params, PRICE_DB):
    base = PRICE_DB["apt_3room"]                     # 7500
    windows = params["windows"] * PRICE_DB["window"] # 4 x 500
    return {"price": base + windows,
            "breakdown": ["3-room clean: 7,500", "windows x4: 2,000"]}
  1. The sandbox executes the code in 120 ms and returns JSON with a price of 9,500.
  2. The answer to the user: “A three-room apartment cleaning with four windows washed comes to 9,500 rubles: 7,500 for the cleaning and 2,000 for the windows. The exact quote follows an on-site inspection”.

The whole path took 1.8 s, of which 260 LLM tokens and 120 ms in the sandbox. If the LLM had done this arithmetic itself, the price would have been equal to the chance of a hallucination.

Practical Implementation (Python)

async def handle_query(user_text: str):
    intent = classify_intent(user_text)
    rag_context = await rag_search(user_text, top_k=5)

    if intent == "calc_price":
        # the LLM generates the calculation code
        code_prompt = f"""
        Based on the context: {rag_context}
        Write a calc_price(params) function for: {user_text}
        Use the price list: PRICE_DB (dict: service -> price)
        Return JSON: {{"price": int, "breakdown": list}}
        """
        code = await llm_generate(code_prompt)
        result = await sandbox_exec(code, {"PRICE_DB": get_price_db()})
        answer = f"Total: {result['price']} rubles. Details: {result['breakdown']}"
    else:
        answer = await llm_answer(rag_context, user_text)

    # link verification
    answer = await verify_links(answer)
    return answer

The Code Execution Sandbox (gVisor)

Running unverified code is a risk. The solution: gVisor (a user-space kernel) + CPU/RAM/time limits. The configuration:

sandbox:
  runtime: gvisor
  cpu_limit: 0.5
  memory_limit: 128Mi
  timeout: 5s
  network: none
  filesystem: readonly (except /tmp)

Over 10,000 requests a day: 0 escape incidents, average code execution time 120 ms, P99 350 ms.

The Sandbox Threat Model: What Is Isolated and Why

  • File system: read-only plus /tmp — generated code must not edit the bot itself or read environment secrets (env variables, API keys).
  • Network: switched off entirely — the code can neither leak data outward nor scan internal services (the price DB, the CRM, the admin panel).
  • Resources: 0.5 CPU, 128 Mi of RAM, 5 seconds — protection against fork bombs, infinite loops, and monopolizing the worker.
  • Kernel: gVisor intercepts syscalls with a user-space layer — even a discovered host kernel vulnerability gives no way out of the isolation.
  • What is not isolated: data inside the sandbox is available to the code (PRICE_DB is passed as an argument), so only the price list goes into the context — never users’ personal data.

LLMs frequently invent URLs. Answer post-processing:

  1. Extract all URLs with a regular expression.
  2. Send a HEAD request (timeout 3 s, follow redirects).
  3. Status 200 — keep it. 404/5xx/timeout — replace with “link outdated”.
  4. Cache the results in Redis (TTL 24 h) — do not spam external services.

Telemetry and the Bot’s SLA

Without observability, a hybrid turns into a black box. The minimal metric set: intent-classifier accuracy against operator labeling, price deviation from manual calculation (the reference is a weekly sample of 100 deals), the share of handoffs to managers, P50/P99 latency per stage (RAG, code generation, sandbox), sandbox timeouts. The dashboard is Grafana, with alerts: success rate below 90% for an hour, P99 above 3 s, sandbox errors above 1%. The SLA: 99.5% availability during business hours, FAQ answers within 3 s, calculations within 5 s; after two failed answers in a row the bot escalates to a live manager — dropping a dialog silently is not allowed.

Quality Metrics

MetricPure RAGRAG + Code
Price hallucinations23%0.2%
Broken links12%0%
Response time (P99)1.2 s1.8 s
User satisfaction3.2/54.7/5

Rollout Plan: Pilot → Shadow → Production

  • Pilot (weeks 1-2): 50 real support questions are run offline, the intent dictionary is labeled, and the share of price hallucinations is measured on historical dialogues.
  • Shadow (weeks 3-6): the bot answers alongside operators, operators correct the phrasings, a diff log of edits is collected; exit thresholds — price hallucinations below 1%, zero broken links, P99 below 3 s.
  • Production (from week 7): enablement on 10% of traffic and two weeks of observation, then to full volume; the whole time, keep a kill-switch — a rollback to pure RAG mode via a single environment variable.

The RAG + code hybrid adds 600 ms of latency but removes 99% of factual errors. For service bots it is a mandatory pattern.

The articles Anti-hallucination for LLM agents and Code agents in production cover related topics.

Useful resources: gVisor documentation, Qdrant documentation.

Analyst bot: the RAG + code hybrid for exact facts (agent rag)

A practical pattern for a hallucination-free bot:
1) Intent classification (BERT) → FAQ / Price / Lead / Handoff.
2) RAG (Qdrant + bge-m3, top-5) for semantic context.
3) If intent=Price → the LLM generates Python code with parameters → sandbox exec (gVisor) → an exact calculation.
4) Every URL in the answer goes through a HEAD check, broken ones are replaced with [link unavailable].
5) A Redis cache of link verifications with a 24 h TTL.
6) Shadow mode before production: the bot answers alongside operators, exit thresholds — price hallucinations below 1%, P99 below 3 s.
Results: price hallucinations 0.2%, broken links 0%, P99 latency 1.8 s.
Like this post? Please share to your friends:
11AI - Your Free LLM
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: