-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient1.py
More file actions
1935 lines (1713 loc) · 86.2 KB
/
client1.py
File metadata and controls
1935 lines (1713 loc) · 86.2 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os, re, json, ast, asyncio
import pandas as pd
import streamlit as st
import base64
from io import BytesIO
from PIL import Image
from langchain_groq import ChatGroq
from langchain_core.messages import HumanMessage, SystemMessage
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
import streamlit.components.v1 as components
import re
from dotenv import load_dotenv
load_dotenv()
# Initialize Groq client with environment variable
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
if not GROQ_API_KEY:
st.error("🔐 GROQ_API_KEY environment variable is not set. Please add it to your environment.")
st.stop()
groq_client = ChatGroq(
groq_api_key=GROQ_API_KEY,
model_name=os.environ.get("GROQ_MODEL", "llama3-70b-8192")
)
# ========== PAGE CONFIG ==========
st.set_page_config(page_title="MCP CRUD Chat", layout="wide")
# ========== GLOBAL CSS ==========
st.markdown("""
<style>
[data-testid="stSidebar"] {
background: linear-gradient(180deg, #4286f4 0%, #397dd2 100%);
color: #fff !important;
min-width: 330px !important;
padding: 0 0 0 0 !important;
}
[data-testid="stSidebar"] .sidebar-title {
color: #fff !important;
font-weight: bold;
font-size: 2.2rem;
letter-spacing: -1px;
text-align: center;
margin-top: 28px;
margin-bottom: 18px;
}
.sidebar-block {
width: 94%;
margin: 0 auto 18px auto;
}
.sidebar-block label {
color: #fff !important;
font-weight: 500;
font-size: 1.07rem;
margin-bottom: 4px;
margin-left: 2px;
display: block;
text-align: left;
}
.sidebar-block .stSelectbox>div {
background: #fff !important;
color: #222 !important;
border-radius: 13px !important;
font-size: 1.13rem !important;
min-height: 49px !important;
box-shadow: 0 3px 14px #0002 !important;
padding: 3px 10px !important;
margin-top: 4px !important;
margin-bottom: 0 !important;
}
.stButton>button {
width: 100%;
height: 3rem;
background: #39e639;
color: #222;
font-size: 1.1rem;
font-weight: bold;
border-radius: 10px;
margin-bottom: 2rem;
}
/* Small refresh button styling */
.small-refresh-button button {
width: auto !important;
height: 2rem !important;
background: #4286f4 !important;
color: #fff !important;
font-size: 0.85rem !important;
font-weight: 500 !important;
border-radius: 6px !important;
margin-bottom: 0.5rem !important;
padding: 0.25rem 0.75rem !important;
border: none !important;
box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
}
.small-refresh-button button:hover {
background: #397dd2 !important;
transform: translateY(-1px) !important;
box-shadow: 0 4px 8px rgba(0,0,0,0.15) !important;
}
.sidebar-logo-label {
margin-top: 30px !important;
margin-bottom: 10px;
font-size: 1.13rem !important;
font-weight: 600;
text-align: center;
color: #fff !important;
letter-spacing: 0.1px;
}
.sidebar-logo-row {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
gap: 20px;
margin-top: 8px;
margin-bottom: 8px;
}
.sidebar-logo-row img {
width: 42px;
height: 42px;
border-radius: 9px;
background: #fff;
padding: 6px 8px;
object-fit: contain;
box-shadow: 0 2px 8px #0002;
}
/* Chat area needs bottom padding so sticky bar does not overlap */
.stChatPaddingBottom { padding-bottom: 98px; }
/* Responsive sticky chatbar */
.sticky-chatbar {
position: fixed;
left: 330px;
right: 0;
bottom: 0;
z-index: 100;
background: #f8fafc;
padding: 0.6rem 2rem 0.8rem 2rem;
box-shadow: 0 -2px 24px #0001;
}
@media (max-width: 800px) {
.sticky-chatbar { left: 0; right: 0; padding: 0.6rem 0.5rem 0.8rem 0.5rem; }
[data-testid="stSidebar"] { display: none !important; }
}
.chat-bubble {
padding: 13px 20px;
margin: 8px 0;
border-radius: 18px;
max-width: 75%;
font-size: 1.09rem;
line-height: 1.45;
box-shadow: 0 1px 4px #0001;
display: inline-block;
word-break: break-word;
}
.user-msg {
background: #e6f0ff;
color: #222;
margin-left: 24%;
text-align: right;
border-bottom-right-radius: 6px;
border-top-right-radius: 24px;
}
.agent-msg {
background: #f5f5f5;
color: #222;
margin-right: 24%;
text-align: left;
border-bottom-left-radius: 6px;
border-top-left-radius: 24px;
}
.chat-row {
display: flex;
align-items: flex-end;
margin-bottom: 0.6rem;
}
.avatar {
height: 36px;
width: 36px;
border-radius: 50%;
margin: 0 8px;
object-fit: cover;
box-shadow: 0 1px 4px #0002;
}
.user-avatar { order: 2; }
.agent-avatar { order: 0; }
.user-bubble { order: 1; }
.agent-bubble { order: 1; }
.right { justify-content: flex-end; }
.left { justify-content: flex-start; }
.chatbar-claude {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
max-width: 850px;
margin: 0 auto;
border-radius: 20px;
background: #fff;
box-shadow: 0 2px 8px #0002;
padding: 8px 14px;
margin-bottom: 0;
}
.claude-hamburger {
background: #f2f4f9;
border: none;
border-radius: 11px;
font-size: 1.35rem;
font-weight: bold;
width: 38px; height: 38px;
cursor: pointer;
display: flex; align-items: center; justify-content: center;
transition: background 0.13s;
}
.claude-hamburger:hover { background: #e6f0ff; }
.claude-input {
flex: 1;
border: none;
outline: none;
font-size: 1.12rem;
padding: 0.45rem 0.5rem;
background: #f5f7fa;
border-radius: 8px;
min-width: 60px;
}
.claude-send {
background: #fe3044 !important;
color: #fff !important;
border: none;
border-radius: 50%;
width: 40px; height: 40px;
font-size: 1.4rem !important;
cursor: pointer;
display: flex; align-items: center; justify-content: center;
transition: background 0.17s;
}
.claude-send:hover { background: #d91d32 !important; }
.tool-menu {
position: fixed;
top: 20px;
right: 20px;
background: #fff;
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
z-index: 1000;
min-width: 200px;
}
.server-title {
font-weight: bold;
margin-bottom: 10px;
color: #333;
}
.expandable {
margin-top: 8px;
}
[data-testid="stSidebar"] .stSelectbox label {
color: #fff !important;
font-weight: 500;
font-size: 1.07rem;
}
</style>
""", unsafe_allow_html=True)
# ========== DYNAMIC TOOL DISCOVERY FUNCTIONS ==========
async def _discover_tools() -> dict:
"""Discover available tools from the MCP server"""
try:
transport = StreamableHttpTransport(f"{st.session_state.get('MCP_SERVER_URL', 'http://localhost:8000')}/mcp")
async with Client(transport) as client:
tools = await client.list_tools()
return {tool.name: tool.description for tool in tools}
except Exception as e:
st.error(f"Failed to discover tools: {e}")
return {}
def discover_tools() -> dict:
"""Synchronous wrapper for tool discovery"""
return asyncio.run(_discover_tools())
def generate_tool_descriptions(tools_dict: dict) -> str:
"""Generate tool descriptions string from discovered tools"""
if not tools_dict:
return "No tools available"
descriptions = ["Available tools:"]
for i, (tool_name, tool_desc) in enumerate(tools_dict.items(), 1):
descriptions.append(f"{i}. {tool_name}: {tool_desc}")
return "\n".join(descriptions)
def get_image_base64(img_path):
img = Image.open(img_path)
buffered = BytesIO()
img.save(buffered, format="PNG")
img_bytes = buffered.getvalue()
img_base64 = base64.b64encode(img_bytes).decode()
return img_base64
# ========== SIDEBAR NAVIGATION ==========
with st.sidebar:
st.markdown("<div class='sidebar-title'>Solutions Scope</div>", unsafe_allow_html=True)
with st.container():
# Application selectbox (with key)
application = st.selectbox(
"Select Application",
["Select Application", "MCP Application"],
key="app_select"
)
# Dynamically choose default options for other selects
# Option lists
protocol_options = ["", "MCP Protocol", "A2A Protocol"]
llm_options = ["", "Groq Llama3-70B", "Groq Llama3-8B", "Groq Mixtral-8x7B", "Groq Gemma"]
# Logic to auto-select defaults if MCP Application is chosen
protocol_index = protocol_options.index(
"MCP Protocol") if application == "MCP Application" else protocol_options.index(
st.session_state.get("protocol_select", ""))
llm_index = llm_options.index("Groq Llama3-70B") if application == "MCP Application" else llm_options.index(
st.session_state.get("llm_select", ""))
protocol = st.selectbox(
"Protocol",
protocol_options,
key="protocol_select",
index=protocol_index
)
llm_model = st.selectbox(
"LLM Models",
llm_options,
key="llm_select",
index=llm_index
)
# Dynamic server tools selection based on discovered tools
if application == "MCP Application" and "available_tools" in st.session_state and st.session_state.available_tools:
server_tools_options = [""] + list(st.session_state.available_tools.keys())
default_tool = list(st.session_state.available_tools.keys())[0] if st.session_state.available_tools else ""
server_tools_index = server_tools_options.index(default_tool) if default_tool else 0
else:
server_tools_options = ["", "sqlserver_crud", "postgresql_crud"] # Fallback
server_tools_index = 0
server_tools = st.selectbox(
"Server Tools",
server_tools_options,
key="server_tools",
index=server_tools_index
)
st.button("Clear/Reset", key="clear_button")
st.markdown('<div class="sidebar-logo-label">Build & Deployed on</div>', unsafe_allow_html=True)
st.markdown(
"""
<div class="sidebar-logo-row">
<img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/googlecloud/googlecloud-original.svg" title="Google Cloud">
<img src="https://a0.awsstatic.com/libra-css/images/logos/aws_logo_smile_1200x630.png" title="AWS">
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a8/Microsoft_Azure_Logo.svg" title="Azure Cloud">
</div>
""",
unsafe_allow_html=True
)
# ========== LOGO/HEADER FOR MAIN AREA ==========
# Updated to use GitHub URL directly
logo_url = "https://github.com/lokit-s/mcp/blob/main/Picture1.png?raw=true"
st.markdown(
f"""
<div style='display: flex; flex-direction: column; align-items: center; margin-bottom:20px;'>
<img src='{logo_url}' width='220'>
</div>
""",
unsafe_allow_html=True
)
st.markdown(
"""
<div style="
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 18px;
padding: 10px 0 10px 0;
">
<span style="
font-size: 2.5rem;
font-weight: bold;
letter-spacing: -2px;
color: #222;
">
MCP-Driven Data Management With Natural Language
</span>
<span style="
font-size: 1.15rem;
color: #555;
margin-top: 0.35rem;
">
Agentic Approach: NO SQL, NO ETL, NO DATA WAREHOUSING, NO BI TOOL
</span>
<hr style="
width: 80%;
border: none;
height: 2px;
background: linear-gradient(90deg, transparent, #4286f4, transparent);
margin: 20px auto;
">
</div>
""",
unsafe_allow_html=True
)
# ========== SESSION STATE INIT ==========
if "messages" not in st.session_state:
st.session_state.messages = []
# Initialize available_tools if not exists
if "available_tools" not in st.session_state:
st.session_state.available_tools = {}
# Initialize MCP_SERVER_URL in session state
if "MCP_SERVER_URL" not in st.session_state:
st.session_state["MCP_SERVER_URL"] = os.getenv("MCP_SERVER_URL", "http://localhost:8000")
# Initialize tool_states dynamically based on discovered tools
if "tool_states" not in st.session_state:
st.session_state.tool_states = {}
if "show_menu" not in st.session_state:
st.session_state["show_menu"] = False
if "menu_expanded" not in st.session_state:
st.session_state["menu_expanded"] = True
if "chat_input_box" not in st.session_state:
st.session_state["chat_input_box"] = ""
# ========== HELPER FUNCTIONS ==========
def _clean_json(raw: str) -> str:
fences = re.findall(r"``````", raw, re.DOTALL)
if fences:
return fences[0].strip()
# If no JSON code fence, try to find JSON-like content
json_match = re.search(r'\{.*\}', raw, re.DOTALL)
return json_match.group(0).strip() if json_match else raw.strip()
# ========== PARAMETER VALIDATION FUNCTION ==========
def validate_and_clean_parameters(tool_name: str, args: dict) -> dict:
"""Validate and clean parameters for specific tools"""
if tool_name == "sales_crud":
# Define allowed parameters for sales_crud (with WHERE clause support)
allowed_params = {
'operation', 'customer_id', 'product_id', 'quantity',
'unit_price', 'total_amount', 'sale_id', 'new_quantity',
'table_name', 'display_format', 'customer_name',
'product_name', 'email', 'total_price',
'columns', # Column selection
'where_clause', # WHERE conditions
'filter_conditions', # Structured filters
'limit' # Row limit
}
# Clean args to only include allowed parameters
cleaned_args = {k: v for k, v in args.items() if k in allowed_params}
# Validate display_format values
if 'display_format' in cleaned_args:
valid_formats = [
'Data Format Conversion',
'Decimal Value Formatting',
'String Concatenation',
'Null Value Removal/Handling'
]
if cleaned_args['display_format'] not in valid_formats:
cleaned_args.pop('display_format', None)
# Clean up columns parameter
if 'columns' in cleaned_args:
if isinstance(cleaned_args['columns'], str) and cleaned_args['columns'].strip():
columns_str = cleaned_args['columns'].strip()
columns_list = [col.strip() for col in columns_str.split(',') if col.strip()]
cleaned_args['columns'] = ','.join(columns_list)
else:
cleaned_args.pop('columns', None)
# Validate WHERE clause
if 'where_clause' in cleaned_args:
if not isinstance(cleaned_args['where_clause'], str) or not cleaned_args['where_clause'].strip():
cleaned_args.pop('where_clause', None)
# Validate limit
if 'limit' in cleaned_args:
try:
limit_val = int(cleaned_args['limit'])
if limit_val <= 0 or limit_val > 1000: # Reasonable limits
cleaned_args.pop('limit', None)
else:
cleaned_args['limit'] = limit_val
except (ValueError, TypeError):
cleaned_args.pop('limit', None)
return cleaned_args
elif tool_name == "sqlserver_crud":
allowed_params = {
'operation', 'name', 'email', 'limit', 'customer_id',
'new_email', 'table_name'
}
return {k: v for k, v in args.items() if k in allowed_params}
elif tool_name == "postgresql_crud":
allowed_params = {
'operation', 'name', 'price', 'description', 'limit',
'product_id', 'new_price', 'table_name'
}
return {k: v for k, v in args.items() if k in allowed_params}
return args
# ========== NEW LLM RESPONSE GENERATOR ==========
def generate_llm_response(operation_result: dict, action: str, tool: str, user_query: str) -> str:
"""Generate LLM response based on operation result with context"""
# Prepare context for LLM
context = {
"action": action,
"tool": tool,
"user_query": user_query,
"operation_result": operation_result
}
system_prompt = (
"You are a helpful database assistant. Generate a brief, natural response "
"explaining what operation was performed and its result. Be conversational "
"and informative. Focus on the business context and user-friendly explanation."
)
user_prompt = f"""
Based on this database operation context, generate a brief natural response:
User asked: "{user_query}"
Operation: {action}
Tool used: {tool}
Result: {json.dumps(operation_result, indent=2)}
Generate a single line response explaining what was done and the outcome.
"""
try:
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content=user_prompt)
]
response = groq_client.invoke(messages)
return response.content.strip()
except Exception as e:
# Fallback response if LLM call fails
if action == "read":
return f"Successfully retrieved data from {tool}."
elif action == "create":
return f"Successfully created new record in {tool}."
elif action == "update":
return f"Successfully updated record in {tool}."
elif action == "delete":
return f"Successfully deleted record from {tool}."
elif action == "describe":
return f"Successfully retrieved table schema from {tool}."
else:
return f"Operation completed successfully using {tool}."
def parse_user_query(query: str, available_tools: dict) -> dict:
"""Enhanced parse user query with display format detection"""
if not available_tools:
return {"error": "No tools available"}
# Build comprehensive tool information for the LLM
tool_info = []
for tool_name, tool_desc in available_tools.items():
tool_info.append(f"- **{tool_name}**: {tool_desc}")
tools_description = "\n".join(tool_info)
system_prompt = (
"You are an intelligent database router for CRUD operations. "
"Your job is to analyze the user's query and select the most appropriate tool based on the context and data being requested.\n\n"
"RESPONSE FORMAT:\n"
"Reply with exactly one JSON object: {\"tool\": string, \"action\": string, \"args\": object}\n\n"
"ACTION MAPPING:\n"
"- 'read': for viewing, listing, showing, displaying, or getting records\n"
"- 'create': for adding, inserting, or creating NEW records\n"
"- 'update': for modifying, changing, or updating existing records\n"
"- 'delete': for removing, deleting, or destroying records\n"
"- 'describe': for showing table structure, schema, or column information\n\n"
"CRITICAL TOOL SELECTION RULES:\n"
"\n"
"1. **PRODUCT QUERIES** → Use 'postgresql_crud':\n"
" - 'list products', 'show products', 'display products'\n"
" - 'product inventory', 'product catalog', 'product information'\n"
" - 'add product', 'create product', 'new product'\n"
" - 'update product', 'change product price', 'modify product'\n"
" - 'delete product', 'remove product', 'delete [ProductName]'\n"
" - Any query primarily about products, pricing, or inventory\n"
"\n"
"2. **CUSTOMER QUERIES** → Use 'sqlserver_crud':\n"
" - 'list customers', 'show customers', 'display customers'\n"
" - 'customer information', 'customer details'\n"
" - 'add customer', 'create customer', 'new customer'\n"
" - 'update customer', 'change customer email', 'modify customer'\n"
" - 'delete customer', 'remove customer', 'delete [CustomerName]'\n"
" - Any query primarily about customers, names, or emails\n"
"\n"
"3. **SALES/TRANSACTION QUERIES** → Use 'sales_crud':\n"
" - 'list sales', 'show sales', 'sales data', 'transactions'\n"
" - 'sales report', 'revenue data', 'purchase history'\n"
" - 'who bought what', 'customer purchases'\n"
" - Cross-database queries combining customer + product + sales info\n"
" - 'create sale', 'add sale', 'new transaction'\n"
" - Any query asking for combined data from multiple tables\n"
" - ETL formatting queries with display_format parameter\n"
"\n"
"ENHANCED DISPLAY FORMAT DETECTION (CRITICAL FOR SALES_CRUD):\n"
"\n"
"For sales_crud queries, detect display_format from these EXACT patterns:\n"
"\n"
"DATA FORMAT CONVERSION PATTERNS:\n"
"- 'with Data Format Conversion' → {\"display_format\": \"Data Format Conversion\"}\n"
"- 'using Data Format Conversion format' → {\"display_format\": \"Data Format Conversion\"}\n"
"- 'Data Format Conversion' (exact match) → {\"display_format\": \"Data Format Conversion\"}\n"
"\n"
"DECIMAL VALUE FORMATTING PATTERNS:\n"
"- 'with Decimal Value Formatting' → {\"display_format\": \"Decimal Value Formatting\"}\n"
"- 'using Decimal Value Formatting format' → {\"display_format\": \"Decimal Value Formatting\"}\n"
"- 'Decimal Value Formatting' (exact match) → {\"display_format\": \"Decimal Value Formatting\"}\n"
"\n"
"STRING CONCATENATION PATTERNS:\n"
"- 'with String Concatenation' → {\"display_format\": \"String Concatenation\"}\n"
"- 'using String Concatenation format' → {\"display_format\": \"String Concatenation\"}\n"
"- 'String Concatenation' (exact match) → {\"display_format\": \"String Concatenation\"}\n"
"\n"
"NULL VALUE REMOVAL/HANDLING PATTERNS:\n"
"- 'with Null Value Removal/Handling' → {\"display_format\": \"Null Value Removal/Handling\"}\n"
"- 'using Null Value Removal/Handling format' → {\"display_format\": \"Null Value Removal/Handling\"}\n"
"- 'Null Value Removal/Handling' (exact match) → {\"display_format\": \"Null Value Removal/Handling\"}\n"
"- 'null handling' → {\"display_format\": \"Null Value Removal/Handling\"}\n"
"- 'clean sales data with null handling' → {\"display_format\": \"Null Value Removal/Handling\"}\n"
"\n"
"EXAMPLES OF DISPLAY FORMAT EXTRACTION:\n"
"\n"
"Query: 'show sales with Data Format Conversion'\n"
"→ {\"tool\": \"sales_crud\", \"action\": \"read\", \"args\": {\"display_format\": \"Data Format Conversion\"}}\n"
"\n"
"Query: 'display sales using Decimal Value Formatting format'\n"
"→ {\"tool\": \"sales_crud\", \"action\": \"read\", \"args\": {\"display_format\": \"Decimal Value Formatting\"}}\n"
"\n"
"Query: 'sales with String Concatenation'\n"
"→ {\"tool\": \"sales_crud\", \"action\": \"read\", \"args\": {\"display_format\": \"String Concatenation\"}}\n"
"\n"
"Query: 'clean sales data with null handling'\n"
"→ {\"tool\": \"sales_crud\", \"action\": \"read\", \"args\": {\"display_format\": \"Null Value Removal/Handling\"}}\n"
"\n"
"ENHANCED DELETE OPERATION EXTRACTION:\n"
"\n"
"For DELETE operations, extract the entity name from these patterns:\n"
"\n"
"PRODUCT DELETE PATTERNS:\n"
"- 'delete [ProductName]' → {\"name\": \"ProductName\"}\n"
"- 'delete product [ProductName]' → {\"name\": \"ProductName\"}\n"
"- 'remove [ProductName]' → {\"name\": \"ProductName\"}\n"
"- 'remove product [ProductName]' → {\"name\": \"ProductName\"}\n"
"\n"
"CUSTOMER DELETE PATTERNS:\n"
"- 'delete [CustomerName]' → {\"name\": \"CustomerName\"}\n"
"- 'delete customer [CustomerName]' → {\"name\": \"CustomerName\"}\n"
"- 'remove [CustomerName]' → {\"name\": \"CustomerName\"}\n"
"- 'remove customer [CustomerName]' → {\"name\": \"CustomerName\"}\n"
"\n"
"ENHANCED UPDATE OPERATION EXTRACTION:\n"
"\n"
"For UPDATE operations, extract both the entity name and new value:\n"
"\n"
"PRODUCT UPDATE PATTERNS:\n"
"- 'update price of [ProductName] to [NewPrice]' → {\"name\": \"ProductName\", \"new_price\": NewPrice}\n"
"- 'change price of [ProductName] to [NewPrice]' → {\"name\": \"ProductName\", \"new_price\": NewPrice}\n"
"- 'set [ProductName] price to [NewPrice]' → {\"name\": \"ProductName\", \"new_price\": NewPrice}\n"
"\n"
"CUSTOMER UPDATE PATTERNS:\n"
"- 'update email of [CustomerName] to [NewEmail]' → {\"name\": \"CustomerName\", \"new_email\": \"NewEmail\"}\n"
"- 'change email of [CustomerName] to [NewEmail]' → {\"name\": \"CustomerName\", \"new_email\": \"NewEmail\"}\n"
"- 'set [CustomerName] email to [NewEmail]' → {\"name\": \"CustomerName\", \"new_email\": \"NewEmail\"}\n"
"\n"
"ENHANCED COLUMN SELECTION EXTRACTION:\n"
"\n"
"For queries that request specific columns, extract them into the 'columns' parameter:\n"
"\n"
"COLUMN EXTRACTION PATTERNS:\n"
"- 'show customer_first_name, total_price' → {\"columns\": \"customer_first_name,total_price\"}\n"
"- 'display customer_first_name and total_price' → {\"columns\": \"customer_first_name,total_price\"}\n"
"- 'show only customer and price' → {\"columns\": \"customer_first_name,total_price\"}\n"
"\n"
"ENHANCED WHERE CLAUSE EXTRACTION:\n"
"\n"
"Extract filtering conditions from natural language and add them to 'where_condition' parameter:\n"
"\n"
"WHERE CLAUSE PATTERNS:\n"
"- 'sales where price > 14' → {\"where_condition\": \"s.total_price > 14\"}\n"
"- 'sales where quantity >= 2' → {\"where_condition\": \"s.quantity >= 2\"}\n"
"- 'sales for customer Alice' → {\"where_condition\": \"c.FirstName = 'Alice'\"}\n"
"\n"
f"AVAILABLE TOOLS:\n{tools_description}\n\n"
"CRITICAL: Always analyze the PRIMARY INTENT of the query:\n"
"- If asking about PRODUCTS specifically → postgresql_crud\n"
"- If asking about CUSTOMERS specifically → sqlserver_crud\n"
"- If asking about SALES/TRANSACTIONS or ETL formatting → sales_crud\n"
"\n"
"FOR DISPLAY FORMAT DETECTION:\n"
"1. Look for exact ETL format names in the query\n"
"2. Match patterns like 'with [FormatName]', 'using [FormatName] format'\n"
"3. Add to display_format parameter with exact string match\n"
"4. Only apply to sales_crud queries\n"
)
user_prompt = f"""User query: "{query}"
Analyze the query step by step:
1. What is the PRIMARY INTENT? (product, customer, or sales operation)
2. What ACTION is being requested? (create, read, update, delete, describe)
3. What DISPLAY FORMAT is requested? (for sales queries - extract exact format name)
4. What ENTITY NAME needs to be extracted? (for delete/update operations)
5. What SPECIFIC COLUMNS are requested? (for read operations)
6. What FILTER CONDITIONS are specified? (for read operations)
DISPLAY FORMAT DETECTION (CRITICAL):
- Look for exact format names: "Data Format Conversion", "Decimal Value Formatting", "String Concatenation", "Null Value Removal/Handling"
- Match patterns: "with [FormatName]", "using [FormatName] format", "[FormatName]"
- For null handling: also match "null handling", "clean data with null"
Respond with the exact JSON format with properly extracted parameters."""
try:
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content=user_prompt)
]
resp = groq_client.invoke(messages)
raw = _clean_json(resp.content)
try:
result = json.loads(raw)
except json.JSONDecodeError:
try:
result = ast.literal_eval(raw)
except:
result = {"tool": list(available_tools.keys())[0], "action": "read", "args": {}}
# Normalize action names
if "action" in result and result["action"] in ["list", "show", "display", "view", "get"]:
result["action"] = "read"
# Enhanced parameter extraction for read operations with display_format detection
if result.get("action") == "read" and result.get("tool") == "sales_crud":
args = result.get("args", {})
# Extract display_format if not already extracted
if "display_format" not in args:
import re
# Look for exact display format patterns
display_format_patterns = [
(r'Data Format Conversion', 'Data Format Conversion'),
(r'Decimal Value Formatting', 'Decimal Value Formatting'),
(r'String Concatenation', 'String Concatenation'),
(r'Null Value Removal/Handling', 'Null Value Removal/Handling'),
(r'null handling', 'Null Value Removal/Handling'),
(r'clean.*?null.*?handling', 'Null Value Removal/Handling'),
(r'handle.*?null.*?values', 'Null Value Removal/Handling'),
]
for pattern, format_name in display_format_patterns:
if re.search(pattern, query, re.IGNORECASE):
args["display_format"] = format_name
print(f"DEBUG: Extracted display_format '{format_name}' from query '{query}'")
break
# Extract columns if not already extracted
if "columns" not in args:
import re
# Look for column specification patterns
column_patterns = [
r'(?:show|display|get|select)\s+only\s+(.+?)(?:\s+from|\s+where|\s*$)',
r'(?:show|display|get|select)\s+(.+?)\s+(?:from|where)',
]
for pattern in column_patterns:
match = re.search(pattern, query, re.IGNORECASE)
if match:
columns_text = match.group(1).strip()
# Clean up and standardize column names
if 'and' in columns_text or ',' in columns_text:
# Multiple columns
columns_list = re.split(r'[,\s]+and\s+|,\s*', columns_text)
cleaned_columns = []
for col in columns_list:
col = col.strip().lower().replace(' ', '_')
# Map common variations
if col in ['name', 'customer']:
cleaned_columns.append('customer_first_name')
elif col in ['price', 'total', 'amount']:
cleaned_columns.append('total_price')
elif col in ['product']:
cleaned_columns.append('product_name')
elif col in ['date']:
cleaned_columns.append('sale_date')
elif col in ['email']:
cleaned_columns.append('customer_email')
else:
cleaned_columns.append(col)
if cleaned_columns:
args["columns"] = ','.join(cleaned_columns)
break
# Extract where_condition if not already extracted
if "where_condition" not in args:
import re
# Look for filtering conditions
where_patterns = [
(r'where\s+price\s*>\s*(\d+)', lambda m: f"s.total_price > {m.group(1)}"),
(r'where\s+quantity\s*>=?\s*(\d+)', lambda m: f"s.quantity >= {m.group(1)}"),
(r'for\s+customer\s+([A-Za-z\s]+)', lambda m: f"c.FirstName = '{m.group(1).strip()}'"),
]
for pattern, formatter in where_patterns:
match = re.search(pattern, query, re.IGNORECASE)
if match:
args["where_condition"] = formatter(match)
print(f"DEBUG: Extracted where_condition '{args['where_condition']}' from query '{query}'")
break
result["args"] = args
# Keep all your existing parameter extraction logic for other operations...
# [Rest of your existing code for delete, update, create operations]
# Validate and clean args
if "args" in result and isinstance(result["args"], dict):
cleaned_args = validate_and_clean_parameters(result.get("tool"), result["args"])
result["args"] = cleaned_args
# Validate tool selection
if "tool" in result and result["tool"] not in available_tools:
result["tool"] = list(available_tools.keys())[0]
# Debug output
print(f"DEBUG: Final parsed result for '{query}': {result}")
return result
except Exception as e:
return {
"tool": list(available_tools.keys())[0] if available_tools else None,
"action": "read",
"args": {},
"error": f"Failed to parse query: {str(e)}"
}
if not available_tools:
return {"error": "No tools available"}
# Build comprehensive tool information for the LLM
tool_info = []
for tool_name, tool_desc in available_tools.items():
tool_info.append(f"- **{tool_name}**: {tool_desc}")
tools_description = "\n".join(tool_info)
system_prompt = (
"You are an intelligent database router for CRUD operations. "
"Your job is to analyze the user's query and select the most appropriate tool based on the context and data being requested.\n\n"
"RESPONSE FORMAT:\n"
"Reply with exactly one JSON object: {\"tool\": string, \"action\": string, \"args\": object}\n\n"
"ACTION MAPPING:\n"
"- 'read': for viewing, listing, showing, displaying, or getting records\n"
"- 'create': for adding, inserting, or creating NEW records\n"
"- 'update': for modifying, changing, or updating existing records\n"
"- 'delete': for removing, deleting, or destroying records\n"
"- 'describe': for showing table structure, schema, or column information\n\n"
"CRITICAL TOOL SELECTION RULES:\n"
"\n"
"1. **PRODUCT QUERIES** → Use 'postgresql_crud':\n"
" - 'list products', 'show products', 'display products'\n"
" - 'product inventory', 'product catalog', 'product information'\n"
" - 'add product', 'create product', 'new product'\n"
" - 'update product', 'change product price', 'modify product'\n"
" - 'delete product', 'remove product', 'delete [ProductName]'\n"
" - Any query primarily about products, pricing, or inventory\n"
"\n"
"2. **CUSTOMER QUERIES** → Use 'sqlserver_crud':\n"
" - 'list customers', 'show customers', 'display customers'\n"
" - 'customer information', 'customer details'\n"
" - 'add customer', 'create customer', 'new customer'\n"
" - 'update customer', 'change customer email', 'modify customer'\n"
" - 'delete customer', 'remove customer', 'delete [CustomerName]'\n"
" - Any query primarily about customers, names, or emails\n"
"\n"
"3. **SALES/TRANSACTION QUERIES** → Use 'sales_crud':\n"
" - 'list sales', 'show sales', 'sales data', 'transactions'\n"
" - 'sales report', 'revenue data', 'purchase history'\n"
" - 'who bought what', 'customer purchases'\n"
" - Cross-database queries combining customer + product + sales info\n"
" - 'create sale', 'add sale', 'new transaction'\n"
" - Any query asking for combined data from multiple tables\n"
"\n"
"ENHANCED DELETE OPERATION EXTRACTION:\n"
"\n"
"For DELETE operations, extract the entity name from these patterns:\n"
"\n"
"PRODUCT DELETE PATTERNS:\n"
"- 'delete [ProductName]' → {\"name\": \"ProductName\"}\n"
"- 'delete product [ProductName]' → {\"name\": \"ProductName\"}\n"
"- 'remove [ProductName]' → {\"name\": \"ProductName\"}\n"
"- 'remove product [ProductName]' → {\"name\": \"ProductName\"}\n"
"\n"
"CUSTOMER DELETE PATTERNS:\n"
"- 'delete [CustomerName]' → {\"name\": \"CustomerName\"}\n"
"- 'delete customer [CustomerName]' → {\"name\": \"CustomerName\"}\n"
"- 'remove [CustomerName]' → {\"name\": \"CustomerName\"}\n"
"- 'remove customer [CustomerName]' → {\"name\": \"CustomerName\"}\n"
"\n"
"EXAMPLES OF CORRECT DELETE EXTRACTION:\n"
"\n"
"Query: 'delete Widget'\n"
"→ {\"tool\": \"postgresql_crud\", \"action\": \"delete\", \"args\": {\"name\": \"Widget\"}}\n"
"\n"
"Query: 'delete product Gadget'\n"
"→ {\"tool\": \"postgresql_crud\", \"action\": \"delete\", \"args\": {\"name\": \"Gadget\"}}\n"
"\n"
"Query: 'remove Tool'\n"
"→ {\"tool\": \"postgresql_crud\", \"action\": \"delete\", \"args\": {\"name\": \"Tool\"}}\n"
"\n"
"Query: 'delete customer Alice'\n"
"→ {\"tool\": \"sqlserver_crud\", \"action\": \"delete\", \"args\": {\"name\": \"Alice\"}}\n"
"\n"
"Query: 'delete Alice Johnson'\n"
"→ {\"tool\": \"sqlserver_crud\", \"action\": \"delete\", \"args\": {\"name\": \"Alice Johnson\"}}\n"
"\n"
"Query: 'remove customer Bob Smith'\n"
"→ {\"tool\": \"sqlserver_crud\", \"action\": \"delete\", \"args\": {\"name\": \"Bob Smith\"}}\n"
"\n"
"ENHANCED UPDATE OPERATION EXTRACTION:\n"
"\n"
"For UPDATE operations, extract both the entity name and new value:\n"
"\n"
"PRODUCT UPDATE PATTERNS:\n"
"- 'update price of [ProductName] to [NewPrice]' → {\"name\": \"ProductName\", \"new_price\": NewPrice}\n"
"- 'change price of [ProductName] to [NewPrice]' → {\"name\": \"ProductName\", \"new_price\": NewPrice}\n"
"- 'set [ProductName] price to [NewPrice]' → {\"name\": \"ProductName\", \"new_price\": NewPrice}\n"
"\n"
"CUSTOMER UPDATE PATTERNS:\n"
"- 'update email of [CustomerName] to [NewEmail]' → {\"name\": \"CustomerName\", \"new_email\": \"NewEmail\"}\n"
"- 'change email of [CustomerName] to [NewEmail]' → {\"name\": \"CustomerName\", \"new_email\": \"NewEmail\"}\n"
"- 'set [CustomerName] email to [NewEmail]' → {\"name\": \"CustomerName\", \"new_email\": \"NewEmail\"}\n"
"\n"
"ENHANCED COLUMN SELECTION EXTRACTION:\n"
"\n"
"For queries that request specific columns, extract them into the 'columns' parameter:\n"
"\n"
"COLUMN EXTRACTION PATTERNS:\n"
"- 'show customer_name, total_price' → {\"columns\": \"customer_name,total_price\"}\n"
"- 'display customer_name and total_price' → {\"columns\": \"customer_name,total_price\"}\n"
"- 'get name and price' → {\"columns\": \"customer_name,total_price\"}\n"
"- 'show only customer and price' → {\"columns\": \"customer_name,total_price\"}\n"