Bhanumani12 commited on
Commit
648f4b9
·
verified ·
1 Parent(s): e7aff49

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -15
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,7 +35,7 @@ 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.",
@@ -104,7 +104,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 +115,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 +123,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 +154,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,11 +164,11 @@ 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():
@@ -181,23 +179,34 @@ def salesforce_chatbot(query, history=[]):
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 +236,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
+ # ---------- Mock 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.",
 
104
 
105
  return issue_type, suggestion, severity
106
 
107
+ # ---------- Metadata Validator ----------
108
  def validate_metadata(metadata, admin_id=None):
109
  if not metadata.strip():
110
  return "No metadata provided.", "", ""
 
115
 
116
  try:
117
  root = ET.fromstring(metadata)
 
118
  description_found = any(elem.tag.endswith('description') for elem in root)
119
 
120
  if not description_found:
 
123
  else:
124
  issue = "Unused field detected"
125
  recommendation = "Remove it to improve performance or document its purpose."
 
126
  except Exception as e:
127
  issue = "Invalid XML"
128
  recommendation = f"Could not parse metadata XML. Error: {str(e)}"
 
154
 
155
  return mtype, issue, recommendation
156
 
157
+ # ---------- Salesforce Chatbot (Updated Prompt) ----------
158
  conversation_history = []
159
 
160
  def salesforce_chatbot(query, history=[]):
 
164
 
165
  salesforce_keywords = [
166
  "apex", "soql", "trigger", "lwc", "aura", "visualforce", "salesforce", "governor limits",
167
+ "dml", "metadata", "batch apex", "queueable", "future method", "api", "sfdc", "heap", "limits"
168
  ]
169
 
170
  if not any(keyword.lower() in query.lower() for keyword in salesforce_keywords):
171
+ return "Please ask a Salesforce-related question (e.g., Apex, SOQL, LWC, limits, etc)."
172
 
173
  query_key = query.lower().strip()
174
  for kb_key, kb_answer in salesforce_knowledge_base.items():
 
179
  return kb_answer
180
 
181
  history_summary = "\n".join([f"User: {q}\nAssistant: {a}" for q, a in conversation_history[-4:]])
182
+
183
  prompt = f"""
184
+ You are an expert Salesforce developer and certified architect. You provide 100% accurate, clear, and practical answers for topics like Apex, SOQL, LWC, governor limits, triggers, metadata, and more.
185
+
186
+ When answering:
187
+ - ALWAYS give at least 2 lines of explanation.
188
+ - Be clear, concise, and technically correct.
189
+ - Mention official Salesforce limits if applicable.
190
+ - Use bullet points or code snippets when helpful.
191
+ - Avoid speculation — if unknown, say so and suggest Trailhead or official docs.
192
+ - Examples must be realistic and follow best practices.
193
 
194
  Conversation History:
195
  {history_summary}
196
 
197
+ User: {query.strip()}
198
+ Assistant:
199
  """
200
 
201
  try:
202
  result = qa_pipeline(prompt, max_new_tokens=1024, do_sample=False, temperature=0.1, top_k=50)
203
  output = result[0]["generated_text"].strip()
204
+ if output.startswith("Assistant:"):
205
+ output = output.replace("Assistant:", "").strip()
206
+
207
  if len(output) < 20:
208
+ output = f"I'm sorry, I couldn't generate a detailed answer for '{query}'. You can also check https://developer.salesforce.com/docs."
209
+
210
  conversation_history.append((query, output))
211
  conversation_history = conversation_history[-6:]
212
  log_to_console({"Question": query, "Answer": output}, "Chatbot Query")
 
236
 
237
  with gr.Tab("Salesforce Chatbot"):
238
  chatbot_output = gr.Chatbot(label="Conversation History", height=400)
239
+ query_input = gr.Textbox(label="Your Question", placeholder="e.g., What is heap size in Apex?")
240
  with gr.Row():
241
  chatbot_button = gr.Button("Ask")
242
  clear_button = gr.Button("Clear Chat")