Spaces:
Sleeping
Sleeping
Delete chatbot.py
Browse files- chatbot.py +0 -165
chatbot.py
DELETED
@@ -1,165 +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 |
-
from plugins.converterPlugin import ConverterPlugin
|
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 |
-
# SQL Generation Plugin
|
37 |
-
class NL2SQLPlugin:
|
38 |
-
@kernel_function(name="generate_sql", description="Generate Cosmos DB SQL query")
|
39 |
-
async def generate_sql(self, question: str) -> str:
|
40 |
-
sql = await self._generate_sql_helper(question)
|
41 |
-
# if ["DELETE", "UPDATE", "INSERT"] in sql:
|
42 |
-
# return ""
|
43 |
-
if "FROM converters c" in sql:
|
44 |
-
sql = sql.replace("FROM converters c", "FROM c")
|
45 |
-
if "SELECT *" not in sql and "FROM c" in sql:
|
46 |
-
sql = sql.replace("SELECT c.*,", "SELECT *")
|
47 |
-
sql = sql.replace("SELECT c.*", "SELECT *")
|
48 |
-
sql = sql.replace("SELECT c", "SELECT *")
|
49 |
-
|
50 |
-
return sql
|
51 |
-
|
52 |
-
async def _generate_sql_helper(self, question: str) -> str:
|
53 |
-
from semantic_kernel.contents import ChatHistory
|
54 |
-
|
55 |
-
chat_service = kernel.get_service("chat")
|
56 |
-
chat_history = ChatHistory()
|
57 |
-
chat_history.add_user_message(f"""Convert to Cosmos DB SQL: {question}
|
58 |
-
Collection: converters (alias 'c')
|
59 |
-
Fields:
|
60 |
-
- type (e.g., '350mA')
|
61 |
-
- artnr (numeric (int) article number e.g., 930546)
|
62 |
-
- output_voltage_v: dictionary with min/max values for output voltage
|
63 |
-
- output_voltage_v.min (e.g., 15)
|
64 |
-
- output_voltage_v.max (e.g., 40)
|
65 |
-
- nom_input_voltage_v: dictionary with min/max values for input voltage
|
66 |
-
- nom_input_voltage_v.min (e.g., 198)
|
67 |
-
- nom_input_voltage_v.max (e.g., 264)
|
68 |
-
- lamps: dictionary with min/max values for lamp types for this converter
|
69 |
-
- lamps["lamp_name"].min (e.g., 1)
|
70 |
-
- lamps["lamp_name"].max (e.g., 10)
|
71 |
-
- class (safety class)
|
72 |
-
- dimmability (e.g. if not dimmable 'NOT DIMMABLE'. if supports dimming, 'DALI/TOUCHDIM','MAINS DIM LC' etc)
|
73 |
-
- listprice (e.g., 58)
|
74 |
-
- lifecycle (e.g., 'Active')
|
75 |
-
- size (e.g., '150x30x30')
|
76 |
-
- dimlist_type (e.g., 'DALI')
|
77 |
-
- pdf_link (link to product PDF)
|
78 |
-
- converter_description (e.g., 'POWERLED CONVERTER REMOTE 180mA 8W IP20 1-10V')
|
79 |
-
- ip (Ingress Protection, integer values e.g., 20,67)
|
80 |
-
- efficiency_full_load (e.g., 0.9)
|
81 |
-
- name (e.g., 'Power Converter 350mA')
|
82 |
-
- unit (e.g., 'PC')
|
83 |
-
- strain_relief (e.g., "NO", "YES")
|
84 |
-
Return ONLY SQL without explanations""")
|
85 |
-
|
86 |
-
response = await chat_service.get_chat_message_content(
|
87 |
-
chat_history=chat_history,
|
88 |
-
settings=AzureChatPromptExecutionSettings()
|
89 |
-
)
|
90 |
-
|
91 |
-
return str(response)
|
92 |
-
|
93 |
-
|
94 |
-
# Register plugins
|
95 |
-
kernel.add_plugin(ConverterPlugin(logger=logger), "CosmosDBPlugin")
|
96 |
-
kernel.add_plugin(NL2SQLPlugin(), "NL2SQLPlugin")
|
97 |
-
|
98 |
-
# Updated query handler using function calling
|
99 |
-
async def handle_query(user_input: str):
|
100 |
-
|
101 |
-
settings = AzureChatPromptExecutionSettings(
|
102 |
-
function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=True)
|
103 |
-
)
|
104 |
-
|
105 |
-
prompt = f"""
|
106 |
-
You are a converter database expert. Process this user query:
|
107 |
-
{user_input}
|
108 |
-
|
109 |
-
Available functions:
|
110 |
-
- generate_sql: Creates SQL queries (use only for complex queries or schema keywords)
|
111 |
-
- query_converters: Executes SQL queries
|
112 |
-
- get_compatible_lamps: Simple artnr-based lamp queries
|
113 |
-
- get_converters_by_lamp_type: Simple lamp type searches
|
114 |
-
- get_lamp_limits: Simple artnr+lamp combinations
|
115 |
-
|
116 |
-
Decision Flow:
|
117 |
-
1. Use simple functions if query matches these patterns:
|
118 |
-
- "lamps for [artnr]" → get_compatible_lamps
|
119 |
-
- "converters for [lamp type]" → get_converters_by_lamp_type
|
120 |
-
- "min/max [lamp] for [artnr]" → get_lamp_limits
|
121 |
-
|
122 |
-
2. Use SQL generation ONLY when:
|
123 |
-
- Query contains schema keywords: voltage, price, type, ip, efficiency, size, class, dimmability
|
124 |
-
- Combining multiple conditions (AND/OR/NOT)
|
125 |
-
- Needs complex filtering/sorting
|
126 |
-
- Requesting technical specifications
|
127 |
-
|
128 |
-
SQL Guidelines (if needed):
|
129 |
-
1. Always use SELECT * instead of field lists
|
130 |
-
2. For exact matches use: WHERE c.[field] = value
|
131 |
-
3. For EXACT ranges ALWAYS use: SELECT * FROM c WHERE c.[field].min = X AND c.[field].max = Y and NEVER >= <=
|
132 |
-
4. Limit results with SELECT TOP 10
|
133 |
-
|
134 |
-
Examples:
|
135 |
-
User: "Show IP67 converters under €100" → generate_sql
|
136 |
-
User: "What lamps are compatible with 930560?" → get_compatible_lamps
|
137 |
-
User: "What converters are compatible with haloled lamps?" → get_converters_by_lamp_type
|
138 |
-
User: "Voltage range for 930562" → generate_sql
|
139 |
-
"""
|
140 |
-
|
141 |
-
result = await kernel.invoke_prompt(
|
142 |
-
prompt=prompt,
|
143 |
-
settings=settings
|
144 |
-
)
|
145 |
-
|
146 |
-
return str(result)
|
147 |
-
|
148 |
-
# Example usage
|
149 |
-
async def main():
|
150 |
-
|
151 |
-
while True:
|
152 |
-
try:
|
153 |
-
query = input("User: ")
|
154 |
-
if query.lower() in ["exit", "quit"]:
|
155 |
-
break
|
156 |
-
|
157 |
-
response = await handle_query(query)
|
158 |
-
print(response)
|
159 |
-
|
160 |
-
except KeyboardInterrupt:
|
161 |
-
break
|
162 |
-
|
163 |
-
if __name__ == "__main__":
|
164 |
-
import asyncio
|
165 |
-
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|