Transform Natural Language into SQL Queries with joehoover/sql-generator

In today's data-driven world, the ability to translate natural language questions into SQL queries can significantly enhance the efficiency of database interactions. The joehoover/sql-generator provides developers with a powerful Cognitive Action that leverages a text-to-SQL model to automate this process. By utilizing this pre-built action, developers can seamlessly convert user inquiries into accurate SQL commands, streamlining data retrieval and manipulation tasks.
Prerequisites
Before you begin integrating the Cognitive Actions from joehoover/sql-generator, you will need:
- An API key for the Cognitive Actions platform to authenticate your requests.
- Basic familiarity with making API calls and handling JSON payloads.
Authentication typically involves passing your API key in the headers of your HTTP requests.
Cognitive Actions Overview
Generate SQL Query from Prompt
The Generate SQL Query from Prompt action is designed to convert natural language questions into SQL queries based on the provided context of a database. This functionality is particularly useful for developers looking to enable users to interact with databases using everyday language.
Input
The input schema for this action requires the following fields:
- prompt (required): A string that guides the model in generating the SQL query based on the user's question.
- seed (optional): An integer to ensure deterministic results. Leaving it blank will use a random seed.
- topK (optional): An integer indicating the number of most likely tokens to consider during generation (default is 50).
- topP (optional): A number between 0 and 1 representing the cumulative probability of token choices (default is 0.9).
- debug (optional): A boolean to enable detailed logging (default is false).
- temperature (optional): A number controlling the randomness of outputs (default is 0.75).
- maximumNewTokens (optional): An integer specifying the maximum number of tokens to generate (default is 128).
- minimumNewTokens (optional): An integer defining the minimum number of tokens to generate, with -1 disabling this constraint (default is -1).
- stopAtSequences (optional): A string of comma-separated sequences that will halt generation when encountered.
Example Input:
{
"topK": 50,
"topP": 0.9,
"debug": false,
"prompt": "You are a powerful text-to-SQL model. Your job is to answer questions about a database. You are given a question and context regarding one or more tables. \n\nYou must output the SQL query that answers the question.\n\n### Input:\nWhat is the total number of decile for the redwood school locality?\n\n### Context:\nCREATE TABLE table_name_34 (decile VARCHAR, name VARCHAR)\n\n### Response:\n",
"temperature": 0.75,
"maximumNewTokens": 128,
"minimumNewTokens": -1
}
Output
The output from this action is the SQL query generated based on the provided prompt and context.
Example Output:
SELECT decile FROM table_name_34 WHERE name = "redwood school"
Conceptual Usage Example (Python)
Below is a conceptual Python code snippet demonstrating how a developer might call the Generate SQL Query from Prompt action:
import requests
import json
# Replace with your Cognitive Actions API key and endpoint
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute" # Hypothetical endpoint
action_id = "0b7e8c9b-d7b9-474f-a8d6-ce0afc30e2db" # Action ID for Generate SQL Query from Prompt
# Construct the input payload based on the action's requirements
payload = {
"topK": 50,
"topP": 0.9,
"debug": false,
"prompt": "You are a powerful text-to-SQL model. Your job is to answer questions about a database. You are given a question and context regarding one or more tables. \n\nYou must output the SQL query that answers the question.\n\n### Input:\nWhat is the total number of decile for the redwood school locality?\n\n### Context:\nCREATE TABLE table_name_34 (decile VARCHAR, name VARCHAR)\n\n### Response:\n",
"temperature": 0.75,
"maximumNewTokens": 128,
"minimumNewTokens": -1
}
headers = {
"Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
"Content-Type": "application/json"
}
try:
response = requests.post(
COGNITIVE_ACTIONS_EXECUTE_URL,
headers=headers,
json={"action_id": action_id, "inputs": payload} # Hypothetical structure
)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
result = response.json()
print("Action executed successfully:")
print(json.dumps(result, indent=2))
except requests.exceptions.RequestException as e:
print(f"Error executing action {action_id}: {e}")
if e.response is not None:
print(f"Response status: {e.response.status_code}")
try:
print(f"Response body: {e.response.json()}")
except json.JSONDecodeError:
print(f"Response body: {e.response.text}")
In this snippet, ensure that you replace the API key and endpoint with your actual credentials. The action_id is set to the ID of the "Generate SQL Query from Prompt" action, and the payload is constructed according to the required input schema.
Conclusion
The joehoover/sql-generator Cognitive Actions provide a robust solution for converting natural language into SQL queries, enhancing user interaction with databases. By integrating these actions, developers can create applications that allow users to query databases effortlessly and intuitively. Whether you're developing a chatbot, a reporting tool, or a data dashboard, leveraging this action can save time and improve user experience. Explore the capabilities of this action and consider how it can be applied in your projects to unlock the power of data.