Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,19 +1,36 @@
|
|
1 |
import streamlit as st
|
2 |
import difflib
|
3 |
-
import os
|
4 |
import re
|
5 |
import hashlib
|
6 |
-
|
7 |
-
|
8 |
-
# --- Page config ---
|
9 |
-
st.set_page_config(page_title="π AI Assistant with Workflow + Semantic Search", layout="wide")
|
10 |
|
11 |
-
# ---
|
12 |
-
|
13 |
-
if not
|
14 |
-
st.error("β Please set your
|
15 |
st.stop()
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
# --- Cache for embeddings ---
|
19 |
embedding_cache = {}
|
@@ -34,7 +51,7 @@ def cosine_similarity(vec1, vec2):
|
|
34 |
|
35 |
def split_code_into_chunks(code, lang):
|
36 |
if lang.lower() == "python":
|
37 |
-
pattern = r'(def
|
38 |
splits = re.split(pattern, code)
|
39 |
chunks = []
|
40 |
for i in range(1, len(splits), 2):
|
@@ -45,13 +62,6 @@ def split_code_into_chunks(code, lang):
|
|
45 |
else:
|
46 |
return [code]
|
47 |
|
48 |
-
def groq_call(prompt):
|
49 |
-
resp = client.chat.completions.create(
|
50 |
-
messages=[{"role": "user", "content": prompt}],
|
51 |
-
model="llama3-70b-8192",
|
52 |
-
)
|
53 |
-
return resp.choices[0].message.content
|
54 |
-
|
55 |
def semantic_search_improved(code, question, lang, skill, role, explain_lang):
|
56 |
chunks = split_code_into_chunks(code, lang)
|
57 |
question_emb = get_embedding(question)
|
@@ -62,21 +72,25 @@ def semantic_search_improved(code, question, lang, skill, role, explain_lang):
|
|
62 |
scored_chunks.append((score, chunk))
|
63 |
scored_chunks.sort(key=lambda x: x[0], reverse=True)
|
64 |
top_chunks = [c for _, c in scored_chunks[:3]]
|
65 |
-
combined_code = "
|
66 |
prompt = (
|
67 |
-
f"You are a friendly and insightful {lang} expert helping a {skill} {role}
|
68 |
-
f"Based on these relevant code snippets
|
69 |
-
f"Answer this question in {explain_lang}
|
70 |
f"Explain which parts handle the question and how to modify them if needed."
|
71 |
)
|
72 |
-
|
|
|
|
|
73 |
|
74 |
def error_detection_and_fixes(refactored_code, lang, skill, role, explain_lang):
|
75 |
prompt = (
|
76 |
f"You are a senior {lang} developer. Analyze this code for bugs, security flaws, "
|
77 |
-
f"and performance issues. Suggest fixes with explanations in {explain_lang}
|
78 |
)
|
79 |
-
|
|
|
|
|
80 |
|
81 |
def agentic_workflow(code, skill_level, programming_language, explanation_language, user_role):
|
82 |
timeline = []
|
@@ -85,24 +99,26 @@ def agentic_workflow(code, skill_level, programming_language, explanation_langua
|
|
85 |
# Explanation
|
86 |
explain_prompt = (
|
87 |
f"You are a friendly and insightful {programming_language} expert helping a {skill_level} {user_role}. "
|
88 |
-
f"Explain this code in {explanation_language} with clear examples, analogies, and why each part matters
|
89 |
)
|
90 |
-
explanation =
|
91 |
timeline.append({"step": "Explain", "description": "Detailed explanation", "output": explanation, "code": code})
|
92 |
suggestions.append("Consider refactoring your code to improve readability and performance.")
|
|
|
93 |
|
94 |
# Refactor
|
95 |
refactor_prompt = (
|
96 |
f"Refactor this {programming_language} code. Explain the changes like a mentor helping a {skill_level} {user_role}. "
|
97 |
-
f"Include best practices and improvements
|
98 |
)
|
99 |
-
refactor_response =
|
|
|
100 |
if "```" in refactor_response:
|
101 |
parts = refactor_response.split("```")
|
102 |
refactored_code = ""
|
103 |
for part in parts:
|
104 |
if part.strip().startswith(programming_language.lower()):
|
105 |
-
refactored_code = part.strip().split('
|
106 |
break
|
107 |
if not refactored_code:
|
108 |
refactored_code = refactor_response
|
@@ -114,9 +130,10 @@ def agentic_workflow(code, skill_level, programming_language, explanation_langua
|
|
114 |
# Review
|
115 |
review_prompt = (
|
116 |
f"As a senior {programming_language} developer, review the refactored code. "
|
117 |
-
f"Give constructive feedback on strengths, weaknesses, performance, security, and improvements in {explanation_language}
|
118 |
)
|
119 |
-
review =
|
|
|
120 |
timeline.append({"step": "Review", "description": "Code review and suggestions", "output": review, "code": refactored_code})
|
121 |
suggestions.append("Incorporate review feedback for cleaner, robust code.")
|
122 |
|
@@ -128,9 +145,10 @@ def agentic_workflow(code, skill_level, programming_language, explanation_langua
|
|
128 |
# Test generation
|
129 |
test_prompt = (
|
130 |
f"Write clear, effective unit tests for this {programming_language} code. "
|
131 |
-
f"Explain what each test does in {explanation_language}, for a {skill_level} {user_role}
|
132 |
)
|
133 |
-
tests =
|
|
|
134 |
timeline.append({"step": "Test Generation", "description": "Generated unit tests", "output": tests, "code": tests})
|
135 |
suggestions.append("Run generated tests locally to validate changes.")
|
136 |
|
@@ -173,7 +191,7 @@ def detect_code_type(code, programming_language):
|
|
173 |
return 'unknown'
|
174 |
|
175 |
def code_complexity(code):
|
176 |
-
lines = code.count('
|
177 |
functions = code.count('def ')
|
178 |
classes = code.count('class ')
|
179 |
comments = code.count('#')
|
@@ -182,12 +200,11 @@ def code_complexity(code):
|
|
182 |
def code_matches_language(code: str, language: str) -> bool:
|
183 |
code_lower = code.strip().lower()
|
184 |
language = language.lower()
|
185 |
-
|
186 |
patterns = {
|
187 |
"python": [
|
188 |
"def ", "class ", "import ", "from ", "try:", "except", "raise", "lambda",
|
189 |
-
"with ", "yield", "async ", "await", "print(", "self.", "__init__", "__name__",
|
190 |
-
"if __name__ == '__main__':", "#!",
|
191 |
],
|
192 |
"c++": [
|
193 |
"#include", "int main(", "std::", "::", "cout <<", "cin >>", "new ", "delete ",
|
@@ -219,12 +236,11 @@ def code_matches_language(code: str, language: str) -> bool:
|
|
219 |
"<table", "<footer", "<header", "<section", "<article", "<nav", "<img", "<a ", "</html>",
|
220 |
],
|
221 |
}
|
222 |
-
|
223 |
match_patterns = patterns.get(language, [])
|
224 |
match_count = sum(1 for pattern in match_patterns if pattern in code_lower)
|
225 |
return match_count >= 1
|
226 |
|
227 |
-
# ---
|
228 |
if 'blackbox_chat_history' not in st.session_state:
|
229 |
st.session_state['blackbox_chat_history'] = []
|
230 |
|
@@ -243,11 +259,11 @@ def show_blackbox_history():
|
|
243 |
else:
|
244 |
for i, entry in enumerate(reversed(st.session_state['blackbox_chat_history'])):
|
245 |
with st.sidebar.expander(f"{entry['mode'].replace('_', ' ').title()} #{len(st.session_state['blackbox_chat_history'])-i}"):
|
246 |
-
st.markdown(f"**Prompt
|
247 |
-
st.markdown(f"**Response
|
248 |
|
249 |
-
#
|
250 |
-
|
251 |
|
252 |
# --- Sidebar ---
|
253 |
st.sidebar.title("π§ Configuration")
|
@@ -258,6 +274,21 @@ explain_lang = st.sidebar.selectbox("Explanation Language", ["English", "Spanish
|
|
258 |
st.sidebar.markdown("---")
|
259 |
st.sidebar.markdown("<span style='color:#fff;'>Powered by <b>BLACKBOX.AI</b></span>", unsafe_allow_html=True)
|
260 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
261 |
tabs = st.tabs(["π§ Full AI Workflow", "π Semantic Search"])
|
262 |
|
263 |
# --- Tab 1: Full AI Workflow ---
|
@@ -300,8 +331,7 @@ with tabs[0]:
|
|
300 |
else:
|
301 |
with st.spinner("Running agentic workflow..."):
|
302 |
timeline, suggestions = agentic_workflow(code_input, skill, lang, explain_lang, role)
|
303 |
-
|
304 |
-
add_to_blackbox_history(f"[Full Workflow] Code:\\n{code_input}", f"{timeline[-1]['output'] if timeline else ''}", mode='workflow')
|
305 |
# Show each step in an expander
|
306 |
for step in timeline:
|
307 |
with st.expander(f"β
{step['step']} - {step['description']}"):
|
@@ -322,7 +352,7 @@ with tabs[0]:
|
|
322 |
|
323 |
report_text = ""
|
324 |
for step in timeline:
|
325 |
-
report_text += f"## {step['step']}
|
326 |
|
327 |
st.download_button(
|
328 |
label="π Download Full Workflow Report",
|
@@ -342,8 +372,6 @@ with tabs[1]:
|
|
342 |
else:
|
343 |
with st.spinner("Running semantic search..."):
|
344 |
answer = semantic_search_improved(sem_code, sem_q, lang, skill, role, explain_lang)
|
345 |
-
# Log to Blackbox chat history
|
346 |
-
add_to_blackbox_history(f"[Semantic Search] Q: {sem_q}\\nCode:\\n{sem_code}", answer, mode='semantic_search')
|
347 |
st.markdown("### π Answer")
|
348 |
st.markdown(answer)
|
349 |
|
|
|
1 |
import streamlit as st
|
2 |
import difflib
|
|
|
3 |
import re
|
4 |
import hashlib
|
5 |
+
import requests
|
6 |
+
import os
|
|
|
|
|
7 |
|
8 |
+
# --- Blackbox AI Agent Key (read from environment variable) ---
|
9 |
+
BLACKBOX_API_KEY = os.environ.get("BLACKBOX_API_KEY")
|
10 |
+
if not BLACKBOX_API_KEY:
|
11 |
+
st.error("β Please set your BLACKBOX_API_KEY environment variable.")
|
12 |
st.stop()
|
13 |
+
BLACKBOX_API_URL = "https://api.blackbox.ai/v1/chat/completions"
|
14 |
+
|
15 |
+
def blackbox_api_call(prompt):
|
16 |
+
headers = {
|
17 |
+
"Content-Type": "application/json",
|
18 |
+
"Authorization": f"Bearer {BLACKBOX_API_KEY}",
|
19 |
+
}
|
20 |
+
data = {
|
21 |
+
"model": "gpt-4",
|
22 |
+
"messages": [
|
23 |
+
{"role": "user", "content": prompt}
|
24 |
+
],
|
25 |
+
"max_tokens": 2048,
|
26 |
+
"temperature": 0.7
|
27 |
+
}
|
28 |
+
response = requests.post(BLACKBOX_API_URL, headers=headers, json=data)
|
29 |
+
if response.status_code == 200:
|
30 |
+
result = response.json()
|
31 |
+
return result["choices"][0]["message"]["content"]
|
32 |
+
else:
|
33 |
+
return f"[Blackbox API Error {response.status_code}]: {response.text}"
|
34 |
|
35 |
# --- Cache for embeddings ---
|
36 |
embedding_cache = {}
|
|
|
51 |
|
52 |
def split_code_into_chunks(code, lang):
|
53 |
if lang.lower() == "python":
|
54 |
+
pattern = r'(def\s+\w+\(.*?\):|class\s+\w+\(?.*?\)?:)'
|
55 |
splits = re.split(pattern, code)
|
56 |
chunks = []
|
57 |
for i in range(1, len(splits), 2):
|
|
|
62 |
else:
|
63 |
return [code]
|
64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
def semantic_search_improved(code, question, lang, skill, role, explain_lang):
|
66 |
chunks = split_code_into_chunks(code, lang)
|
67 |
question_emb = get_embedding(question)
|
|
|
72 |
scored_chunks.append((score, chunk))
|
73 |
scored_chunks.sort(key=lambda x: x[0], reverse=True)
|
74 |
top_chunks = [c for _, c in scored_chunks[:3]]
|
75 |
+
combined_code = "\n\n".join(top_chunks)
|
76 |
prompt = (
|
77 |
+
f"You are a friendly and insightful {lang} expert helping a {skill} {role}.\n"
|
78 |
+
f"Based on these relevant code snippets:\n{combined_code}\n"
|
79 |
+
f"Answer this question in {explain_lang}:\n{question}\n"
|
80 |
f"Explain which parts handle the question and how to modify them if needed."
|
81 |
)
|
82 |
+
answer = blackbox_api_call(prompt)
|
83 |
+
add_to_blackbox_history(prompt, answer, "semantic_search")
|
84 |
+
return answer
|
85 |
|
86 |
def error_detection_and_fixes(refactored_code, lang, skill, role, explain_lang):
|
87 |
prompt = (
|
88 |
f"You are a senior {lang} developer. Analyze this code for bugs, security flaws, "
|
89 |
+
f"and performance issues. Suggest fixes with explanations in {explain_lang}:\n\n{refactored_code}"
|
90 |
)
|
91 |
+
answer = blackbox_api_call(prompt)
|
92 |
+
add_to_blackbox_history(prompt, answer, "workflow")
|
93 |
+
return answer
|
94 |
|
95 |
def agentic_workflow(code, skill_level, programming_language, explanation_language, user_role):
|
96 |
timeline = []
|
|
|
99 |
# Explanation
|
100 |
explain_prompt = (
|
101 |
f"You are a friendly and insightful {programming_language} expert helping a {skill_level} {user_role}. "
|
102 |
+
f"Explain this code in {explanation_language} with clear examples, analogies, and why each part matters:\n\n{code}"
|
103 |
)
|
104 |
+
explanation = blackbox_api_call(explain_prompt)
|
105 |
timeline.append({"step": "Explain", "description": "Detailed explanation", "output": explanation, "code": code})
|
106 |
suggestions.append("Consider refactoring your code to improve readability and performance.")
|
107 |
+
add_to_blackbox_history(explain_prompt, explanation, "workflow")
|
108 |
|
109 |
# Refactor
|
110 |
refactor_prompt = (
|
111 |
f"Refactor this {programming_language} code. Explain the changes like a mentor helping a {skill_level} {user_role}. "
|
112 |
+
f"Include best practices and improvements:\n\n{code}"
|
113 |
)
|
114 |
+
refactor_response = blackbox_api_call(refactor_prompt)
|
115 |
+
add_to_blackbox_history(refactor_prompt, refactor_response, "workflow")
|
116 |
if "```" in refactor_response:
|
117 |
parts = refactor_response.split("```")
|
118 |
refactored_code = ""
|
119 |
for part in parts:
|
120 |
if part.strip().startswith(programming_language.lower()):
|
121 |
+
refactored_code = part.strip().split('\n', 1)[1] if '\n' in part else ""
|
122 |
break
|
123 |
if not refactored_code:
|
124 |
refactored_code = refactor_response
|
|
|
130 |
# Review
|
131 |
review_prompt = (
|
132 |
f"As a senior {programming_language} developer, review the refactored code. "
|
133 |
+
f"Give constructive feedback on strengths, weaknesses, performance, security, and improvements in {explanation_language}:\n\n{refactored_code}"
|
134 |
)
|
135 |
+
review = blackbox_api_call(review_prompt)
|
136 |
+
add_to_blackbox_history(review_prompt, review, "workflow")
|
137 |
timeline.append({"step": "Review", "description": "Code review and suggestions", "output": review, "code": refactored_code})
|
138 |
suggestions.append("Incorporate review feedback for cleaner, robust code.")
|
139 |
|
|
|
145 |
# Test generation
|
146 |
test_prompt = (
|
147 |
f"Write clear, effective unit tests for this {programming_language} code. "
|
148 |
+
f"Explain what each test does in {explanation_language}, for a {skill_level} {user_role}:\n\n{refactored_code}"
|
149 |
)
|
150 |
+
tests = blackbox_api_call(test_prompt)
|
151 |
+
add_to_blackbox_history(test_prompt, tests, "workflow")
|
152 |
timeline.append({"step": "Test Generation", "description": "Generated unit tests", "output": tests, "code": tests})
|
153 |
suggestions.append("Run generated tests locally to validate changes.")
|
154 |
|
|
|
191 |
return 'unknown'
|
192 |
|
193 |
def code_complexity(code):
|
194 |
+
lines = code.count('\n') + 1
|
195 |
functions = code.count('def ')
|
196 |
classes = code.count('class ')
|
197 |
comments = code.count('#')
|
|
|
200 |
def code_matches_language(code: str, language: str) -> bool:
|
201 |
code_lower = code.strip().lower()
|
202 |
language = language.lower()
|
|
|
203 |
patterns = {
|
204 |
"python": [
|
205 |
"def ", "class ", "import ", "from ", "try:", "except", "raise", "lambda",
|
206 |
+
"with ", "yield", "async ", "await ", "print(", "self.", "__init__", "__name__",
|
207 |
+
"if __name__ == '__main__':", "#!",
|
208 |
],
|
209 |
"c++": [
|
210 |
"#include", "int main(", "std::", "::", "cout <<", "cin >>", "new ", "delete ",
|
|
|
236 |
"<table", "<footer", "<header", "<section", "<article", "<nav", "<img", "<a ", "</html>",
|
237 |
],
|
238 |
}
|
|
|
239 |
match_patterns = patterns.get(language, [])
|
240 |
match_count = sum(1 for pattern in match_patterns if pattern in code_lower)
|
241 |
return match_count >= 1
|
242 |
|
243 |
+
# --- Chat History ---
|
244 |
if 'blackbox_chat_history' not in st.session_state:
|
245 |
st.session_state['blackbox_chat_history'] = []
|
246 |
|
|
|
259 |
else:
|
260 |
for i, entry in enumerate(reversed(st.session_state['blackbox_chat_history'])):
|
261 |
with st.sidebar.expander(f"{entry['mode'].replace('_', ' ').title()} #{len(st.session_state['blackbox_chat_history'])-i}"):
|
262 |
+
st.markdown(f"**Prompt:**\n{entry['prompt']}")
|
263 |
+
st.markdown(f"**Response:**\n{entry['response']}")
|
264 |
|
265 |
+
# --- Page config ---
|
266 |
+
st.set_page_config(page_title="π AI Assistant with Workflow + Semantic Search", layout="wide")
|
267 |
|
268 |
# --- Sidebar ---
|
269 |
st.sidebar.title("π§ Configuration")
|
|
|
274 |
st.sidebar.markdown("---")
|
275 |
st.sidebar.markdown("<span style='color:#fff;'>Powered by <b>BLACKBOX.AI</b></span>", unsafe_allow_html=True)
|
276 |
|
277 |
+
# Show chat history in sidebar
|
278 |
+
show_blackbox_history()
|
279 |
+
|
280 |
+
# Download chat history
|
281 |
+
if st.session_state['blackbox_chat_history']:
|
282 |
+
chat_history_text = ""
|
283 |
+
for entry in st.session_state['blackbox_chat_history']:
|
284 |
+
chat_history_text += f"Mode: {entry['mode']}\nPrompt: {entry['prompt']}\nResponse: {entry['response']}\n\n"
|
285 |
+
st.sidebar.download_button(
|
286 |
+
label="Download Chat History",
|
287 |
+
data=chat_history_text,
|
288 |
+
file_name="blackbox_chat_history.txt",
|
289 |
+
mime="text/plain"
|
290 |
+
)
|
291 |
+
|
292 |
tabs = st.tabs(["π§ Full AI Workflow", "π Semantic Search"])
|
293 |
|
294 |
# --- Tab 1: Full AI Workflow ---
|
|
|
331 |
else:
|
332 |
with st.spinner("Running agentic workflow..."):
|
333 |
timeline, suggestions = agentic_workflow(code_input, skill, lang, explain_lang, role)
|
334 |
+
|
|
|
335 |
# Show each step in an expander
|
336 |
for step in timeline:
|
337 |
with st.expander(f"β
{step['step']} - {step['description']}"):
|
|
|
352 |
|
353 |
report_text = ""
|
354 |
for step in timeline:
|
355 |
+
report_text += f"## {step['step']}\n{step['description']}\n\n{step['output']}\n\n"
|
356 |
|
357 |
st.download_button(
|
358 |
label="π Download Full Workflow Report",
|
|
|
372 |
else:
|
373 |
with st.spinner("Running semantic search..."):
|
374 |
answer = semantic_search_improved(sem_code, sem_q, lang, skill, role, explain_lang)
|
|
|
|
|
375 |
st.markdown("### π Answer")
|
376 |
st.markdown(answer)
|
377 |
|