Bhanumani12 commited on
Commit
9f00d49
·
verified ·
1 Parent(s): fe32a7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -37
app.py CHANGED
@@ -5,7 +5,7 @@ from datetime import datetime
5
  from transformers import pipeline
6
  from simple_salesforce import Salesforce, SalesforceLogin
7
  from dotenv import load_dotenv
8
- import xml.etree.ElementTree as ET # NEW: for parsing metadata
9
 
10
  # ---------- Load Environment Variables ----------
11
  load_dotenv()
@@ -35,22 +35,8 @@ severities = {
35
  "Best Practice": "Low"
36
  }
37
 
38
- # ---------- Knowledge Base ----------
39
- salesforce_knowledge_base = {
40
- "governor limits soql": "In Salesforce, the governor limit for SOQL queries is 100 per synchronous transaction and 200 per asynchronous transaction.",
41
- "governor limits dml": "The governor limit for DML statements is 150 per transaction.",
42
- "bulkify apex trigger": "...",
43
- "soql injection": "...",
44
- "lwc best practices": "...",
45
- "batch apex": "..."
46
- }
47
-
48
  # ---------- Load QnA Model ----------
49
- try:
50
- qa_pipeline = pipeline("text2text-generation", model="google/flan-t5-large")
51
- except Exception as e:
52
- print(f"Model loading error: {e}. Falling back to flan-t5-base.")
53
- qa_pipeline = pipeline("text2text-generation", model="google/flan-t5-base")
54
 
55
  # ---------- Logging ----------
56
  def log_to_console(data, log_type):
@@ -104,7 +90,7 @@ def analyze_code(code):
104
 
105
  return issue_type, suggestion, severity
106
 
107
- # ---------- Metadata Validator (Updated with dynamic XML parsing) ----------
108
  def validate_metadata(metadata, admin_id=None):
109
  if not metadata.strip():
110
  return "No metadata provided.", "", ""
@@ -115,7 +101,6 @@ def validate_metadata(metadata, admin_id=None):
115
 
116
  try:
117
  root = ET.fromstring(metadata)
118
- # Detect missing <description> tag
119
  description_found = any(elem.tag.endswith('description') for elem in root)
120
 
121
  if not description_found:
@@ -124,7 +109,6 @@ def validate_metadata(metadata, admin_id=None):
124
  else:
125
  issue = "Unused field detected"
126
  recommendation = "Remove it to improve performance or document its purpose."
127
-
128
  except Exception as e:
129
  issue = "Invalid XML"
130
  recommendation = f"Could not parse metadata XML. Error: {str(e)}"
@@ -156,7 +140,7 @@ def validate_metadata(metadata, admin_id=None):
156
 
157
  return mtype, issue, recommendation
158
 
159
- # ---------- Salesforce Chatbot ----------
160
  conversation_history = []
161
 
162
  def salesforce_chatbot(query, history=[]):
@@ -166,38 +150,42 @@ def salesforce_chatbot(query, history=[]):
166
 
167
  salesforce_keywords = [
168
  "apex", "soql", "trigger", "lwc", "aura", "visualforce", "salesforce", "governor limits",
169
- "dml", "metadata", "batch apex", "queueable", "future method", "api", "sfdc"
170
  ]
171
 
172
  if not any(keyword.lower() in query.lower() for keyword in salesforce_keywords):
173
  return "Please ask a Salesforce-related question."
174
 
175
- query_key = query.lower().strip()
176
- for kb_key, kb_answer in salesforce_knowledge_base.items():
177
- if kb_key in query_key:
178
- conversation_history.append((query, kb_answer))
179
- conversation_history = conversation_history[-6:]
180
- log_to_console({"Question": query, "Answer": kb_answer}, "Chatbot Query")
181
- return kb_answer
182
-
183
  history_summary = "\n".join([f"User: {q}\nAssistant: {a}" for q, a in conversation_history[-4:]])
 
184
  prompt = f"""
185
- You are an expert Salesforce developer...
 
 
 
 
 
 
 
 
 
186
 
187
  Conversation History:
188
  {history_summary}
189
 
190
- Question: {query.strip()}
191
- Answer:
192
  """
193
 
194
  try:
195
  result = qa_pipeline(prompt, max_new_tokens=1024, do_sample=False, temperature=0.1, top_k=50)
196
  output = result[0]["generated_text"].strip()
197
- if output.startswith("Answer:"):
198
- output = output[7:].strip()
199
- if len(output) < 20:
200
- output = f"I'm sorry, I couldn't find a precise answer for '{query}'. Please refer to Salesforce docs."
 
 
201
  conversation_history.append((query, output))
202
  conversation_history = conversation_history[-6:]
203
  log_to_console({"Question": query, "Answer": output}, "Chatbot Query")
@@ -227,7 +215,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
227
 
228
  with gr.Tab("Salesforce Chatbot"):
229
  chatbot_output = gr.Chatbot(label="Conversation History", height=400)
230
- query_input = gr.Textbox(label="Your Question", placeholder="e.g., How do I bulkify an Apex trigger?")
231
  with gr.Row():
232
  chatbot_button = gr.Button("Ask")
233
  clear_button = gr.Button("Clear Chat")
 
5
  from transformers import pipeline
6
  from simple_salesforce import Salesforce, SalesforceLogin
7
  from dotenv import load_dotenv
8
+ import xml.etree.ElementTree as ET
9
 
10
  # ---------- Load Environment Variables ----------
11
  load_dotenv()
 
35
  "Best Practice": "Low"
36
  }
37
 
 
 
 
 
 
 
 
 
 
 
38
  # ---------- Load QnA Model ----------
39
+ qa_pipeline = pipeline("text2text-generation", model="google/flan-t5-large")
 
 
 
 
40
 
41
  # ---------- Logging ----------
42
  def log_to_console(data, log_type):
 
90
 
91
  return issue_type, suggestion, severity
92
 
93
+ # ---------- Metadata Validator ----------
94
  def validate_metadata(metadata, admin_id=None):
95
  if not metadata.strip():
96
  return "No metadata provided.", "", ""
 
101
 
102
  try:
103
  root = ET.fromstring(metadata)
 
104
  description_found = any(elem.tag.endswith('description') for elem in root)
105
 
106
  if not description_found:
 
109
  else:
110
  issue = "Unused field detected"
111
  recommendation = "Remove it to improve performance or document its purpose."
 
112
  except Exception as e:
113
  issue = "Invalid XML"
114
  recommendation = f"Could not parse metadata XML. Error: {str(e)}"
 
140
 
141
  return mtype, issue, recommendation
142
 
143
+ # ---------- Salesforce Chatbot (Final Improved Prompt) ----------
144
  conversation_history = []
145
 
146
  def salesforce_chatbot(query, history=[]):
 
150
 
151
  salesforce_keywords = [
152
  "apex", "soql", "trigger", "lwc", "aura", "visualforce", "salesforce", "governor limits",
153
+ "dml", "metadata", "batch apex", "queueable", "future method", "api", "sfdc", "heap", "limits"
154
  ]
155
 
156
  if not any(keyword.lower() in query.lower() for keyword in salesforce_keywords):
157
  return "Please ask a Salesforce-related question."
158
 
 
 
 
 
 
 
 
 
159
  history_summary = "\n".join([f"User: {q}\nAssistant: {a}" for q, a in conversation_history[-4:]])
160
+
161
  prompt = f"""
162
+ You are a certified Salesforce developer and architect. You answer Salesforce questions with 100% accuracy and clarity, using official platform knowledge.
163
+
164
+ Guidelines:
165
+ - Always give answers that are at least 2 full lines long.
166
+ - When asked about Apex limits (e.g., DML, SOQL, heap), always:
167
+ - Mention the numeric limit (e.g., 150 DML statements)
168
+ - Include the transaction context (sync/async)
169
+ - Suggest using monitoring methods like Limits.getDMLStatements()
170
+ - Avoid making up numbers — if unsure, suggest Trailhead or official docs.
171
+ - Format clearly, using bullet points or code if helpful.
172
 
173
  Conversation History:
174
  {history_summary}
175
 
176
+ User: {query.strip()}
177
+ Assistant:
178
  """
179
 
180
  try:
181
  result = qa_pipeline(prompt, max_new_tokens=1024, do_sample=False, temperature=0.1, top_k=50)
182
  output = result[0]["generated_text"].strip()
183
+ if output.startswith("Assistant:"):
184
+ output = output.replace("Assistant:", "").strip()
185
+
186
+ if len(output.split()) < 20:
187
+ output += "\n\nPlease refer to: https://developer.salesforce.com/docs"
188
+
189
  conversation_history.append((query, output))
190
  conversation_history = conversation_history[-6:]
191
  log_to_console({"Question": query, "Answer": output}, "Chatbot Query")
 
215
 
216
  with gr.Tab("Salesforce Chatbot"):
217
  chatbot_output = gr.Chatbot(label="Conversation History", height=400)
218
+ query_input = gr.Textbox(label="Your Question", placeholder="e.g., How many DML operations are allowed in Apex?")
219
  with gr.Row():
220
  chatbot_button = gr.Button("Ask")
221
  clear_button = gr.Button("Clear Chat")