forked from lokit-s/mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient1.py
More file actions
1898 lines (1665 loc) · 79.9 KB
/
client1.py
File metadata and controls
1898 lines (1665 loc) · 79.9 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", "openai/gpt-oss-20b")
)
# ========== 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;
}
/* Visualization styles */
.visualization-container {
margin: 20px 0;
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
background: #f9f9f9;
}
.visualization-title {
font-size: 1.2rem;
font-weight: bold;
margin-bottom: 10px;
color: #333;
}
</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)
logo_base64 = get_image_base64("llm.png")
st.markdown(
f"""
<div class="sidebar-logo-row">
<img src="https://media.licdn.com/dms/image/v2/D560BAQFIon13R1UG4g/company-logo_200_200/company-logo_200_200/0/1733990910443/llm_at_scale_logo?e=2147483647&v=beta&t=WtAgFOcGQuTS0aEIqZhNMzWraHwL6FU0z5EPyPrty04" title="Logo" style="width: 50px; height: 50px;">
<img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/googlecloud/googlecloud-original.svg" title="Google Cloud" style="width: 50px; height: 50px;">
<img src="https://a0.awsstatic.com/libra-css/images/logos/aws_logo_smile_1200x630.png" title="AWS" style="width: 50px; height: 50px;">
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a8/Microsoft_Azure_Logo.svg" title="Azure Cloud" style="width: 50px; height: 50px;">
</div>
""",
unsafe_allow_html=True
)
# ========== LOGO/HEADER FOR MAIN AREA ==========
logo_path = "llm.png"
logo_base64 = get_image_base64(logo_path) if os.path.exists(logo_path) else ""
if logo_base64:
st.markdown(
f"""
<div style='display: flex; flex-direction: column; align-items: center; margin-bottom:20px;'>
<img src='data:image/png;base64,{logo_base64}' 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"] = ""
# Initialize visualization state
if "visualizations" not in st.session_state:
st.session_state.visualizations = []
# ========== 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()
import requests
def call_mcp_tool(tool_name: str, operation: str, args: dict) -> dict:
"""
Synchronous helper that calls the MCP server REST endpoint for a tool.
Adjust URL/path depending on your FastMCP HTTP transport.
"""
url = st.session_state.get("MCP_SERVER_URL", "http://localhost:8000") + f"/call_tool"
payload = {"tool": tool_name, "operation": operation, "args": args}
try:
resp = requests.post(url, json=payload, timeout=15)
resp.raise_for_status()
return resp.json()
except Exception as e:
return {"sql": None, "result": f"❌ error calling MCP tool: {e}"}
# ========== 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, history_limit: int = 10) -> str:
"""Generate LLM response based on operation result with context (includes chat history)."""
# collect last N messages from session (if available)
messages_for_llm = []
history = st.session_state.get("messages", [])[-history_limit:]
for m in history:
role = m.get("role", "user")
content = m.get("content", "")
# convert to System/Human/Assistant roles for your LLM client
if role == "assistant":
messages_for_llm.append(HumanMessage(content=f"(assistant) {content}"))
else:
messages_for_llm.append(HumanMessage(content=f"(user) {content}"))
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"""
User asked: "{user_query}"
Operation: {action}
Tool used: {tool}
Result: {json.dumps(operation_result, indent=2)}
Please respond naturally and reference prior conversation context where helpful.
"""
try:
messages = [SystemMessage(content=system_prompt)] + messages_for_llm + [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}."
# ========== VISUALIZATION GENERATOR ==========
def generate_visualization(data: any, user_query: str, tool: str) -> tuple:
"""
Generate JavaScript visualization code based on data and query.
Streams code live while generating, then renders.
Returns tuple of (HTML/JS code for the visualization, raw code).
"""
# Prepare context for the LLM
context = {
"user_query": user_query,
"tool": tool,
"data_type": type(data).__name__,
"data_sample": data[:5] if isinstance(data, list) and len(data) > 0 else data
}
system_prompt = """
You are a JavaScript visualization expert. Generate interactive charts using Chart.js.
Analyze the data structure and user query to determine the most appropriate visualization. Make it aesthetic and informative.
RULES:
1. Return ONLY raw HTML and JavaScript code
2. Use Chart.js for visualizations (include CDN link)
3. Make it responsive but set fixed height for charts (max 400px)
4. Include appropriate titles and labels based on the user query
5. Handle both tabular data and simple results
6. No markdown, no explanations, just code
7. If data is complex, create multiple chart types (bar, line, pie) but limit to 2-5 charts
8. Use container div with fixed height and overflow: auto
9. Add 'chart-container' class to all chart containers
"""
user_prompt = f"""
Create an interactive visualization for this data:
User Query: "{user_query}"
Tool Used: {tool}
Data Type: {context['data_type']}
Data Sample: {json.dumps(context['data_sample'], indent=2)}
Generate a comprehensive visualization that helps understand the data.
Focus on the most important insights from the query.
Make sure charts have fixed heights and don't overflow.
"""
try:
# Prepare messages
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content=user_prompt)
]
# Placeholder to show live code generation
placeholder = st.empty()
code_accum = ""
# Stream response tokens
for event in groq_client.stream(messages):
token = getattr(event, "content", "")
if token:
code_accum += token
placeholder.code(code_accum, language="html")
visualization_code = code_accum.strip()
# Return both the code and the rendered HTML
return visualization_code, visualization_code
except Exception as e:
# Fallback to a simple table if visualization generation fails
if isinstance(data, list) and len(data) > 0:
fallback_code = f"""
<div class="visualization-container" style="height: 400px; overflow: auto;">
<div class="visualization-title">Data Table</div>
<div id="table-container"></div>
</div>
<script>
const data = {json.dumps(data)};
let tableHtml = '<table border="1" style="width:100%; border-collapse: collapse;">';
// Add headers
tableHtml += '<tr>';
Object.keys(data[0]).forEach(key => {{
tableHtml += `<th style="padding: 8px; background: #f2f2f2;">${{key}}</th>`;
}});
tableHtml += '</tr>';
// Add rows
data.forEach(row => {{
tableHtml += '<tr>';
Object.values(row).forEach(value => {{
tableHtml += `<td style="padding: 8px;">${{value}}</td>`;
}});
tableHtml += '</tr>';
}});
tableHtml += '</table>';
document.getElementById('table-container').innerHTML = tableHtml;
</script>
"""
else:
fallback_code = f"""
<div class="visualization-container" style="height: 200px; overflow: auto;">
<div class="visualization-title">Result</div>
<p>{str(data)}</p>
</div>
"""
return fallback_code, fallback_code
# Add this CSS for the split layout
st.markdown("""
<style>
.split-container {
display: flex;
width: 100%;
gap: 20px;
margin: 20px 0;
}
.code-panel {
flex: 1;
background: #f8f9fa;
border-radius: 8px;
padding: 15px;
border: 1px solid #e9ecef;
max-height: 500px;
overflow-y: auto;
}
.viz-panel {
flex: 1;
background: #f8f9fa;
border-radius: 8px;
padding: 15px;
border: 1px solid #e9ecef;
max-height: 500px;
overflow-y: auto;
}
.code-header, .viz-header {
font-weight: bold;
margin-bottom: 10px;
color: #333;
display: flex;
justify-content: space-between;
align-items: center;
}
.copy-button {
background: #4286f4;
color: white;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
font-size: 0.8rem;
}
.copy-button:hover {
background: #397dd2;
}
.chart-container {
height: 350px !important;
margin-bottom: 20px;
}
.visualization-container {
height: 400px;
overflow: auto;
}
</style>
""", unsafe_allow_html=True)
def parse_user_query(query: str, available_tools: dict) -> dict:
"""Enhanced parse user query with better DELETE operation handling"""
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"
"- 'analyze': for analytical queries and statistical reports (calllogs_crud only)\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"
"4. **CARE PLAN QUERIES** → Use 'careplan_crud':\n"
" - 'show care plans', 'list patients', 'display care plans', 'patient records'\n"
" - 'list care plans with name John', 'patients with diabetes'\n"
" - 'show care plan details', 'display patient information'\n"
" - 'patients needing housing assistance', 'care plans with employment status'\n"
" - 'reentry care plans', 'general care plans'\n"
" - Any query related to healthcare records, patient information, or care management\n\n"
"5. **CALL LOG ANALYSIS QUERIES** → Use 'calllogs_crud':\n"
" - 'analyze call logs', 'show call statistics', 'call center metrics'\n"
" - 'agent performance', 'sentiment analysis', 'issue frequency'\n"
" - 'call volume trends', 'escalation analysis', 'resolution rates'\n"
" - 'show calls by agent [AgentName]', 'calls with negative sentiment'\n"
" - 'call duration analysis', 'wait time statistics'\n"
" - 'top issue categories', 'service quality metrics'\n"
" - Use 'operation': 'analyze' for analytical reports\n"
" - Use 'operation': 'read' for raw call log data\n"
" - Any query related to call logs, agent performance, or customer service metrics\n\n"
"**ENHANCED CARE PLAN FIELD MAPPING:**\n"
"The CarePlan table now includes comprehensive real-world fields:\n"
"- Base: 'actual_release_date', 'name_of_youth', 'race_ethnicity', 'medi_cal_id_number'\n"
"- Health: 'health_screenings', 'health_assessments', 'chronic_conditions', 'prescribed_medications'\n"
"- Reentry: 'housing', 'employment', 'income_benefits', 'transportation', 'life_skills'\n"
"- Clinical: 'screenings', 'clinical_assessments', 'treatment_history', 'scheduled_appointments'\n"
"- Support: 'family_children', 'emergency_contacts', 'service_referrals', 'court_dates'\n"
"- Equipment: 'home_modifications', 'durable_medical_equipment'\n"
"- Metadata: 'care_plan_type', 'status', 'notes'\n\n"
"**ETL & DISPLAY FORMATTING RULES:**\n"
"For any data formatting requests (e.g., rounding decimals, changing date formats, handling nulls), "
"you MUST use the `display_format` parameter within the `sales_crud` tool.\n\n"
"1. **DECIMAL FORMATTING:**\n"
" - If the user asks to 'round', 'format to N decimal places', or mentions 'decimals'.\n"
" - Use: {\"display_format\": \"Decimal Value Formatting\"}\n"
" - **Example Query:** 'show sales with 2 decimal places'\n"
" - **→ Correct Tool Call:** {\"tool\": \"sales_crud\", \"action\": \"read\", \"args\": {\"display_format\": \"Decimal Value Formatting\"}}\n"
"2. **DATE FORMATTING:**\n"
" - If the user asks to 'format date', 'show date as YYYY-MM-DD', or similar.\n"
" - Use: {\"display_format\": \"Data Format Conversion\"}\n"
" - **Example Query:** 'show sales with formatted dates'\n"
" - **→ Correct Tool Call:** {\"tool\": \"sales_crud\", \"action\": \"read\", \"args\": {\"display_format\": \"Data Format Conversion\"}}\n"
"3. **NULL VALUE HANDLING:**\n"
" - If the user asks to 'remove nulls', 'replace empty values', or 'handle missing data'.\n"
" - Use: {\"display_format\": \"Null Value Removal/Handling\"}\n"
" - **Example Query:** 'show sales but remove records with missing info'\n"
" - **→ Correct Tool Call:** {\"tool\": \"sales_crud\", \"action\": \"read\", \"args\": {\"display_format\": \"Null Value Removal/Handling\"}}\n"
"4. **STRING CONCATENATION:**\n"
" - If the user asks to 'combine names', 'create a full description', or 'show full name'.\n"
" - Use: {\"display_format\": \"String Concatenation\"}\n"
" - **Example Query:** 'show sales with customer full names'\n"
" - **→ Correct Tool Call:** {\"tool\": \"sales_crud\", \"action\": \"read\", \"args\": {\"display_format\": \"String Concatenation\"}}\n"
"5. **CARE PLAN COLUMN FILTERING:**\n"
" - If the user asks to 'show only name and chronic conditions', 'remove address', or 'exclude phone'.\n"
" - Use: `columns` field in args with positive or negative column names.\n"
" - **Example Query:** 'show only name and chronic conditions from care plans'\n"
" - **→ Correct Tool Call:** {\"tool\": \"careplan_crud\", \"action\": \"read\", \"args\": {\"columns\": \"name_of_youth,chronic_conditions\"}}\n"
" - **Example Query:** 'show care plans without address and phone'\n"
" - **→ Correct Tool Call:** {\"tool\": \"careplan_crud\", \"action\": \"read\", \"args\": {\"columns\": \"*,-residential_address,-telephone\"}}\n"
"6. **CARE PLAN FILTERING BY TEXT OR VALUE:**\n"
" - If user asks 'care plans mentioning diabetes in chronic conditions', use LIKE\n"
" - Use: {\"where_clause\": \"chronic_conditions LIKE '%diabetes%'\"}\n"
" - **Example Query:** 'list patients with diabetes'\n"
" - **→ Correct Tool Call:** {\"tool\": \"careplan_crud\", \"action\": \"read\", \"args\": {\"where_clause\": \"chronic_conditions LIKE '%diabetes%'\"}}\n"
" - **Example Query:** 'care plans where name is John'\n"
" - **→ Correct Tool Call:** {\"tool\": \"careplan_crud\", \"action\": \"read\", \"args\": {\"where_clause\": \"name_of_youth = 'John'\"}}\n"
" - **Example Query:** 'show patients needing housing assistance'\n"
" - **→ Correct Tool Call:** {\"tool\": \"careplan_crud\", \"action\": \"read\", \"args\": {\"where_clause\": \"housing LIKE '%assistance%' OR housing = 'Homeless'\"}}\n"
"7. **CARE PLAN TYPE FILTERING:**\n"
" - If user asks for 'reentry care plans' or 'general care plans'\n"
" - Use: {\"care_plan_type\": \"Reentry Care Plan\"} or {\"care_plan_type\": \"General Care Plan\"}\n"
" - **Example Query:** 'show reentry care plans'\n"
" - **→ Correct Tool Call:** {\"tool\": \"careplan_crud\", \"action\": \"read\", \"args\": {\"care_plan_type\": \"Reentry Care Plan\"}}\n"
"8. **CALL LOGS ANALYSIS TYPES:**\n"
" - sentiment_by_agent: Agent sentiment performance\n"
" - issue_frequency: Most common issues\n"
" - call_volume_trends: Daily call trends\n"
" - escalation_analysis: Escalation rates by issue\n"
" - agent_performance: Comprehensive agent metrics\n"
" - **Example Query:** 'analyze agent performance'\n"
" - **→ Correct Tool Call:** {\"tool\": \"calllogs_crud\", \"action\": \"analyze\", \"args\": {\"analysis_type\": \"agent_performance\"}}\n"
"9. **CALL LOGS FILTERING:**\n"
" - Use 'agent_name', 'issue_category', 'sentiment_threshold' for filtering\n"
" - **Example Query:** 'show calls with negative sentiment'\n"
" - **→ Correct Tool Call:** {\"tool\": \"calllogs_crud\", \"action\": \"read\", \"args\": {\"sentiment_threshold\": -0.1}}\n"
" - **Example Query:** 'calls handled by Sarah Chen'\n"
" - **→ Correct Tool Call:** {\"tool\": \"calllogs_crud\", \"action\": \"read\", \"args\": {\"agent_name\": \"Sarah Chen\"}}\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 ENTITY NAME needs to be extracted? (for delete/update operations)
4. What SPECIFIC COLUMNS are requested? (for read operations - extract into 'columns' parameter)
5. What FILTER CONDITIONS are specified? (for read operations - extract into 'where_clause' parameter)
6. What PARAMETERS need to be extracted from the natural language?
ENTITY NAME EXTRACTION GUIDELINES (CRITICAL FOR DELETE/UPDATE):
- For "delete Widget" → extract "Widget" and put in 'name' parameter
- For "delete product Gadget" → extract "Gadget" and put in 'name' parameter
- For "delete customer Alice" → extract "Alice" and put in 'name' parameter
- For "update price of Tool to 30" → extract "Tool" and put in 'name' parameter, extract "30" and put in 'new_price'
COLUMN EXTRACTION GUIDELINES:
- Look for patterns like "show X, Y", "display X and Y", "get X, Y from Z"
- Extract only the column names, map them to standard names
- Put them in a comma-separated string in the 'columns' parameter
WHERE CLAUSE EXTRACTION GUIDELINES:
- Look for filtering conditions like "exceed", "above", "greater than", "with price over"
- Convert natural language to SQL-like conditions
- Handle currency symbols and numbers properly
- Put the condition in the 'where_clause' parameter
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 DELETE and UPDATE operations
if result.get("action") in ["delete", "update"]:
args = result.get("args", {})
# Extract entity name for delete/update operations if not already extracted
if "name" not in args:
import re
# Enhanced regex patterns for delete operations
delete_patterns = [
r'(?:delete|remove)\s+customer\s+([A-Za-z]+(?:\s+[A-Za-z]+)?)',
r'(?:delete|remove)\s+product\s+([A-Za-z]+(?:\s+[A-Za-z]+)?)',