Talk to Data Template
The Talk to Data template enables natural language queries against your structured data, transforming plain English questions into SQL queries and visualizations. It’s like having a data analyst available 24/7.
Topic: Natural Language Data Analysis
This template is perfect for:
- Business intelligence dashboards
- Self-service analytics
- Report generation on demand
- Data exploration without SQL knowledge
- Executive summaries and KPI tracking
The Code
ADD TOOL "query-data"
ADD TOOL "create-chart"
ADD TOOL "export-data"
ADD TOOL "notify-latest-orders"
SET ANSWER MODE "sql"
CLEAR SUGGESTIONS
ADD SUGGESTION "products" AS "Top products chart"
ADD SUGGESTION "sales" AS "Sales across years"
ADD SUGGESTION "orders" AS "Latest orders"
ADD SUGGESTION "chart" AS "Create a chart"
ADD SUGGESTION "export" AS "Export data"
SET CONTEXT "talk-to-data" AS "You are a data analyst assistant helping users query and visualize their data. Convert natural language questions into SQL queries and generate charts. Be helpful and suggest visualizations."
BEGIN TALK
**Talk To Data**
I can help you analyze your data with natural language queries.
**Examples:**
• Show me top products in a rainbow colored pie chart
• Sales across years
• Latest orders this month
• Compare revenue by region
Just ask me anything about your data.
END TALK
BEGIN SYSTEM PROMPT
You are a data analysis assistant that converts natural language to SQL queries.
Chart types:
- timeseries: For data over time
- bar: For comparisons
- pie/donut: For proportions
- line: For trends
When users ask about data:
1. Understand the intent
2. Generate appropriate SQL
3. Suggest relevant visualizations
4. Offer to export if needed
Always use LOWER() for text comparisons.
Use LIKE with %% for partial matches.
Return clear, actionable insights.
END SYSTEM PROMPT
Sample Dialogs
These conversations show how the Talk to Data template works in real-world scenarios.
Dialog 1: Simple Data Query
📊
Data Analyst
online
Today
Dialog 2: Creating a Visualization
📊
Data Analyst
online
Dialog 3: Time Series Analysis
📊
Data Analyst
online
Dialog 4: Latest Orders Notification
📊
Data Analyst
online
Keywords Used
| Keyword | Purpose |
|---|---|
ADD TOOL | Register data query and visualization tools |
SET ANSWER MODE | Configure SQL query generation mode |
SET CONTEXT | Define the data analyst role |
ADD SUGGESTION | Create quick query buttons |
BEGIN TALK | Welcome message with examples |
BEGIN SYSTEM PROMPT | Instructions for SQL generation |
How It Works
- Natural Language Input: User asks a question in plain English
- Intent Understanding: AI interprets what data is needed
- SQL Generation: Query is automatically generated
- Data Retrieval: SQL executes against your database
- Visualization: Results are formatted or charted
- Insights: AI provides analysis and recommendations
Query Tool: query-data.bas
PARAM query AS STRING LIKE "top 10 products by revenue" DESCRIPTION "Natural language data query"
PARAM format AS STRING LIKE "table" DESCRIPTION "Output format: table, chart, export" OPTIONAL
DESCRIPTION "Query data using natural language and return results"
' Convert natural language to SQL using AI
sql = LLM "Convert this to SQL for our database: " + query + ". Tables: products, orders, customers, order_items."
' Execute query
results = SQL sql
IF UBOUND(results) = 0 THEN
TALK "No data found for your query. Try rephrasing or ask what data is available."
RETURN NULL
END IF
' Format output based on request
IF format = "chart" OR INSTR(LOWER(query), "chart") > 0 THEN
' Determine chart type
IF INSTR(LOWER(query), "pie") > 0 THEN
chartType = "pie"
ELSE IF INSTR(LOWER(query), "line") > 0 OR INSTR(LOWER(query), "trend") > 0 THEN
chartType = "line"
ELSE IF INSTR(LOWER(query), "bar") > 0 THEN
chartType = "bar"
ELSE
chartType = "bar" ' Default
END IF
chart = CREATE CHART chartType, results
TALK chart
ELSE
' Display as table
TALK TABLE results
END IF
' Offer insights
IF UBOUND(results) > 5 THEN
insight = LLM "Provide a brief insight about this data: " + TOJSON(results)
TALK "💡 **Insight:** " + insight
END IF
RETURN results
Chart Tool: create-chart.bas
PARAM data_query AS STRING LIKE "sales by month" DESCRIPTION "Data to visualize"
PARAM chart_type AS STRING LIKE "bar" DESCRIPTION "Chart type: bar, line, pie, donut, timeseries"
PARAM title AS STRING LIKE "Monthly Sales" DESCRIPTION "Chart title" OPTIONAL
PARAM colors AS STRING LIKE "rainbow" DESCRIPTION "Color scheme: rainbow, blue, green, custom" OPTIONAL
DESCRIPTION "Create a visualization from data query"
' Get the data
results = CALL query-data(data_query, "raw")
IF NOT results THEN
TALK "Could not retrieve data for chart."
RETURN NULL
END IF
' Set chart options
WITH chartOptions
type = chart_type
title = IIF(title, title, data_query)
colorScheme = IIF(colors, colors, "default")
showLegend = TRUE
showValues = TRUE
END WITH
' Generate chart
chart = CREATE CHART chartOptions.type, results, chartOptions
TALK chart
' Provide chart summary
TALK "📊 Chart shows " + UBOUND(results) + " data points."
RETURN chart
Notify Latest Orders: notify-latest-orders.bas
PARAM since AS STRING LIKE "1 hour" DESCRIPTION "Time period for orders" OPTIONAL
PARAM notify AS STRING LIKE "sales@company.com" DESCRIPTION "Email to notify" OPTIONAL
DESCRIPTION "Get latest orders and optionally send notification"
IF NOT since THEN
since = "1 hour"
END IF
' Calculate time filter
cutoff = DATEADD(NOW(), -1, "hours")
IF INSTR(since, "day") > 0 THEN
cutoff = DATEADD(NOW(), -1, "days")
ELSE IF INSTR(since, "week") > 0 THEN
cutoff = DATEADD(NOW(), -7, "days")
END IF
' Query orders
orders = SQL "SELECT * FROM orders WHERE created_at >= '" + FORMAT(cutoff, "YYYY-MM-DD HH:mm:ss") + "' ORDER BY created_at DESC LIMIT 10"
IF UBOUND(orders) = 0 THEN
TALK "No new orders in the last " + since + "."
RETURN NULL
END IF
' Calculate totals
totalRevenue = 0
FOR EACH order IN orders
totalRevenue = totalRevenue + order.total
NEXT
' Display orders
TALK "🛒 **Latest Orders** (Last " + since + ")"
TALK ""
FOR EACH order IN orders
timeAgo = DATEDIFF(NOW(), order.created_at, "minutes")
TALK "**#" + order.order_number + "** - " + timeAgo + " min ago"
TALK "Customer: " + order.customer_name + " | $" + FORMAT(order.total, "#,##0.00") + " | " + order.status
TALK ""
NEXT
TALK "**Summary:** " + UBOUND(orders) + " orders, $" + FORMAT(totalRevenue, "#,##0.00") + " revenue"
' Send notification if requested
IF notify THEN
emailBody = "New orders in the last " + since + ":\n\n"
emailBody = emailBody + "Total Orders: " + UBOUND(orders) + "\n"
emailBody = emailBody + "Total Revenue: $" + FORMAT(totalRevenue, "#,##0.00")
SEND MAIL notify, "Order Update - " + UBOUND(orders) + " new orders", emailBody
TALK "📧 Notification sent to " + notify
END IF
RETURN orders
Setting Up Your Data
Connecting to Data Sources
The Talk to Data template works with various data sources:
' CSV files
data = FIND "sales.csv"
' Excel files
data = FIND "reports.xlsx", "Sheet1"
' SQL databases
data = SQL "SELECT * FROM products"
' External APIs
data = GET "https://api.example.com/sales"
Schema Configuration
For best results, configure your data schema:
SET CONTEXT "data-schema" AS "
Available tables:
- products: id, name, category, price, stock
- orders: id, customer_id, total, status, created_at
- customers: id, name, email, region
- order_items: order_id, product_id, quantity, price
"
Customization Ideas
Add Scheduled Reports
PARAM reportType AS STRING
IF reportType = "daily summary" THEN
SET SCHEDULE "0 8 * * *" ' Run at 8 AM daily
results = CALL query-data("sales summary for yesterday")
SEND MAIL "team@company.com", "Daily Sales Summary", results
TALK "Daily report sent."
END IF
IF reportType = "weekly dashboard" THEN
SET SCHEDULE "0 9 * * 1" ' Run at 9 AM on Mondays
results = CALL query-data("weekly sales by region")
chart = CALL create-chart("weekly sales", "bar")
SEND MAIL "executives@company.com", "Weekly Dashboard", chart
END IF
Add Natural Language Filters
' Enhanced query understanding
PARAM question AS STRING
' Extract time filters
IF INSTR(LOWER(question), "yesterday") > 0 THEN
dateFilter = "date = '" + FORMAT(NOW() - 1, "YYYY-MM-DD") + "'"
ELSE IF INSTR(LOWER(question), "last week") > 0 THEN
dateFilter = "date >= '" + FORMAT(NOW() - 7, "YYYY-MM-DD") + "'"
ELSE IF INSTR(LOWER(question), "this month") > 0 THEN
dateFilter = "MONTH(date) = " + MONTH(NOW())
END IF
' Apply to query
sql = sql + " WHERE " + dateFilter
Add Comparative Analysis
PARAM metric AS STRING LIKE "revenue"
PARAM compare AS STRING LIKE "this month vs last month"
DESCRIPTION "Compare metrics across time periods"
' Parse comparison periods
IF INSTR(compare, "month") > 0 THEN
current = SQL "SELECT SUM(" + metric + ") FROM sales WHERE MONTH(date) = " + MONTH(NOW())
previous = SQL "SELECT SUM(" + metric + ") FROM sales WHERE MONTH(date) = " + (MONTH(NOW()) - 1)
change = ((current - previous) / previous) * 100
TALK "📊 **" + metric + " Comparison**"
TALK "This month: $" + FORMAT(current, "#,##0")
TALK "Last month: $" + FORMAT(previous, "#,##0")
IF change > 0 THEN
TALK "📈 Change: +" + FORMAT(change, "#,##0.0") + "%"
ELSE
TALK "📉 Change: " + FORMAT(change, "#,##0.0") + "%"
END IF
END IF
Best Practices
- Define Your Schema: Provide clear table and column descriptions in context
- Use Examples: Include example queries in the welcome message
- Handle Edge Cases: Always check for empty results
- Provide Insights: Don’t just show data—interpret it
- Offer Next Steps: Suggest related queries or visualizations
Related Templates
- ai-search.bas - Search documents with AI
- analytics-dashboard.bas - System monitoring
- erp.bas - Enterprise resource planning