Overview
The Natural Language Query tools enable agents to convert natural language questions into SQL queries, execute them against the database, and return results in natural language format. These tools are workspace-context-aware, automatically applying portfolio filters, date ranges, and focus modes from the current user context. The system uses a three-stage pipeline: natural language to SQL translation, SQL validation for safety, and intelligent result formatting.nl_query
Convert a natural language question to SQL, validate, execute, and return formatted results. Type: Tool Required: Yes Since: v1.0 Status: ProductionDescription
This tool transforms conversational questions into database queries while respecting workspace context. It performs validation to prevent destructive operations, executes the query, and formats results in natural language with optional SQL transparency. The tool is workspace-context-aware, automatically incorporating:- Selected portfolio filtering
- Date and date range constraints
- Focus mode (validation, dashboard, visual query builder)
- User preferences for data presentation
Parameters
question (string, required)
The natural language question about the database. Examples: “Show me all active portfolios”, “What are today’s validation breaches?”, “Which portfolios have the highest VaR?”
include_sql (boolean, optional)
Include the generated SQL query in the response. Useful for transparency and debugging. Default: true
max_results (integer, optional)
Maximum number of results to return from the query. Prevents memory issues with large result sets. Default: 100, Range: 1-10000
config (RunnableConfig, optional)
Agent runtime configuration containing workspace context and state. Automatically populated by the agent framework.
Returns
Dictionary with the following structure:Throws
- Generation Error: Failed to convert natural language to SQL
- Validation Error: Generated SQL failed safety validation (DROP, DELETE, etc.)
- Database Error: Query execution failed
- Context Error: Invalid workspace context provided
Processing Pipeline
- Extract Workspace Context: Retrieves portfolio, date, and focus mode from agent config
- Load Schema: Loads cached database schema with full table and column definitions
- Enhance Question: Augments the natural language question with workspace filters
- Generate SQL: Uses GPT-4 to convert enhanced question to SQL with full schema context
- Validate SQL: Checks for destructive operations and validates syntax
- Execute Query: Runs validated query with automatic row limits
- Format Results: Converts raw results to natural language summary
- Store History: Records query for learning and pattern extraction
Examples
Simple Selection Query
Context-Aware Aggregation
Date-Filtered Analysis
Error Handling
Workspace Context Features
When workspace context is available, the tool automatically:- Filters by
selected_portfolio_idif a portfolio is selected - Applies single date filter if
selected_dateis set - Applies date range if
selected_date_rangecontains start/end dates - Focuses schema hints based on
focus_mode:validation: Emphasizes validation schema tablesdashboard: Emphasizes analytics and performance metricsvisual_query_builder: Suggests tables for visual query construction
Safety & Validation
All generated SQL is validated before execution:- Blocks destructive operations (DROP, DELETE, TRUNCATE, ALTER)
- Validates SQL syntax
- Enforces row limits to prevent runaway queries
- Records all queries in history for audit trail
- Returns safety score (0.0-1.0) in response
get_query_history
Retrieve recent natural language queries with pattern analysis and suggestions. Type: Tool Required: No Since: v1.0 Status: ProductionDescription
This tool retrieves the history of natural language queries executed in the workspace. It analyzes successful queries to extract common patterns and generates suggestions for similar queries. Useful for learning what queries have worked well and improving query generation through examples.Parameters
limit (integer, optional)
Number of recent queries to retrieve. Default: 20, Range: 1-100
user_id (string, optional)
Filter history by specific user ID. If not provided, returns all users’ queries in the workspace. Default: null
Returns
Dictionary with the following structure:Throws
- Database Error: Failed to retrieve history from database
- Invalid User ID: User ID format invalid or user not found
Pattern Recognition
The tool automatically identifies five query pattern types:- Simple Select: Basic SELECT queries without complex clauses
- Aggregation: Queries with GROUP BY and aggregate functions
- Multi-table Join: Queries joining multiple tables
- Time-filtered Query: Queries filtering by date/timestamp
- Top N Query: Queries with ORDER BY and LIMIT
Examples
Retrieve All Recent Queries
User-Specific Query History
Learning & Suggestions
The tool improves over time by:- Tracking successful queries as examples
- Identifying common query patterns
- Extracting schema hints from usage
- Suggesting effective queries based on historical success
- Recording failed queries for debugging
Integration with Agent Framework
Both tools integrate seamlessly with the agent framework:Best Practices
- Use Specific Questions: “Show me validation failures for portfolio X today” works better than “What’s wrong?”
- Leverage Workspace Context: Select a portfolio/date before querying for automatic filtering
- Check Query History: Review past successful queries to learn effective patterns
- Enable SQL Transparency: Set
include_sql=truewhen learning SQL patterns - Monitor Safety Scores: Review validation warnings for unexpected query generation
Performance Considerations
- Database schema is cached to avoid repeated loading
- Query results automatically limited to
max_results(default 100) - Queries added to history asynchronously (failures don’t block)
- Workspace context filtering reduces result set sizes
- Pattern extraction limited to 20 most recent queries by default