sales-bot / app.py
skolmuirgheasa's picture
Update app.py
2b4bb0c verified
Raw History Blame Contribute Delete
13.5 kB
import os
import re
import logging
import requests
import lxml
import gradio as gr
import asyncio
from bs4 import BeautifulSoup
import openai
from pinecone import Pinecone, ServerlessSpec
from lxml import etree
import tiktoken
import time
import PyPDF2
import numpy as np
import csv
import json
from uuid import uuid4
import certifi
import urllib3.contrib.pyopenssl
import nltk
# Download necessary nltk data
nltk.download("punkt")
nltk.download("averaged_perceptron_tagger")
# Configure SSL certificate
os.environ["SSL_CERT_FILE"] = certifi.where()
urllib3.contrib.pyopenssl.inject_into_urllib3()
# Configure logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("pinecone").setLevel(logging.WARNING)
## When hosting on huggingface switch to
openai.api_key = os.environ.get('OPENAI_API_KEY')
PINECONE_API_KEY = os.environ.get('PINECONE_API_KEY')
pc = Pinecone(api_key=PINECONE_API_KEY)
index_name = 'openai-index'
# Check if the index exists, and create it if it does not
if index_name not in pc.list_indexes().names():
pc.create_index(
name=index_name,
dimension=1536,
metric='cosine',
spec=ServerlessSpec(
cloud='gcp', # Change to 'aws' or 'gcp' as needed
region='us-east1' # Adjust the region according to your Pinecone plan
)
)
# Use the index for operations
index = pc.Index(name=index_name)
def create_embeddings(text_chunks, model="text-embedding-ada-002", encoding_name="cl100k_base"):
embeddings = []
try:
prepared_chunks = [chunk.replace("\n", " ") for chunk in text_chunks]
response = openai.Embedding.create(input=prepared_chunks, model=model)
if response and "data" in response:
for data in response["data"]:
embedding = data["embedding"]
if len(embedding) == 1536: # Check if the embedding has the correct dimension
embeddings.append(embedding)
else:
print(f"Invalid embedding dimension: {len(embedding)}")
return embeddings
except Exception as e:
print(f"Error creating embeddings: {e}")
return embeddings # Always return embeddings, even if it's empty
def store_embeddings_in_pinecone(ids, embeddings_list, metadata_list):
if len(ids) != len(embeddings_list) or len(ids) != len(metadata_list):
print("Error: IDs, embeddings, and metadata lists must have the same length.")
return
to_upsert = []
for i in range(len(ids)):
id = ids[i]
embedding = embeddings_list[i]
metadata = metadata_list[i]
metadata["timestamp"] = time.time()
to_upsert.append((id, embedding, metadata))
if metadata['source'] == 'document':
print(f"Storing document: {metadata['filename']} with id: {id}")
elif metadata['source'] == 'chat':
print(f"Storing chat: {metadata.get('input')} with id: {id}")
else:
print(f"Storing {metadata['source']} with id: {id}")
try:
index.upsert(vectors=to_upsert) # Modify this line
except Exception as e:
print(f"Error storing embeddings in Pinecone: {e}")
def fetch_webpage_content(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')
text_elements = soup.select('p, h1, h2, h3, h4, h5, h6')
text = ' '.join([element.get_text() for element in text_elements])
return text
def process_directory(directory_path):
print(f"Processing directory: {directory_path}")
for file in os.listdir(directory_path):
if file.endswith(".txt"):
with open(os.path.join(directory_path, file), 'r') as f:
text = f.read()
embeddings = create_embeddings([text])
id = str(uuid4())
metadata = {'source': 'document', 'timestamp': time.time()}
store_embeddings_in_pinecone([id], embeddings, [metadata])
def num_tokens_from_string(string: str, encoding_name: str) -> int:
"""Returns the number of tokens in a text string."""
enc = tiktoken.get_encoding(encoding_name)
tokens = enc.encode(string)
return len(tokens)
def chunk_document(text, encoding_name, max_tokens):
chunks = []
current_chunk = []
current_token_count = 0
for sentence in text.split('. '):
sentence_tokens = num_tokens_from_string(sentence, encoding_name)
if current_token_count + sentence_tokens <= max_tokens:
current_chunk.append(sentence)
current_token_count += sentence_tokens
else:
chunks.append('. '.join(current_chunk))
current_chunk = [sentence]
current_token_count = sentence_tokens
if current_chunk:
chunks.append('. '.join(current_chunk))
return chunks
def index_documents():
max_tokens_per_chunk = 2048
encoding_name = "cl100k_base"
model = "text-embedding-ada-002"
for filename in os.listdir("docs"):
if filename.endswith(".txt"):
with open(os.path.join("docs", filename), 'r') as f:
text = f.read()
elif filename.endswith(".pdf"):
with open(os.path.join("docs", filename), 'rb') as f:
pdf = PyPDF2.PdfFileReader(f)
text = " ".join(page.extract_text() for page in pdf.pages)
elif filename.endswith(".csv"):
with open(os.path.join("docs", filename), 'r') as csvfile:
reader = csv.reader(csvfile)
text = " ".join(" ".join(row) for row in reader)
else:
continue # Skip other file types
chunks = chunk_document(text, encoding_name, max_tokens_per_chunk)
for i, chunk in enumerate(chunks):
embeddings = create_embeddings([chunk], model, encoding_name)
if embeddings:
id = str(uuid4())
metadata = {'source': 'document', 'filename': f"{filename}_chunk_{i}", 'text': chunk, 'timestamp': time.time()}
store_embeddings_in_pinecone([id], embeddings, [metadata])
# Define a dictionary to store conversation history. Currently disabled.
# conversation_history = {}
def chatbot(input_text, user_id):
# Store user's prompt in conversation history
# if user_id not in conversation_history:
# conversation_history[user_id] = {'user_prompts': [], 'bot_responses': []}
# conversation_history[user_id]['user_prompts'].append(input_text)
url_pattern = re.compile(r'https?://[^\s]+')
url_match = url_pattern.search(input_text)
embeddings = []
webpage_text = ""
if url_match:
specific_url = url_match.group()
input_text = url_pattern.sub('', input_text)
webpage_text = fetch_webpage_content(specific_url)
chunks = chunk_document(webpage_text, "cl100k_base", 2048)
for chunk in chunks:
chunk_embeddings = create_embeddings([chunk])
if chunk_embeddings:
id = str(uuid4())
metadata = {'source': 'website', 'url': specific_url, 'text': chunk, 'timestamp': time.time()}
store_embeddings_in_pinecone([id], chunk_embeddings, [metadata])
input_text = f"From the website: {webpage_text}\n\nQuestion: {input_text}"
embeddings = create_embeddings([webpage_text]) # Create embeddings from the webpage text
id = str(uuid4())
metadata = {'source': 'website', 'url': specific_url, 'timestamp': time.time()}
store_embeddings_in_pinecone([id], embeddings, [metadata])
# Query Pinecone for similar embeddings
if embeddings: # Only query Pinecone if embeddings were created
results = index.query(queries=[embeddings[0]], top_k=5) # Query Pinecone with the webpage embeddings
else:
# Create embeddings from the input text if no URL was found
embeddings = create_embeddings([input_text])
if embeddings: # Only query Pinecone if embeddings were created
results = index.query(queries=[embeddings[0]], top_k=5) # Query Pinecone with the input text embeddings
else:
results = {'results': [{'matches': []}]} # Create an empty results object
print("Results:", results)
results_data = results['results'][0]['matches']
result_ids = [result['id'] for result in results_data]
# Find the best matches based on the weighted score and token limit
token_limit = 3500
similarity_threshold = 0.6 # Customize this value as needed
user_prompt_tokens = num_tokens_from_string(input_text, "cl100k_base")
matches = []
total_tokens = user_prompt_tokens
for result_id, result_data in zip(result_ids, results_data):
if result_data['score'] >= similarity_threshold:
fetched_data = index.fetch([result_id])['vectors'][result_id]['metadata']
match_text = ""
if fetched_data['source'] == 'document':
match_text = f"From the document {fetched_data['filename']}: {fetched_data.get('text', '')}"
elif fetched_data['source'] == 'website':
match_text = f"From the website {fetched_data['url']}: {fetched_data.get('text', '')}"
elif fetched_data['source'] == 'chat':
match_text = f"Previously, I mentioned: {fetched_data.get('response')}"
tokens_in_match = num_tokens_from_string(match_text, "cl100k_base")
if total_tokens + tokens_in_match <= token_limit:
matches.append(match_text)
total_tokens += tokens_in_match
# Prepare the final input text to be sent to ChatGPT-3.5
input_text = f"{' '.join(matches)}\nEND OF MEMORY, NOW REVIEW THE CONVERSATION WITH THE PROSPECT\n{input_text}"
# Print the final input text
print(f"Final input text: {input_text}")
# Get the response from ChatGPT-3.5
response = get_gpt_response(input_text, user_id)
# Store bot's response in conversation history
# conversation_history[user_id]['bot_responses'].append(response)
return response
# Define an async function to handle the chat
def handle_chat(input):
# history.value += [["user", input]]
response = chatbot(input, "user_id") # Replace "user_id" with actual user id
# history.value += [["assistant", response]]
return response
# Get the response from ChatGPT-3.5
def get_gpt_response(prompt, user_id):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {openai.api_key}",
}
# Initialize messages with the system message
messages = [
{"role": "system", "content": "You are a sales rep for Resquared."},
{"role": "user", "content": "give clear and helpful answers to help sell Resquared to me"},
]
# Add the conversation history to the messages
# for user_prompt, bot_response in zip(conversation_history[user_id]['user_prompts'], conversation_history[user_id]['bot_responses']):
# messages.append({"role": "user", "content": user_prompt})
# messages.append({"role": "assistant", "content": bot_response})
# Add the current user prompt to the messages
messages.append({
"role": "user",
"content": f"Your goal is to evaluate if you are chatting with a qualified prospective client of Resquared and understand their pain points related to selling to local businesses. A qualified client is someone who works for a business with at least 5 employees and they sell a product to brick and mortar businesses. Assess the chat history and specifically respond to the last message you see from the user. If they are qualified and you understand their painpoints or what they want Resquared to solve, encourage them to book a demo here https://meetings.hubspot.com/leonardo120/30min-demo-with-resquared This is your MEMORY of Resquared as well as the current history of the chat with Resquared's prospect {prompt}. Your responses should be concise and short and always be concluded with a single question either to understand if they are qualified or find pain points, or if this is already know this get them to book a demo using the link."
})
data = {
"model": "gpt-4-turbo-preview",
"messages": messages,
"temperature": 0.5
}
try:
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers=headers,
data=json.dumps(data)
)
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
return f"HTTP Error: {errh}"
except requests.exceptions.ConnectionError as errc:
return f"Error Connecting: {errc}"
except requests.exceptions.Timeout as errt:
return f"Timeout Error: {errt}"
except requests.exceptions.RequestException as err:
return f"Something went wrong: {err}"
response_json = response.json()
if "choices" in response_json and response_json["choices"]:
return response_json["choices"][0]["message"]["content"].strip()
else:
return "Sorry, I couldn't generate a response."
# Launch Gradio interface
if __name__ == "__main__":
index_documents()
history = gr.State([])
iface = gr.Interface(fn=handle_chat,
inputs=gr.inputs.Textbox(lines=7, label="Enter your text (if you aren't sure what to say, start with: What is Resquared?)"),
outputs=gr.outputs.Textbox(),
title="Resquared Sales Bot")
iface.launch()