Spaces:
Sleeping

RAG_OpenAI_gr / app.py
KMS2024's picture
Update app.py
5cc90af verified
Raw History Blame Contribute Delete
3.11 kB
import gradio as gr
import os
import os.path
from openai import OpenAI
from llama_index.core import (
VectorStoreIndex,
SimpleDirectoryReader,
StorageContext,
load_index_from_storage,
)
import bcrypt
from llama_index.llms.openai import OpenAI
from llama_index.core.memory import ChatMemoryBuffer
from llama_index.core.chat_engine import CondensePlusContextChatEngine
# os.environ["OPENAI_API_KEY"] =os.getenv("OPENAI_API_KEY")
pswd = os.getenv("PSWD")
api_key = os.getenv("API_KEY")
client = OpenAI(api_key=api_key)
llm = OpenAI(temperature=0.2, model="gpt-4o")
# check if storage already exists
PERSIST_DIR = "storage3"
if not os.path.exists(PERSIST_DIR):
# load the documents and create the index
documents = SimpleDirectoryReader("olah").load_data()
index = VectorStoreIndex.from_documents(documents)
# store it for later
index.storage_context.persist(persist_dir=PERSIST_DIR)
else:
# load the existing index
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
index = load_index_from_storage(storage_context)
# Either way we can now query the index
query_engine = index.as_query_engine(llm=llm)
memory = ChatMemoryBuffer.from_defaults(token_limit=1900)
# Inisialisasi chat engine dengan retriever yang mengambil dokumen dari sistem
chat_engine = index.as_chat_engine(
chat_mode="condense_plus_context",
memory=memory, # Memory digunakan untuk melacak percakapan sebelumnya
llm=llm,
context_prompt=(
"You are a chatbot, only talk about Regulations related to the Ministry of Transportation, Indonesia, as well as talk "
"you can only talk about Regulations related to the Ministry of Transportation, Indonesia."
"Here are the relevant documents for the context:\n"
"{context_str}\n"
"Instruction: Use the previous chat history, or the context above, to interact and help the user."
),
verbose=False,
)
chat_engine.reset()
def generate_response(message, history):
response = chat_engine.stream_chat(message)
text = ""
source_info = ""
# Check if there is any source_node to reference
if hasattr(response, 'source_nodes') and len(response.source_nodes) > 0:
file_name = response.source_nodes[0].metadata.get('file_name', 'No file name found')
source_info = f"\n\n**Sumber Rujukan Dokumen:**\n- {file_name}"
for token in response.response_gen:
text += token
yield text + source_info # Append source_info with every token
def clear_history(value):
chat_engine.reset()
clear_btn = gr.Button("Clear")
js_func = """
function refresh() {
const url = new URL(window.location);
if (url.searchParams.get('__theme') !== 'dark') {
url.searchParams.set('__theme', 'dark');
window.location.href = url.href;
}
}
"""
with gr.Blocks(js=js_func, fill_height=True) as demo:
clear_btn.click(clear_history)
gr.ChatInterface(generate_response, clear_btn=clear_btn, title="RAG LLM - Regulasi Perhubungan")
demo.launch(auth=("admin", pswd))
# demo.launch(auth=("admin", "pass1234"))