Building an LLM-Powered Data Query Agent: From Prototype to Open Source Practice

    This article walks through the design and open source evolution of a lightweight LLM-powered data query agent that converts natural language into executable SQL. It covers the core architecture—dynamic schema injection, safe SQL sandbox execution, and a feedback-driven self-correction loop—along with adaptation strategies for desktop, web, and terminal interfaces, and lessons learned from maintaining the project as an open source effort.

    Introduction: The Rise of Natural Language-Driven Data Querying

    In enterprise data applications, non-technical users often face a steep learning curve for data analysis. Traditional analytics workflows require business users to master SQL syntax or rely on data engineers to extract data, leading to high communication costs and long response cycles. As large language model (LLM) capabilities have advanced rapidly, Text-to-SQL technology has matured, making it possible to query databases directly through natural language.

    Recently, to explore this technical direction and contribute to an open source community initiative, I built a lightweight data interaction agent plugin. Its core goal was simple: enable an LLM to autonomously connect to a database, understand table structures, and write and execute SQL statements. Unexpectedly, the project quickly gained the attention of over a hundred developers. Seeing real installation numbers and community feedback, I decided to maintain it as a long-term open source project. This article reviews the agent’s technical architecture design and its open source evolution in detail.

    Core Architecture Design: Enabling Safe Dialogue Between LLMs and Databases

    Building a reliable data query agent is far more than simply wiring an LLM to a database—it requires a rigorous engineering architecture to ensure query accuracy, security, and stability. The core processing pipeline consists of the following key modules:

    1. Database Connection and Dynamic Schema Injection

    The prerequisite for an LLM to generate accurate SQL is a thorough understanding of the database’s table structures. After establishing a connection, the agent dynamically extracts metadata from the target database, including table names, column names, field types, primary/foreign key relationships, and comments.

    To help the LLM digest this information efficiently, the plugin adopts a hierarchical prompt construction strategy. First, general SQL generation guidelines (such as requiring standard SQL syntax and avoiding full table scans) are injected into the system prompt. Second, based on the intent of the user’s question, the DDL (Data Definition Language) structures of relevant tables are dynamically selected and injected into the context in a compact format, avoiding token waste and reducing hallucination risk.

    2. SQL Generation and Sandbox Execution

    When a user inputs a natural language question, the agent sends it to the LLM along with the structured prompt. The SQL statement returned by the LLM is not executed directly—it must pass through a strict validation mechanism.

    At the execution layer, security is the top priority. The agent enforces read-only permissions for the execution session and adds query row limits at the underlying level (for example, limiting results to the first 1,000 rows by default) to prevent database crashes caused by unbounded full-table joins. Additionally, basic anti-injection validation via regular expressions intercepts dangerous operations such as DROP, TRUNCATE, and DELETE.

    Below is an illustrative example of the safe execution logic:

    1. def execute_sql_safely(db_conn, sql_query, max_rows=1000):
    2. # Intercept dangerous operations
    3. forbidden_keywords = ["DROP", "TRUNCATE", "DELETE", "ALTER", "INSERT", "UPDATE"]
    4. if any(keyword in sql_query.upper() for keyword in forbidden_keywords):
    5. raise ValueError("Illegal write operation detected; execution blocked")
    6. # Limit the number of returned rows
    7. safe_sql = f"SELECT * FROM ({sql_query}) AS subquery LIMIT {max_rows}"
    8. cursor = db_conn.cursor()
    9. try:
    10. cursor.execute(safe_sql)
    11. results = cursor.fetchall()
    12. return results
    13. except Exception as e:
    14. # Catch the exception and hand it to the LLM for self-correction
    15. return {"error": str(e)}

    3. Result Feedback and the Self-Correction Loop

    Since LLMs may generate syntax that doesn’t conform to a specific database dialect, execution errors can occur. The agent implements an “execute-feedback-retry” closed loop. When SQL execution fails, the agent does not surface the error directly to the user. Instead, it appends the database’s error message to the prompt and asks the LLM to fix the SQL based on the error details and re-execute it. This feedback-driven refinement mechanism significantly improves the success rate of complex queries.

    Compatibility and Adaptation Across Multiple Interaction Frontends

    Developers vary greatly in their workflows and usage habits. To make the plugin truly integrate into real-world workflows, multi-frontend compatibility was considered from the very beginning. To achieve this, we fully decoupled the core agent orchestration logic from the UI presentation layer, abstracted an independent core service layer, and adapted it to different interaction forms.

    1. Desktop Adaptation

    For users accustomed to local tools, the desktop version provides an intuitive graphical interface. Users can configure multiple data source connections and view the results of LLM-generated SQL directly as visual charts. The desktop version’s advantage lies in leveraging local computing power for partial data preprocessing, with all data flows kept entirely local—meeting the needs of scenarios with strict data privacy requirements.

    2. Web Adaptation

    The web version is better suited for team collaboration and cloud deployment. By combining Baidu AI Cloud’s container platform with a microservices architecture, the web-based agent can be deployed as a microservice node within an internal data platform. Users can query data simply through a browser, and query results can be easily shared and exported. The web version also supports centralized access control and can integrate with enterprise SSO (Single Sign-On) systems.

    3. TUI Adaptation

    For heavy command-line users, the TUI (Terminal User Interface) form has irreplaceable appeal. The TUI version consumes minimal resources and starts instantly, allowing developers to quickly validate data logic with natural language directly in the terminal between coding sessions. By integrating mainstream terminal UI libraries, the TUI version also supports highlighted table display and multi-line SQL rendering, greatly improving the experience for developer-oriented users.

    Evolution from Personal Prototype to Open Source Community

    The vitality of an open source project lies in continuous maintenance and community feedback. Although the project was initially just a personal “side project,” the response from the developer community far exceeded expectations. Faced with hundreds of stars, real installation numbers, and numerous issues, the project’s maintenance strategy had to shift from “personal toy” to “engineered project.”

    1. Keeping Pace with Underlying Framework Iterations

    The agent plugin depends on an underlying LLM application framework. As LLM reasoning capabilities and framework specifications evolve rapidly, breaking changes occur from time to time. To avoid becoming a source of technical debt, the project established an automated testing pipeline: whenever the underlying framework releases a new version, core test cases run automatically, ensuring the plugin adapts to the latest version promptly and stays technically current.

    2. Embracing Community Feedback with Standardized Processes

    Many developers, in real-world usage, connected the plugin to a wide variety of heterogeneous databases—different versions of MySQL, PostgreSQL, and even time-series databases. These real-world scenarios exposed numerous edge cases in the schema injection logic.

    In response to community PRs (Pull Requests) and issues, I established a standardized triage mechanism: core bugs are reproduced locally with priority and hotfix releases are published; new feature requests are added to the version roadmap for evaluation; and the CONTRIBUTING.md documentation was improved to encourage more developers to participate in collaborative development, forming a healthy technical ecosystem loop.

    Conclusion

    Building an LLM-based data query agent hinges on connecting three critical stages: natural language intent understanding, schema context construction, and a safe SQL execution loop. Through proper architectural abstraction, compatibility across multiple interaction frontends can greatly broaden the tool’s application scenarios. Open source, meanwhile, is not just about publishing code—it is a collaborative model of co-evolution with developers. Going forward, the agent will continue to explore query performance optimization and complex business logic understanding, providing sustained technical support for lowering the barrier to enterprise data consumption.