Implementation:Guardrails ai Guardrails Text2Sql
| Knowledge Sources | |
|---|---|
| Domains | Applications, NLP, SQL |
| Last Updated | 2026-02-14 00:00 GMT |
Overview
The Text2Sql class provides an end-to-end application for converting natural language queries into validated SQL statements using LLMs, vector-based example retrieval, and Guardrails validation.
Description
This module implements a full natural language to SQL pipeline. The Text2Sql class combines several components:
- SQL Driver - Connects to a database and extracts schema information for prompt context.
- Guard - Validates the generated SQL against a Rail specification to ensure correctness.
- Document Store - Stores example question-query pairs and retrieves semantically similar examples to include in the prompt via vector similarity search.
- Embedding & VectorDB - Encodes examples into embeddings and stores them in a vector database (default: FAISS) for efficient retrieval.
The class also includes a reask prompt template (REASK_PROMPT) used when the initial LLM output fails validation, and an example_formatter function that formats retrieved examples for inclusion in the prompt.
Usage
Use Text2Sql when you need to build a natural language to SQL interface with built-in validation. The class is callable -- pass a natural language string and it returns a validated SQL query string. It is suitable for use cases where user-facing queries need to be translated to SQL with guardrails ensuring correctness.
Code Reference
Source Location
- Repository: Guardrails
- File:
guardrails/applications/text2sql.py - Lines: 1-219
Signature
def example_formatter(
input: str, output: str, output_schema: Optional[Callable] = None
) -> str:
class Text2Sql:
def __init__(
self,
conn_str: str,
schema_file: Optional[str] = None,
examples: Optional[Dict] = None,
embedding: Type[EmbeddingBase] = OpenAIEmbedding,
vector_db: Type[VectorDBBase] = Faiss,
document_store: Type[DocumentStoreBase] = EphemeralDocumentStore,
rail_spec: Optional[str] = None,
rail_params: Optional[Dict] = None,
example_formatter: Callable = example_formatter,
reask_messages: list[Dict[str, str]] = [...],
llm_api: Optional[Callable] = None,
llm_api_kwargs: Optional[Dict] = None,
num_relevant_examples: int = 2,
):
def __call__(self, text: str) -> Optional[str]:
Import
from guardrails.applications.text2sql import Text2Sql, example_formatter
I/O Contract
__init__ Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
conn_str |
str |
required | Database connection string. |
schema_file |
Optional[str] |
None |
Path to the database schema file. |
examples |
Optional[Dict] |
None |
Example question-query pairs for the document store. |
embedding |
Type[EmbeddingBase] |
OpenAIEmbedding |
Embedding class for encoding examples. |
vector_db |
Type[VectorDBBase] |
Faiss |
Vector database class for similarity search. |
document_store |
Type[DocumentStoreBase] |
EphemeralDocumentStore |
Document store class for example storage. |
rail_spec |
Optional[str] |
None |
Path to a custom Rail specification file. Defaults to built-in text2sql.rail.
|
rail_params |
Optional[Dict] |
None |
Template parameters for the Rail specification. |
example_formatter |
Callable |
example_formatter |
Function to format examples for prompt inclusion. |
reask_messages |
list[Dict[str, str]] |
[REASK_PROMPT] |
Messages used when reasking the LLM after validation failure. |
llm_api |
Optional[Callable] |
None |
LLM API callable. Defaults to openai.completions.create.
|
llm_api_kwargs |
Optional[Dict] |
None |
Additional keyword arguments for the LLM API. Defaults to {"max_tokens": 512}.
|
num_relevant_examples |
int |
2 |
Number of similar examples to retrieve from the document store. |
__call__
| Parameter | Type | Description |
|---|---|---|
text |
str |
Natural language query to convert to SQL. |
| Return Type | Description |
|---|---|
Optional[str] |
The validated SQL query string, or None if generation or validation fails.
|
Usage Examples
from guardrails.applications.text2sql import Text2Sql
# Basic usage with a SQLite database
text2sql = Text2Sql(
conn_str="sqlite:///my_database.db",
schema_file="schema.sql",
)
# Convert natural language to SQL
sql = text2sql("Show me all users who signed up last month")
# sql: "SELECT * FROM users WHERE signup_date >= '2026-01-01' AND ..."
# With examples for better accuracy
examples = [
{"question": "Get all active users", "query": "SELECT * FROM users WHERE active = 1"},
{"question": "Count orders by status", "query": "SELECT status, COUNT(*) FROM orders GROUP BY status"},
]
text2sql = Text2Sql(
conn_str="sqlite:///my_database.db",
examples=examples,
num_relevant_examples=2,
)
sql = text2sql("Find all inactive users")
Related Pages
- Guardrails_ai_Guardrails_DocumentStore - The document store used for storing and retrieving example queries
- Guardrails_ai_Guardrails_Embedding - Embedding classes used to encode examples for similarity search