Refactoring your Flask routes can significantly improve code readability, maintainability, and reduce duplication. Based on the two routes you've provided (/completion_lease and /completion_plan), there are several common patterns and functionalities that can be abstracted into reusable components. Below is a comprehensive approach to refactor these routes effectively.
Refactoring Steps
-
Extract Common Functionality:
- Message Filtering: Both routes filter incoming messages to exclude system messages and conditionally exclude the first assistant message.
- Conversation and Dialog Retrieval: Both routes retrieve conversation and dialog details based on
conversation_id.
- Appending Messages: Both routes append user messages and prepare placeholders for assistant responses.
- Error Handling: Consistent error handling mechanisms can be centralized.
- Streaming Response Generation: Both routes handle streaming responses in a similar manner.
-
Create Helper Functions:
filter_messages(req): Filters incoming messages based on specific criteria.
retrieve_conversation_and_dialog(conversation_id): Retrieves conversation and dialog objects.
initialize_conversation(conv): Initializes conversation references and appends placeholders.
stream_response(generator_func): Standardizes the streaming response setup.
handle_error(e): Centralizes error responses.
-
Organize Code into Services or Utilities:
- Consider moving helper functions into separate service modules or utility files for better organization.
-
Use Decorators for Common Pre-processing:
- If there's common pre-processing required for multiple routes, using decorators can help reduce redundancy.
-
Implement a Base Handler Class (Optional):
- For more complex applications, using class-based views can encapsulate shared logic effectively.
Refactored Code
Below is the refactored version of your routes, incorporating the above refactoring strategies:
from flask import Blueprint, request, Response, jsonify
from functools import wraps
from copy import deepcopy
import json
import requests
manager = Blueprint('manager', __name__)
# Helper Functions
def filter_messages(req):
"""
Filters incoming messages to exclude system messages and conditionally exclude the first assistant message.
"""
msg = []
for m in req.get("messages", []):
if m["role"] == "system":
continue
if m["role"] == "assistant" and not msg:
continue
msg.append({"role": m["role"], "content": m["content"]})
return msg
def retrieve_conversation_and_dialog(conversation_id):
"""
Retrieves conversation and dialog objects based on conversation_id.
"""
e, conv = ConversationService.get_by_id(conversation_id)
if not e:
return None, None, "Conversation not found!"
e, dia = DialogService.get_by_id(conv.dialog_id)
if not e:
return None, None, "Dialog not found!"
return conv, dia, None
def initialize_conversation(conv):
"""
Initializes conversation references and appends placeholders for assistant responses.
"""
if not conv.reference:
conv.reference = []
conv.message.append({"role": "assistant", "content": ""})
conv.reference.append({"chunks": [], "doc_aggs": []})
def stream_response(generator_func):
"""
Standardizes the streaming response setup.
"""
resp = Response(generator_func(), mimetype="text/event-stream")
resp.headers.add("Cache-Control", "no-cache")
resp.headers.add("Connection", "keep-alive")
resp.headers.add("X-Accel-Buffering", "no")
resp.headers.add("Content-Type", "text/event-stream; charset=utf-8")
return resp
def handle_error(e):
"""
Centralizes error responses.
"""
return jsonify({"retcode": 500, "retmsg": str(e), "data": {"answer": f"**ERROR**: {str(e)}", "reference": []}}), 500
def login_required(f):
"""
Dummy login_required decorator. Replace with actual implementation.
"""
@wraps(f)
def decorated_function(*args, **kwargs):
# Implement actual authentication check
return f(*args, **kwargs)
return decorated_function
# Unified Response Function
def get_json_result(data, retcode=0, retmsg=""):
"""
Standardizes JSON responses.
"""
return jsonify({"retcode": retcode, "retmsg": retmsg, "data": data})
def get_data_error_result(retmsg, retcode=1):
"""
Standardizes error JSON responses.
"""
return jsonify({"retcode": retcode, "retmsg": retmsg, "data": None})
# Route Handlers
@manager.route('/completion_lease', methods=['POST'])
@login_required
def completion_lease():
"""
API route to handle the completion of a conversation in LISA - Lease context.
"""
try:
req = request.json
msg = filter_messages(req)
if not msg:
return get_data_error_result("No valid messages found in the request.")
# Extract the last user message for processing
test_que = msg[-1]['content']
print("Here is the test question ------", test_que)
doc_name = extract_from_quotes(test_que)
print('Extracted Document Name:', doc_name)
# Classify the message
matched_prompt = classify_message(test_que)
print("Matched Prompt:", matched_prompt)
if matched_prompt == 'Quantitative Chat':
return handle_quantitative_chat(req, msg, test_que, doc_name)
elif matched_prompt == 'General Chat':
return handle_general_chat(req, msg, doc_name)
else:
return get_data_error_result("Unknown prompt classification.")
except Exception as e:
return handle_error(e)
def handle_quantitative_chat(req, msg, test_que, doc_name):
"""
Handles the 'Quantitative Chat' prompt classification.
"""
print('Matched prompt, processing document retrieval')
conv, dia, error = retrieve_conversation_and_dialog(req.get("conversation_id"))
if error:
return get_data_error_result(retmsg=error)
print('Conversation details:', conv)
print('Dialog KB IDs:', dia.kb_ids)
# Fetch knowledgebase items based on dialog's KB IDs
kbs = KnowledgebaseService.get_by_ids(dia.kb_ids)
print('Fetched knowledgebase:', kbs)
# Retrieve documents by knowledgebase ID
docs, tol = DocumentService.get_by_kb_id(dia.kb_ids, 1, 20, "create_time", True, "")
docs_combined = [{"count": index + 1, "doc_id": doc["id"], "doc_name": doc["name"]} for index, doc in enumerate(docs)]
print('Documents retrieved:', docs_combined)
# Append the latest message and assistant response
conv.message.append(deepcopy(msg[-1]))
resp_msg = 'Here are the documents requested'
conv.message.append({"role": "assistant", "content": resp_msg})
# Add document references to the conversation
conv.reference.append({"chunks": [], "doc_aggs": docs_combined})
ConversationService.update_by_id(conv.id, conv.to_dict())
# Final output to return
final_output = {
'answer': resp_msg,
'reference': {
'total': tol,
'chunks': [],
'doc_aggs': docs_combined
}
}
# Streaming response if requested
if req.get("stream", True):
def generate_response():
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": final_output}, ensure_ascii=False) + "\n\n"
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
return stream_response(generate_response)
else:
return get_json_result(data=final_output)
def handle_general_chat(req, msg, doc_name):
"""
Handles the 'General Chat' prompt classification.
"""
try:
print('No prompt match, proceeding with non-matched flow.')
conv, dia, error = retrieve_conversation_and_dialog(req.get("conversation_id"))
if error:
return get_data_error_result(retmsg=error)
conv.message.append(deepcopy(msg[-1]))
print('Dialog KB IDs:', dia.kb_ids)
# Fetch documents by knowledgebase ID
docs, tol = DocumentService.get_by_kb_id(dia.kb_ids, 1, 20, "create_time", True, "")
docs_combined = [{"count": index + 1, "doc_id": doc["id"], "doc_name": doc["name"]} for index, doc in enumerate(docs)]
print('Documents combined:', docs_combined)
# Function to get document ID by name
def get_doc_id_by_name(doc_name, docs_combined):
for doc in docs_combined:
if doc['doc_name'] == doc_name:
return doc['doc_id']
return None
doc_name_to_search = doc_name[0]
print("Document name to search:", doc_name_to_search)
got_doc_id = get_doc_id_by_name(doc_name_to_search, docs_combined)
print('Document ID retrieved:', got_doc_id)
if not got_doc_id:
return get_data_error_result(retmsg="Document not found!")
# Remove unnecessary keys from the request
req.pop("conversation_id", None)
req.pop("messages", None)
print('Removed conversation_id and messages from request.')
# Initialize conversation references if not present
initialize_conversation(conv)
print('Initialized conversation references.')
def fillin_conv(ans):
""" Helper function to fill the assistant's response """
if not conv.reference:
conv.reference.append(ans["reference"])
else:
conv.reference[-1] = ans["reference"]
conv.message[-1] = {"role": "assistant", "content": ans["answer"]}
# Streaming responses handling
def stream():
try:
print('Starting streaming response.')
for ans in chat(dia, msg, stream=True, doc_ids=got_doc_id, **req):
fillin_conv(ans)
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
ConversationService.update_by_id(conv.id, conv.to_dict())
except Exception as e:
print('Error during streaming:', e)
yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
"data": {"answer": f"**ERROR**: {str(e)}", "reference": []}},
ensure_ascii=False) + "\n\n"
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
if req.get("stream", True):
print('Streaming is enabled.')
return stream_response(stream)
else:
print('Streaming is disabled, processing synchronously.')
answer = None
for ans in chat(dia, msg, **req):
answer = ans
fillin_conv(ans)
ConversationService.update_by_id(conv.id, conv.to_dict())
break
return get_json_result(data=answer)
except Exception as e:
return handle_error(e)
@manager.route('/completion_plan', methods=['POST'])
@login_required
def completion_plan():
"""
API route to handle the completion of a conversation with Lisa-Plan.
"""
try:
print('Processing /completion_plan request.')
req = request.json
msg = filter_messages(req)
if not msg:
return get_data_error_result("No valid messages found in the request.")
# Retrieve the conversation and dialog
conv, dia, error = retrieve_conversation_and_dialog(req.get("conversation_id"))
if error:
return get_data_error_result(retmsg=error)
# Append the last user message to the conversation
conv.message.append(deepcopy(msg[-1]))
print('Appended user message.')
# Remove unnecessary keys from the request
req.pop("conversation_id", None)
req.pop("messages", None)
print('Removed conversation_id and messages from request.')
# Initialize the assistant's response in the conversation
initialize_conversation(conv)
print('Initialized conversation references.')
def fillin_conv(ans):
"""
Helper function to fill in the assistant's response in the conversation.
"""
conv.message[-1] = {"role": "assistant", "content": ans["answer"]}
def stream():
"""
Generator function to handle streaming responses.
"""
try:
print("Starting streaming response for /completion_plan.")
payload = {
"query": msg[-1]["content"],
"conversation_history": [m for m in conv.message if m["role"] != "system"]
}
response = requests.post("http://127.0.0.1:5000/query", json=payload)
response.raise_for_status() # Raises stored HTTPError, if one occurred.
response_data = response.json()
ans = {
"answer": response_data,
"reference": []
}
fillin_conv(ans)
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
ConversationService.update_by_id(conv.id, conv.to_dict())
except Exception as e:
print('Error during streaming:', e)
yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
"data": {"answer": f"**ERROR**: {str(e)}", "reference": []}},
ensure_ascii=False) + "\n\n"
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
if req.get("stream", True):
print('Streaming is enabled for /completion_plan.')
return stream_response(stream)
else:
print('Streaming is disabled for /completion_plan, processing synchronously.')
try:
payload = {
"query": msg[-1]["content"],
"conversation_history": [m for m in conv.message if m["role"] != "system"]
}
response = requests.post("http://127.0.0.1:5000/query", json=payload)
response.raise_for_status()
response_data = response.json()
ans = {
"answer": response_data,
"reference": []
}
fillin_conv(ans)
ConversationService.update_by_id(conv.id, conv.to_dict())
return get_json_result(data=response_data)
except Exception as e:
return handle_error(e)
except Exception as e:
return handle_error(e)
Key Improvements
-
Modularization:
- Helper Functions: By creating helper functions like
filter_messages, retrieve_conversation_and_dialog, and initialize_conversation, the code becomes cleaner and each function has a single responsibility.
- Error Handling: Centralized error handling through
handle_error ensures consistent error responses across all routes.
-
Reduced Duplication:
- Shared logic between routes is abstracted, minimizing code duplication and making it easier to maintain.
-
Enhanced Readability:
- Clear separation of concerns makes the code easier to follow and understand.
- Meaningful print statements aid in debugging without cluttering the core logic.
-
Streamlined Response Generation:
- The
stream_response function standardizes how streaming responses are handled, ensuring consistency.
-
Robust Error Checks:
- Added checks like
response.raise_for_status() to catch HTTP errors during external API calls.
- Ensured that critical variables (like
got_doc_id) are validated before proceeding.
-
Scalability:
- With this structure, adding new routes with similar patterns becomes straightforward by reusing helper functions.
Additional Recommendations
-
Logging:
- Replace
print statements with a proper logging framework (e.g., Python’s built-in logging module) to control log levels and outputs more effectively.
-
Configuration Management:
- Externalize configurations like API endpoints (
"http://127.0.0.1:5000/query") using environment variables or configuration files for better flexibility.
-
Validation:
- Implement request validation using libraries like
marshmallow or pydantic to ensure that incoming data adheres to expected formats.
-
Asynchronous Handling:
- For better performance, especially with I/O-bound operations like API calls, consider using asynchronous frameworks or libraries (e.g.,
Quart instead of Flask, or asyncio with aiohttp).
-
Testing:
- Write unit tests for helper functions and integration tests for routes to ensure that refactoring doesn’t introduce regressions.
-
Documentation:
- Use docstrings and possibly API documentation tools like Swagger to document the API routes and their expected inputs/outputs.
By following this refactored structure and incorporating the additional recommendations, your application will be more maintainable, scalable, and robust against potential future changes.