Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
!pip install langchain
|
| 2 |
+
!pip install langchain pypdf
|
| 3 |
+
!pip install openai==0.28
|
| 4 |
+
!pip install chromadb
|
| 5 |
+
!pip install tiktoken
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import openai
|
| 9 |
+
import numpy as np
|
| 10 |
+
import getpass
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
from langchain.llms import OpenAI
|
| 14 |
+
from langchain.vectorstores import Chroma
|
| 15 |
+
from langchain_community.document_loaders import TextLoader
|
| 16 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter
|
| 17 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 18 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 19 |
+
|
| 20 |
+
documents = []
|
| 21 |
+
loader = TextLoader("sentences.txt")
|
| 22 |
+
documents.extend(loader.load())
|
| 23 |
+
|
| 24 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 25 |
+
chunk_size = 1000,
|
| 26 |
+
chunk_overlap = 150
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Recursive Splitting the whole text of emails into chunks
|
| 30 |
+
splits = text_splitter.split_documents(documents)
|
| 31 |
+
|
| 32 |
+
# Creating the Embeddings from the splits we created
|
| 33 |
+
embedding = OpenAIEmbeddings(openai_api_key='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')
|
| 34 |
+
|
| 35 |
+
# Storing the Embeddings into ChromaDB
|
| 36 |
+
persist_directory = 'docs/chroma/'
|
| 37 |
+
vectordb = Chroma.from_documents(
|
| 38 |
+
documents=splits[0:500],
|
| 39 |
+
embedding=embedding,
|
| 40 |
+
persist_directory=persist_directory
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
retriever = vectordb.as_retriever(search_type="similarity", search_kwargs={"k":2})
|
| 44 |
+
qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), retriever)
|
| 45 |
+
|
| 46 |
+
def respond(message, history):
|
| 47 |
+
chat_history = []
|
| 48 |
+
print(message)
|
| 49 |
+
print(chat_history)
|
| 50 |
+
# Getting the response from QA langchain
|
| 51 |
+
response = qa({"question": message, "chat_history": chat_history})
|
| 52 |
+
|
| 53 |
+
# Append user messages and responses to chat history
|
| 54 |
+
chat_history.append((message, response['answer']))
|
| 55 |
+
print(chat_history)
|
| 56 |
+
return response['answer']
|
| 57 |
+
|
| 58 |
+
gr.ChatInterface(respond).launch(debug=True)
|