{"id":25656597,"url":"https://github.com/nitin27may/sqlqueryopenai","last_synced_at":"2026-04-17T10:31:06.184Z","repository":{"id":270623885,"uuid":"910951463","full_name":"nitin27may/SQLQueryOpenAI","owner":"nitin27may","description":"SQLQueryAI leverages .NET 9, Microsoft SQL Server, and OpenAI's GPT-4o model to enable natural language-driven SQL query generation and execution. It simplifies database interaction for non-technical users while offering robust schema-based query accuracy.","archived":false,"fork":false,"pushed_at":"2025-01-22T16:12:17.000Z","size":29,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-23T22:43:30.181Z","etag":null,"topics":["dotnet9","mssql","net9","openai","openai-api","sqlserver"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nitin27may.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-01-01T22:08:45.000Z","updated_at":"2025-01-22T16:12:20.000Z","dependencies_parsed_at":"2025-01-01T23:22:24.773Z","dependency_job_id":"2c509d06-a739-489e-8952-aa75bbcccc43","html_url":"https://github.com/nitin27may/SQLQueryOpenAI","commit_stats":null,"previous_names":["nitin27may/aiquerybuilder","nitin27may/sqlqueryopenai"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nitin27may%2FSQLQueryOpenAI","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nitin27may%2FSQLQueryOpenAI/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nitin27may%2FSQLQueryOpenAI/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nitin27may%2FSQLQueryOpenAI/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nitin27may","download_url":"https://codeload.github.com/nitin27may/SQLQueryOpenAI/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240390702,"owners_count":19793782,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dotnet9","mssql","net9","openai","openai-api","sqlserver"],"created_at":"2025-02-23T22:43:33.025Z","updated_at":"2026-04-17T10:31:06.175Z","avatar_url":"https://github.com/nitin27may.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# SQL Query AI Builder\n\n![GitHub license](https://img.shields.io/github/license/mashape/apistatus.svg)\n\n## TL;DR\n\nSQL Query AI Builder is a multi-provider AI platform that transforms natural language into SQL queries. It supports multiple LLM providers (OpenAI, Azure OpenAI, Anthropic's Claude, and Google's Gemini), allowing you to easily switch between them using configuration settings. The application includes a .NET 10 backend API that generates and executes SQL against a demo database, all containerized with Docker for easy setup.\n\nKey features include:\n- Dynamic provider selection using environment variables or appsettings.json\n- Consistent prompt formatting across all AI providers\n- Robust SQL Server container configuration with separated database initialization\n- Factory pattern for AI service implementation\n- Schema-aware SQL generation with direct query execution\n\n## Features\n\n- **Multi-Provider LLM Integration:** Supports OpenAI, Azure OpenAI, Claude, and Gemini models\n- **Natural Language SQL Query Generation:** Converts user prompts into accurate SQL queries\n- **SQL Query Execution:** Executes generated SQL queries against a SQL Server database\n- **Schema-Aware Generation:** Uses database schema and relationships for context-aware query creation\n- **Docker Support:** Easy deployment with Docker and Docker Compose\n- **Factory Pattern Architecture:** Dynamically selects the appropriate AI service based on configuration\n\n## Architecture\n\nThe application uses a service factory pattern to dynamically select the appropriate AI service based on configuration settings:\n\n```mermaid\nflowchart LR\n    subgraph Frontend\n        UI[Web Interface]\n    end\n    \n    subgraph \"API Layer\"\n        API[ASP.NET Core API]\n        SqlController[SqlController]\n        SqlAiServiceFactory[SqlAiServiceFactory]\n    end\n    \n    subgraph \"AI Services\"\n        ISqlAiService[ISqlAiService]\n        OpenAiService[OpenAiService]\n        AzureOpenAI[AzureOpenAI Service]\n        ClaudeService[Claude Service]\n        GeminiService[Gemini Service]\n    end\n    \n    subgraph \"Database Layer\"\n        DBService[Database Service]\n        MSSQL[(SQL Server)]\n        DBSchema[Schema Information]\n    end\n    \n    UI --\u003e SqlController\n    SqlController --\u003e SqlAiServiceFactory\n    SqlAiServiceFactory --\u003e ISqlAiService\n    ISqlAiService --\u003e OpenAiService \u0026 AzureOpenAI \u0026 ClaudeService \u0026 GeminiService\n    \n    SqlController --\u003e DBService\n    DBService --\u003e MSSQL\n    MSSQL --\u003e DBSchema\n    DBSchema --\u003e ISqlAiService\n    \n    OpenAiService --\u003e GeneratedSQL[SQL Query]\n    AzureOpenAI --\u003e GeneratedSQL\n    ClaudeService --\u003e GeneratedSQL\n    GeminiService --\u003e GeneratedSQL\n    GeneratedSQL --\u003e DBService\n    \n    classDef apiBox fill:#f9f,stroke:#333,stroke-width:1px;\n    classDef aiBox fill:#bbf,stroke:#333,stroke-width:1px;\n    classDef dbBox fill:#bfb,stroke:#333,stroke-width:1px;\n    classDef frontend fill:#ff9,stroke:#333,stroke-width:1px;\n    \n    class API,SqlController,SqlAiServiceFactory apiBox;\n    class ISqlAiService,OpenAiService,AzureOpenAI,ClaudeService,GeminiService,GeneratedSQL aiBox;\n    class DBService,MSSQL,DBSchema dbBox;\n    class UI frontend;\n```\n\nThe architecture follows a factory pattern that allows dynamic selection of AI services:\n\n## Prerequisites\n\n- **Without Docker:**\n  - .NET 10.0 SDK or later\n  - Microsoft SQL Server\n  - API keys for your chosen LLM provider(s)\n\n- **With Docker:**\n  - Docker Desktop\n\n## Setup\n\n### 1. Clone the Repository\n\n```sh\ngit clone https://github.com/yourusername/AIQueryBuilder.git\ncd AIQueryBuilder\n```\n\n### 2. Configure Environment Variables\n\nCreate a `.env` file in the root directory based on the provided `.env-example`:\n\n```sh\ncp .env-example .env\n```\n\nEdit the `.env` file to configure your environment:\n\n```ini\n# Environment\nENVIRONMENT=Development\n\n# SQL Server Configuration\nSQL_SERVER=mssql\nSQL_DATABASE=DemoDB\nSQL_USER=sa\nSQL_PASSWORD=YourStrong@Passw0rd\n\n# AI Provider Configuration - Choose one: OpenAI, AzureOpenAI, Claude, Gemini\nAI_PROVIDER_TYPE=OpenAI\n\n# Provider-specific keys (only need to fill in the one you're using)\n# OpenAI Configuration\nOPENAI_API_KEY=your-openai-api-key-here\nOPENAI_MODEL=gpt-4o\n\n# Azure OpenAI Configuration\nAZURE_OPENAI_API_KEY=your-azure-openai-api-key-here\nAZURE_OPENAI_ENDPOINT=your-azure-openai-endpoint-here\nAZURE_OPENAI_DEPLOYMENT_NAME=your-azure-deployment-name-here\nAZURE_OPENAI_MODEL=gpt-4\n\n# Claude Configuration\nCLAUDE_API_KEY=your-claude-api-key-here\nCLAUDE_MODEL=claude-3-sonnet-20240229\n\n# Gemini Configuration\nGEMINI_API_KEY=your-gemini-api-key-here\nGEMINI_MODEL=gemini-pro\n```\n\n### 3. Running with Docker\n\n1. **Build and start the containers:**\n\n```sh\ndocker-compose up --build\n```\n\n2. **Access the application:**\n   - The API will be available at `http://localhost:8000`\n   - The database will be initialized automatically via the separate db-init service\n\n3. **In case of database initialization issues:**\n   If you encounter issues with database initialization (which can happen with SQL Server containers), you can manually seed the database:\n\n```sh\ndocker exec -it sqlserver_express /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P YourStrong@Passw0rd -d master -i /scripts/seed-data.sql\n```\n\nReplace `YourStrong@Passw0rd` with the password you set in your `.env` file.\n\n### 4. Running Without Docker\n\n1. **Set up your SQL Server:**\n   - Create a database named `DemoDB`\n   - Run the `scripts/seed-data.sql` script to create tables and seed data\n\n2. **Configure application settings:**\n   - Update `api/appsettings.Development.json` with your database connection string and LLM provider details\n\n3. **Build and run the application:**\n\n```sh\ncd api\ndotnet build\ndotnet run\n```\n\n4. The API will be available at `http://localhost:5275`\n\n## Using the API\n\n### 1. Generate SQL Query\n\nSend a POST request to generate SQL from natural language:\n\n```http\nPOST http://localhost:8000/api/sql/generate\nContent-Type: application/json\n\n\"List all orders with order details, customer name placed in December 2023, including order IDs and total amounts.\"\n```\n\n![Generate SQL Query](docs/screenshots/generate_query.png)\n\n### 2. Execute SQL Query\n\nSend a POST request to execute a SQL query:\n\n\nYou can use `SQLQueryAI.http` file in VS Code or Visual Studio for calling rest apis.\n\n```http\nPOST http://localhost:8000/api/sql/execute\nContent-Type: application/json\n\n\"SELECT o.OrderID, c.CustomerName, o.OrderDate, o.TotalAmount, od.ProductName, od.Quantity, od.Price \nFROM [Order] o\nJOIN OrderDetails od ON o.OrderID = od.OrderID\nJOIN Customer c ON o.CustomerID = c.CustomerID\nWHERE o.OrderDate \u003e= '2023-12-01' AND o.OrderDate \u003c '2024-01-01';\"\n```\n\n### 3. Generate and Execute in One Step\n\nSend a POST request to generate SQL from natural language and execute it immediately:\n\n```http\nPOST http://localhost:8000/api/sql/generate-and-execute\nContent-Type: application/json\n\n\"List all orders with order details, customer name placed in December 2023, including order IDs and total amounts.\"\n```\n\n![Generate and Execute](docs/screenshots/generate_and_execute.png)\n\n## Switching AI Providers\n\nYou can switch between AI providers by changing the `AI_PROVIDER_TYPE` in your `.env` file or by setting the corresponding environment variable. Available options:\n\n- `OpenAI` - Uses OpenAI's models (default: gpt-4o)\n- `AzureOpenAI` - Uses Azure OpenAI deployment\n- `Claude` - Uses Anthropic's Claude model\n- `Gemini` - Uses Google's Gemini model\n\nMake sure to provide the corresponding API keys and configuration for your chosen provider.\n\n### Provider Configuration Details\n\n#### OpenAI\n```ini\nAI_PROVIDER_TYPE=OpenAI\nOPENAI_API_KEY=your-openai-api-key-here\nOPENAI_MODEL=gpt-4o  # You can also use: gpt-4, gpt-3.5-turbo, etc.\n```\n\n#### Azure OpenAI\n```ini\nAI_PROVIDER_TYPE=AzureOpenAI\nAZURE_OPENAI_API_KEY=your-azure-openai-api-key-here\nAZURE_OPENAI_ENDPOINT=https://your-resource-name.openai.azure.com/\nAZURE_OPENAI_DEPLOYMENT_NAME=your-deployment-name-here\nAZURE_OPENAI_MODEL=gpt-4  # The underlying model used in your Azure deployment\n```\n\n#### Claude (Anthropic)\n```ini\nAI_PROVIDER_TYPE=Claude\nCLAUDE_API_KEY=your-claude-api-key-here\nCLAUDE_MODEL=claude-3-sonnet-20240229  # You can also use: claude-3-opus-20240229, claude-3-haiku-20240307\n```\n\n#### Gemini (Google)\n```ini\nAI_PROVIDER_TYPE=Gemini\nGEMINI_API_KEY=your-gemini-api-key-here\nGEMINI_MODEL=gemini-pro  # You can also use: gemini-pro-vision, gemini-ultra (if available)\n```\n\n## Troubleshooting\n\n### Common Issues\n\n1. **SQL Server Container Not Starting:** \n   - Ensure you've set a strong password in your `.env` file meeting SQL Server requirements\n   - Check container logs: `docker logs sqlserver_express`\n   - Make sure port 1433 is not already in use on your host machine\n   - Try increasing the healthcheck timeout in docker-compose.yml if initialization is slow\n\n2. **Database Seeding Issues:**\n   - If the db-init service fails, check the logs: `docker logs aiquerybuilder-db-init-1`\n   - Wait until SQL Server is fully initialized before manually running the seed script\n   - Verify your SQL credentials in the `.env` file match what's used in docker-compose.yml\n\n3. **API Connection Issues:**\n   - Ensure environment variables are correctly set in your `.env` file\n   - Check that the SQL Server is healthy: `docker ps` should show it as running\n   - Verify the connection string in the API's logs: `docker logs aiquerybuilder-api-1`\n   - Make sure your firewall allows connections to the SQL Server container\n\n4. **AI Provider Issues:**\n   - Verify you've set the correct API keys for your chosen provider in the `.env` file\n   - Check that the AI_PROVIDER_TYPE variable matches the provider whose API key you've configured\n   - Review the API logs for error messages from the AI provider\n\n### Database Connection\n\nThe connection string is set via environment variables. If you're not using Docker, make sure to update the connection string in `appsettings.Development.json`. The default connection string format is:\n\n```\nServer=mssql;Database=DemoDB;User ID=sa;Password=YourStrong@Passw0rd;Trusted_Connection=False;Encrypt=False;\n```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnitin27may%2Fsqlqueryopenai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnitin27may%2Fsqlqueryopenai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnitin27may%2Fsqlqueryopenai/lists"}