File size: 1,896 Bytes
2466361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os
from pathlib import Path

import gradio as gr
import hpqa
from langchain import VectorDBQA
from langchain.llms import OpenAI

os.environ["OPENAI_API_KEY"] = ""
index_path = Path("data/hpqa_faiss_index_500")


examples = [
    "How would you sneak into Hogwarts without being detected?",
    "Why did Snape kill Dumbledore?",
    "Who is the most badass wizard in the world?",
    "Who would win a fight between Dumbledore and a grizzly bear?",
    "How many siblings does Hermione have?",
    "Why are the Dursleys so mean to Harry?",
]


def api(question, temperature, api_key=None):
    if api_key is None or len(api_key) == 0:
        return "You must provide an OpenAI API key to use this demo πŸ‘‡"
    if len(question) == 0:
        return ""
    document_store = hpqa.load_document_store(index_path, openai_api_key=api_key)
    chain = VectorDBQA.from_chain_type(
        llm=OpenAI(temperature=temperature, openai_api_key=api_key),
        chain_type="stuff",
        vectorstore=document_store,
        return_source_documents=True,
    )
    response = chain(question)
    return response["result"].strip()


demo = gr.Blocks()

with demo:
    gr.Markdown("# πŸͺ„ Harry Potter Question-Answering with GPT πŸ€–")
    with gr.Row():
        with gr.Column():
            question = gr.Textbox(lines=4, label="Question")
            temperature = gr.Slider(0.0, 2.0, 0.7, step=0.1, label="🍺 Butterbeer Consumed")
            with gr.Row():
                clear = gr.Button("Clear")
                btn = gr.Button("Submit", variant="primary")
        with gr.Column():
            answer = gr.Textbox(lines=4, label="Answer")
            openai_api_key = gr.Textbox(type="password", label="OpenAI API key")
    btn.click(api, [question, temperature, openai_api_key], answer)
    clear.click(lambda _: "", question, question)
    gr.Examples(examples, question)
demo.launch()