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llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex, StorageContext
|
| 6 |
+
from llama_index.vector_stores.milvus import MilvusVectorStore
|
| 7 |
+
from llama_index.core.node_parser import SentenceSplitter
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
# Assuming xAI provides their endpoint for generating text
|
| 14 |
+
XAI_API_URL = "https://api.x.ai/v1/chat/completions" # Replace with actual endpoint
|
| 15 |
+
|
| 16 |
+
# Custom LLM class for xAI
|
| 17 |
+
class XAILLM:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.api_key = os.getenv('XAI_API_KEY')
|
| 20 |
+
if not self.api_key:
|
| 21 |
+
raise ValueError("XAI_API_KEY environment variable is not set")
|
| 22 |
+
|
| 23 |
+
def complete(self, prompt, **kwargs):
|
| 24 |
+
headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
|
| 25 |
+
data = {
|
| 26 |
+
"model": "grok-beta", # Adjust model name as per xAI's API
|
| 27 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 28 |
+
"stream": False # or True if you want streaming responses
|
| 29 |
+
}
|
| 30 |
+
response = requests.post(XAI_API_URL, headers=headers, json=data)
|
| 31 |
+
response.raise_for_status()
|
| 32 |
+
return response.json()['choices'][0]['message']['content'] # Adjust based on actual API response structure
|
| 33 |
+
|
| 34 |
+
Settings.llm = XAILLM()
|
| 35 |
+
|
| 36 |
+
# Custom Embedding class for xAI
|
| 37 |
+
class XAIEmbedding:
|
| 38 |
+
def __init__(self):
|
| 39 |
+
self.api_key = os.getenv('XAI_API_KEY')
|
| 40 |
+
self.model_id = "v1" # Replace with the correct model ID
|
| 41 |
+
|
| 42 |
+
def get_text_embedding(self, text):
|
| 43 |
+
headers = {
|
| 44 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 45 |
+
"Content-Type": "application/json"
|
| 46 |
+
}
|
| 47 |
+
data = {
|
| 48 |
+
"input": text,
|
| 49 |
+
"model": self.model_id
|
| 50 |
+
}
|
| 51 |
+
response = requests.post("xAI's embed endpoint URL", headers=headers, json=data)
|
| 52 |
+
response.raise_for_status()
|
| 53 |
+
return response.json()['data'][0]['embedding'] # Adjust based on xAI's API response structure
|
| 54 |
+
|
| 55 |
+
Settings.embed_model = XAIEmbedding()
|
| 56 |
+
Settings.text_splitter = SentenceSplitter(chunk_size=400)
|
| 57 |
+
|
| 58 |
+
# Ensure GPU usage
|
| 59 |
+
if torch.cuda.is_available():
|
| 60 |
+
logger.info("GPU is available and will be used.")
|
| 61 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0' # Assuming you want to use GPU 0
|
| 62 |
+
else:
|
| 63 |
+
logger.warning("GPU not detected or not configured correctly. Falling back to CPU.")
|
| 64 |
+
|
| 65 |
+
index = None
|
| 66 |
+
query_engine = None
|
| 67 |
+
|
| 68 |
+
def get_files_from_input(file_objs):
|
| 69 |
+
if not file_objs:
|
| 70 |
+
return []
|
| 71 |
+
return [file_obj.name for file_obj in file_objs]
|
| 72 |
+
|
| 73 |
+
def load_documents(file_objs):
|
| 74 |
+
global index, query_engine
|
| 75 |
+
try:
|
| 76 |
+
if not file_objs:
|
| 77 |
+
return "Error: No files selected."
|
| 78 |
+
|
| 79 |
+
file_paths = get_files_from_input(file_objs)
|
| 80 |
+
documents = []
|
| 81 |
+
for file_path in file_paths:
|
| 82 |
+
directory = os.path.dirname(file_path)
|
| 83 |
+
documents.extend(SimpleDirectoryReader(input_files=[file_path]).load_data())
|
| 84 |
+
|
| 85 |
+
if not documents:
|
| 86 |
+
return f"No documents found in the selected files."
|
| 87 |
+
|
| 88 |
+
vector_store = MilvusVectorStore(
|
| 89 |
+
host="127.0.0.1",
|
| 90 |
+
port=19530,
|
| 91 |
+
dim=1024, # Ensure this matches xAI's embedding model output dimension
|
| 92 |
+
collection_name="your_collection_name",
|
| 93 |
+
gpu_id=0
|
| 94 |
+
)
|
| 95 |
+
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
| 96 |
+
|
| 97 |
+
# Create the index from the documents
|
| 98 |
+
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
|
| 99 |
+
|
| 100 |
+
# Create the query engine after the index is created
|
| 101 |
+
query_engine = index.as_query_engine(similarity_top_k=20, streaming=True)
|
| 102 |
+
return f"Successfully loaded {len(documents)} documents from {len(file_paths)} files."
|
| 103 |
+
except Exception as e:
|
| 104 |
+
return f"Error loading documents: {str(e)}"
|
| 105 |
+
|
| 106 |
+
def chat(message, history):
|
| 107 |
+
global query_engine
|
| 108 |
+
if query_engine is None:
|
| 109 |
+
return history + [("Please upload a file first.",None)]
|
| 110 |
+
try:
|
| 111 |
+
response = query_engine.query(message)
|
| 112 |
+
return history + [(message, response.response)]
|
| 113 |
+
except Exception as e:
|
| 114 |
+
return history + [(message,f"Error processing query: {str(e)}")]
|
| 115 |
+
|
| 116 |
+
def stream_response(message, history):
|
| 117 |
+
global query_engine
|
| 118 |
+
if query_engine is None:
|
| 119 |
+
yield history + [("Please upload a file first.",None)]
|
| 120 |
+
return
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
response = query_engine.query(message)
|
| 124 |
+
for text in response.response_gen:
|
| 125 |
+
yield history + [(message, text)]
|
| 126 |
+
except Exception as e:
|
| 127 |
+
yield history + [(message, f"Error processing query: {str(e)}")]
|
| 128 |
+
|
| 129 |
+
# Create the Gradio interface
|
| 130 |
+
with gr.Blocks() as demo:
|
| 131 |
+
gr.Markdown("# RAG Chatbot")
|
| 132 |
+
|
| 133 |
+
with gr.Row():
|
| 134 |
+
file_input = gr.File(label="Select files to upload", file_count="multiple")
|
| 135 |
+
load_btn = gr.Button("Load Documents")
|
| 136 |
+
|
| 137 |
+
load_output = gr.Textbox(label="Load Status")
|
| 138 |
+
|
| 139 |
+
chatbot = gr.Chatbot()
|
| 140 |
+
msg = gr.Textbox(label="Enter your question")
|
| 141 |
+
clear = gr.Button("Clear")
|
| 142 |
+
|
| 143 |
+
load_btn.click(load_documents, inputs=[file_input], outputs=[load_output])
|
| 144 |
+
msg.submit(stream_response, inputs=[msg, chatbot], outputs=[chatbot])
|
| 145 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 146 |
+
|
| 147 |
+
if __name__ == "__main__":
|
| 148 |
+
demo.queue().launch(share=True, debug=True)
|