|
|
|
from llama_cpp import Llama |
|
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings |
|
from llama_index.core.llms import ChatMessage |
|
from llama_index.llms.llama_cpp import LlamaCPP |
|
from llama_index.embeddings.huggingface import HuggingFaceEmbedding |
|
from huggingface_hub import hf_hub_download |
|
from llama_index.core.node_parser import SentenceSplitter |
|
import gradio as gr |
|
import os |
|
|
|
|
|
def initialize_llama_model(): |
|
|
|
model_path = hf_hub_download( |
|
repo_id="Georgia47/Llama-2-7b-chat-hf-Q4_K_M-GGUF", |
|
filename="llama-2-7b-chat-hf-q4_k_m.gguf", |
|
cache_dir="./models" |
|
) |
|
return model_path |
|
|
|
|
|
def initialize_settings(model_path): |
|
Settings.llm = LlamaCPP( |
|
model_path=model_path, |
|
model_kwargs={"n_gpu_layers": 1, |
|
"temperature": 0.7, |
|
"top_p": 0.9, |
|
} |
|
) |
|
|
|
|
|
def initialize_index(): |
|
|
|
documents = SimpleDirectoryReader(input_dir="./bahandokumen").load_data() |
|
|
|
parser = SentenceSplitter(chunk_size=150, chunk_overlap=10) |
|
nodes = parser.get_nodes_from_documents(documents) |
|
|
|
embedding = HuggingFaceEmbedding("sentence-transformers/all-MiniLM-L6-v2") |
|
Settings.embed_model = embedding |
|
index = VectorStoreIndex(nodes) |
|
|
|
return index |
|
|
|
|
|
def initialize_chat_engine(index): |
|
from llama_index.core.prompts import PromptTemplate |
|
from llama_index.core.chat_engine.condense_plus_context import CondensePlusContextChatEngine |
|
retriever = index.as_retriever(similarity_top_k=1) |
|
chat_engine = CondensePlusContextChatEngine.from_defaults( |
|
retriever=retriever, |
|
verbose=True, |
|
) |
|
return chat_engine |
|
|
|
|
|
def generate_response(message, history, chat_engine): |
|
response = chat_engine.stream_chat(message) |
|
text = "".join(response.response_gen) |
|
history.append((message, text)) |
|
return history |
|
|
|
def clear_history(chat_engine): |
|
chat_engine.clear() |
|
|
|
|
|
def launch_gradio(chat_engine): |
|
with gr.Blocks() as demo: |
|
|
|
clear_btn = gr.Button("Clear") |
|
clear_btn.click(lambda: clear_history(chat_engine)) |
|
|
|
|
|
chat_interface = gr.ChatInterface( |
|
lambda message, history: generate_response(message, history, chat_engine) |
|
) |
|
|
|
demo.launch() |
|
|
|
|
|
def main(): |
|
|
|
model_path = initialize_llama_model() |
|
initialize_settings(model_path) |
|
|
|
|
|
index = initialize_index() |
|
chat_engine = initialize_chat_engine(index) |
|
|
|
|
|
launch_gradio(chat_engine) |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|