<!-- Chat container -->
<div id="chat-container">
<!-- Chat box -->
<div id="chat-box">
<div id="model-slider-container">
<label for="model-slider">Select Model behavior:</label>
<div id="model-slider-labels">
<span>Speedy and Basic</span>
<span>Slow and Comprehensive</span>
</div>
<input type="range" id="model-slider" min="0" max="4" step="1" value="0">
</div>
<div id="message-container"></div>
<form id="question-form">
<input type="text" id="question-input" placeholder="Ask a question..." required />
<button type="submit" id="send-button">Send</button>
</form>
</div>
</div>
<script>
const websocketUrl = "ws://172.21.6.131:8000/ws";
let socket;
const models = [
"qwen2:0.5b",
"qwen2:1.5b",
"gemma2:2b",
"phi3:3.8b",
"llama3.1"
];
function initWebSocket() {
socket = new WebSocket(websocketUrl);
socket.onopen = function() {
console.log("Connected to WebSocket");
};
socket.onmessage = function(event) {
try {
const data = JSON.parse(event.data);
console.log("Received data:", data); // Debug log
if (data.result) {
displayMessage(data.result, "ai-message");
if (data.score !== undefined) {
displayRelevanceLevel(data.score); // Display relevance level
}
if (data.sources) {
displaySources(data.sources); // Display sources
}
} else {
displayMessage("Unexpected response format from server.", "ai-message");
}
document.getElementById("send-button").disabled = false; // Re-enable the send button
} catch (error) {
console.error("Error parsing message from server:", error);
displayMessage("Error parsing response from server.", "ai-message");
document.getElementById("send-button").disabled = false; // Re-enable the send button
}
};
socket.onerror = function(error) {
console.error("WebSocket error:", error);
document.getElementById("send-button").disabled = false; // Re-enable the send button
};
socket.onclose = function() {
console.log("Disconnected from WebSocket, reconnecting...");
setTimeout(initWebSocket, 1000); // Try to reconnect after 1 second
};
}
// Initialize WebSocket connection
initWebSocket();
// Helper function to display messages
function displayMessage(text, className) {
const messageContainer = document.getElementById("message-container");
const messageElement = document.createElement("div");
messageElement.textContent = text;
messageElement.className = `message ${className}`;
messageContainer.appendChild(messageElement);
messageContainer.scrollTop = messageContainer.scrollHeight; // Scroll to the bottom
}
// Display relevance level
function displayRelevanceLevel(score) {
const relevanceContainer = document.createElement("div");
relevanceContainer.classList.add("relevance-box");
if (score >= 0.85) {
relevanceContainer.classList.add("very-high");
relevanceContainer.textContent = "Relevance: Very High";
} else if (score >= 0.7) {
relevanceContainer.classList.add("high");
relevanceContainer.textContent = "Relevance: High";
} else if (score >= 0.5) {
relevanceContainer.classList.add("medium");
relevanceContainer.textContent = "Relevance: Medium";
} else {
relevanceContainer.classList.add("low");
relevanceContainer.textContent = "Relevance: Low";
}
document.getElementById("message-container").appendChild(relevanceContainer);
}
// Display sources (if any)
function displaySources(sources) {
const sourcesContainer = document.createElement("div");
sourcesContainer.classList.add("message", "ai-message");
sourcesContainer.textContent = `Sources: ${sources.join(", ")}`;
document.getElementById("message-container").appendChild(sourcesContainer);
}
// Handle form submission (send question to WebSocket server)
document.getElementById("question-form").onsubmit = function(event) {
event.preventDefault();
const questionInput = document.getElementById("question-input");
const question = questionInput.value.trim();
if (question) {
displayMessage(question, "user-message");
socket.send(JSON.stringify({ question, model: models[document.getElementById("model-slider").value] }));
document.getElementById("send-button").disabled = true; // Disable the send button until the response comes
}
questionInput.value = ""; // Clear the input field
};
</script>
Assistant
my backend:
import os
import logging
import time
import psutil
import asyncio
import json
import uuid
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from typing import Optional, Dict
from langchain_core.prompts import PromptTemplate
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_core.output_parsers import StrOutputParser
from llama_index.core import StorageContext, load_index_from_storage
from llama_index.core.storage.docstore import SimpleDocumentStore
from llama_index.core.storage.index_store import SimpleIndexStore
from llama_index.core.vector_stores import SimpleVectorStore
from langchain_community.llms import Ollama
from sentence_transformers import SentenceTransformer
Define a custom RAG prompt with instructions for different content types
custom_rag_prompt = """
You are a helpful assistant. Provide a clear, structured, and concise response to the following question using the given context.
Ensure your answer is quick and efficient, and correct. Include detailed steps if needed. Do not repeat statements in your answer.
Question: {question}
Answer:
{context}
Note: The information was retrieved from the following sources:
{source_info}
"""
Create a PromptTemplate with the custom RAG prompt
if not question:
await websocket.send(json.dumps({"error": "No question provided."}))
continue
logging.info(f"Received question: {question}")
# Start processing the QA request in the background
asyncio.create_task(process_qa(question, task_id=task_id))
except WebSocketDisconnect:
logging.info(f"WebSocket connection closed for task {task_id}")
del websockets[task_id]
except Exception as e:
logging.error(f"WebSocket error: {e}")
del websockets[task_id]
please make sure they will work propperly toghter, below is my logs when I ran, it did the retrieval but the actual processing and sending the awnser with relavance score and all is not coming back or running:
C:\Users\FourieH>uvicorn API_RAG:app --host 0.0.0.0 --port 8000 --workers 1
2024-11-13 11:23:40,561 - INFO - Use pytorch device_name: cpu
2024-11-13 11:23:40,561 - INFO - Load pretrained SentenceTransformer: sentence-transformers/all-mpnet-base-v2
2024-11-13 11:23:45,603 - INFO - Use pytorch device_name: cpu
2024-11-13 11:23:45,603 - INFO - Load pretrained SentenceTransformer: sentence-transformers/all-mpnet-base-v2
2024-11-13 11:24:31,374 - INFO - Loading all indices.
C:\Users\FourieH\AppData\Local\anaconda3\Lib\site-packages\llama_index\core\bridge\langchain.py:23: LangChainDeprecationWarning: Importing ChatMessageHistory from langchain.memory is deprecated. Please replace deprecated imports:
from langchain.memory import ChatMessageHistory
with new imports of:
from langchain_community.chat_message_histories import ChatMessageHistory
You can use the langchain cli to automatically upgrade many imports. Please see documentation here https://python.langchain.com/docs/versions/v0_2/
from langchain.memory import (
INFO: Started server process [31424]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: ('172.21.18.79', 56402) - "WebSocket /ws" [accepted]
INFO: connection open
INFO: ('172.21.18.79', 56403) - "WebSocket /ws" [accepted]
INFO: connection open
INFO: ('172.21.18.79', 56408) - "WebSocket /ws" [accepted]
INFO: connection open
2024-11-13 11:24:49,734 - INFO - WebSocket connection closed for task ce17507d-2203-487b-8faf-3c3f1d6f8dc2
INFO: connection closed
2024-11-13 11:24:50,765 - INFO - WebSocket connection closed for task 3ea02dc5-366a-4f33-bf2b-994c2821a9b4
INFO: connection closed
2024-11-13 11:25:05,172 - INFO - Received question: What is our golf cart policy?
2024-11-13 11:25:06,174 - INFO - CPU Usage: 0.7%
2024-11-13 11:25:06,174 - INFO - Memory Usage: 14.0% (Available: 70471.77MB)
2024-11-13 11:25:06,174 - INFO - Disk Read: 207946.63MB, Disk Write: 922366.77MB
2024-11-13 11:25:07,583 - INFO - Document retrieval time: 1.4092886447906494 seconds
2024-11-13 11:25:07,583 - INFO - Retrieved Documents: [TextNode(id_='73cd2284-8a16-48c4-aca9-ed35ff4d75e3', embedding=None, metadata={'pages': 'Table-8', 'name': 'GOLF CART SAFE WORKING PROCEDURE'}, excluded_embed_metadata_keys=[], excluded_llm_metadata_keys=[], relationships={<NodeRelationship.SOURCE: '1'>: RelatedNodeInfo(node_id='GOLF CART SAFE WORKING PROCEDURE_table_8', node_type=<ObjectType.DOCUMENT: '4'>, metadata={'pages': 'Table-8', 'name': 'GOLF CART SAFE WORKING PROCEDURE'}, hash='8d322df42b07cc13beae1e20e92cff28095e8af083f6f354775617465c4ef908')}, text='0 1\n WARNING:\n Descend steep grades slowly with foot on brake. Death or serious personal injury\n can result from failing to comply with the safety and warning instructions affixed\n to the golf cart or utility vehicle.\n• Sharp Turns, Blind Corners, Bridge Approaches: Chain or rope off \nthese\n potentially hazardous areas or identify them with a suitable warning describing\n the nature of the hazard and the proper precautions to be taken to avoid the\n hazard.\n• Wet areas: Wet grass or roads may cause a golf cart to lose traction and may affect\n stability. Golf cart operators should reduce speed in wet areas or during periods\n of inclement weather.\n• Loose Terrain: Loose terrain may cause a golf cart to lose traction and may affect\n stability. Repairs lose terrain, chain or rope off these areas, or identify loose\n terrain with a suitable warning.\n• Golf cart and Pedestrian Interference: Reroute golf cart traffic or pedestrian traffic\n in congested areas wherever possible to prevent accidents. If it is impractical to\n reroute traffic, erect warning signs to warn pedestrians of vehicle / golf cart traffic,\n and to warn golf cart operators to drive slowly, use caution, and watch for\n pedestrians.\n• Speed, do not overtake any vehicles, reduce speed at crossings, stop streets,\n pedestrian crossings and blind spots. Not allowed to travel at the maximum\n speed of the golf cart, reduce speed to 80% of the maximum speed.\n• Overloading the golf cart: Maximum two persons in the front and two on the back\n seat if design accordingly. Secure any tools and equipment to prevent moving\n during transportation and fall from the golf cart damage property and injured\n bystanders.\n• Brakes may fail, daily pre-use inspection and monthly detail condition inspection.\n All inspections to be recorded. Report any unsafe conditions immediately to the\n Store Man.\n• Use of Cell phone prohibited, park the golf cart safely next to the road before\n answering the cell phone.', start_char_idx=0, end_char_idx=3071, text_template='{metadata_str}\n\n{content}', metadata_template='{key}: {value}', metadata_seperator='\n'), TextNode(id_='a6e6a923-1224-42f7-a562-3b0e050527a9', embedding=None, metadata={'pages': 'Table-1', 'name': 'GOLF CART SAFE WORKING PROCEDURE'}, excluded_embed_metadata_keys=[], excluded_llm_metadata_keys=[], relationships={<NodeRelationship.SOURCE: '1'>: RelatedNodeInfo(node_id='GOLF CART SAFE WORKING PROCEDURE_table_1', node_type=<ObjectType.DOCUMENT: '4'>, metadata={'pages': 'Table-1', 'name': 'GOLF CART SAFE WORKING PROCEDURE'}, hash='3d9849f1ee115f371cdcd55430839757e66cd40811caf2949495f2a5930298c9')}, text='0 1 2 3 4\n Senior Management (Section 16.2 Appointees), Operational\n RESPONSIBILITY OF: \n Management, Technicians, Handyman and Assistants \n1 INTRODUCTION \n Experience has shown that golf carts are safe when operated in accordance with the safety \n warnings affixed to every golf carts. This Safe Operating Procedure is enhanced when golf carts \n are used according to the safety rules and practices established to meet the terrain and conditions \n they are used on. \n Like all machines, golf carts can cause injury if improperly used or maintained. This document \n contains a broad safety practice required for safe golf carts operation. Before golf carts are \n operated, management and staff should establish any additional safety practices that may be \n required for safe operation. \n The information contained here is intended for management and staff responsible for golf carts \n safety. If you are responsible for the operation and maintenance of golf carts, you are responsible \n to implement this golf cart safety program.', start_char_idx=0, end_char_idx=3585, text_template='{metadata_str}\n\n{content}', metadata_template='{key}: {value}', metadata_seperator='\n')]
2024-11-13 11:25:07,583 - INFO - Document formatting time: 0.0 seconds
2024-11-13 11:25:07,583 - INFO - Prompt:
You are a helpful assistant. Provide a clear, structured, and concise response to the following question using the given context.
Ensure your answer is quick and efficient, and correct. Include detailed steps if needed. Do not repeat statements in your answer.
Question: What is our golf cart policy?
Answer:
0 1
WARNING:
Descend steep grades slowly with foot on brake. Death or serious personal injury
can result from failing to comply with the safety and warning instructions affixed
to the golf cart or utility vehicle.
• Sharp Turns, Blind Corners, Bridge Approaches: Chain or rope off \nthese
potentially hazardous areas or identify them with a suitable warning describing
the nature of the hazard and the proper precautions to be taken to avoid the
hazard.
• Wet areas: Wet grass or roads may cause a golf cart to lose traction and may affect
stability. Golf cart operators should reduce speed in wet areas or during periods
of inclement weather.
• Loose Terrain: Loose terrain may cause a golf cart to lose traction and may affect
stability. Repairs lose terrain, chain or rope off these areas, or identify loose
terrain with a suitable warning.
• Golf cart and Pedestrian Interference: Reroute golf cart traffic or pedestrian traffic
in congested areas wherever possible to prevent accidents. If it is impractical to
reroute traffic, erect warning signs to warn pedestrians of vehicle / golf cart traffic,
and to warn golf cart operators to drive slowly, use caution, and watch for
pedestrians.
• Speed, do not overtake any vehicles, reduce speed at crossings, stop streets,
pedestrian crossings and blind spots. Not allowed to travel at the maximum
speed of the golf cart, reduce speed to 80% of the maximum speed.
• Overloading the golf cart: Maximum two persons in the front and two on the back
seat if design accordingly. Secure any tools and equipment to prevent moving
during transportation and fall from the golf cart damage property and injured
bystanders.
• Brakes may fail, daily pre-use inspection and monthly detail condition inspection.
All inspections to be recorded. Report any unsafe conditions immediately to the
Store Man.
• Use of Cell phone prohibited, park the golf cart safely next to the road before
answering the cell phone.
0 1 2 3 4
Senior Management (Section 16.2 Appointees), Operational
RESPONSIBILITY OF:
Management, Technicians, Handyman and Assistants
1 INTRODUCTION
Experience has shown that golf carts are safe when operated in accordance with the safety
warnings affixed to every golf carts. This Safe Operating Procedure is enhanced when golf carts
are used according to the safety rules and practices established to meet the terrain and conditions
they are used on.
Like all machines, golf carts can cause injury if improperly used or maintained. This document
contains a broad safety practice required for safe golf carts operation. Before golf carts are
operated, management and staff should establish any additional safety practices that may be
required for safe operation.
The information contained here is intended for management and staff responsible for golf carts
safety. If you are responsible for the operation and maintenance of golf carts, you are responsible
to implement this golf cart safety program.
Note: The information was retrieved from the following sources:
GOLF CART SAFE WORKING PROCEDURE, Pages: Table-8
GOLF CART SAFE WORKING PROCEDURE, Pages: Table-1
C:\Users\FourieH\API_RAG.py:181: LangChainDeprecationWarning: The class Ollama was deprecated in LangChain 0.3.1 and will be removed in 1.0.0. An updated version of the class exists in the :class:~langchain-ollama package and should be used instead. To use it run pip install -U :class:~langchain-ollama and import as from :class:~langchain_ollama import OllamaLLM``.
llm = Ollama(model=model_mapping[model])
Based on the information you've provided, it appears that the issue lies in the way the WebSocket connection is being handled between your frontend and backend code. Specifically, the backend is not properly sending the response back to the frontend because the websocket object is not correctly passed or accessed in your asynchronous tasks.
Here's a detailed analysis and solution to address the issue:
Problem Explanation
WebSocket Scope and Availability:
In your websocket_endpoint function, you accept the WebSocket connection and store it in a dictionary called websockets using a unique task_id.
You then start the process_qa task asynchronously using asyncio.create_task(process_qa(...)).
However, in the process_qa function (which runs outside of the websocket_endpoint scope), you try to send the result back to the client via the WebSocket without properly accessing the websocket object.
Missing WebSocket Reference:
The websocket object is not directly passed to the process_qa function or send_result_to_websocket helper function.
As a result, when send_result_to_websocket tries to send data using await websocket.send(...), it fails because websocket is None.
Client Disconnect:
In your logs, you also have entries indicating that the WebSocket connection was closed before the processing completed:
INFO: connection closed
This suggests that the client may have disconnected, perhaps due to not keeping the connection open while awaiting the response.
Solution
To resolve this issue, you need to ensure that the websocket object used to communicate with the client is properly accessed within your asynchronous tasks. Here's how you can modify your code:
1. Modify send_result_to_websocket to Access the Correct WebSocket
Update your send_result_to_websocket function to retrieve the websocket instance from the websockets dictionary using the task_id.
async def send_result_to_websocket(task_id: str, result: str, score: float, source_info: Optional[dict]):
try:
formatted_response = format_json_response(task_id, result, score, source_info)
websocket = websockets.get(task_id)
if websocket:
await websocket.send_text(formatted_response)
else:
logging.error(f"No websocket found for task {task_id}")
except Exception as e:
logging.error(f"Failed to send result to WebSocket: {str(e)}")
Explanation: This function now retrieves the correct websocket instance associated with the task_id and uses it to send the response back to the client.
2. Ensure the WebSocket Connection Remains Open
On the frontend, make sure that the WebSocket connection remains open until the response is received. This involves properly handling the WebSocket lifecycle and ensuring that the connection isn't prematurely closed.
3. Update Exception Handling in process_qa
Ensure that all exceptions are properly caught and logged in the process_qa function, and that you attempt to send an error response back to the client if possible.
except Exception as e:
logging.error(f"Error in process_qa: {str(e)}")
tasks[task_id] = {"status": "Failed", "error": str(e)}
await send_result_to_websocket(task_id, f"Task failed: {str(e)}", 0, "")
# No need to raise HTTPException here since it's a WebSocket connection
4. Handle Client Disconnection Gracefully
Modify your websocket_endpoint to handle potential client disconnections and ensure that any background tasks are cancelled if the client disconnects.
try:
while True:
data = await websocket.receive_text()
request_data = json.loads(data)
question = request_data.get("question")
# ... rest of your code
except WebSocketDisconnect:
logging.info(f"WebSocket connection closed for task {task_id}")
websocket = websockets.pop(task_id, None)
# Optionally, cancel any ongoing tasks associated with this task_id
5. Use Correct WebSocket Send Methods
Ensure that you're using the correct method to send data over the WebSocket. Since you're sending a JSON-formatted string, you should use websocket.send_text.
6. Update Frontend to Handle Asynchronous Responses
Ensure that your frontend JavaScript code properly handles incoming messages from the WebSocket, even if there are delays due to processing time.
socket.onmessage = function(event) {
try {
const data = JSON.parse(event.data);
// Handle the received data
} catch (error) {
console.error("Error parsing message from server:", error);
// Handle error
}
};
Additional Notes
Deprecation Warnings: The logs indicate a deprecation warning for the Ollama class. Ensure that you're using the updated class from langchain_ollama if necessary.
from langchain_ollama import OllamaLLM
Update your code to use the latest version and import statement.
Performance Considerations: Since you're handling potentially long-running tasks, consider implementing timeouts or task cancellation if the client disconnects.
Thread Safety: If you expect multiple clients, consider using thread-safe data structures or synchronization mechanisms when accessing shared resources like the websockets and tasks dictionaries.
Conclusion
By ensuring that the websocket object is correctly accessed within your asynchronous tasks and handling the WebSocket lifecycle appropriately, you should be able to send the response back to the frontend successfully. This will allow your frontend and backend to work together properly.