MCPcopy Create free account
hub / github.com/caesarHQ/textSQL / text_to_sql

Function text_to_sql

api/app/api/routes.py:97–140  ·  view source on GitHub ↗

Convert natural language query to SQL

()

Source from the content-addressed store, hash-verified

95
96@bp.route('/text_to_sql', methods=['POST'])
97def text_to_sql():
98 """
99 Convert natural language query to SQL
100 """
101 request_body = request.get_json()
102 natural_language_query = request_body.get("natural_language_query")
103 table_names = request_body.get("table_names")
104 scope = request_body.get('scope', "USA")
105 session_id = request_body.get("session_id")
106 generation_id = request_body.get("generation_id")
107 if session_id in ["", "None", "null" ]:
108 session_id = None
109
110 if not natural_language_query:
111 error_msg = '`natural_language_query` is missing from request body'
112 return make_response(jsonify({"error": error_msg}), 400)
113
114 # if it's featured, just pull it from the db
115 cached_sql = featured_queries.get_featured_sql(natural_language_query, scope)
116 if cached_sql:
117 result = execute_sql(cached_sql)
118 return make_response(jsonify({'result': result, 'sql_query': cached_sql}), 200)
119
120 natural_language_query = replace_unsupported_localities(natural_language_query, scope)
121
122 try:
123 if not table_names:
124 table_names = get_all_table_names(scope=scope)
125 # table_names = get_relevant_tables(natural_language_query, scope)
126 result, sql_query = text_to_sql_with_retry(natural_language_query, table_names, scope=scope, session_id=session_id)
127 except Exception as e:
128 capture_exception(e)
129 error_msg = f'Error processing request: {str(e)}'
130 if generation_id:
131 update_input_classification(generation_id, False, 0, None)
132
133 return make_response(jsonify({"error": error_msg}), 500)
134
135 if generation_id:
136 is_successful = result is not None
137 temp_result = result or {}
138 update_input_classification(generation_id, is_successful, len(temp_result.get('results', [])), sql_query)
139
140 return make_response(jsonify({'result': result, 'sql_query': sql_query}), 200)
141
142
143@bp.route('/get_suggestion_failed_query', methods=['POST'])

Callers

nothing calls this directly

Calls 5

get_all_table_namesFunction · 0.85
execute_sqlFunction · 0.50
text_to_sql_with_retryFunction · 0.50

Tested by

no test coverage detected