Spaces:
Build error
Build error
from langchain.chains import ConversationalRetrievalChain | |
from langchain.chat_models import ChatOpenAI | |
from langchain.vectorstores import Pinecone | |
from langchain.embeddings.openai import OpenAIEmbeddings | |
from langchain.memory import ConversationBufferMemory | |
import pinecone | |
import os | |
import logging | |
# Load environment variables | |
from dotenv import load_dotenv | |
load_dotenv() | |
# Retrieve values from .env file | |
pinecone_api_key = '228cca47-e537-42af-bcef-569cb18fb7cf' | |
pinecone_environment = 'us-west1-gcp-free' | |
pinecone_index_name = 'chatbot' | |
openai_api_key = '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' | |
# Set up logging | |
logging.basicConfig(level=logging.DEBUG) | |
logger = logging.getLogger(__name__) | |
def create_conversation(query: str, chat_history: list) -> tuple: | |
logger.debug("Starting create_conversation function") | |
try: | |
logger.debug("Initializing Pinecone") | |
pinecone.init(api_key=pinecone_api_key, environment=pinecone_environment) | |
logger.debug("Pinecone initialized") | |
logger.debug("Creating embeddings") | |
embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key) | |
logger.debug("Embeddings created") | |
logger.debug("Accessing existing Pinecone index") | |
db = Pinecone.from_existing_index(index_name=pinecone_index_name, embedding=embeddings) | |
logger.debug("Index accessed") | |
logger.debug("Setting up memory for conversation") | |
memory = ConversationBufferMemory(memory_key='chat_history', return_messages=False) | |
logger.debug("Memory set up") | |
logger.debug("Creating ConversationalRetrievalChain") | |
cqa = ConversationalRetrievalChain.from_llm( | |
llm=ChatOpenAI(temperature=0.0, openai_api_key=openai_api_key), | |
retriever=db.as_retriever(), | |
memory=memory, | |
get_chat_history=lambda h: h, | |
) | |
logger.debug("ConversationalRetrievalChain created") | |
logger.debug(f"Processing query: {query}") | |
result = cqa({'question': query, 'chat_history': chat_history}) | |
logger.debug(f"Received result: {result}") | |
logger.debug("Appending result to chat history") | |
chat_history.append((query, result['answer'])) | |
logger.debug(f"Updated chat history: {chat_history}") | |
return '', chat_history | |
except Exception as e: | |
logger.exception("Exception occurred in create_conversation") | |
chat_history.append((query, "Error: " + str(e))) | |
return '', chat_history | |