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()