Spaces:
Runtime error
Runtime error
File size: 11,615 Bytes
6c0508a 84db1d7 19d1eae 6c0508a ab850a0 6c0508a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | import os
import re
import logging
import requests
import lxml
import gradio as gr
from bs4 import BeautifulSoup
import openai
import pinecone
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)
# Set OpenAI API key and Pinecone API key (secrets)
openai.api_key = os.environ.get('OPENAI_API_KEY')
PINECONE_API_KEY = os.environ.get('PINECONE_API_KEY')
# Initialize Pinecone
pinecone.init(api_key=PINECONE_API_KEY, environment="us-east1-gcp")
index_name = 'openai-index'
if index_name not in pinecone.list_indexes():
pinecone.create_index(index_name, dimension=1536, metric='cosine')
index = pinecone.Index(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])
def chatbot(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)}\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)
return response
# Get the response from ChatGPT-3.5
def get_gpt_response(prompt):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {openai.api_key}",
}
data = {
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": "You are a customer success manager for Resquared that answers questions based on the knowledge base and adapts our pre-made templates based on user requests."},
{"role": "user", "content": "generate a response and be sure to analyze the data from our knowledge base you are provided"},
{
"role": "user",
"content": f"I am a client with a request based on the Resquared knowledge base. Resquared's product has data on every local business and tools for contacting them. Model your answer, in fact tone and style, on the following information from the Resquared knowledge base. If i ask you for a template, you should generate a concise and informal template that closely resembles the structure, length, tone, and style of the example templates I provided which should never be more than 90 words.: {prompt}"
}
],
"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()
iface = gr.Interface(fn=chatbot,
inputs=gr.inputs.Textbox(lines=7, label="Enter your text"),
outputs=gr.outputs.Textbox(),
title="Resquared Knowledge Base Bot")
iface.launch()
|