To refactor your /completion_lease route to utilize the external FastAPI /query endpoint similarly to how you've implemented /completion_plan, you'll need to modify the General Chat section of your lease route to delegate processing to the external service. This involves sending user messages to the external endpoint, handling both streaming and non-streaming responses, and appropriately updating the conversation in your database.
Below is a comprehensive guide on how to achieve this, including the necessary code modifications.
Overview of the Refactoring Steps
-
Modularize Common Functionality: Extract common functionalities such as message preprocessing and communication with the external endpoint to reusable functions.
-
Integrate External /query Endpoint: Modify the General Chat path in /completion_lease to send requests to the external FastAPI /query endpoint.
-
Handle Streaming Responses: Ensure that streaming responses from the external endpoint are properly relayed to the client.
-
Maintain Conversation State: Update the conversation with responses from the external service.
-
Error Handling and Logging: Enhance error handling and logging for better traceability and debugging.
Detailed Implementation
1. Modularize Common Functionality
First, create helper functions to handle sending requests to the external /query endpoint and processing the responses. This promotes code reuse and makes your routes cleaner.
import json
import requests
from flask import Response, request
from copy import deepcopy
from your_app.services import ConversationService, DialogService, KnowledgebaseService, DocumentService # Adjust imports as necessary
from your_app.utils import get_json_result, get_data_error_result, server_error_response # Adjust imports as necessary
EXTERNAL_QUERY_URL = "http://127.0.0.1:8003/query" # Update with the actual URL if different
def send_query_to_external_endpoint(payload, stream=False):
try:
response = requests.post(EXTERNAL_QUERY_URL, json=payload, stream=stream)
response.raise_for_status()
return response
except requests.RequestException as e:
raise Exception(f"Error communicating with external /query endpoint: {e}")
def process_streaming_response(response):
"""
Generator to yield streaming responses from external endpoint.
"""
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
if decoded_line.startswith("data:"):
data_json = decoded_line[5:]
yield f"data:{data_json}\n\n"
2. Refactor /completion_lease Route
Modify your /completion_lease route to integrate the external /query endpoint, especially within the General Chat path.
@manager.route('/completion_lease', methods=['POST'])
@login_required
def completion_lease():
print('LOLLLLLLLLL')
"""
API route to handle the completion of a conversation in LISA - Lease context.
"""
try:
req = request.json
print("Lease payload received:", req)
# Filter and prepare messages for processing
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"]})
if not msg:
return get_data_error_result(retmsg="No valid messages provided.")
# 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':
# Existing Quantitative Chat processing ...
# (Keep this section as is or refactor if needed)
# Ensure it remains separate if specialized processing is required
# Your existing Quantitative Chat logic here
# For brevity, assuming it's unchanged
pass # Replace this with your Quantitative Chat logic
elif matched_prompt == 'General Chat':
try:
print('Processing General Chat with external endpoint.')
# Retrieve the conversation and dialog details
e, conv = ConversationService.get_by_id(req.get("conversation_id"))
if not e:
return get_data_error_result(retmsg="Conversation not found!")
conv.message.append(deepcopy(msg[-1]))
e, dia = DialogService.get_by_id(conv.dialog_id)
if not e:
return get_data_error_result(retmsg="Dialog not found!")
print('Dialog KB IDs:', dia.kb_ids)
# Fetch relevant documents if needed
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 user message and prepare for assistant response
conv.message.append({"role": "assistant", "content": ""})
# If document reference is required, handle accordingly
# For example, include document IDs in the payload
# Here, assuming you might need to pass them
doc_ids = [doc['doc_id'] for doc in docs_combined] # Adjust based on your requirements
# Prepare payload for external endpoint
payload = {
"query": test_que, # Or the appropriate message content
"conversation_history": [m for m in conv.message if m["role"] != "system"],
"doc_ids": doc_ids # Include if needed by external endpoint
}
# Decide whether to stream or not based on the request
stream_response = req.get("stream", False)
# Send request to external endpoint
external_response = send_query_to_external_endpoint(payload, stream=stream_response)
if stream_response:
# Handle streaming response
def generate_response():
try:
for data in process_streaming_response(external_response):
yield data
# Update the conversation after streaming
conv.reference.append({"chunks": [], "doc_aggs": docs_combined})
ConversationService.update_by_id(conv.id, conv.to_dict())
yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
except Exception as e:
yield "data:" + json.dumps({
"retcode": 500,
"retmsg": str(e),
"data": {"answer": "**ERROR**: " + str(e), "reference": []}
}, ensure_ascii=False) + "\n\n"
resp = Response(generate_response(), 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
else:
# Handle non-streaming response
response_data = external_response.json()
ans = {
"answer": response_data.get("answer"),
"reference": [] # Adjust based on response structure
}
# Update the conversation with the assistant's answer
conv.reference.append({"chunks": [], "doc_aggs": docs_combined}) # Adjust if needed
conv.message[-1] = {"role": "assistant", "content": ans["answer"]}
ConversationService.update_by_id(conv.id, conv.to_dict())
final_output = {
'answer': ans["answer"],
'reference': {
'total': tol,
'chunks': [],
'doc_aggs': docs_combined
}
}
return get_json_result(data=final_output)
except Exception as e:
return server_error_response(e)
else:
return get_data_error_result(retmsg="Unrecognized prompt type.")
except Exception as e:
return server_error_response(e)
3. Explanation of the Refactored Code
-
Message Preprocessing: The route filters the incoming messages, excluding system messages and ensuring there's at least one user message to process.
-
Message Classification: It uses classify_message(test_que) to determine whether to process the message as Quantitative Chat or General Chat.
-
General Chat Processing:
-
Conversation Retrieval: Retrieves the current conversation and dialog details using ConversationService and DialogService.
-
Document Retrieval: Fetches relevant documents based on knowledge base IDs associated with the dialog.
-
Payload Preparation: Prepares a payload containing the query, conversation history, and document IDs to send to the external /query endpoint.
-
External Endpoint Communication: Sends the payload to the external /query endpoint using the send_query_to_external_endpoint helper function. It handles both streaming and non-streaming responses based on the stream flag in the request.
-
Streaming Response Handling: If streaming is enabled, it defines a generator generate_response that yields data as it arrives from the external endpoint. It also updates the conversation after streaming is complete.
-
Non-Streaming Response Handling: If streaming is not enabled, it processes the complete JSON response from the external endpoint and updates the conversation accordingly.
-
Error Handling: The route includes comprehensive error handling to catch and respond to exceptions that may occur during processing.
4. Update Required Imports and Configurations
Ensure that you have the necessary imports and configurations at the top of your Flask application. Here's an example:
import os
import json
from flask import Flask, Response, request
from copy import deepcopy
from your_app.services import ConversationService, DialogService, KnowledgebaseService, DocumentService # Replace with actual paths
from your_app.utils import get_json_result, get_data_error_result, server_error_response # Replace with actual paths
import requests
app = Flask(__name__)
# Constants
EXTERNAL_QUERY_URL = "http://127.0.0.1:8003/query" # Update if different
5. Ensure External Endpoint is Accessible
Make sure that your FastAPI application (external endpoint) is running and accessible from your Flask application. If they are running on different servers or containers, ensure network configurations allow communication between them.
6. Testing the Integration
After refactoring, thoroughly test both streaming and non-streaming scenarios to ensure that:
- Messages are correctly sent to the external
/query endpoint.
- Responses are properly received and relayed to the client.
- The conversation state is accurately updated in your database.
- Error scenarios are gracefully handled and appropriate messages are returned to the client.
7. Optional Enhancements
-
Timeouts: Consider setting timeouts for the requests.post calls to prevent hanging requests.
response = requests.post(EXTERNAL_QUERY_URL, json=payload, stream=stream, timeout=(5, 30)) # (connect timeout, read timeout)
-
Retries: Implement retry logic for transient failures when communicating with the external endpoint.
-
Authentication: If your external endpoint requires authentication, include necessary headers or tokens in the requests.post call.
-
Logging: Enhance logging to include more contextual information, which can help in debugging issues.
import logging
logger = logging.getLogger(__name__)
# Use logger.debug(), logger.info(), logger.error() instead of print statements
Final Thoughts
By modularizing the functionality and cleanly separating the responsibilities between your Flask application and the external FastAPI service, you create a more maintainable and scalable architecture. This setup allows you to leverage specialized processing in your external service while keeping your Flask routes focused on request handling and response delivery.
Ensure that both services are robustly tested and monitored in production to handle real-world usage effectively.