Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
| 9 |
|
| 10 |
# ---------- Load Environment Variables ----------
|
| 11 |
load_dotenv()
|
|
@@ -35,8 +35,22 @@ severities = {
|
|
| 35 |
"Best Practice": "Low"
|
| 36 |
}
|
| 37 |
|
| 38 |
-
# ----------
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
# ---------- Logging ----------
|
| 42 |
def log_to_console(data, log_type):
|
|
@@ -90,7 +104,7 @@ def analyze_code(code):
|
|
| 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,6 +115,7 @@ def validate_metadata(metadata, admin_id=None):
|
|
| 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,6 +124,7 @@ def validate_metadata(metadata, admin_id=None):
|
|
| 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,7 +156,7 @@ def validate_metadata(metadata, admin_id=None):
|
|
| 140 |
|
| 141 |
return mtype, issue, recommendation
|
| 142 |
|
| 143 |
-
# ---------- Salesforce Chatbot
|
| 144 |
conversation_history = []
|
| 145 |
|
| 146 |
def salesforce_chatbot(query, history=[]):
|
|
@@ -150,41 +166,38 @@ 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"
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
|
|
|
| 161 |
prompt = f"""
|
| 162 |
-
You are
|
| 163 |
-
|
| 164 |
-
Your answers MUST:
|
| 165 |
-
- Always be at least two lines long.
|
| 166 |
-
- Be correct, clear, and production-safe.
|
| 167 |
-
- Include official Salesforce governor limits when applicable.
|
| 168 |
-
- Use bullet points or code snippets when needed.
|
| 169 |
-
- Recommend Trailhead or official docs if the answer isn't definitive.
|
| 170 |
-
- Follow real-world practices (bulkification, error handling, etc).
|
| 171 |
|
| 172 |
Conversation History:
|
| 173 |
{history_summary}
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
"""
|
| 178 |
|
| 179 |
try:
|
| 180 |
result = qa_pipeline(prompt, max_new_tokens=1024, do_sample=False, temperature=0.1, top_k=50)
|
| 181 |
output = result[0]["generated_text"].strip()
|
| 182 |
-
if output.startswith("
|
| 183 |
-
output = output
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
output += "\n\nRefer to: https://developer.salesforce.com/docs for more."
|
| 187 |
-
|
| 188 |
conversation_history.append((query, output))
|
| 189 |
conversation_history = conversation_history[-6:]
|
| 190 |
log_to_console({"Question": query, "Answer": output}, "Chatbot Query")
|
|
@@ -214,7 +227,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 214 |
|
| 215 |
with gr.Tab("Salesforce Chatbot"):
|
| 216 |
chatbot_output = gr.Chatbot(label="Conversation History", height=400)
|
| 217 |
-
query_input = gr.Textbox(label="Your Question", placeholder="e.g., How
|
| 218 |
with gr.Row():
|
| 219 |
chatbot_button = gr.Button("Ask")
|
| 220 |
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 # NEW: for parsing metadata
|
| 9 |
|
| 10 |
# ---------- Load Environment Variables ----------
|
| 11 |
load_dotenv()
|
|
|
|
| 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 |
|
| 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 |
|
| 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 |
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 |
|
| 157 |
return mtype, issue, recommendation
|
| 158 |
|
| 159 |
+
# ---------- Salesforce Chatbot ----------
|
| 160 |
conversation_history = []
|
| 161 |
|
| 162 |
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 |
|
| 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")
|