Spaces:
Sleeping
Sleeping
Update chatbot_backend.py
Browse files- chatbot_backend.py +40 -32
chatbot_backend.py
CHANGED
|
@@ -1,41 +1,49 @@
|
|
| 1 |
import os
|
| 2 |
-
|
| 3 |
-
from langchain_community.embeddings import OllamaEmbeddings
|
| 4 |
from langchain_community.document_loaders import TextLoader
|
| 5 |
-
from langchain.text_splitter import
|
| 6 |
-
from
|
| 7 |
-
from langchain.
|
| 8 |
from langchain.chains import ConversationalRetrievalChain
|
| 9 |
|
| 10 |
-
|
| 11 |
-
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
loader = TextLoader("data.txt"
|
| 18 |
docs = loader.load()
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
vectorstore
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
return_source_documents=False
|
| 33 |
)
|
| 34 |
|
| 35 |
-
#
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import asyncio
|
|
|
|
| 3 |
from langchain_community.document_loaders import TextLoader
|
| 4 |
+
from langchain.text_splitter import CharacterTextSplitter
|
| 5 |
+
from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
|
| 6 |
+
from langchain.vectorstores import FAISS
|
| 7 |
from langchain.chains import ConversationalRetrievalChain
|
| 8 |
|
| 9 |
+
google_api_key = os.getenv("GOOGLE_API_KEY")
|
|
|
|
| 10 |
|
| 11 |
+
# π’ Event loop safe embeddings initializer
|
| 12 |
+
def get_embeddings():
|
| 13 |
+
try:
|
| 14 |
+
asyncio.get_running_loop()
|
| 15 |
+
except RuntimeError:
|
| 16 |
+
loop = asyncio.new_event_loop()
|
| 17 |
+
asyncio.set_event_loop(loop)
|
| 18 |
+
|
| 19 |
+
return GoogleGenerativeAIEmbeddings(
|
| 20 |
+
model="models/embedding-001",
|
| 21 |
+
google_api_key=google_api_key
|
| 22 |
+
)
|
| 23 |
|
| 24 |
+
# π’ Use loader safely
|
| 25 |
+
loader = TextLoader("data.txt")
|
| 26 |
docs = loader.load()
|
| 27 |
+
|
| 28 |
+
# π’ Split text into chunks
|
| 29 |
+
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
|
| 30 |
+
documents = text_splitter.split_documents(docs)
|
| 31 |
+
|
| 32 |
+
# π’ Create vectorstore with embeddings
|
| 33 |
+
embeddings = get_embeddings()
|
| 34 |
+
db = FAISS.from_documents(documents, embeddings)
|
| 35 |
+
|
| 36 |
+
# π’ Conversational chain
|
| 37 |
+
qa = ConversationalRetrievalChain.from_llm(
|
| 38 |
+
ChatGoogleGenerativeAI(model="gemini-2.5-flash", google_api_key=google_api_key),
|
| 39 |
+
db.as_retriever()
|
|
|
|
| 40 |
)
|
| 41 |
|
| 42 |
+
# π’ Function to interact with bot
|
| 43 |
+
chat_history = []
|
| 44 |
+
|
| 45 |
+
def ask_bot(query: str):
|
| 46 |
+
global chat_history
|
| 47 |
+
result = qa({"question": query, "chat_history": chat_history})
|
| 48 |
+
chat_history.append((query, result["answer"]))
|
| 49 |
+
return result["answer"]
|