Skip to main content

Natural language to SQL query engine powered by LangChain and DuckDB

Project description

NLQE (Natural Language NLQE)

A natural language to SQL query engine powered by LangChain and DuckDB. Ask questions about your data in plain English — works with OpenAI, Anthropic, or any LangChain-compatible model.

Version: v0.1.0 | Python: 3.11+ | License: MIT


Examples

Single query

from nlqe import QueryEngine, QueryEngineConfig

# Reads NLQE_OPENAI_API_KEY from environment or .env
config = QueryEngineConfig()
engine = QueryEngine(config)
engine.load_datasource("transactions.parquet")

response = engine.query("What was total revenue by region last month?")
print(response.answer)
# "North America led with $1.2M, followed by Europe at $890K ..."

print(f"SQL: {response.generated_sql}")
print(f"Rows: {len(response.data)}  Confidence: {response.confidence_score:.0%}")

Multi-turn conversation

conv = engine.start_conversation()

r1 = conv.query("Show me the top 5 products by revenue")
r2 = conv.query("Which of those had the highest return rate?")  # uses context from r1
r3 = conv.query("Compare that to last month")

print(r3.answer)

Switch to LLM Providers

from langchain_anthropic import ChatAnthropic
from nlqe import QueryEngine, QueryEngineConfig
from nlqe.llm import LLMClient

# Anthropic
llm = ChatAnthropic(model="claude-3-5-sonnet-20241022")
engine = QueryEngine(QueryEngineConfig(), custom_llm_client=LLMClient(llm))

# Ollama (Local)
from langchain_ollama import ChatOllama
engine = QueryEngine(QueryEngineConfig(), custom_llm_client=LLMClient(ChatOllama(model="llama3")))

Installation

# Install core package
pip install pynlqe

# Install with development tools
pip install "pynlqe[dev]"

Generate the sample dataset for testing:

python create_sample_data.py

Configuration

Copy .env.example to .env and fill in your credentials:

cp .env.example .env
NLQE_LLM_PROVIDER=openai
NLQE_OPENAI_API_KEY=sk-...
NLQE_LLM_MODEL=gpt-4o

Overview

NLQE translates plain English into SQL executed against structured data (Parquet, CSV) via DuckDB. It uses an iterative debug loop to automatically recover from SQL errors.

Key features:

  • Swappable LLM providers (OpenAI, Anthropic, Ollama, etc.)
  • Multi-turn conversations with context preservation
  • Automatic SQL error recovery (Iterative Debug Loop)
  • Robust evaluation framework with "golden datasets"
  • High test coverage and strict type safety

Architecture Overview

Component Location Purpose
QueryEngine engine.py Main entry point
LLMClient llm/client.py SQL generation, debugging, and synthesis
DuckDBExecutor duckdb/executor.py Safe SQL execution via DuckDB
QueryLoop query/loop.py Orchestration logic
ConversationManager conversation/manager.py Multi-turn history tracking

For more details see ARCHITECTURE.md.


Development

Use the provided Makefile for common development tasks:

make install    # Install dependencies
make lint       # Run ruff and mypy
make format     # Format code with ruff
make test       # Run all tests
make build      # Build distribution packages

Running the Evaluation Suite

Evaluate the engine against standardized test cases:

python -m nlqe.testing.cli evaluate --dataset fixtures/golden_datasets.yaml

Documentation

Document Description
API.md Public API reference and detailed usage
ARCHITECTURE.md Technical design and component data flows
DESIGN.md High-level goals and philosophy
TESTING.md Evaluation strategy and accuracy metrics
FAQ.md Design decisions and common questions

Future Roadmap

  • v0.2.0: Support for PostgreSQL and Snowflake datasources, result caching, and custom synthesizers.
  • v1.0.0: Cloud-native API, fine-tuning support, and advanced production monitoring.

License

This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pynlqe-0.1.0.tar.gz (463.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pynlqe-0.1.0-py3-none-any.whl (40.0 kB view details)

Uploaded Python 3

File details

Details for the file pynlqe-0.1.0.tar.gz.

File metadata

  • Download URL: pynlqe-0.1.0.tar.gz
  • Upload date:
  • Size: 463.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.28 {"installer":{"name":"uv","version":"0.9.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for pynlqe-0.1.0.tar.gz
Algorithm Hash digest
SHA256 6186faec096c708e92f4167a461b81a470db9e98de522c34c7142ffb6d3922a0
MD5 73ada517d5268abe03b2c4b22ebb082e
BLAKE2b-256 edafa2e3ddb41a49c22c2c42dd8f9790fe7e2de1155e10030272ece6297b3ab6

See more details on using hashes here.

File details

Details for the file pynlqe-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: pynlqe-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 40.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.28 {"installer":{"name":"uv","version":"0.9.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for pynlqe-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3c7c4da2c07d4613d37a97e3b4138c8d81548a927e9ac764728c8ba6846e87b9
MD5 e88a350bef909485051c5826b7088706
BLAKE2b-256 950884f032e9f25fd6107f622188ea332c60d2cef4cbaf094f54c7630f95e6c2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page