Spaces:
Sleeping
Sleeping
Delete sql-genonly-chatbot.py
Browse files- sql-genonly-chatbot.py +0 -182
sql-genonly-chatbot.py
DELETED
@@ -1,182 +0,0 @@
|
|
1 |
-
import logging
|
2 |
-
from semantic_kernel import Kernel
|
3 |
-
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
|
4 |
-
from semantic_kernel.functions import kernel_function
|
5 |
-
from azure.cosmos import CosmosClient
|
6 |
-
from semantic_kernel.connectors.ai.open_ai.prompt_execution_settings.azure_chat_prompt_execution_settings import (
|
7 |
-
AzureChatPromptExecutionSettings,
|
8 |
-
)
|
9 |
-
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
|
10 |
-
from models.converterModels import PowerConverter
|
11 |
-
|
12 |
-
import os
|
13 |
-
from dotenv import load_dotenv
|
14 |
-
load_dotenv()
|
15 |
-
|
16 |
-
logger = logging.getLogger("kernel")
|
17 |
-
logger.setLevel(logging.DEBUG)
|
18 |
-
handler = logging.StreamHandler()
|
19 |
-
handler.setFormatter(logging.Formatter(
|
20 |
-
"[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s"
|
21 |
-
))
|
22 |
-
logger.addHandler(handler)
|
23 |
-
|
24 |
-
|
25 |
-
# Initialize Semantic Kernel
|
26 |
-
kernel = Kernel()
|
27 |
-
|
28 |
-
# Add Azure OpenAI Chat Service
|
29 |
-
kernel.add_service(AzureChatCompletion(
|
30 |
-
service_id="chat",
|
31 |
-
deployment_name=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
|
32 |
-
endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
|
33 |
-
api_key=os.getenv("AZURE_OPENAI_KEY")
|
34 |
-
))
|
35 |
-
|
36 |
-
# Database Plugin
|
37 |
-
class CosmosDBPlugin:
|
38 |
-
def __init__(self):
|
39 |
-
self.client = CosmosClient(
|
40 |
-
os.getenv("AZURE_COSMOS_DB_ENDPOINT"),
|
41 |
-
os.getenv("AZURE_COSMOS_DB_KEY")
|
42 |
-
)
|
43 |
-
self.database = self.client.get_database_client("TAL_DB")
|
44 |
-
self.container = self.database.get_container_client("Converters")
|
45 |
-
self.logger = logger
|
46 |
-
|
47 |
-
@kernel_function(
|
48 |
-
name="query_converters",
|
49 |
-
description="Execute SQL query against Cosmos DB converters collection"
|
50 |
-
)
|
51 |
-
async def query_converters(self, query: str) -> str:
|
52 |
-
try:
|
53 |
-
print(f"Executing query: {query}")
|
54 |
-
items = list(self.container.query_items(
|
55 |
-
query=query,
|
56 |
-
enable_cross_partition_query=True
|
57 |
-
))
|
58 |
-
print(f"Query returned {len(items)} items")
|
59 |
-
items = items[:10]
|
60 |
-
self.logger.debug(f"Raw items: {items}")
|
61 |
-
|
62 |
-
items = [PowerConverter(**item) for item in items] if items else []
|
63 |
-
|
64 |
-
self.logger.info(f"Query returned {len(items)} items after conversion")
|
65 |
-
self.logger.debug(f"Items: {items}")
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
return str(items)
|
70 |
-
except Exception as e:
|
71 |
-
self.logger.info(f"Query failed: {str(e)}")
|
72 |
-
return f"Query failed: {str(e)}"
|
73 |
-
|
74 |
-
# SQL Generation Plugin
|
75 |
-
class NL2SQLPlugin:
|
76 |
-
@kernel_function(name="generate_sql", description="Generate Cosmos DB SQL query")
|
77 |
-
async def generate_sql(self, question: str) -> str:
|
78 |
-
sql = await self._generate_sql_helper(question)
|
79 |
-
if "SELECT *" not in sql and "FROM c" in sql:
|
80 |
-
sql = sql.replace("SELECT c.*", "SELECT *")
|
81 |
-
sql = sql.replace("SELECT c", "SELECT *")
|
82 |
-
return sql
|
83 |
-
|
84 |
-
async def _generate_sql_helper(self, question: str) -> str:
|
85 |
-
from semantic_kernel.contents import ChatHistory
|
86 |
-
|
87 |
-
chat_service = kernel.get_service("chat")
|
88 |
-
chat_history = ChatHistory()
|
89 |
-
chat_history.add_user_message(f"""Convert to Cosmos DB SQL: {question}
|
90 |
-
Collection: converters (alias 'c')
|
91 |
-
Fields:
|
92 |
-
- type (e.g., '350mA')
|
93 |
-
- artnr (numeric (int) article number e.g., 930546)
|
94 |
-
- output_voltage_v: dictionary with min/max values for output voltage
|
95 |
-
- output_voltage_v.min (e.g., 15)
|
96 |
-
- output_voltage_v.max (e.g., 40)
|
97 |
-
- input_voltage_v: dictionary with min/max values for input voltage
|
98 |
-
- input_voltage_v.min (e.g., 198)
|
99 |
-
- input_voltage_v.max (e.g., 264)
|
100 |
-
- lamps: dictionary with min/max values for lamp types for this converter
|
101 |
-
- lamps["lamp_name"].min (e.g., 1)
|
102 |
-
- lamps["lamp_name"].max (e.g., 10)
|
103 |
-
- nom_input_voltage (e.g, '198-264V')
|
104 |
-
- class (safety class)
|
105 |
-
- dimmability (e.g., 'MAINS DIM LC')
|
106 |
-
- listprice (e.g., 58)
|
107 |
-
- lifecycle (e.g., 'Active')
|
108 |
-
- size (e.g., '150x30x30')
|
109 |
-
- dimlist_type (e.g., 'DALI')
|
110 |
-
- pdf_link (link to product PDF)
|
111 |
-
- converter_description (e.g., 'POWERLED CONVERTER REMOTE 180mA 8W IP20 1-10V')
|
112 |
-
- ip (Ingress Protection, integer values e.g., 20,67)
|
113 |
-
- efficiency_full_load (e.g., 0.9)
|
114 |
-
- name (e.g., 'Power Converter 350mA')
|
115 |
-
- unit (e.g., 'PC')
|
116 |
-
Return ONLY SQL without explanations""")
|
117 |
-
|
118 |
-
response = await chat_service.get_chat_message_content(
|
119 |
-
chat_history=chat_history,
|
120 |
-
settings=AzureChatPromptExecutionSettings()
|
121 |
-
)
|
122 |
-
|
123 |
-
return str(response)
|
124 |
-
|
125 |
-
|
126 |
-
# Register plugins
|
127 |
-
kernel.add_plugin(CosmosDBPlugin(), "CosmosDBPlugin")
|
128 |
-
kernel.add_plugin(NL2SQLPlugin(), "NL2SQLPlugin")
|
129 |
-
|
130 |
-
# Updated query handler using function calling
|
131 |
-
async def handle_query(user_input: str):
|
132 |
-
|
133 |
-
settings = AzureChatPromptExecutionSettings(
|
134 |
-
function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=True)
|
135 |
-
)
|
136 |
-
|
137 |
-
prompt = f"""
|
138 |
-
You are a converter database expert. Process this user query:
|
139 |
-
{user_input}
|
140 |
-
|
141 |
-
Available functions:
|
142 |
-
- generate_sql: Creates SQL queries from natural language
|
143 |
-
- query_converters: Executes SQL queries against the database
|
144 |
-
|
145 |
-
Follow these steps:
|
146 |
-
1. Generate SQL using generate_sql
|
147 |
-
2. Execute query with query_converters
|
148 |
-
3. Format results into natural language response
|
149 |
-
|
150 |
-
Query Guidelines:
|
151 |
-
1. When performing SELECT ALL queries always use SELECT *. Never use SELECT c.* or SELECT c
|
152 |
-
2. For questions about lamp compatibility, ALWAYS use SELECT * FROM c WHERE IS_DEFINED(c.lamps["lamp_name"])
|
153 |
-
3. For questions about lamps that can be used with a converter, ALWAYS use SELECT c.lamps FROM c WHERE c.artnr = @artnr
|
154 |
-
5. For questions about lamp limits, query for the lamps dictionary and return min/max values
|
155 |
-
|
156 |
-
"""
|
157 |
-
|
158 |
-
result = await kernel.invoke_prompt(
|
159 |
-
prompt=prompt,
|
160 |
-
settings=settings
|
161 |
-
)
|
162 |
-
|
163 |
-
return str(result)
|
164 |
-
|
165 |
-
# Example usage
|
166 |
-
async def main():
|
167 |
-
|
168 |
-
while True:
|
169 |
-
try:
|
170 |
-
query = input("User: ")
|
171 |
-
if query.lower() in ["exit", "quit"]:
|
172 |
-
break
|
173 |
-
|
174 |
-
response = await handle_query(query)
|
175 |
-
print(response)
|
176 |
-
|
177 |
-
except KeyboardInterrupt:
|
178 |
-
break
|
179 |
-
|
180 |
-
if __name__ == "__main__":
|
181 |
-
import asyncio
|
182 |
-
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|