|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import aioodbc |
| 4 | +from typing import Annotated |
| 5 | +from utils.ai_search_utils import run_ai_search_query |
| 6 | +import json |
| 7 | +import asyncio |
| 8 | + |
| 9 | +USE_QUERY_CACHE = os.environ.get("Text2Sql__UseQueryCache", "False").lower() == "true" |
| 10 | + |
| 11 | +PRE_RUN_QUERY_CACHE = ( |
| 12 | + os.environ.get("Text2Sql__PreRunQueryCache", "False").lower() == "true" |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +async def get_entity_schemas( |
| 17 | + text: Annotated[ |
| 18 | + str, |
| 19 | + "The text to run a semantic search against. Relevant entities will be returned.", |
| 20 | + ], |
| 21 | +) -> str: |
| 22 | + """Gets the schema of a view or table in the SQL Database by selecting the most relevant entity based on the search term. Several entities may be returned. |
| 23 | +
|
| 24 | + Args: |
| 25 | + ---- |
| 26 | + text (str): The text to run the search against. |
| 27 | +
|
| 28 | + Returns: |
| 29 | + str: The schema of the views or tables in JSON format. |
| 30 | + """ |
| 31 | + |
| 32 | + schemas = await run_ai_search_query( |
| 33 | + text, |
| 34 | + ["DescriptionEmbedding"], |
| 35 | + ["Entity", "EntityName", "Description", "Columns"], |
| 36 | + os.environ["AIService__AzureSearchOptions__Text2Sql__Index"], |
| 37 | + os.environ["AIService__AzureSearchOptions__Text2Sql__SemanticConfig"], |
| 38 | + top=3, |
| 39 | + ) |
| 40 | + |
| 41 | + for schema in schemas: |
| 42 | + entity = schema["Entity"] |
| 43 | + database = os.environ["Text2Sql__DatabaseName"] |
| 44 | + schema["SelectFromEntity"] = f"{database}.{entity}" |
| 45 | + |
| 46 | + return json.dumps(schemas, default=str) |
| 47 | + |
| 48 | + |
| 49 | +async def query_execution(sql_query: str) -> list[dict]: |
| 50 | + """Run the SQL query against the database. |
| 51 | +
|
| 52 | + Args: |
| 53 | + ---- |
| 54 | + sql_query (str): The SQL query to run against the database. |
| 55 | +
|
| 56 | + Returns: |
| 57 | + ------- |
| 58 | + list[dict]: The results of the SQL query. |
| 59 | + """ |
| 60 | + connection_string = os.environ["Text2Sql__DatabaseConnectionString"] |
| 61 | + async with await aioodbc.connect(dsn=connection_string) as sql_db_client: |
| 62 | + async with sql_db_client.cursor() as cursor: |
| 63 | + await cursor.execute(sql_query) |
| 64 | + |
| 65 | + columns = [column[0] for column in cursor.description] |
| 66 | + |
| 67 | + rows = await cursor.fetchall() |
| 68 | + results = [dict(zip(columns, returned_row)) for returned_row in rows] |
| 69 | + |
| 70 | + logging.debug("Results: %s", results) |
| 71 | + return results |
| 72 | + |
| 73 | + |
| 74 | +async def fetch_queries_from_cache(question: str) -> str: |
| 75 | + """Fetch the queries from the cache based on the question. |
| 76 | +
|
| 77 | + Args: |
| 78 | + ---- |
| 79 | + question (str): The question to use to fetch the queries. |
| 80 | +
|
| 81 | + Returns: |
| 82 | + ------- |
| 83 | + str: The formatted string of the queries fetched from the cache. This is injected into the prompt. |
| 84 | + """ |
| 85 | + cached_schemas = await run_ai_search_query( |
| 86 | + question, |
| 87 | + ["QuestionEmbedding"], |
| 88 | + ["Question", "SqlQueryDecomposition", "Schemas"], |
| 89 | + os.environ["AIService__AzureSearchOptions__Text2SqlQueryCache__Index"], |
| 90 | + os.environ["AIService__AzureSearchOptions__Text2SqlQueryCache__SemanticConfig"], |
| 91 | + top=1, |
| 92 | + include_scores=True, |
| 93 | + minimum_score=1.5, |
| 94 | + ) |
| 95 | + |
| 96 | + if len(cached_schemas) == 0: |
| 97 | + return None |
| 98 | + else: |
| 99 | + database = os.environ["Text2Sql__DatabaseName"] |
| 100 | + for entry in cached_schemas: |
| 101 | + for schema in entry["Schemas"]: |
| 102 | + entity = schema["Entity"] |
| 103 | + schema["SelectFromEntity"] = f"{database}.{entity}" |
| 104 | + |
| 105 | + if PRE_RUN_QUERY_CACHE and len(cached_schemas) > 0: |
| 106 | + logging.info("Cached schemas: %s", cached_schemas) |
| 107 | + |
| 108 | + # check the score |
| 109 | + if cached_schemas[0]["@search.reranker_score"] > 2.75: |
| 110 | + logging.info("Score is greater than 3") |
| 111 | + |
| 112 | + sql_queries = cached_schemas[0]["SqlQueryDecomposition"] |
| 113 | + query_result_store = {} |
| 114 | + |
| 115 | + query_tasks = [] |
| 116 | + |
| 117 | + for sql_query in sql_queries: |
| 118 | + logging.info("SQL Query: %s", sql_query) |
| 119 | + |
| 120 | + # Run the SQL query |
| 121 | + query_tasks.append(query_execution(sql_query["SqlQuery"])) |
| 122 | + |
| 123 | + sql_results = await asyncio.gather(*query_tasks) |
| 124 | + |
| 125 | + for sql_query, sql_result in zip(sql_queries, sql_results): |
| 126 | + query_result_store[sql_query["SqlQuery"]] = { |
| 127 | + "result": sql_result, |
| 128 | + "schemas": sql_queries["schemas"], |
| 129 | + } |
| 130 | + |
| 131 | + return query_result_store |
| 132 | + |
| 133 | + return {"cached_questions": cached_schemas} |
0 commit comments