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:
- 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.
- 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.
- 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 toIntl.NumberFormatandIntl.DateTimeFormatacross 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 (
Omnifor photo OCR,Nanofor fast shorthand parsing and grounding checks,Superfor weekly synthesis, andUltraonly 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
Supersynthesizes an answer, a mandatory second pass (task: verify_groundingonNano) verifies each claim against the retrieved source text and strips unsupported numbers or eligibility claims.
| Task Type | Assigned NVIDIA Nemotron Tier | Latency / Cost Profile & Responsibility |
|---|---|---|
read_notebook_photo | Nemotron Omni (Vision) | Multimodal extraction of handwritten ledger rows across Latin & non-Latin scripts |
parse_shorthand, draft_reminder, plan_search, verify_grounding | Nemotron Nano | Sub-second structured JSON tasks and post-synthesis citation verification |
synthesize_advisor, weekly_summary | Nemotron Super | Mid-size reasoning combining shop ledger aggregates with Tavily search extracts |
multi_tool_investigation | Nemotron Ultra | Reserved 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.
Camera upload, integer minor-unit balance table, and multilingual reminder drafts
Displays cited web insights plus live AiCall and WebCall telemetry logs
Decides Ledger vs. Web vs. Both; strips all customer names and phone numbers before web search
Caches by (query + country) for 24h; enforces daily shop credit budget and selective extract
Checks every synthesized claim against retrieved source text; strips ungrounded numbers/rates
Shop settings, minor-unit transactions, 24h search cache, AiCall, and WebCall logs
OpenAI-compatible routing across Omni, Nano, Super, and Ultra tiers
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:
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:
- 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 fromitem names,shopCategory,countryCode, andlanguage. - Post-Synthesis Verification (`Rule T2`): Every statement synthesized by
Superis checked by averify_groundingpass 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:
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 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
- 00:00One Handwritten Notebook, Many Global Names — Designing a single zero-assumption codebase for shopkeepers in India (khata), Brazil (fiado), Mexico, and the Philippines (utang).
- 01:15Multi-Tier NVIDIA Nemotron Routing on Nebius — Routing tasks across Omni (vision OCR), Nano (shorthand parsing & grounding verification), Super (synthesis), and Ultra.
- 02:35Two-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 automatedaudit:globalcheck to scan source files for forbidden hardcoded currency literals and country strings kept the codebase strictly driven byShopSettings. - 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 callingextractonly 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 inWebCall(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 completeAGENTS.mdv3 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
ShopSettingsandwatchlistitems (and cannot even read theCustomertable) 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.