|
import os, sys, json |
|
import gradio as gr |
|
import openai |
|
from openai import OpenAI |
|
import time |
|
|
|
from langchain.chains import LLMChain, RetrievalQA |
|
from langchain.chat_models import ChatOpenAI |
|
from langchain.document_loaders import PyPDFLoader, WebBaseLoader |
|
from langchain.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader |
|
from langchain.document_loaders.generic import GenericLoader |
|
from langchain.document_loaders.parsers import OpenAIWhisperParser |
|
from langchain.schema import AIMessage, HumanMessage |
|
|
|
from langchain.embeddings.openai import OpenAIEmbeddings |
|
from langchain.prompts import PromptTemplate |
|
from langchain.text_splitter import RecursiveCharacterTextSplitter |
|
from langchain.vectorstores import Chroma |
|
|
|
|
|
|
|
|
|
from dotenv import load_dotenv, find_dotenv |
|
_ = load_dotenv(find_dotenv()) |
|
|
|
|
|
|
|
|
|
|
|
|
|
splittet = False |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
template = """Antworte in deutsch, wenn es nicht explizit anders gefordert wird. Wenn du die Antwort nicht kennst, antworte einfach, dass du es nicht weißt. Versuche nicht, die Antwort zu erfinden oder aufzumocken. Halte die Antwort so kurz aber exakt.""" |
|
|
|
llm_template = "Beantworte die Frage am Ende. " + template + "Frage: {question} Hilfreiche Antwort: " |
|
rag_template = "Nutze die folgenden Kontext Teile, um die Frage zu beantworten am Ende. " + template + "{context} Frage: {question} Hilfreiche Antwort: " |
|
|
|
|
|
|
|
LLM_CHAIN_PROMPT = PromptTemplate(input_variables = ["question"], |
|
template = llm_template) |
|
RAG_CHAIN_PROMPT = PromptTemplate(input_variables = ["context", "question"], |
|
template = rag_template) |
|
|
|
|
|
HUGGINGFACEHUB_API_TOKEN = os.getenv("HF_ACCESS") |
|
OAI_API_KEY=os.getenv("OPENAI_API_KEY") |
|
|
|
|
|
PATH_WORK = "." |
|
CHROMA_DIR = "/chroma" |
|
YOUTUBE_DIR = "/youtube" |
|
|
|
|
|
|
|
PDF_URL = "https://arxiv.org/pdf/2303.08774.pdf" |
|
WEB_URL = "https://openai.com/research/gpt-4" |
|
YOUTUBE_URL_1 = "https://www.youtube.com/watch?v=--khbXchTeE" |
|
YOUTUBE_URL_2 = "https://www.youtube.com/watch?v=hdhZwyf24mE" |
|
YOUTUBE_URL_3 = "https://www.youtube.com/watch?v=vw-KWfKwvTQ" |
|
|
|
|
|
|
|
|
|
MODEL_NAME = "gpt-3.5-turbo-16k" |
|
|
|
|
|
|
|
|
|
|
|
|
|
os.environ["HUGGINGFACEHUB_API_TOKEN"] = HUGGINGFACEHUB_API_TOKEN |
|
|
|
|
|
|
|
|
|
def add_text(history, text): |
|
history = history + [(text, None)] |
|
return history, gr.Textbox(value="", interactive=False) |
|
|
|
|
|
def add_file(history, file): |
|
history = history + [((file.name,), None)] |
|
return history |
|
|
|
|
|
|
|
def document_loading_splitting(): |
|
global splittet |
|
|
|
docs = [] |
|
|
|
loader = PyPDFLoader(PDF_URL) |
|
docs.extend(loader.load()) |
|
|
|
loader = WebBaseLoader(WEB_URL) |
|
docs.extend(loader.load()) |
|
|
|
loader = GenericLoader(YoutubeAudioLoader([YOUTUBE_URL_1, |
|
YOUTUBE_URL_2, |
|
YOUTUBE_URL_3], PATH_WORK + YOUTUBE_DIR), |
|
OpenAIWhisperParser()) |
|
docs.extend(loader.load()) |
|
|
|
text_splitter = RecursiveCharacterTextSplitter(chunk_overlap = 150, |
|
chunk_size = 1500) |
|
splits = text_splitter.split_documents(docs) |
|
|
|
splittet = True |
|
return splits |
|
|
|
|
|
def document_storage_chroma(splits): |
|
Chroma.from_documents(documents = splits, |
|
embedding = OpenAIEmbeddings(disallowed_special = ()), |
|
persist_directory = PATH_WORK + CHROMA_DIR) |
|
|
|
|
|
def document_storage_mongodb(splits): |
|
MongoDBAtlasVectorSearch.from_documents(documents = splits, |
|
embedding = OpenAIEmbeddings(disallowed_special = ()), |
|
collection = MONGODB_COLLECTION, |
|
index_name = MONGODB_INDEX_NAME) |
|
|
|
|
|
def document_retrieval_chroma(llm, prompt): |
|
embeddings = OpenAIEmbeddings() |
|
|
|
|
|
db = Chroma(embedding_function = embeddings, |
|
persist_directory = PATH_WORK + CHROMA_DIR) |
|
|
|
return db |
|
|
|
|
|
def document_retrieval_mongodb(llm, prompt): |
|
db = MongoDBAtlasVectorSearch.from_connection_string(MONGODB_URI, |
|
MONGODB_DB_NAME + "." + MONGODB_COLLECTION_NAME, |
|
OpenAIEmbeddings(disallowed_special = ()), |
|
index_name = MONGODB_INDEX_NAME) |
|
return db |
|
|
|
|
|
|
|
|
|
|
|
def llm_chain(llm, prompt): |
|
llm_chain = LLMChain(llm = llm, prompt = LLM_CHAIN_PROMPT) |
|
result = llm_chain.run({"question": prompt}) |
|
return result |
|
|
|
|
|
def rag_chain(llm, prompt, db): |
|
rag_chain = RetrievalQA.from_chain_type(llm, |
|
chain_type_kwargs = {"prompt": RAG_CHAIN_PROMPT}, |
|
retriever = db.as_retriever(search_kwargs = {"k": 3}), |
|
return_source_documents = True) |
|
result = rag_chain({"query": prompt}) |
|
return result["result"] |
|
|
|
|
|
|
|
|
|
|
|
def generate_prompt_with_history(text, history, max_length=2048): |
|
|
|
|
|
prompt="" |
|
history = ["\n{}\n{}".format(x[0],x[1]) for x in history] |
|
history.append("\n{}\n".format(text)) |
|
history_text = "" |
|
flag = False |
|
for x in history[::-1]: |
|
history_text = x + history_text |
|
flag = True |
|
|
|
if flag: |
|
return prompt+history_text |
|
else: |
|
return None |
|
|
|
|
|
def generate_prompt_with_history_openai(prompt, history): |
|
history_openai_format = [] |
|
for human, assistant in history: |
|
history_openai_format.append({"role": "user", "content": human }) |
|
history_openai_format.append({"role": "assistant", "content":assistant}) |
|
|
|
history_openai_format.append({"role": "user", "content": prompt}) |
|
return history_openai_format |
|
|
|
|
|
def generate_prompt_with_history_hf(prompt, history): |
|
history_transformer_format = history + [[prompt, ""]] |
|
|
|
|
|
messages = "".join(["".join(["\n<human>:"+item[0], "\n<bot>:"+item[1]]) |
|
for item in history_transformer_format]) |
|
|
|
|
|
def generate_prompt_with_history_langchain(prompt, history): |
|
history_langchain_format = [] |
|
for human, ai in history: |
|
history_langchain_format.append(HumanMessage(content=human)) |
|
history_langchain_format.append(AIMessage(content=ai)) |
|
history_langchain_format.append(HumanMessage(content=prompt)) |
|
|
|
return history_langchain_format |
|
|
|
|
|
|
|
|
|
def invoke (prompt, history, openai_api_key, rag_option, temperature=0.9, max_new_tokens=512, top_p=0.6, repetition_penalty=1.3,): |
|
global splittet |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
history_text_und_prompt = generate_prompt_with_history_langchain(prompt, history) |
|
|
|
if (openai_api_key == "" or openai_api_key == "sk-"): |
|
|
|
|
|
openai_api_key= OAI_API_KEY |
|
if (rag_option is None): |
|
raise gr.Error("Retrieval Augmented Generation ist erforderlich.") |
|
if (prompt == ""): |
|
raise gr.Error("Prompt ist erforderlich.") |
|
try: |
|
|
|
llm = ChatOpenAI(model_name = MODEL_NAME, |
|
openai_api_key = openai_api_key, |
|
temperature = 0) |
|
|
|
if (rag_option == "Chroma"): |
|
|
|
if not splittet: |
|
splits = document_loading_splitting() |
|
document_storage_chroma(splits) |
|
db = document_retrieval_chroma(llm, history_text_und_prompt) |
|
result = rag_chain(llm, history_text_und_prompt, db) |
|
elif (rag_option == "MongoDB"): |
|
|
|
|
|
db = document_retrieval_mongodb(llm, history_text_und_prompt) |
|
result = rag_chain(llm, history_text_und_prompt, db) |
|
else: |
|
result = llm_chain(llm, history_text_und_prompt) |
|
|
|
except Exception as e: |
|
raise gr.Error(e) |
|
|
|
|
|
for i in range(len(result)): |
|
time.sleep(0.05) |
|
yield result[: i+1] |
|
|
|
|
|
|
|
|
|
|
|
|
|
title = "LLM mit RAG" |
|
description = """<strong>Überblick:</strong> Hier wird ein <strong>Large Language Model (LLM)</strong> mit |
|
<strong>Retrieval Augmented Generation (RAG)</strong> auf <strong>externen Daten</strong> demonstriert.\n\n |
|
<strong>Genauer:</strong> Folgende externe Daten sind als Beispiel gegeben: |
|
<a href='""" + YOUTUBE_URL_1 + """'>YouTube</a>, <a href='""" + PDF_URL + """'>PDF</a>, and <a href='""" + WEB_URL + """'>Web.</a> <br> |
|
Alle neueren Datums!. |
|
<ul style="list-style-type:square;"> |
|
<li>Setze "Retrieval Augmented Generation" auf "<strong>Off</strong>" und gib einen Prompt ein." Das entspricht <strong> ein LLM nutzen ohne RAG</strong></li> |
|
<li>Setze "Retrieval Augmented Generation" to "<strong>Chroma</strong>" und gib einen Prompt ein. Das <strong>LLM mit RAG</strong> weiß auch Antworten zu aktuellen Themen aus den angefügten Datenquellen</li> |
|
<li>Experimentiere mit Prompts, z.B. Antworte in deutsch, englisch, ..." oder "schreibe ein Python Programm, dass die GPT-4 API aufruft."</li> |
|
</ul>\n\n |
|
""" |
|
css = """.toast-wrap { display: none !important } """ |
|
examples=[['Was ist ChtGPT-4?'],['schreibe ein Python Programm, dass die GPT-4 API aufruft.']] |
|
|
|
def vote(data: gr.LikeData): |
|
if data.liked: print("You upvoted this response: " + data.value) |
|
else: print("You downvoted this response: " + data.value) |
|
|
|
additional_inputs = [ |
|
gr.Textbox(label = "OpenAI API Key", value = "sk-", lines = 1), |
|
|
|
gr.Radio(["Off", "Chroma"], label="Retrieval Augmented Generation", value = "Off"), |
|
gr.Slider(label="Temperature", value=0.9, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Höhere Werte erzeugen diversere Antworten"), |
|
gr.Slider(label="Max new tokens", value=256, minimum=0, maximum=4096, step=64, interactive=True, info="Maximale Anzahl neuer Tokens"), |
|
gr.Slider(label="Top-p (nucleus sampling)", value=0.6, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Höhere Werte verwenden auch Tokens mit niedrigerer Wahrscheinlichkeit."), |
|
gr.Slider(label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Strafe für wiederholte Tokens") |
|
] |
|
|
|
chatbot_stream = gr.Chatbot() |
|
|
|
chat_interface_stream = gr.ChatInterface(fn=invoke, |
|
|
|
title = "Generative AI - LLM & RAG", |
|
theme="soft", |
|
chatbot=chatbot_stream, |
|
retry_btn="Wiederholen", |
|
undo_btn="Letztes löschen", |
|
clear_btn="Verlauf löschen", |
|
additional_inputs=additional_inputs, |
|
description = description) |
|
|
|
with gr.Blocks() as demo: |
|
with gr.Tab("Chatbot"): |
|
chatbot_stream.like(vote, None, None) |
|
chat_interface_stream.queue().launch() |