# solon-ai-nl2sql **Repository Path**: ai-space-org/solon-ai-nl2sql ## Basic Information - **Project Name**: solon-ai-nl2sql - **Description**: 基于 Solon 框架的 NL2SQL(自然语言转SQL)智能框架,Solon版本的SuperSQL。 - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: https://supersql.ai-space.com.cn/ - **GVP Project**: No ## Statistics - **Stars**: 4 - **Forks**: 0 - **Created**: 2026-04-18 - **Last Updated**: 2026-08-02 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README
Solon AI NL2SQL

Solon AI NL2SQL

Intelligent SQL Generation Engine Based on Solon Framework | Natural Language to SQL

Introduction · Key Features · Quick Start · Architecture · API Docs

Solon Java License Build Maven

Gitee GitHub GitCode

--- ## 📖 Project Introduction **Solon AI NL2SQL** is an intelligent SQL generation framework based on the Solon framework, utilizing advanced AI technology and RAG (Retrieval-Augmented Generation) technology to achieve intelligent conversion from natural language to SQL. This project is a Solon framework rewrite of the **SuperSQL** project, retaining the core design concepts and excellent architecture of SuperSQL, while fully leveraging the lightweight and efficient features of the Solon framework. ### 🌟 Project Origins - **Parent Project**: [SuperSQL](https://github.com/guocjsh/SuperSQL) - Developed by GuoChengJie - **Gitee**: [https://gitee.com/guocjsh/super-sql](https://gitee.com/guocjsh/super-sql) - **GitHub**: [https://github.com/guocjsh/SuperSQL](https://github.com/guocjsh/SuperSQL) - **GitCode**: [https://gitcode.com/GuoChengJie/SuperSQL](https://gitcode.com/GuoChengJie/SuperSQL) ### 📌 Key Features - ✅ **Natural Language to SQL** - Supports intelligent conversion from Chinese natural language to SQL - ✅ **RAG Technology** - Improve SQL accuracy through retrieval-augmented generation - ✅ **Vector Database Integration** - Supports Chroma vector database storage and retrieval - ✅ **Multi-Model Support** - Supports OpenAI, Azure OpenAI, Kimi, and other AI models - ✅ **Multi-Database Support** - Supports MySQL, PostgreSQL, Oracle, SQL Server, and other mainstream databases - ✅ **SQL Self-Healing** - Built-in SQL validation and self-healing mechanism - ✅ **Reranking Mechanism** - Supports Rerank to improve retrieval quality - ✅ **Type Safety** - Uses Java generics mechanism to ensure compile-time type checking - ✅ **Easy to Extend** - Uses Strategy Pattern, Factory Pattern, and other design patterns for easy functionality extension - ✅ **Solon Framework Integration** - Perfect integration with the Solon ecosystem, lightweight and efficient --- ## 🚀 Quick Start ### Requirements - JDK 21+ - Maven 3.8+ - Solon 3.10.3+ - ChromaDB 1.0.0+ ### Installation Add dependency to `pom.xml`: ```xml uno.aispace solon-ai-nl2sql-plugin 1.0.0 ``` ### Configuration Configure in `app.yml`: ```yaml # Solon AI Configuration solon: ai: # Chat Model Configuration chat: nl2sql: api-key: your-api-key api-url: https://ark.cn-beijing.volces.com/api/v3/chat/completions model: kimi-k2-5-260127 provider: openai # Embedding Model Configuration embed: azure: api-key: your-azure-api-key api-url: https://your-azure-endpoint/openai/deployments/your-deployment/embeddings?api-version=2023-05-15 model: your-deployment-name provider: openai # Vector Database Configuration repo: chroma: url: http://localhost:8000 ``` ### Code Example ```java @Inject private SqlEngine sqlEngine; public void demo() { // 1. Generate SQL String sql = sqlEngine.generateSql("查询所有年龄大于18岁的用户"); System.out.println(sql); // Output: SELECT * FROM users WHERE age > 18 // 2. Inject DDL (Recommended) TrainingRequest ddlRequest = TrainingRequest.builder() .policy(TrainingPolicy.DDL) .ddl("CREATE TABLE users (id INT, name VARCHAR(50), age INT)") .tableName("users") .build(); sqlEngine.train(ddlRequest); // 3. Train SQL Example TrainingRequest sqlRequest = TrainingRequest.ofSql( "查询所有男性用户", "SELECT * FROM users WHERE gender = 'male'" ); sqlEngine.train(sqlRequest); } ``` ### Start the Project ```bash # Build the project mvn clean install # Start the console cd solon-ai-nl2sql-console mvn solon:run ``` Or use the provided scripts: ```bash # Windows start.bat # Start with official API start-with-official-api.bat ``` --- ## 💡 Usage Examples ### 1. Basic SQL Generation ```java // Simple query String sql = sqlEngine.generateSql("查询所有用户"); // Specify database type String sql = sqlEngine.generateSql("查询所有订单", DatabaseType.POSTGRESQL); ``` ### 2. Advanced Configuration ```java // Using RAG configuration RagOptions options = RagOptions.builder() .topN(5) .limitScore(0.7) .rerank(true) .validateSql(true) .temperature(0.3) .build(); String sql = sqlEngine.withOptions(options) .withDatabaseType(DatabaseType.MYSQL) .generateSql("统计每个部门的员工数量"); ``` ### 3. Training Model ```java // DDL training (Recommended: Inject table schema to improve accuracy) TrainingRequest ddlRequest = TrainingRequest.builder() .policy(TrainingPolicy.DDL) .ddl("CREATE TABLE users (id INT, name VARCHAR(50), age INT)") .tableName("users") .build(); // SQL training TrainingRequest sqlRequest = TrainingRequest.ofSql( "查询所有成年用户", "SELECT * FROM users WHERE age >= 18" ); // Batch training sqlEngine.trainBatch(Arrays.asList(ddlRequest, sqlRequest)); ``` ### 4. DDL Injection (Important) **It's recommended to inject DDL for all core tables at project startup to let AI know exact table and field names: ```java // Inject DDL via REST API POST /api/sql/train/ddl { "ddl": "CREATE TABLE `dtp_hospital` (...)", "tableName": "dtp_hospital", "databaseName": "default" } ``` **Effect Comparison: - ❌ **Without DDL Injection**: AI guesses table name → `SELECT * FROM hospitals WHERE ...` (Wrong) - ✅ **With DDL Injection**: AI knows exact table name → `SELECT * FROM dtp_hospital WHERE ...` (Correct) ### 5. REST API Usage The project provides complete REST API endpoints: ```bash # Generate SQL POST /api/sql/generate?question=查询北京的医院数量&dbType=MYSQL # Advanced SQL generation POST /api/sql/generate/advanced { "question": "统计每个省份的医院数量", "dbType": "MYSQL", "topN": 5, "limitScore": 0.7, "rerank": false, "validateSql": true, "temperature": 0.3 } # Train DDL POST /api/sql/train/ddl { "ddl": "CREATE TABLE ...", "tableName": "dtp_hospital", "databaseName": "default" } # Batch training POST /api/sql/train/batch [{...}, {...}] # Validate SQL GET /api/sql/validate?sql=SELECT * FROM dtp_hospital ``` --- ## 🏗️ Architecture Design ### Module Structure ``` solon-ai-nl2sql ├── solon-ai-nl2sql-core # Core Module │ ├── engine # Engine Interface and Abstract Implementation │ ├── enums # Enum Types │ ├── model # Data Models │ ├── prompt # Prompt Templates │ ├── vector # Vector Store Interface │ ├── validator # SQL Validator │ ├── healer # SQL Self-Healer │ ├── rerank # Reranker │ ├── training # Training Manager │ └── util # Utilities ├── solon-ai-nl2sql-plugin # Solon Plugin Module │ ├── config # Auto Configuration │ ├── engine # Solon AI Engine Implementation │ └── vector # Vector Store Implementation └── solon-ai-nl2sql-console # Console Example ├── controller # REST Controllers └── example # Example Code ``` ### Design Patterns This project uses several excellent design patterns: #### 1. Strategy Pattern For supporting different database types and AI models. ```java public interface SqlEngine { String generateSql(String question, DatabaseType dbType); } ``` #### 2. Builder Pattern For building complex configuration objects. ```java RagOptions options = RagOptions.builder() .topN(5) .limitScore(0.7) .build(); ``` #### 3. Template Method Pattern For defining the core SQL generation process. ```java public abstract class AbstractSqlEngine implements SqlEngine { @Override public String generateSql(String question, DatabaseType dbType, RagOptions options) { // 1. Parameter validation validateParameters(question, options); // 2. RAG retrieval List docs = retrieveRelevantDocuments(question, options); // 3. Build prompt String prompt = buildPrompt(question, dbType, docs, options); // 4. Call AI model String response = callAiModel(prompt, options); // 5. Extract SQL return extractSql(response); } } ``` #### 4. Factory Pattern For creating different types of engines and clients. #### 5. Adapter Pattern For adapting different AI models and vector databases. ### Technical Architecture Diagram ``` ┌─────────────────────────────────────────────────────────┐ │ Client Layer ├─────────────────────────────────────────────────────────┤ │ │ │ ┌────────────────────────────────────────────────────┐ │ │ │ SqlEngine (SQL Engine) │ │ │ │ ┌──────────────────────────────────────┐ │ │ │ │ │ AbstractSqlEngine (Template Method) │ │ │ │ │ └──────────────────────────────────────┘ │ │ │ │ ↓ │ │ │ │ ┌──────────────────────────────────────┐ │ │ │ │ │ SolonSqlEngine (Solon Implementation) │ │ │ │ │ └──────────────────────────────────────┘ │ │ │ └────────────────────────────────────────────────────┘ │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ │ │ │ VectorStore │◄─┤ Reranker │◄─┤Healer│ │ │ └──────────────┘ └──────────────┘ └──────────┘ │ │ │ │ ┌──────────────────────────────────────────────┐ │ │ │ Solon AI (ChatModel + EmbeddingModel) │ │ │ └──────────────────────────────────────────────┘ │ │ │ │ ┌──────────────────────────────────────────────┐ │ │ │ Chroma Repository (Vector Database) │ │ │ └──────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────┘ ``` --- ## 🎨 Tech Stack | Technology | Version | Description | |------------|---------|-------------| | Solon | 3.10.3 | Lightweight Java Framework | | Solon AI | 3.10.3 | Solon AI Ecosystem | | Java | 21 | Programming Language | | Hutool | 5.8.35 | Java Tool Library | | FastJSON2 | 2.0.51 | JSON Processing | | Lombok | 1.18.32 | Code Simplification | | MyBatis Plus | 3.5.8 | ORM Framework | | MySQL | 8.0.33 | Database | | H2 | 2.2.224 | In-Memory Database | | ChromaDB | 1.0.0+ | Vector Database | --- ## 📝 API Documentation ### SqlEngine API ```java public interface SqlEngine { // Basic SQL Generation String generateSql(String question); String generateSql(String question, DatabaseType dbType); // Chained Calls SqlEngine withOptions(RagOptions options); SqlEngine withDatabaseType(DatabaseType dbType); // Training void train(TrainingRequest request); void trainBatch(List requests); // Validation boolean validateSql(String sql); } ``` ### TrainingRequest API ```java // DDL Training TrainingRequest.ofDdl(String ddl); // SQL Training TrainingRequest.ofSql(String question, String sql); // Document Training TrainingRequest.ofDocument(String document); // Full Builder TrainingRequest.builder() .policy(TrainingPolicy policy) .ddl(String ddl) .sql(String sql) .question(String question) .document(String document) .tableName(String tableName) .databaseName(String databaseName) .metadata(Map metadata) .build(); ``` ### RagOptions API ```java RagOptions.builder() .topN(int topN) // Number of results .limitScore(double limitScore) // Minimum similarity threshold .rerank(boolean rerank) // Whether to rerank .validateSql(boolean validateSql) // Whether to validate SQL .temperature(double temperature) // Temperature parameter .build(); ``` --- ## 🤝 Contributing We welcome community contributions! ### How to Contribute 1. Fork this repository 2. Create a feature branch (`git checkout -b feature/AmazingFeature`) 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request ### Code Standards - Follow Java coding conventions - Add necessary comments and documentation - Write unit tests - Keep code clean and concise ### Development Workflow ```bash # 1. Clone the project git clone https://gitee.com/ai-space-org/solon-ai-nl2sql.git # 2. Build the project mvn clean install # 3. Run tests mvn test # 4. Start the console cd solon-ai-nl2sql-console mvn solon:run ``` --- ## 📄 License This project is licensed under Apache 2.0 License. See [LICENSE](LICENSE) for details. --- ## 👨‍💻 Author **GuoChengJie** - Email: chengjie.x.guo@gsk.com - Organization: AI Space - GitHub: [@GuoChengJie](https://github.com/guocjsh) - Gitee: [@guocjsh](https://gitee.com/guocjsh) --- ## 🙏 Acknowledgments Thanks to the following projects for inspiration: - [SuperSQL](https://github.com/guocjsh/SuperSQL) - Original Project - [Solon](https://solon.noear.org/) - Excellent Java Framework - [Spring AI](https://spring.io/projects/spring-ai) - AI Integration Reference --- ## 📚 Related Documents - [Quick Start Guide](quick-start-guide.md) - [Azure OpenAI Configuration Guide](AZURE_OPENAI_CONFIG.md) - [Official API Migration Guide](OFFICIAL_API_MIGRATION.md) - [Configuration Complete Report](CONFIGURATION_COMPLETE.md) - [Test Report](TEST_REPORT.md) ---

Let AI Light Up Your Life | AI Space © 2026

If this project is helpful to you, please give us a ⭐️ Star!

中文版