File size: 1,324 Bytes
9304e75
 
 
 
 
4d43118
caeea50
4d43118
 
 
 
 
b08fa5c
4d43118
b08fa5c
 
 
 
398904b
9304e75
 
 
 
 
 
2b8b5e7
9304e75
 
 
 
 
 
 
 
 
 
 
 
f746608
 
 
 
 
 
02d873f
 
f746608
 
 
 
 
 
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

import os 
import openai
from dotenv import load_dotenv


API_KEY = os.getenv("open_ai-key")

# Write the API key to the .env file
with open(".env", "w") as env_file:
    env_file.write(f"openai_api_key={API_KEY}\n")
    
load_dotenv(".env")

openai.api_key = os.environ.get("openai_api_key")

os.environ["OPENAI_API_KEY"] = openai.api_key

with open("guide1.txt") as f:
    hitchhikersguide = f.read()

from langchain.text_splitter import CharacterTextSplitter

text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0, separator = "\n")
texts = text_splitter.split_text(hitchhikersguide)

from langchain.embeddings.openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()

from langchain.vectorstores import Chroma

docsearch = Chroma.from_texts(texts, embeddings, metadatas=[{"source": str(i)} for i in range(len(texts))]).as_retriever()

from langchain.chains.question_answering import load_qa_chain
from langchain.llms import OpenAI

chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff")

def question(text):
    query = text
    docs = docsearch.get_relevant_documents(query)
    return chain.run(input_documents=docs, question=query)

import gradio as gr

gr.Interface(
    question,
    inputs="text",
    outputs="text",
    title="Hitchhikers Guide Question Answering",
).launch()