DEV Community

Cover image for ChatWithSQL — Secure, Schema-Validated Text-to-SQL Python Library, Eliminating Arbitrary Query Risks from LLMs
Sathnindu Kottage
Sathnindu Kottage

Posted on

ChatWithSQL — Secure, Schema-Validated Text-to-SQL Python Library, Eliminating Arbitrary Query Risks from LLMs

Library: https://pypi.org/project/chatwithsql
GitHub: https://github.com/sathninduk/chatwithsql

As software evolves, the demand for intuitive, secure, and efficient database interaction grows exponentially. Enter ChatWithSQL, a groundbreaking Python library that transforms how developers interact with SQL databases. By combining the power of Natural Language Processing (NLP) with schema-validated SQL generation and data retrieval, ChatWithSQL sets a new benchmark for secure and efficient data retrieval.

🌟 What Makes ChatWithSQL Unique?

Text-to-SQL tools are not new, but most have a glaring flaw: the potential to generate and execute arbitrary queries. This poses critical risks:

  • Unauthorized data access.
  • SQL injection vulnerabilities.
  • Query inefficiencies.

ChatWithSQL redefines safety and reliability by implementing a schema-based validation approach. By ensuring all queries adhere to a predefined schema, the library eliminates unauthorized access while maintaining unparalleled performance.

🗺️ Architecture

Image description

🔒 Security Beyond Compare

Unlike traditional Text-to-SQL systems, ChatWithSQL validates each query against strict schema definitions before execution, ensuring:

  • No arbitrary SQL queries.
  • Comprehensive parameter sanitization and validation.
  • A secure pipeline that mitigates malicious input risks.

This security-first approach positions ChatWithSQL as the go-to solution for developers seeking both simplicity and trustworthiness.

🚀 Key Features

1. Intuitive Natural Language Interface

Write prompts like:

“Show me the details of the user with ID 5.”
“Show me all the orders on 25th November 2024”
“What is the Birth Day of user ID 34”
“What are the orders higher than USD 500?”

And let ChatWithSQL handle the rest, converting it into actionable SQL.

2. Robust Schema Validation

Define exactly what queries are permissible:

query_schema = [
    {
        "description": "Fetch user data by ID",
        "name": "get_user_data",
        "sql": "SELECT * FROM users WHERE id = ?",
        "params": {"id": {"type": "int", "default": None}},
    },
]
Enter fullscreen mode Exit fullscreen mode

Only queries within this schema are executed, eliminating risks of misuse.

3. Seamless Integration with Top LLMs

ChatWithSQL supports leading Language Learning Models (LLMs), including:

  • OpenAI: GPT-4, GPT-3.5
  • Gemini
  • LlamaAPI
  • Ollama

Switching between these LLMs is as simple as a configuration change.

4. Dynamic Query Parameters

ChatWithSQL dynamically extracts, validates, and maps query parameters to ensure accurate results every time.

5. Database Agnostic

Whether you’re using PostgreSQL, MySQL, SQLite, or any other SQL database, ChatWithSQL supports it via a universal URI format.

6. Built-In Observability

With detailed logging, ChatWithSQL makes debugging a breeze:

  • Spot malformed prompts.
  • Validate query construction.
  • Track every interaction with your database.

📦 Quick Installation and Setup

Install ChatWithSQL

pip install chatwithsql
Enter fullscreen mode Exit fullscreen mode

Initialize Your Instance

from chat_with_sql import ChatWithSQL
chat_with_sql = ChatWithSQL(
    database_url="your_database_url",
    llm="openai",
    model="gpt-3.5-turbo",
    llm_api_key="your_llm_api_key",
    query_schema=[
        {
            "description": "Fetch user by ID",
            "name": "get_user",
            "sql": "SELECT * FROM users WHERE id = ?",
            "params": {"id": {"type": "int", "default": None}},
        },
    ],
)
Enter fullscreen mode Exit fullscreen mode

Execute a Query

response = chat_with_sql.load_data("Get user details for ID 10.")
print(response)
Enter fullscreen mode Exit fullscreen mode

🔧 Designed for Developers, Built for Scale

Use Cases

  • Analytics Dashboards: Enable non-technical teams to query databases securely.
  • Enterprise Applications: Add intelligent query capabilities to apps while maintaining strict controls.
  • Data Exploration: Empower analysts with natural language access to structured data.

Advanced Query Schema Example

query_schema = [
    {
        "description": "Fetch user details by date of birth",
        "name": "get_user_by_dob",
        "sql": "SELECT * FROM users WHERE dob = ?",
        "params": {"dob": {"type": "date", "default": None}},
    },
    {
        "description": "Count orders by status",
        "name": "count_orders_by_status",
        "sql": "SELECT COUNT(*) FROM orders WHERE status = ?",
        "params": {"status": {"type": "str", "default": "pending"}},
    },
]
Enter fullscreen mode Exit fullscreen mode

🌐 Why Developers Love ChatWithSQL

  • Security: No other Text-to-SQL solution offers such rigorous validation.
  • Flexibility: Use it with your favorite LLMs and databases.
  • Efficiency: Skip the hassle of manually crafting SQL queries.
  • Simplicity: A single library that transforms natural language into database power.

🛣️ Roadmap

Currently, ChatWithSQL supports only SELECT queries, but there are plans to extend support to other SQL operations, including INSERT, UPDATE, and DELETE.

Additionally, this library is the first component of a broader initiative to develop a comprehensive, free, and open-source framework for AI Chat Agents. This framework addresses a significant business need in the nowadays software engineering industry by simplifying complex requirements into a few simple steps.

🤝 Join the ChatWithSQL Revolution

Ready to experience the next level of database interaction? Start using ChatWithSQL today, and empower your applications with intelligent, secure, and efficient query handling.

GitHub Repository: ChatWithSQL
Support Email: hello@bysatha.com

Contribute and Collaborate

We welcome contributions! Submit pull requests or report issues to help shape the future of ChatWithSQL.

With ChatWithSQL, natural language meets SQL in a way that’s secure, reliable, and game-changing. Join the movement, and take your applications to the next level today!

Top comments (0)