Update app.py
Browse files
app.py
CHANGED
|
@@ -44,9 +44,9 @@ CORS(app)
|
|
| 44 |
# --- LLM setup ---
|
| 45 |
# Using a model that's good for coding tasks
|
| 46 |
llm = ChatGroq(
|
| 47 |
-
model=os.getenv("LLM_MODEL", "
|
| 48 |
-
temperature=0.1,
|
| 49 |
-
max_tokens=2048,
|
| 50 |
api_key=GROQ_API_KEY,
|
| 51 |
)
|
| 52 |
|
|
@@ -74,34 +74,31 @@ Rules:
|
|
| 74 |
"""
|
| 75 |
|
| 76 |
def extract_json_from_llm_response(raw_response: str) -> dict:
|
| 77 |
-
# Helper function remains largely the same, adapted for new keys
|
| 78 |
default = {
|
| 79 |
"assistant_reply": "I'm sorry — I couldn't understand that. Could you please rephrase?",
|
| 80 |
"state_updates": {},
|
| 81 |
"suggested_tags": [],
|
| 82 |
}
|
| 83 |
-
# ... [JSON parsing logic remains similar] ...
|
| 84 |
if not raw_response or not isinstance(raw_response, str):
|
| 85 |
return default
|
| 86 |
m = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", raw_response)
|
| 87 |
json_string = m.group(1).strip() if m else raw_response
|
| 88 |
first = json_string.find('{')
|
| 89 |
last = json_string.rfind('}')
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
candidate = json_string[first:last+1]
|
| 97 |
candidate = re.sub(r',\s*(?=[}\]])', '', candidate)
|
|
|
|
| 98 |
try:
|
| 99 |
parsed = json.loads(candidate)
|
| 100 |
except Exception as e:
|
| 101 |
-
logger.warning("Failed to parse JSON from LLM output: %s", e)
|
| 102 |
return default
|
| 103 |
|
| 104 |
-
# Validation for new keys
|
| 105 |
if isinstance(parsed, dict) and "assistant_reply" in parsed and isinstance(parsed["assistant_reply"], str) and parsed["assistant_reply"].strip():
|
| 106 |
parsed.setdefault("state_updates", {})
|
| 107 |
parsed.setdefault("suggested_tags", [])
|
|
@@ -114,13 +111,10 @@ def extract_json_from_llm_response(raw_response: str) -> dict:
|
|
| 114 |
@app.route("/", methods=["GET"])
|
| 115 |
def serve_frontend():
|
| 116 |
try:
|
| 117 |
-
# Assuming you will update frontend.html for the new assistant
|
| 118 |
return app.send_static_file("frontend.html")
|
| 119 |
except Exception:
|
| 120 |
return "<h3>frontend.html not found in static/ — please add your frontend.html there.</h3>", 404
|
| 121 |
|
| 122 |
-
# UPLOAD routes are removed as they are no longer needed.
|
| 123 |
-
|
| 124 |
@app.route("/chat", methods=["POST"])
|
| 125 |
def chat():
|
| 126 |
data = request.get_json(force=True)
|
|
@@ -128,36 +122,30 @@ def chat():
|
|
| 128 |
return jsonify({"error": "invalid request body"}), 400
|
| 129 |
|
| 130 |
chat_history: List[Dict[str, str]] = data.get("chat_history") or []
|
| 131 |
-
# Using 'assistant_state' to clearly separate from old patient_state
|
| 132 |
assistant_state: AssistantState = data.get("assistant_state") or {}
|
| 133 |
|
| 134 |
-
# Initialize/Clean up state
|
| 135 |
state: AssistantState = {
|
| 136 |
"conversationSummary": assistant_state.get("conversationSummary", ""),
|
| 137 |
"lastUserMessage": "",
|
| 138 |
-
"language": assistant_state.get("language", "Python"),
|
| 139 |
"taggedReplies": assistant_state.get("taggedReplies", []),
|
| 140 |
}
|
| 141 |
|
| 142 |
-
# Find the last user message
|
| 143 |
for msg in reversed(chat_history):
|
| 144 |
if msg.get("role") == "user" and msg.get("content"):
|
| 145 |
state["lastUserMessage"] = msg["content"]
|
| 146 |
break
|
| 147 |
|
| 148 |
-
# --- Language Detection (Simple check for common programming languages) ---
|
| 149 |
last_msg_lower = state["lastUserMessage"].lower()
|
| 150 |
known_languages = ["python", "javascript", "java", "c++", "c#", "go", "ruby", "php", "typescript", "swift"]
|
| 151 |
|
| 152 |
-
# A simple regex to detect a language mention in the last message
|
| 153 |
lang_match = re.search(r'\b(in|using|for)\s+(' + '|'.join(known_languages) + r')\b', last_msg_lower)
|
| 154 |
if lang_match:
|
| 155 |
detected_lang = lang_match.group(2).capitalize()
|
| 156 |
-
if detected_lang != state["language"]:
|
| 157 |
logger.info("Detected new language: %s", detected_lang)
|
| 158 |
state["language"] = detected_lang
|
| 159 |
|
| 160 |
-
# --- LLM Prompt Construction ---
|
| 161 |
action_hint = ""
|
| 162 |
if state["language"]:
|
| 163 |
action_hint = f"Focus your answer on the {state['language']} programming language. If the user asks a conceptual question, use {state['language']} for examples."
|
|
@@ -165,7 +153,7 @@ def chat():
|
|
| 165 |
action_hint = "The current language is unknown. Please ask the user to specify the programming language they are working in."
|
| 166 |
|
| 167 |
user_prompt = f"""
|
| 168 |
-
Current State: {json.dumps({"language": state["language"], "summary": state["conversationSummary"]})}
|
| 169 |
Last user message: {state["lastUserMessage"]}
|
| 170 |
|
| 171 |
SYSTEM_HINT: {action_hint}
|
|
@@ -190,10 +178,8 @@ Return ONLY valid JSON with keys: assistant_reply, state_updates, suggested_tags
|
|
| 190 |
logger.exception("LLM invocation failed")
|
| 191 |
return jsonify({"error": "LLM invocation failed", "detail": str(e)}), 500
|
| 192 |
|
| 193 |
-
# --- State Update from LLM ---
|
| 194 |
updated_state_from_llm = parsed_result.get("state_updates", {})
|
| 195 |
|
| 196 |
-
# Update state fields that the LLM is allowed to modify
|
| 197 |
if 'conversationSummary' in updated_state_from_llm:
|
| 198 |
state["conversationSummary"] = updated_state_from_llm["conversationSummary"]
|
| 199 |
if 'language' in updated_state_from_llm:
|
|
@@ -203,16 +189,14 @@ Return ONLY valid JSON with keys: assistant_reply, state_updates, suggested_tags
|
|
| 203 |
if not assistant_reply or not isinstance(assistant_reply, str) or not assistant_reply.strip():
|
| 204 |
assistant_reply = "I'm here to help with your code! What programming language are you using?"
|
| 205 |
|
| 206 |
-
# --- Final Response Payload ---
|
| 207 |
response_payload = {
|
| 208 |
"assistant_reply": assistant_reply,
|
| 209 |
"updated_state": state,
|
| 210 |
-
"suggested_tags": parsed_result.get("suggested_tags", []),
|
| 211 |
}
|
| 212 |
|
| 213 |
return jsonify(response_payload)
|
| 214 |
|
| 215 |
-
# --- New Route for Tagging/Bookmarking Replies ---
|
| 216 |
@app.route("/tag_reply", methods=["POST"])
|
| 217 |
def tag_reply():
|
| 218 |
data = request.get_json(force=True)
|
|
@@ -226,12 +210,10 @@ def tag_reply():
|
|
| 226 |
if not reply_content or not tags:
|
| 227 |
return jsonify({"error": "Missing 'reply' or 'tags' in request"}), 400
|
| 228 |
|
| 229 |
-
# Ensure tags is a list of strings
|
| 230 |
tags = [str(t).strip() for t in tags if str(t).strip()]
|
| 231 |
if not tags:
|
| 232 |
return jsonify({"error": "Tags list cannot be empty"}), 400
|
| 233 |
|
| 234 |
-
# Clean up state dictionary
|
| 235 |
state: AssistantState = {
|
| 236 |
"conversationSummary": assistant_state.get("conversationSummary", ""),
|
| 237 |
"lastUserMessage": "",
|
|
@@ -244,7 +226,6 @@ def tag_reply():
|
|
| 244 |
"tags": tags,
|
| 245 |
}
|
| 246 |
|
| 247 |
-
# Add the new tagged reply
|
| 248 |
state["taggedReplies"].append(new_tagged_reply)
|
| 249 |
|
| 250 |
logger.info("Reply tagged with: %s", tags)
|
|
@@ -254,55 +235,10 @@ def tag_reply():
|
|
| 254 |
"updated_state": state,
|
| 255 |
}), 200
|
| 256 |
|
| 257 |
-
# --- Filtering/Search Route for Bookmarked Replies ---
|
| 258 |
-
@app.route("/search_tags", methods=["GET"])
|
| 259 |
-
def search_tags():
|
| 260 |
-
tag_query = request.args.get("tag")
|
| 261 |
-
# Using POST for /chat, so we'll pass state in the body
|
| 262 |
-
# For a simple GET search, we'd need the state to be sent here,
|
| 263 |
-
# but for simplicity, let's assume the state is passed in a POST body
|
| 264 |
-
# or fetched/maintained on the frontend and this route is just for logic.
|
| 265 |
-
|
| 266 |
-
# Assuming the frontend sends the current state via a POST request for search
|
| 267 |
-
if request.method == "GET":
|
| 268 |
-
return jsonify({"error": "Please use POST and include 'assistant_state' in the body for tag search."}), 405
|
| 269 |
-
|
| 270 |
-
# If using POST, you'd process request.get_json() here to get assistant_state
|
| 271 |
-
# For now, let's stick to the simpler GET and assume the frontend handles the state.
|
| 272 |
-
# To demonstrate the filtering logic:
|
| 273 |
-
|
| 274 |
-
# --- DUMMY STATE FOR DEMO ---
|
| 275 |
-
dummy_state: AssistantState = {
|
| 276 |
-
"conversationSummary": "",
|
| 277 |
-
"lastUserMessage": "",
|
| 278 |
-
"language": "Python",
|
| 279 |
-
"taggedReplies": [
|
| 280 |
-
{"reply": "A Python loop example.", "tags": ["Python", "Loop Concept"]},
|
| 281 |
-
{"reply": "Fix for 'undefined' error in JS.", "tags": ["JavaScript", "Debugging"]},
|
| 282 |
-
{"reply": "Explanation of Polymorphism.", "tags": ["Java", "OOP"]},
|
| 283 |
-
],
|
| 284 |
-
}
|
| 285 |
-
|
| 286 |
-
if not tag_query:
|
| 287 |
-
# Return all tagged replies if no query
|
| 288 |
-
return jsonify({"tag_query": "", "results": dummy_state["taggedReplies"]}), 200
|
| 289 |
-
|
| 290 |
-
tag_query_lower = tag_query.lower()
|
| 291 |
-
|
| 292 |
-
filtered_results = [
|
| 293 |
-
reply for reply in dummy_state["taggedReplies"]
|
| 294 |
-
if any(tag_query_lower in tag.lower() for tag in reply["tags"])
|
| 295 |
-
]
|
| 296 |
-
|
| 297 |
-
return jsonify({
|
| 298 |
-
"tag_query": tag_query,
|
| 299 |
-
"results": filtered_results
|
| 300 |
-
}), 200
|
| 301 |
-
|
| 302 |
@app.route("/ping", methods=["GET"])
|
| 303 |
def ping():
|
| 304 |
return jsonify({"status": "ok"})
|
| 305 |
|
| 306 |
if __name__ == "__main__":
|
| 307 |
port = int(os.getenv("PORT", 7860))
|
| 308 |
-
app.run(host="0.0.0.0", port=port, debug=True)
|
|
|
|
| 44 |
# --- LLM setup ---
|
| 45 |
# Using a model that's good for coding tasks
|
| 46 |
llm = ChatGroq(
|
| 47 |
+
model=os.getenv("LLM_MODEL", "meta-llama/llama-4-scout-17b-16e-instruct"), # Use the supported model
|
| 48 |
+
temperature=0.1,
|
| 49 |
+
max_tokens=2048,
|
| 50 |
api_key=GROQ_API_KEY,
|
| 51 |
)
|
| 52 |
|
|
|
|
| 74 |
"""
|
| 75 |
|
| 76 |
def extract_json_from_llm_response(raw_response: str) -> dict:
|
|
|
|
| 77 |
default = {
|
| 78 |
"assistant_reply": "I'm sorry — I couldn't understand that. Could you please rephrase?",
|
| 79 |
"state_updates": {},
|
| 80 |
"suggested_tags": [],
|
| 81 |
}
|
|
|
|
| 82 |
if not raw_response or not isinstance(raw_response, str):
|
| 83 |
return default
|
| 84 |
m = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", raw_response)
|
| 85 |
json_string = m.group(1).strip() if m else raw_response
|
| 86 |
first = json_string.find('{')
|
| 87 |
last = json_string.rfind('}')
|
| 88 |
+
|
| 89 |
+
if first != -1 and last != -1 and first < last:
|
| 90 |
+
candidate = json_string[first:last+1]
|
| 91 |
+
else:
|
| 92 |
+
candidate = json_string # Fallback to the whole string if braces aren't clear
|
| 93 |
+
|
|
|
|
| 94 |
candidate = re.sub(r',\s*(?=[}\]])', '', candidate)
|
| 95 |
+
|
| 96 |
try:
|
| 97 |
parsed = json.loads(candidate)
|
| 98 |
except Exception as e:
|
| 99 |
+
logger.warning("Failed to parse JSON from LLM output: %s. Raw candidate: %s", e, candidate)
|
| 100 |
return default
|
| 101 |
|
|
|
|
| 102 |
if isinstance(parsed, dict) and "assistant_reply" in parsed and isinstance(parsed["assistant_reply"], str) and parsed["assistant_reply"].strip():
|
| 103 |
parsed.setdefault("state_updates", {})
|
| 104 |
parsed.setdefault("suggested_tags", [])
|
|
|
|
| 111 |
@app.route("/", methods=["GET"])
|
| 112 |
def serve_frontend():
|
| 113 |
try:
|
|
|
|
| 114 |
return app.send_static_file("frontend.html")
|
| 115 |
except Exception:
|
| 116 |
return "<h3>frontend.html not found in static/ — please add your frontend.html there.</h3>", 404
|
| 117 |
|
|
|
|
|
|
|
| 118 |
@app.route("/chat", methods=["POST"])
|
| 119 |
def chat():
|
| 120 |
data = request.get_json(force=True)
|
|
|
|
| 122 |
return jsonify({"error": "invalid request body"}), 400
|
| 123 |
|
| 124 |
chat_history: List[Dict[str, str]] = data.get("chat_history") or []
|
|
|
|
| 125 |
assistant_state: AssistantState = data.get("assistant_state") or {}
|
| 126 |
|
|
|
|
| 127 |
state: AssistantState = {
|
| 128 |
"conversationSummary": assistant_state.get("conversationSummary", ""),
|
| 129 |
"lastUserMessage": "",
|
| 130 |
+
"language": assistant_state.get("language", "Python"),
|
| 131 |
"taggedReplies": assistant_state.get("taggedReplies", []),
|
| 132 |
}
|
| 133 |
|
|
|
|
| 134 |
for msg in reversed(chat_history):
|
| 135 |
if msg.get("role") == "user" and msg.get("content"):
|
| 136 |
state["lastUserMessage"] = msg["content"]
|
| 137 |
break
|
| 138 |
|
|
|
|
| 139 |
last_msg_lower = state["lastUserMessage"].lower()
|
| 140 |
known_languages = ["python", "javascript", "java", "c++", "c#", "go", "ruby", "php", "typescript", "swift"]
|
| 141 |
|
|
|
|
| 142 |
lang_match = re.search(r'\b(in|using|for)\s+(' + '|'.join(known_languages) + r')\b', last_msg_lower)
|
| 143 |
if lang_match:
|
| 144 |
detected_lang = lang_match.group(2).capitalize()
|
| 145 |
+
if detected_lang.lower() != state["language"].lower():
|
| 146 |
logger.info("Detected new language: %s", detected_lang)
|
| 147 |
state["language"] = detected_lang
|
| 148 |
|
|
|
|
| 149 |
action_hint = ""
|
| 150 |
if state["language"]:
|
| 151 |
action_hint = f"Focus your answer on the {state['language']} programming language. If the user asks a conceptual question, use {state['language']} for examples."
|
|
|
|
| 153 |
action_hint = "The current language is unknown. Please ask the user to specify the programming language they are working in."
|
| 154 |
|
| 155 |
user_prompt = f"""
|
| 156 |
+
Current State: {json.dumps({"language": state["language"], "summary": state["conversationSummary"][:200]})}
|
| 157 |
Last user message: {state["lastUserMessage"]}
|
| 158 |
|
| 159 |
SYSTEM_HINT: {action_hint}
|
|
|
|
| 178 |
logger.exception("LLM invocation failed")
|
| 179 |
return jsonify({"error": "LLM invocation failed", "detail": str(e)}), 500
|
| 180 |
|
|
|
|
| 181 |
updated_state_from_llm = parsed_result.get("state_updates", {})
|
| 182 |
|
|
|
|
| 183 |
if 'conversationSummary' in updated_state_from_llm:
|
| 184 |
state["conversationSummary"] = updated_state_from_llm["conversationSummary"]
|
| 185 |
if 'language' in updated_state_from_llm:
|
|
|
|
| 189 |
if not assistant_reply or not isinstance(assistant_reply, str) or not assistant_reply.strip():
|
| 190 |
assistant_reply = "I'm here to help with your code! What programming language are you using?"
|
| 191 |
|
|
|
|
| 192 |
response_payload = {
|
| 193 |
"assistant_reply": assistant_reply,
|
| 194 |
"updated_state": state,
|
| 195 |
+
"suggested_tags": parsed_result.get("suggested_tags", []),
|
| 196 |
}
|
| 197 |
|
| 198 |
return jsonify(response_payload)
|
| 199 |
|
|
|
|
| 200 |
@app.route("/tag_reply", methods=["POST"])
|
| 201 |
def tag_reply():
|
| 202 |
data = request.get_json(force=True)
|
|
|
|
| 210 |
if not reply_content or not tags:
|
| 211 |
return jsonify({"error": "Missing 'reply' or 'tags' in request"}), 400
|
| 212 |
|
|
|
|
| 213 |
tags = [str(t).strip() for t in tags if str(t).strip()]
|
| 214 |
if not tags:
|
| 215 |
return jsonify({"error": "Tags list cannot be empty"}), 400
|
| 216 |
|
|
|
|
| 217 |
state: AssistantState = {
|
| 218 |
"conversationSummary": assistant_state.get("conversationSummary", ""),
|
| 219 |
"lastUserMessage": "",
|
|
|
|
| 226 |
"tags": tags,
|
| 227 |
}
|
| 228 |
|
|
|
|
| 229 |
state["taggedReplies"].append(new_tagged_reply)
|
| 230 |
|
| 231 |
logger.info("Reply tagged with: %s", tags)
|
|
|
|
| 235 |
"updated_state": state,
|
| 236 |
}), 200
|
| 237 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
@app.route("/ping", methods=["GET"])
|
| 239 |
def ping():
|
| 240 |
return jsonify({"status": "ok"})
|
| 241 |
|
| 242 |
if __name__ == "__main__":
|
| 243 |
port = int(os.getenv("PORT", 7860))
|
| 244 |
+
app.run(host="0.0.0.0", port=port, debug=True)
|