File size: 7,568 Bytes
116cc62 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | from typing import *
import json
def reformat_gt_schema(schema):
output_schema = {"database_name": schema['name']}
output_schema['tables'] = schema['tables']
for t in output_schema['tables'].keys():
output_schema['tables'][t].pop('name', None)
for col in output_schema['tables'][t]['columns']:
col.pop('expanded_name', None) # the current data seems to never have any actual expanded name
if col["foreign_key"]:
col["foreign_key"] = f'{col["foreign_key"][0]}.{col["foreign_key"][1]}'
return json.dumps(output_schema, indent=4)
def structured_DP_creation_prompt(*,
col_details: Dict[str, Dict[str, str]],
DPR: str,
imagine_question_count:int=10,
genqsql:bool=False,
use_markdown:bool=False
) -> str:
col_details = reformat_gt_schema(col_details)
if use_markdown:
usemd = '\nUse markdown formatting to organize your thoughts.\n'
else:
usemd = ''
if not genqsql:
if imagine_question_count > 0:
qpart = f"""Think through the task and consider what kinds of questions a user might ask based on the request.
Start by imagining a diverse set of {imagine_question_count} specific questions that might fall under the kind of analysis based on the user request.
Then, try to identify a set of logical groupings of columns which should be in a view to address such questions, and more broadly address the user request. Also consider what, if any, transformations we should apply to create new derived columns which might capture useful concepts.
"""
else:
qpart = "Try to identify a set of logical groupings of columns which should be in a view to address the user request. Also consider what, if any, transformations we should apply to create new derived columns which might capture useful concepts."
else:
assert imagine_question_count > 0
qpart = f"""Think through the task and consider what kinds of questions a user might ask based on the request.
Start by imagining a diverse set of {imagine_question_count} specific questions that might fall under the kind of analysis based on the user request. For each question, generate the question text followed by the SQL query that can be used to answer it.
Then, try to identify a set of logical groupings of columns which should be in a view to address such questions and SQL queries, and more broadly address the user request. Also consider what, if any, transformations we should apply to create new derived columns which might capture useful concepts.
"""
# col_details = json.dumps(col_details, indent=4)
concise_part = "Be thorough with this selection - we will not plan to go back to the original database to retrieve missing information after we have made our selection."
# concise_part = "We want to produce a concise set of columns from the database which are sufficient to address the user request."
prompt_text = f"""You are an expert data engineer, and you are tasked with identifying a focused subset of our SQLite database to make complex queries easier for users.
The database schema is defined by the following tables and columns:
<DESCRIPTIONS>
{col_details}
</DESCRIPTIONS>
Users are interested in analyzing the contents of this database. The kinds of analyses they are interested in are described by the following request:
<REQUEST>
{DPR}
</REQUEST>
Based on the provided schema and request, what tables and columns appear most useful help to make queries of interest easier?
We want to select a subset of the table columns, and possibly derive new columns which might provide useful information or metrics which the user would query about. New columns might be produced by computing mathematical operations, performing aggregations, or transformations over numeric or date-time columns.
Your goal is to select a subset of tables and columns of the database that will help to answer the kinds of questions a user might ask based on the request. {concise_part}
First, we want to sketch out how to tackle this problem.
{qpart}{usemd}Wrap the output of this step with XML tags like <sketch></sketch>.
Then, start to thoroughly listing out which columns from each table we should keep in our output data.
We must select the primary keys of all tables which we want to keep and foreign keys connecting tables.
The selection should contain as many columns as needed to fully address the user request and answer a range of user questions.
Derived columns should be able to help answer user questions by capturing operations which might be reused often by a variety of questions related to the user request.
Output a detailed listing of all tables and columns we should include. Additionally list out any new derived columns which you think would be useful, as well as the columns needed to produce these new columns.
Wrap the output of this step with XML tags like <columns></columns>.
Lastly, output your selection of a useful subset of the database as a python dict.
For columns which you are directly selecting from the database, format them as dictionaries where the key is the table name and the value is a list of columns to keep from that table.
For any new derived columns, output a list of dictionaries under the "DERIVED_COLUMNS" key. Each of these dictionaries should contain the name of the derived column, a SQLITE query to produce the derived column, and the source tables and columns used to produce the derivation.
Wrap your final answer wih XML tags like the following example:
<answer>
{{
"table_1": ["column_A", "column_B", ...],
"table_2": [...],
...
"DERIVED_COLUMNS": [
{{
"name": "derived_column_name",
"SQL": "SQLite statement to produce the derived column",
"source_columns": {{
"table_1": ["column_X", "column_Y", ...],
"table_2": [...],
...
}}
}},
{{
...
}}
]
}}
</answer>
Do not apply any extra formatting to the view XML tags or contents, simply use them to wrap python dict objects.
"""
return prompt_text
def text2sql_prompt(*,
database: str,
question: str,
schema: Dict):
schema_text = reformat_gt_schema(schema)
prompt_text = f"""You are an expert data engineer who is working on translating natural language questions into valid SQLite queries over our database.
The database schema is defined by the following tables and columns:
<DESCRIPTIONS>
{schema_text}
</DESCRIPTIONS>
A user is interested in answering the following question:
<QUESTION>
{question}
</QUESTION>
Your task is to write out a SQL query using SQLite syntax to answer the question based on the provided schema descriptions. Your query must only use columns and tables which are available in the provided database schema.
First, think through the task thoroughly.
Write out how to interpret the question, then think through which tables, columns, and operations will be needed to answer it.
Plan out how to answer the question, and wrap your answer for this step in XML tags like <plan></plan>.
Then, produce your final answer for a SQL query to answer the question.
Output your final answer as an SQLite query which can be directly executed, and wrap with XML tags, like <answer>SELECT ...</answer>
"""
return prompt_text |