File size: 2,115 Bytes
c9745b7
3fbc487
c9745b7
55c50f0
e053397
 
c9745b7
 
 
 
 
 
 
 
55c50f0
c9745b7
 
 
 
 
 
 
 
 
3fbc487
 
 
 
 
 
c9745b7
 
 
 
 
 
 
 
 
 
 
 
 
 
55c50f0
c9745b7
 
 
 
 
 
3fbc487
 
 
 
 
 
 
c9745b7
 
 
 
 
 
 
 
 
 
 
 
96f9472
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
import openai
import gradio as gr
import chromadb
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings

# Set the OpenAI API key
os.environ["OPENAI_API_KEY"] = "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"

# Create an instance of the OpenAIEmbeddings class
embeddings = openai.OpenAIEmbeddings(model="text-embedding-ada-002")

# Create a Chroma database
database = chromadb.Database("database.db")

# Function to create embeddings from a text document
def create_embeddings(text):
    return embeddings.create_embeddings(text)

# Function to save embeddings to the Chroma database
def save_embeddings(embeddings):
    database.insert_embeddings(embeddings)

# Function to load the source document
def load_source_document():
    with open("source.txt", "r") as f:
        text = f.read()
    return text

# Function to create a chatbot
def create_chatbot():
    engine = gr.engine.Engine(title="Chatbot")

    # Function to handle user input
    def handle_input(input_text):
        # Get the embeddings for the user input
        embeddings = create_embeddings(input_text)

        # Find the most similar document in the database
        document = database.find_most_similar_document(embeddings)

        # Generate a response using the GPT-3.5 Turbo model
        response = openai.Completion.create(
            engine="text-davinci-003",
            prompt="Generate a response to the query: " + document["text"],
            max_tokens=100,
        )

        return response["choices"][0]["text"]

    # Load the source document
    text = load_source_document()

    # Create embeddings from the source document and save them in the Chroma database
    embeddings = create_embeddings(text)
    save_embeddings(embeddings)

    # Create a button to start the chatbot
    button = gr.Button(label="Start Chatting", description="Click to start chatting", on_click=handle_input)

    # Add the button to the chatbot
    engine.add_element(button)

    return engine

# Create the chatbot
chatbot = create_chatbot()

# Run the chatbot
chatbot.launch()