My front end:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ask BeyondFM - AI Chatbot</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f4f4f4;
        }
        #header {
            width: 100%;
            background-color: #0e0a40;
            color: white;
            display: flex;
            align-items: center;
            padding: 10px 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 0;
            left: 0;
            z-index: 1000;
        }
        #logo {
            height: 70px;
            margin-right: 20px;
        }
        #title {
            font-size: 30px;
            margin-left: -190px;
            flex-grow: 1;
            text-align: center;
            font-family: 'Courier New', monospace;
        }
        #chat-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
            max-width: 900px;
            margin-top: 80px; /* Space for header */
            padding: 20px;
            border: 1px solid #ddd;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        #chat-box {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-height: 800px;
            width: 100%;
        }
        #message-container {
            height: 350px;
            overflow-y: auto;
            border-bottom: 1px solid #ddd;
            padding-bottom: 20px;
            margin-bottom: 20px;
        }
        .message {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            white-space: pre-wrap;
        }
        .user-message {
            background-color: #5993c3;
            text-align: right;
        }
        .ai-message {
            background-color: #0e0a40;
            text-align: left;
            color: white;
            position: relative;
        }
        .relevance-box {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 5px;
            margin-top: 10px;
            font-size: 12px;
            font-weight: bold;
            border: 1px solid;
        }
        .low {
            background-color: #f0f0f0; /* Light gray */
            border-color: #a0a0a0; /* Dark gray */
            color: #5a5a5a; /* Gray text */
        }
        .medium {
            background-color: #fff7cc; /* Light yellow */
            border-color: #e6b800; /* Gold */
            color: #996600; /* Dark gold */
        }
        .high {
            background-color: #d0e8d0; /* Light green */
            border-color: #8bb38b; /* Olive green */
            color: #4a734a; /* Dark olive */
        }
        .very-high {
            background-color: #d0e6f0; /* Light blue */
            border-color: #709bc0; /* Dark blue */
            color: #3b5f85; /* Deep blue */
        }
        #model-slider-container {
            text-align: center;
            margin-bottom: 20px;
        }
        #model-slider {
            width: 100%;
            max-width: 800px;
        }
        #model-slider-labels {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            margin-bottom: 10px;
        }
        #question-form {
            display: flex;
            justify-content: space-between;
            gap: 10px;
        }
        #question-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        #send-button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        #send-button:hover {
            background-color: #0056b3;
        }
        #send-button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.3.0/raphael.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/justgage/1.4.0/justgage.min.js"></script>
</head>
<body>
    <!-- Header with logo and title -->
    <div id="header">
        <img id="logo" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUPoUDekcAAAAASUVORK5CYII=" alt="Company Logo"> <!-- Base64 logo -->
        <div id="title">Ask BeyondFM</div>
    </div>

    <!-- 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>
</body>
</html>


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

# Initialize the FastAPI app
app = FastAPI()

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Initialize the SentenceTransformer model
sentence_transformer_model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')

# Initialize HuggingFaceEmbeddings with the SentenceTransformer model
huggingface_embedding = HuggingFaceEmbeddings(model_name='sentence-transformers/all-mpnet-base-v2')

# Define the persist directory and normalize the path
persist_dir = os.path.normpath("D:/Storage_Comp")

# Initialize the storage context with the correct persist_dir
storage_context = StorageContext.from_defaults(
    docstore=SimpleDocumentStore.from_persist_dir(persist_dir=persist_dir),
    vector_store=SimpleVectorStore.from_persist_dir(persist_dir=persist_dir),
    index_store=SimpleIndexStore.from_persist_dir(persist_dir=persist_dir)
)

# Load the single combined index from the storage context
index = load_index_from_storage(
    storage_context=storage_context,
    embed_model=huggingface_embedding,
)

# Create a retriever from the index
retriever = index.as_retriever(retriever_mode='llm', choice_batch_size=10)

# 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
custom_rag_prompt_template = PromptTemplate(
    template=custom_rag_prompt,
    input_variables=["question", "context", "source_info"]
)



# Function to format documents and extract source information
def format_docs_and_sources(docs):
    formatted_docs = []
    source_info = []

    for doc in docs:
        if hasattr(doc, 'text') and hasattr(doc, 'metadata'):
            content = f"Table:\n{doc.text}" if "table" in doc.id_ else doc.text
            formatted_docs.append(content)

            doc_metadata = getattr(doc, 'metadata', {})
            doc_name = doc_metadata.get('name', 'Unknown Document Name')
            pages_info = doc_metadata.get('pages', 'No page information available')
            source_info.append(f"{doc_name}, Pages: {pages_info}")
        else:
            formatted_docs.append("No text available")
            source_info.append("No source information available")

    formatted_docs = "\n\n".join(formatted_docs)
    source_info = "\n".join(list(set(source_info)))

    return formatted_docs, source_info

# Function to log server performance
def log_performance():
    cpu_usage = psutil.cpu_percent(interval=1)
    memory_info = psutil.virtual_memory()
    disk_io = psutil.disk_io_counters()

    logging.info(f"CPU Usage: {cpu_usage}%")
    logging.info(f"Memory Usage: {memory_info.percent}% (Available: {memory_info.available / (1024 * 1024):.2f}MB)")
    logging.info(f"Disk Read: {disk_io.read_bytes / (1024 * 1024):.2f}MB, Disk Write: {disk_io.write_bytes / (1024 * 1024):.2f}MB")

# Dictionary to manage background tasks and their statuses
tasks: Dict[str, dict] = {}
websockets: Dict[str, WebSocket] = {}

# Define the request body model
class QARequest(BaseModel):
    question: str
    model: str = "stablelm-zephyr"
    temperature: float = 0.7
    top_p: float = 0.1
    top_k: int = 50
  

# Asynchronous function to handle the QA chain processing
async def process_qa(question: str, model: str = "stablelm-zephyr", temperature: float = 0.7, top_p: float = 0.1, top_k: int = 50, task_id: Optional[str] = None):
    try:
        start_time = time.time()  # Start time for the entire process

        # Log initial performance metrics
        log_performance()

        # Retrieve relevant documents
        retrieve_start_time = time.time()
        retrieved_docs_with_scores = await asyncio.get_event_loop().run_in_executor(None, lambda: retriever.retrieve(question))
        retrieve_end_time = time.time()
        logging.info(f"Document retrieval time: {retrieve_end_time - retrieve_start_time} seconds")

        if not retrieved_docs_with_scores:
            tasks[task_id] = {"status": "Completed", "result": "No relevant information found."}
            await send_result_to_websocket(task_id, "No relevant information found.", 0, "")  # Pass empty string for source info
            return "No relevant information found.", "", 0

        # Extract documents and scores
        retrieved_docs = [doc.node for doc in retrieved_docs_with_scores]
        retriever_scores = [doc.score for doc in retrieved_docs_with_scores]
        logging.info(f"Retrieved Documents: {retrieved_docs}")

        # Format the retrieved documents and extract metadata
        format_start_time = time.time()
        formatted_context, source_info = format_docs_and_sources(retrieved_docs)
        format_end_time = time.time()
        logging.info(f"Document formatting time: {format_end_time - format_start_time} seconds")

        # Prepare the prompt
        inputs = {
            "context": formatted_context,
            "question": question,
            "source_info": source_info
        }
        prompt = custom_rag_prompt_template.format(**inputs)

        # Log prompt for debugging
        logging.info(f"Prompt: {prompt}")

        # Start monitoring CPU usage before model invocation
        cpu_usage_start = psutil.cpu_percent(interval=None)
        model_start_time = time.time()

        # Initialize the correct model based on the model_name
        model_mapping = {
            "stablelm-zephyr": "stablelm-zephyr",
            "llama3.1": "llama3.1",
            "gemma:2b": "gemma:2b",
            "wizardlm2:7b": "wizardlm2:7b",
            "qwen2:0.5b": "qwen2:0.5b",
            "phi3:3.8b": "phi3:3.8b",
            "qwen2:1.5b": "qwen2:1.5b",
            "gemma2:2b": "gemma2:2b"
        }

        if model not in model_mapping:
            raise ValueError(f"Unknown model name: {model}")

        llm = Ollama(model=model_mapping[model])

        # Invoke the model with top_k and top_p
        answer = await asyncio.get_event_loop().run_in_executor(None, lambda: llm.invoke(
            prompt,
            temperature=temperature,
            top_k=top_k,
            top_p=top_p
        ))

        # Stop monitoring CPU usage after model invocation
        model_end_time = time.time()
        cpu_usage_end = psutil.cpu_percent(interval=None)
        cpu_usage_during_model = (cpu_usage_start + cpu_usage_end) / 2

        logging.info(f"Model invocation time: {model_end_time - model_start_time} seconds")
        logging.info(f"Average CPU Usage during model invocation: {cpu_usage_during_model}%")

        # Log final performance metrics
        log_performance()

        # Correctly format the final answer with source info
        parsed_answer = StrOutputParser().parse(answer)
        final_answer = f"{parsed_answer}\n\nSources:\n{source_info}"

        end_time = time.time()  # End time for the entire process
        logging.info(f"Total process time: {end_time - start_time} seconds")

        # Calculate average retriever score (confidence)
        avg_retriever_score = sum(retriever_scores) / len(retriever_scores) if retriever_scores else 0

        # Update task status and result
        tasks[task_id] = {"status": "Completed", "result": final_answer, "score": avg_retriever_score}

        # Send the result and the score to the WebSocket
        await send_result_to_websocket(task_id, final_answer, avg_retriever_score, source_info)

        return final_answer, source_info, avg_retriever_score
    except asyncio.CancelledError:
        logging.info(f"Task {task_id} was cancelled")
        tasks[task_id] = {"status": "Cancelled"}
        await send_result_to_websocket(task_id, "Task was cancelled.", 0, "")
    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, "")
        raise HTTPException(status_code=500, detail=f"Task failed: {str(e)}")


# Helper function to send the result via WebSocket
async def send_result_to_websocket(task_id: str, result: str, score: float, source_info: Optional[dict], websocket=None):
    try:
        formatted_response = format_json_response(task_id, result, score, source_info)
        await websocket.send(formatted_response)
    except Exception as e:
        logging.error(f"Failed to send result to WebSocket: {str(e)}")

# Helper function to format the JSON response
def format_json_response(task_id: str, result: str, score: float, source_info: Optional[dict]):
    return json.dumps({
        "task_id": task_id,
        "result": result,
        "score": score,
        "source_info": source_info
    })

# Handle WebSocket connections
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    task_id = str(uuid.uuid4())
    websockets[task_id] = websocket
    try:
        while True:
            data = await websocket.receive_text()
            request_data = json.loads(data)
            question = request_data.get("question")

            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])