Skip to main content
09 // ENGINEERING SPECIFICATIONGlobal AI Hackathon Architecture

Khata Agent: Locale-Agnostic Credit Ledger & Grounded Market Awareness System

A global, mobile-first web architecture designed for the Nebius x NVIDIA Global AI Hackathon that digitizes handwritten shopkeeper credit notebooks (khata, fiado, utang) and pairs ledger balances with source-grounded live market awareness via multi-tier NVIDIA Nemotron routing and Tavily search.

Published 2026-10-118 min readGitHub Repository
Next.js (App Router)TypeScriptNVIDIA Nemotron (Nebius)Tavily APInext-intlPrismaZod

1. Overview#

Khata Agent is a mobile-first web system designed for the Nebius x NVIDIA Global AI Hackathon to serve small shopkeepers worldwide who record customer credit sales in handwritten notebooks (khata/udhaar, fiado, utang).

The system connects two complementary capabilities:

  • Part A — Digital Credit Ledger: A shopkeeper photographs a handwritten notebook page; vision and fast parsing models convert the page into structured credit sales and payments in integer minor units, track customer balances, and draft polite payment reminders in the customer's preferred language.
  • Part B — Grounded Market Awareness (Tavily + Nemotron): An advisory agent monitors live web developments relevant to the shop's inventory watchlist and country (wholesale commodity price shifts, supply news, and small-business grant/funding programs) and combines external web evidence with the shop's internal ledger.

2. The Problem#

Small neighborhood merchants operate on thin margins with two disconnected sources of risk:

  1. Unstructured credit notebooks: Handwritten ledgers mix scripts, regional shorthand, and local number groupings, making it slow to tally overdue balances or send timely, polite reminders.
  2. Blindness to external supply and funding shifts: When wholesale prices for staple goods spike or local small-business credit programs open, shopkeepers often find out too late—and general-purpose AI chatbots frequently hallucinate interest rates, eligibility criteria, or commodity prices when asked about local markets.
  3. Hardcoded regional assumptions in software: Most bookkeeping apps hardcode a single currency symbol (₹ or $), date format, or country domain list, making them unusable across borders.

3. The Approach#

Khata Agent is governed by three strict architectural rule sets defined in AGENTS.md: Global Rules (`G1–G7`), Tavily Grounding Rules (`T1–T7`), and Tech & Model Routing Rules (`1–9`):

  • Zero Hardcoded Country Assumptions (`G1–G4`): Code, prompts, and UI use neutral domain vocabulary (ledger, credit sale, payment, customer, balance). Currency is stored exclusively as integer minor units + ISO 4217 code (never floating-point numbers, with zero implicit currency conversion), phone numbers use E.164, and display formatting delegates to Intl.NumberFormat and Intl.DateTimeFormat across launch locales (en, hi, es, pt).
  • Task-Specific NVIDIA Nemotron Routing (Nebius Token Factory): Instead of routing every prompt to a single slow frontier model, tasks are dispatched to the smallest capable NVIDIA Nemotron tier (Omni for photo OCR, Nano for fast shorthand parsing and grounding checks, Super for weekly synthesis, and Ultra only for complex multi-tool queries).
  • Two-Pass Tavily Citation & Grounding Verification (`T1–T5`): Every web-derived statement must display its source title, URL, and publication/retrieval date. After Super synthesizes an answer, a mandatory second pass (task: verify_grounding on Nano) verifies each claim against the retrieved source text and strips unsupported numbers or eligibility claims.
Specification table (Task Type, Assigned NVIDIA Nemotron Tier, Latency / Cost Profile & Responsibility)
Task TypeAssigned NVIDIA Nemotron TierLatency / Cost Profile & Responsibility
read_notebook_photoNemotron Omni (Vision)Multimodal extraction of handwritten ledger rows across Latin & non-Latin scripts
parse_shorthand, draft_reminder, plan_search, verify_groundingNemotron NanoSub-second structured JSON tasks and post-synthesis citation verification
synthesize_advisor, weekly_summaryNemotron SuperMid-size reasoning combining shop ledger aggregates with Tavily search extracts
multi_tool_investigationNemotron UltraReserved strictly for complex multi-hop ledger + market queries

4. System Architecture#

The architecture enforces a hard privacy firewall between the internal customer ledger and external web search queries, while logging every AI and web invocation (AiCall and WebCall audit tables) for cost and latency transparency.

SYSTEM SCHEMATIC // KHATA AGENT MULTI-MODEL ROUTING & TWO-PASS TAVILY GROUNDING ARCHITECTURE
01. Global Mobile-First Web Client (Next.js App Router + next-intl)
Notebook Capture & Ledger View

Camera upload, integer minor-unit balance table, and multilingual reminder drafts

Intl.NumberFormat · E.164
Market Advisor & AI Activity Panel

Displays cited web insights plus live AiCall and WebCall telemetry logs

React · Tailwind CSS
Locale-Aware Actions (en, hi, es, pt)
02. Orchestration, Privacy Firewall & Grounding Verification
Ask Router & Privacy Filter

Decides Ledger vs. Web vs. Both; strips all customer names and phone numbers before web search

plan_search (Nemotron Nano)
Tavily Search & 24h Cache Layer

Caches by (query + country) for 24h; enforces daily shop credit budget and selective extract

Tavily API · WebCall Table
Two-Pass Grounding Verifier

Checks every synthesized claim against retrieved source text; strips ungrounded numbers/rates

verify_grounding (Nemotron Nano)
Zod-Validated Tool & Model Calls
03. Persistence & Nebius Token Factory Model Tiers
Relational Ledger & Audit Store

Shop settings, minor-unit transactions, 24h search cache, AiCall, and WebCall logs

Prisma · PostgreSQL
Nebius Token Factory (Nemotron)

OpenAI-compatible routing across Omni, Nano, Super, and Ultra tiers

NVIDIA Nemotron Models
Figure: Khata Agent Multi-Model Routing & Two-Pass Tavily Grounding Architecture

5. Engineering Deep Dive#

5.1 Locale-Agnostic Monetary & Internationalization Contract#

Financial bugs frequently arise when applications store currency as IEEE 754 floats (19.99) or hardcode locale assumptions. Khata Agent's global specification enforces integer minor units (e.g., paise, centavos, cents) paired with an explicit ISO 4217 currency code from ShopSettings, formatting values at the presentation boundary via Intl.NumberFormat:

Locale-Neutral Money & Shop Settings Contracttypescript
import { z } from "zod";

export const ShopSettingsSchema = z.object({
  countryCode: z.string().length(2),       // ISO 3166-1 alpha-2 (e.g. "IN", "BR", "MX", "PH")
  currencyCode: z.string().length(3),      // ISO 4217 (e.g. "INR", "BRL", "MXN", "PHP")
  locale: z.string().min(2),               // BCP-47 (e.g. "hi-IN", "pt-BR", "es-MX", "en-PH")
  timezone: z.string().min(1),             // IANA timezone
  notebookLanguages: z.array(z.string()).min(1),
  reminderLanguage: z.string().min(2),
  shopCategory: z.string().min(1),
  dailySearchCap: z.number().int().positive().default(25),
});

export interface MinorUnitMoney {
  amountMinor: number; // Integer minor units only — never floating-point
  currency: string;    // ISO 4217 code
}

export function formatShopMoney(
  money: MinorUnitMoney,
  locale: string
): string {
  const formatter = new Intl.NumberFormat(locale, {
    style: "currency",
    currency: money.currency,
  });
  const parts = formatter.resolvedOptions();
  const divisor = Math.pow(10, parts.maximumFractionDigits ?? 2);
  return formatter.format(money.amountMinor / divisor);
}

5.2 Two-Pass Tavily Grounding & PII Isolation Pipeline#

When a shopkeeper asks a question that requires both ledger context and live web data (for example, "Rice wholesale prices are rising—which of my wholesale buyers have overdue balances and are there any working-capital grants open in my state?"), the orchestrator enforces two strict invariants:

  1. Zero PII in Web Queries (`Rule 7`): Customer names and E.164 phone numbers are never passed into plan_search. Web queries are constructed solely from item names, shopCategory, countryCode, and language.
  2. Post-Synthesis Verification (`Rule T2`): Every statement synthesized by Super is checked by a verify_grounding pass against the raw Tavily snippets. If a price, interest rate, or eligibility percentage cannot be located in the retrieved source text, it is removed before rendering:
Two-Pass Grounded Synthesis Contracttypescript
import { z } from "zod";

export const CitedClaimSchema = z.object({
  statement: z.string().min(1),
  sourceTitle: z.string().min(1),
  sourceUrl: z.string().url(),
  sourceDate: z.string().min(1), // Published date or retrieved date
  dateType: z.enum(["published", "retrieved"]),
});

export const GroundedSynthesisSchema = z.object({
  status: z.enum(["grounded", "insufficient_evidence"]),
  claims: z.array(CitedClaimSchema),
  neutralNotice: z.string().optional(),
});

6. Technical Demo#

Technical Walkthrough & Verification
Recorded video walkthrough coming soon

Technical walkthrough recording coming soon

Architectural walkthrough of Khata Agent: locale-agnostic minor-unit ledger accounting, multi-tier NVIDIA Nemotron model routing, and two-pass Tavily citation grounding.

Walkthrough Sequence & Checkpoints

  1. 00:00
    One Handwritten Notebook, Many Global Names — Designing a single zero-assumption codebase for shopkeepers in India (khata), Brazil (fiado), Mexico, and the Philippines (utang).
  2. 01:15
    Multi-Tier NVIDIA Nemotron Routing on Nebius — Routing tasks across Omni (vision OCR), Nano (shorthand parsing & grounding verification), Super (synthesis), and Ultra.
  3. 02:35
    Two-Pass Tavily Grounding & Privacy Isolation — Ensuring customer PII never leaves the ledger while every web market claim is verified against source text.
View Written Walkthrough Summary / Transcript ▾

Across emerging and local markets worldwide, millions of small shopkeepers track customer credit in handwritten notebooks—called khata or udhaar in South Asia, fiado in Latin America, and utang in the Philippines. The underlying data model is identical, yet software tools almost always hardcode a single country's currency symbol, language, and phone format.

Khata Agent was designed for the Nebius x NVIDIA Global AI Hackathon around two connected halves: a digitized credit ledger from notebook photos, and a live market awareness advisor powered by Tavily that watches wholesale commodity prices and local small-business funding programs.

Every architectural rule in AGENTS.md enforces strict global neutrality (ISO 4217 integer minor units, E.164 phone numbers, BCP-47 locales via next-intl) and strict web grounding: customer names and phone numbers are never sent to Tavily, and every web-derived synthesis passes through a second Nemotron Nano verify_grounding pass that strips any claim not backed by a cited URL and date.

7. Challenges and Trade-offs#

  • Preventing Regional Hardcoding Across Four Launch Markets: Supporting synthetic demo shops across India (INR, hi/en), Brazil (BRL, pt), Mexico (MXN, es), and the Philippines (PHP, en) meant eliminating hardcoded domain lists or currency symbols from prompts and UI components. Designing an automated audit:global check to scan source files for forbidden hardcoded currency literals and country strings kept the codebase strictly driven by ShopSettings.
  • Controlling Tavily API Credit Consumption: Running deep web extraction on every user question quickly depletes search credits. By defaulting to search_depth: "basic", caching search results for 24 hours keyed by (normalizedQuery, countryCode), and calling extract only on the top URLs selected for the final synthesis, the architecture bounds API spend predictably.
  • Transparency Over "Black-Box" Agent Calls: Judges and technical users want to see which model tier ran and why. Logging every model call in AiCall (task, model tier, language, tokens, latency, estimated cost) and every search in WebCall (query, endpoint, country, latency, cache hit) and surfacing both in an inspectable AI Activity Panel turned backend observability into a user-visible feature.

8. Testing and Validation#

  • Global Neutrality Audit (`AGENTS.md` Rules G1–G7): Established strict global rules prohibiting hardcoded currency symbols, country codes, or regional terms outside marketing copy, verified across four multi-currency shop profiles (INR, BRL, MXN, PHP).
  • Current Repository State: The repository (E:\khata-agent) contains the complete AGENTS.md v3 system specification and the initialized Next.js 16 + TypeScript + Tailwind CSS 4 foundation (src/app/), documenting the full multi-model routing and Tavily grounding architecture.

9. What I Learned#

  • Internationalization is a data-model decision, not a translation file: Storing money as integer minor units with ISO 4217 codes and enforcing logical CSS properties from day one prevents painful rewrites when expanding from one country to four.
  • Separate query planning from customer context: Enforcing a structural boundary where the search-planning function only receives ShopSettings and watchlist items (and cannot even read the Customer table) makes PII leakage into third-party search APIs impossible by construction.

10. Future Improvements#

  • Offline Notebook Photo Queue: Add IndexedDB queuing for captured notebook photos so shopkeepers with intermittent mobile connectivity can snap pages offline and sync when connectivity returns.
  • Automated Benchmark Harness: Complete the Phase 0 OCR accuracy benchmark suite across handwritten Hindi, Spanish, Portuguese, and English ledger samples.