Natural language to SQL query builder powered by DSPy (PostgreSQL and SQL Server)
Project description
oiko-query-builder
Natural language to PostgreSQL SQL query builder powered by DSPy.
Write questions in plain language, get optimized SQL queries back.
Installation
# Core (SQL generation only)
pip install oiko-query-builder
# With sync PostgreSQL support (psycopg)
pip install oiko-query-builder[sync]
# With async PostgreSQL support (asyncpg)
pip install oiko-query-builder[async]
# Everything
pip install oiko-query-builder[all]
Quick Start
from oiko_query_builder import QueryAgent
agent = QueryAgent(
lm="openai/gpt-4o-mini",
api_key="sk-...",
schema="""
Table: users
- id: integer, PK
- name: varchar
- email: varchar
- active: boolean
- created_at: timestamp
Table: orders
- id: integer, PK
- user_id: integer, FK -> users.id
- total: numeric
- status: varchar
- created_at: timestamp
""",
)
# Generate SQL
result = agent.query("show me the 10 most recent active users")
print(result.sql)
# SELECT id, name, email, created_at
# FROM users
# WHERE active = true
# ORDER BY created_at DESC LIMIT 10
With Database Execution
agent = QueryAgent(
lm="openai/gpt-4o-mini",
api_key="sk-...",
dsn="postgresql://user:pass@localhost:5432/mydb",
)
# Auto-discover schema
agent.introspect()
# Generate + execute
result = agent.execute("how many orders were placed this month?")
print(result.rows) # [{"count": 142}]
print(result.sql) # SELECT COUNT(*) AS count FROM orders WHERE ...
Async Support
import asyncio
from oiko_query_builder import QueryAgent
async def main():
agent = QueryAgent(
lm="openai/gpt-4o-mini",
api_key="sk-...",
dsn="postgresql://user:pass@localhost:5432/mydb",
)
await agent.aintrospect()
result = await agent.aexecute("top 5 customers by total spending")
print(result.rows)
asyncio.run(main())
Multi-turn Conversations
agent = QueryAgent(lm="openai/gpt-4o-mini", api_key="sk-...", schema="...")
# First question
result = agent.query("show me user John Smith")
print(result.sql) # SELECT ... WHERE name = 'John Smith'
# Follow-up (agent remembers context)
result = agent.query("show their orders")
print(result.sql) # SELECT ... FROM orders WHERE user_id = ...
# Set entities manually
agent.set_entity("User", "John Smith (id=7)")
result = agent.query("show their recent orders")
Safety Levels
from oiko_query_builder import QueryAgent, SafetyLevel
# STRICT (default) - SELECT only
agent = QueryAgent(lm="...", api_key="...", safety_level=SafetyLevel.STRICT)
# MODERATE - SELECT, INSERT, UPDATE allowed
agent = QueryAgent(lm="...", api_key="...", safety_level="moderate")
# PERMISSIVE - all operations except DROP DATABASE
agent = QueryAgent(lm="...", api_key="...", safety_level="permissive")
Custom Examples
import dspy
from oiko_query_builder import QueryAgent
agent = QueryAgent(lm="openai/gpt-4o-mini", api_key="sk-...", schema="...")
# Add domain-specific examples for better generation
agent.add_examples([
dspy.Example(
question="Show VIP customers",
db_schema="Table: customers\n - id: integer\n - tier: varchar",
context=None,
memory_context=None,
sql_query="SELECT id, name FROM customers WHERE tier = 'vip'",
has_limit=False,
limit_value=None,
).with_inputs("question", "db_schema", "context", "memory_context"),
])
DSPy Optimization
from oiko_query_builder import QueryAgent, create_training_example
agent = QueryAgent(lm="openai/gpt-4o-mini", api_key="sk-...", schema="...")
# Create training data
train = [
create_training_example(
question="active users count",
schema="Table: users\n - id: integer\n - active: boolean",
expected_sql="SELECT COUNT(*) FROM users WHERE active = true",
),
# ... more examples
]
# Optimize prompts automatically
agent.optimize(train_examples=train)
Supported LLMs
Any LLM supported by DSPy works out of the box:
# OpenAI
agent = QueryAgent(lm="openai/gpt-4o-mini", api_key="sk-...")
# Anthropic
agent = QueryAgent(lm="anthropic/claude-sonnet-4-20250514", api_key="sk-ant-...")
# Ollama (local)
agent = QueryAgent(lm="ollama_chat/llama3.2", api_key="")
# Any other DSPy-supported provider
agent = QueryAgent(lm="together_ai/meta-llama/...", api_key="...")
API Reference
QueryAgent
| Method | Description |
|---|---|
query(question) |
Generate SQL from natural language |
execute(question) |
Generate + execute SQL |
aquery(question) |
Async SQL generation |
aexecute(question) |
Async generate + execute |
introspect() |
Auto-discover database schema |
set_schema(schema) |
Set schema manually |
add_examples(examples) |
Add few-shot examples |
optimize(train) |
Optimize with DSPy |
explain(sql) |
Explain SQL in natural language |
set_entity(key, value) |
Set entity in memory |
clear_memory() |
Clear conversation history |
GenerationResult
| Field | Type | Description |
|---|---|---|
sql |
str |
Generated SQL query |
success |
bool |
Whether generation succeeded |
has_limit |
bool |
Whether SQL has LIMIT |
limit_value |
int? |
LIMIT value if present |
explanation |
str? |
Chain-of-thought reasoning |
retries_used |
int |
Number of retries used |
QueryResult
| Field | Type | Description |
|---|---|---|
sql |
str |
Executed SQL query |
success |
bool |
Whether execution succeeded |
rows |
list[dict]? |
Query result rows |
row_count |
int? |
Number of rows |
execution_time_ms |
float? |
Execution time |
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
oiko_query_builder-0.2.0.tar.gz
(21.7 kB
view details)
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file oiko_query_builder-0.2.0.tar.gz.
File metadata
- Download URL: oiko_query_builder-0.2.0.tar.gz
- Upload date:
- Size: 21.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
73740b56686ebb1b6d5aa3165dfc40a922ad1b1948c29cbac368fd5fbd206f10
|
|
| MD5 |
ed9392f35e9c99153e3fd2af24000c17
|
|
| BLAKE2b-256 |
bf0d23204895210232e08a20e93d8722c1ebbf1de773f80ed5cb49d54da6ac6d
|
File details
Details for the file oiko_query_builder-0.2.0-py3-none-any.whl.
File metadata
- Download URL: oiko_query_builder-0.2.0-py3-none-any.whl
- Upload date:
- Size: 27.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d2499a641c76ed5defc098e4efa3022ee01e17655ecfb8db260502593e04b799
|
|
| MD5 |
554a5d19b76b623a9938a5e82d34b783
|
|
| BLAKE2b-256 |
01f9eeb082aa44c4703001025fafe800ae1d88f68e7121a5bdb2abdb857e22e6
|