AI Integration with Tally Prime ERP

TypeTechnical Reference
Technology StackPython, Flask, Groq AI (LLaMA 3.3), Tally Prime
Cost to Implement100% FREE – No Credit Card Required

EXECUTIVE SUMMARY

The project demonstrates a real-world AI integration: connecting Tally Prime ERP software with a free Large Language Model (Groq/LLaMA) to enable natural language business queries โ€” allowing any business owner to simply ask questions like ‘Show today’s sales’ or ‘What is my profit this month?’ and receive instant, intelligent answers.

Key Innovation Points

  • First-of-its-kind Tally Prime + Free AI integration using verified XML report names
  • 100% free implementation โ€” uses Groq API (no credit card, 14,400 requests/day)
  • Beautiful HTML chat interface โ€” works directly in any browser
  • Natural language queries replace complex Tally navigation
  • Combines local ERP data with AI intelligence in real time

 Technology Stack

ComponentTechnologyPurpose / Why Chosen
AI ModelGroq + LLaMA 3.3 70BFree, fast, highly accurate for business data
BackendPython 3 + FlaskSimple, beginner-friendly, widely taught
ERP SystemTally PrimeMost used accounting software in India
API ProtocolXML over HTTPNative Tally API โ€” no plugins needed
FrontendHTML5 + CSS3 + JSNo framework needed, opens in any browser
Cross-OriginFlask-CORSAllows browser to call local Python server
HTTP ClientPython RequestsStandard library for API calls

Verified Tally Prime Report Names

These report names were discovered through systematic testing and are confirmed working with Tally Prime via XML API:

XML Report NameQuery Keywords DetectedBusiness Use Case
Day Booksales, invoice, today, transactionDaily transaction register
Ledgerledger, account, partyAccount master list
Balance Sheetbalance sheet, assets, liabilitiesFinancial position
Profit and Lossprofit, loss, income, expenseBusiness performance
Trial Balancetrial, debit, creditAccount balances
Stock Summarystock, inventory, goodsInventory position
Cash Flowcash flow, cashCash movement analysis
Ratio Analysisratio, working capital, liquidityFinancial ratios

System Architecture Flow

StepDescription
Step 1User types query in HTML browser interface
Step 2JavaScript sends POST request to Flask server at localhost:5000/ask
Step 3Python analyses query keywords to select the appropriate Tally report
Step 4Python sends XML envelope request to Tally Prime at localhost:9000
Step 5Tally Prime returns raw XML data for the requested report
Step 6Python combines user query + Tally XML data into a Groq AI prompt
Step 7Groq API processes with LLaMA 3.3 70B and returns plain English answer
Step 8Flask returns JSON response to browser with answer + metadata
Step 9HTML displays formatted answer with source badges (Tally / Web)

3.4 Groq API โ€” Free Tier Limits

Limit TypeValue
Requests per Day14,400 requests (free tier)
Requests per Minute30 requests per minute
Model Usedllama-3.3-70b-versatile
Max Tokens per Request1,024 tokens (our setting)
Response TimeTypically, 1 to 3 seconds
CostRs. 0 โ€” completely free, no card needed
RegistrationGmail account only at console.groq.com

What This Project Does โ€” In Simple Terms

Imagine you have a very knowledgeable assistant sitting next to your computer. This assistant knows everything about accounting, GST, and Indian business practices. Whenever you want to know something about your business โ€” instead of opening Tally, clicking through menus, finding the right report, and reading complex numbers โ€” you simply ask your assistant a question.

This project creates exactly that assistant. It connects your existing Tally Prime software (where all your accounts live) with a modern AI (that understands language and numbers) and puts a simple chat window in your browser where you can type any question.

Real Business Questions This Can Answer

  • What is my total sales for today?
  • Which customers owe me money?
  • Am I making a profit this month?
  • What is my current cash balance?
  • What is the GST rate for my product category?
  • When is my next GST filing deadline?
  • How does my working capital look this quarter?
  • Which expense head is highest this month?

Why This Matters for Commerce Education

StakeholderBenefit
StudentsLearn AI + accounting integration โ€” highly employable skill
FacultyTeach cutting-edge fintech with a real working project
Business OwnersGet instant answers without Tally expertise
CA / AccountantsFaster data access and client reporting
TrainingProgrammeDemonstrates practical AI application in commerce domain

Comparison: Before vs After

TaskBefore (Traditional)After (AI Assistant)
Check today’s salesOpen Tally > Day Book > Set date > ReadType: Show today’s sales
Check profitReports > P&L > Set period > InterpretType: What is my profit?
GST rate querySearch government website or call CAType: GST rate for electronics
Balance sheetReports > Balance Sheet > ExportType: Show balance sheet
Staff training needed2 to 3 days Tally training5 minutes to type questions

COMPLETE SETUP GUIDE

Prerequisites Checklist

  • Tally Prime installed and running with a company loaded
  • Python 3.9 or higher installed (python.org)
  • Free Groq account โ€” sign up at console.groq.com using Gmail
  • Any modern browser (Chrome, Edge, Firefox)
  • tally_server.py and index.html files (provided in download)

Tally Prime Configuration

  1. Open Tally Prime and load your company
  2. Press F1 > Help > Settings > Connectivity
  3. Enable ‘Tally Gateway Server’ and set Port to 9000
  4. Press Enter to save โ€” Tally is now an HTTP server

Python Setup Commands

pip install flask flask-cors requests

Run the Application

cd “D:\Desktop\Tally Whatsapp”

python tally_server.py

Then double-click index.html to open in browser. The green badge confirms Tally is connected.

RELEVANCE

Learning Outcomes for Students

  • Understanding of REST API architecture and HTTP communication
  • Practical XML data parsing and manipulation
  • Integration of AI/LLM APIs in real business applications
  • Full-stack development: backend (Python) + frontend (HTML/JS)
  • Understanding of ERP systems and their data structures
  • Prompt engineering for business intelligence applications
  • Real-world problem-solving combining commerce and technology

Subjects This Project Covers

Subject AreaHow This Project Applies
AccountancyTally ERP reports โ€” P&L, Balance Sheet, Trial Balance
Computer ApplicationsPython programming, Flask web framework, API integration
Information TechnologyHTTP servers, XML APIs, JSON data exchange
Artificial IntelligenceLLM APIs, prompt engineering, AI response parsing
Business StudiesERP systems, business intelligence, financial analysis
EntrepreneurshipCost-zero implementation, practical business tool building

Possible Extensions for Advanced Students

  • WhatsApp integration โ€” query Tally via WhatsApp messages
  • Voice input โ€” speak questions using browser speech recognition
  • Automated daily email reports with AI-generated business summary
  • Multi-company support โ€” switch between Tally companies
  • Dashboard with charts using Chart.js for visual data
  • GST return preparation assistant using Tally data

FREE SOURCE CODE is here ๐Ÿ‘‡

โœ… tally_server.py โ€”

“””

Tally Prime + Groq Backend Server (100% FREE)

Setup:

  1. Get free API key from https://console.groq.com
  2. Paste your key below where it says GROQ_API_KEY
  3. Run: python tally_server.py
  4. Open index.html in your browser
    “””

from flask import Flask, request, jsonify
from flask_cors import CORS
import requests

app = Flask(name)
CORS(app)

โ”€โ”€โ”€ CONFIG โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

TALLY_URL = “http://localhost:9000”
GROQ_API_KEY = “your-groq-key-here” # ๐Ÿ‘ˆ Paste your free key here
GROQ_URL = “https://api.groq.com/openai/v1/chat/completions”
GROQ_MODEL = “llama-3.3-70b-versatile”

โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

โœ… Verified working report names for Tally Prime

TALLY_REPORTS = {
“ledger”: “Ledger”,
“daybook”: “Day Book”,
“balance”: “Balance Sheet”,
“profit”: “Profit and Loss”,
“trial”: “Trial Balance”,
“stock”: “Stock Summary”,
“cashflow”: “Cash Flow”,
“ratio”: “Ratio Analysis”,
}

def get_tally_data(query_lower):
“””Pick and fetch the best Tally Prime report for the user’s question.”””

# Choose report based on keywords
if any(w in query_lower for w in [“stock”, “inventory”, “item”, “product”, “goods”, “godown”]):
report_key = “stock”
elif any(w in query_lower for w in [“sales”, “sale”, “purchase”, “invoice”, “voucher”, “transaction”, “today”, “entry”, “day book”]):
report_key = “daybook”
elif any(w in query_lower for w in [“balance sheet”, “assets”, “liabilities”, “capital”]):
report_key = “balance”
elif any(w in query_lower for w in [“profit”, “loss”, “p&l”, “income”, “expense”, “indirect”, “direct”]):
report_key = “profit”
elif any(w in query_lower for w in [“trial”, “tb”, “debit”, “credit”]):
report_key = “trial”
elif any(w in query_lower for w in [“cash flow”, “cashflow”, “cash”]):
report_key = “cashflow”
elif any(w in query_lower for w in [“ratio”, “working capital”, “liquidity”, “analysis”]):
report_key = “ratio”
else:
report_key = “ledger”

report_name = TALLY_REPORTS[report_key]

xml_body = “””
Export Data

“”” + report_name + “”” $$SysName:XML
“””

try:
    resp = requests.post(
        TALLY_URL,
        data=xml_body.encode("utf-8"),
        headers={"Content-Type": "text/xml"},
        timeout=10
    )
    text = resp.text

    # Check for errors in response
    if "LINEERROR" in text or "Unknown Request" in text:
        return {
            "success": False,
            "report": report_name,
            "data": f"Tally returned an error for report: {report_name}"
        }

    return {"success": True, "report": report_name, "data": text}

except requests.exceptions.ConnectionError:
    return {
        "success": False,
        "report": report_name,
        "data": "TALLY_OFFLINE: Cannot connect to Tally on port 9000. Please make sure Tally Prime is open with a company loaded."
    }
except requests.exceptions.Timeout:
    return {
        "success": False,
        "report": report_name,
        "data": f"Tally took too long to respond for report: {report_name}. Try a simpler query."
    }
except Exception as e:
    return {"success": False, "report": report_name, "data": f"ERROR: {str(e)}"}

def ask_groq(user_query, tally_result):
“””Send question + Tally data to Groq AI.”””

system_prompt = """You are a smart, friendly Indian business assistant integrated with Tally Prime ERP.

You help business owners understand their accounts, GST, stock, and business finances.

Your behavior:

  • Carefully parse the Tally XML data and extract meaningful numbers, account names, and balances
  • Present data in a clean, readable format โ€” use tables or bullet points when listing accounts
  • Format all amounts in Indian style: use lakhs and crores (e.g. 5,84,000 = 5.84 Lakhs)
  • If you see Dr/Cr in amounts, explain what it means simply
  • Give a clear direct answer to the user’s question first, then show supporting data
  • If Tally is offline or returned no data, answer from your own knowledge
  • For GST rates, tax deadlines, RBI rates โ€” answer from knowledge and note it may have changed
  • Company name in Tally: “Tally with Chat GPT”
  • End with 1-2 short actionable tips when useful
  • Be concise and friendly like a CA friend””” user_message = f”””Question: {user_query}

Tally Report Used: {tally_result[‘report’]}
Tally Status: {“Connected – data received” if tally_result[‘success’] else “Error/Offline”}

Raw Tally Data:
{tally_result[‘data’][:5000]}

Please answer the question based on this Tally data.”””

headers = {
    "Authorization": f"Bearer {GROQ_API_KEY}",
    "Content-Type": "application/json"
}

payload = {
    "model": GROQ_MODEL,
    "messages": [
        {"role": "system", "content": system_prompt},
        {"role": "user",   "content": user_message}
    ],
    "max_tokens": 1024,
    "temperature": 0.5
}

resp = requests.post(GROQ_URL, headers=headers, json=payload, timeout=30)
resp.raise_for_status()
return resp.json()["choices"][0]["message"]["content"]

@app.route(“/ask”, methods=[“POST”])
def ask():
body = request.get_json()
user_query = body.get(“query”, “”).strip()

if not user_query:
    return jsonify({"error": "Empty query"}), 400

tally_result = get_tally_data(user_query.lower())

try:
    answer = ask_groq(user_query, tally_result)
    return jsonify({
        "answer": answer,
        "tally_connected": tally_result["success"],
        "report_used": tally_result["report"],
        "web_searched": False
    })

except requests.exceptions.HTTPError as e:
    status = e.response.status_code
    if status == 401:
        return jsonify({"error": "Invalid Groq API key. Get your free key at console.groq.com"}), 401
    elif status == 429:
        return jsonify({"error": "Rate limit hit. Please wait a moment and try again."}), 429
    else:
        return jsonify({"error": f"Groq error {status}: {e.response.text}"}), 500
except Exception as e:
    return jsonify({"error": str(e)}), 500

@app.route(“/status”, methods=[“GET”])
def status():
“””Check if Tally is reachable.”””
try:
requests.post(TALLY_URL, data=b””, timeout=3)
return jsonify({“tally”: “online”})
except:
return jsonify({“tally”: “offline”})

if name == “main“:
print(“=” * 55)
print(” Tally Prime + Groq Assistant (FREE)”)
print(” Server: http://localhost:5000″)
print(” Open index.html in your browser”)
print(“=” * 55)
print()
print(” Working Tally Prime Reports:”)
for k, v in TALLY_REPORTS.items():
print(f” – {v}”)
print()
app.run(host=”0.0.0.0″, port=5000, debug=False)

โœ… index.html โ€”

Get FREE Groq API Key: https://console.groq.comย  ๐Ÿ’ฌ

Drop a comment if you get it working! I reply to every question.ย ย ย 

Leave a Comment