import gradio as gr from huggingface_hub import InferenceClient from langchain.vectorstores import FAISS from langchain.embeddings import HuggingFaceEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader client = InferenceClient("HuggingFaceH4/zephyr-7b-beta") # Funktion zum Laden und Indexieren eines Dokuments def load_and_index_document(file_path: str): loader = TextLoader(file_path) documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100) chunks = text_splitter.split_documents(documents) embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2") vector_store = FAISS.from_documents(chunks, embeddings) return vector_store # Antwortfunktion für den RAG-Chatbot def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p, file): # Dateipfad des hochgeladenen Dokuments file_path = file.name # Dokument laden und indexieren vector_store = load_and_index_document(file_path) # Historie und Systemnachricht aufbereiten messages = [{"role": "system", "content": system_message}] for val in history: if val[0]: messages.append({"role": "user", "content": val[0]}) if val[1]: messages.append({"role": "assistant", "content": val[1]}) # Abruf relevanter Abschnitte aus dem Dokument docs = vector_store.similarity_search(message, k=3) # Abrufen von 3 relevanten Dokumentabschnitten context = "\n".join([doc.page_content for doc in docs]) # Nachricht an das Modell full_message = f"{context}\n\nUser: {message}\nAssistant:" response = "" try: # Generierung der Antwort for message in client.chat_completion( [{"role": "system", "content": system_message}, {"role": "user", "content": full_message}], max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p, ): token = message.choices[0].delta.content response += token yield response except Exception as e: yield f"An error occurred: {str(e)}" # Gradio-UI erstellen def create_gradio_ui(): demo = gr.Interface( fn=respond, inputs=[ gr.Textbox(value="You are a helpful assistant.", label="System message"), gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"), gr.File(label="Upload Document") # Datei-Upload ], live=True ) return demo if __name__ == "__main__": ui = create_gradio_ui() ui.launch()