Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,8 @@
|
|
| 1 |
-
import openai
|
| 2 |
-
import streamlit as st
|
| 3 |
-
import smtplib
|
| 4 |
-
from email.mime.multipart import MIMEMultipart
|
| 5 |
-
from email.mime.text import MIMEText
|
| 6 |
-
import os
|
| 7 |
-
import asyncio
|
| 8 |
import logging
|
|
|
|
|
|
|
| 9 |
from dotenv import load_dotenv
|
|
|
|
| 10 |
from langchain_openai import ChatOpenAI
|
| 11 |
from langchain_community.vectorstores import FAISS
|
| 12 |
from langchain_openai import OpenAIEmbeddings
|
|
@@ -17,6 +13,8 @@ from langchain.agents.format_scratchpad.openai_tools import format_to_openai_too
|
|
| 17 |
from langchain_core.messages import AIMessage, HumanMessage
|
| 18 |
from langchain_community.document_loaders import TextLoader
|
| 19 |
from langchain_text_splitters import CharacterTextSplitter
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# Initialize logging
|
| 22 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -25,97 +23,161 @@ logger = logging.getLogger(__name__)
|
|
| 25 |
# Load environment variables from .env file
|
| 26 |
load_dotenv()
|
| 27 |
|
| 28 |
-
# API
|
| 29 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 30 |
-
|
| 31 |
-
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD")
|
| 32 |
-
SMTP_SERVER = "mail.privateemail.com"
|
| 33 |
-
SMTP_PORT = 587
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
st.error("API keys
|
| 38 |
-
|
| 39 |
|
| 40 |
# Initialize OpenAI client
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
try:
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
| 56 |
except Exception as e:
|
| 57 |
-
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
@st.cache_resource
|
| 61 |
-
def load_knowledge_base():
|
| 62 |
-
loader = TextLoader("./data_source/time_to_rethink_trust_book.md")
|
| 63 |
-
documents = loader.load()
|
| 64 |
-
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
|
| 65 |
-
return text_splitter.split_documents(documents)
|
| 66 |
|
| 67 |
# Initialize embeddings and FAISS index
|
| 68 |
-
|
| 69 |
-
embeddings = OpenAIEmbeddings()
|
| 70 |
-
db = FAISS.from_documents(knowledge_base, embeddings)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
#
|
| 73 |
def rag_response(query):
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
llm = ChatOpenAI(model="gpt-4o", temperature=0.5)
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import logging
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
+
import openai
|
| 6 |
from langchain_openai import ChatOpenAI
|
| 7 |
from langchain_community.vectorstores import FAISS
|
| 8 |
from langchain_openai import OpenAIEmbeddings
|
|
|
|
| 13 |
from langchain_core.messages import AIMessage, HumanMessage
|
| 14 |
from langchain_community.document_loaders import TextLoader
|
| 15 |
from langchain_text_splitters import CharacterTextSplitter
|
| 16 |
+
import serpapi
|
| 17 |
+
import streamlit as st
|
| 18 |
|
| 19 |
# Initialize logging
|
| 20 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 23 |
# Load environment variables from .env file
|
| 24 |
load_dotenv()
|
| 25 |
|
| 26 |
+
# Define and validate API keys
|
| 27 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 28 |
+
serper_api_key = os.getenv("SERPER_API_KEY")
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
if not openai_api_key or not serper_api_key:
|
| 31 |
+
logger.error("API keys are not set properly.")
|
| 32 |
+
st.error("API keys for OpenAI and SERPER must be set in the .env file.")
|
| 33 |
+
st.stop()
|
| 34 |
|
| 35 |
# Initialize OpenAI client
|
| 36 |
+
try:
|
| 37 |
+
openai.api_key = openai_api_key
|
| 38 |
+
logger.info("OpenAI client initialized successfully.")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.error(f"Error initializing OpenAI client: {e}")
|
| 41 |
+
st.error(f"Error initializing OpenAI client: {e}")
|
| 42 |
+
st.stop()
|
| 43 |
+
|
| 44 |
+
# Load knowledge base
|
| 45 |
+
def load_knowledge_base():
|
| 46 |
try:
|
| 47 |
+
loader = TextLoader("./data_source/time_to_rethink_trust_book.md")
|
| 48 |
+
documents = loader.load()
|
| 49 |
+
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
|
| 50 |
+
docs = text_splitter.split_documents(documents)
|
| 51 |
+
return docs
|
| 52 |
except Exception as e:
|
| 53 |
+
logger.error(f"Error loading knowledge base: {e}")
|
| 54 |
+
st.error(f"Error loading knowledge base: {e}")
|
| 55 |
+
st.stop()
|
| 56 |
|
| 57 |
+
knowledge_base = load_knowledge_base()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
# Initialize embeddings and FAISS index
|
| 60 |
+
try:
|
| 61 |
+
embeddings = OpenAIEmbeddings()
|
| 62 |
+
db = FAISS.from_documents(knowledge_base, embeddings)
|
| 63 |
+
except Exception as e:
|
| 64 |
+
logger.error(f"Error initializing FAISS index: {e}")
|
| 65 |
+
st.error(f"Error initializing FAISS index: {e}")
|
| 66 |
+
st.stop()
|
| 67 |
+
|
| 68 |
+
# Define search function for knowledge base
|
| 69 |
+
def search_knowledge_base(query):
|
| 70 |
+
try:
|
| 71 |
+
output = db.similarity_search(query)
|
| 72 |
+
return output
|
| 73 |
+
except Exception as e:
|
| 74 |
+
logger.error(f"Error searching knowledge base: {e}")
|
| 75 |
+
return ["Error occurred during knowledge base search"]
|
| 76 |
+
|
| 77 |
+
# SERPER API Google Search function
|
| 78 |
+
def google_search(query):
|
| 79 |
+
try:
|
| 80 |
+
search_client = serpapi.Client(api_key=serper_api_key)
|
| 81 |
+
results = search_client.search({"engine": "google", "q": query})
|
| 82 |
+
snippets = [result["snippet"] for result in results.get("organic_results", [])]
|
| 83 |
+
return snippets
|
| 84 |
+
except requests.exceptions.HTTPError as http_err:
|
| 85 |
+
logger.error(f"HTTP error occurred: {http_err}")
|
| 86 |
+
return ["HTTP error occurred during Google search"]
|
| 87 |
+
except Exception as e:
|
| 88 |
+
logger.error(f"General Error: {e}")
|
| 89 |
+
return ["Error occurred during Google search"]
|
| 90 |
|
| 91 |
+
# RAG response function
|
| 92 |
def rag_response(query):
|
| 93 |
+
try:
|
| 94 |
+
retrieved_docs = search_knowledge_base(query)
|
| 95 |
+
context = "\n".join(doc.page_content for doc in retrieved_docs)
|
| 96 |
+
prompt = f"Context:\n{context}\n\nQuestion: {query}\nAnswer:"
|
| 97 |
+
llm = ChatOpenAI(model="gpt-4o", temperature=0.5, api_key=openai_api_key)
|
| 98 |
+
response = llm.invoke(prompt)
|
| 99 |
+
return response.content
|
| 100 |
+
except Exception as e:
|
| 101 |
+
logger.error(f"Error generating RAG response: {e}")
|
| 102 |
+
return "Error occurred during RAG response generation"
|
| 103 |
+
|
| 104 |
+
# Define tools using LangChain's `tool` decorator
|
| 105 |
+
@tool
|
| 106 |
+
def knowledge_base_tool(query: str):
|
| 107 |
+
return rag_response(query)
|
| 108 |
+
|
| 109 |
+
@tool
|
| 110 |
+
def google_search_tool(query: str):
|
| 111 |
+
return google_search(query)
|
| 112 |
+
|
| 113 |
+
tools = [knowledge_base_tool, google_search_tool]
|
| 114 |
+
|
| 115 |
+
# Create the prompt template
|
| 116 |
+
prompt_message = """
|
| 117 |
+
Act as an expert copywriter who specializes in creating compelling marketing copy using AI technologies.
|
| 118 |
+
Engage in a friendly and informative conversation based on the knowledge base.
|
| 119 |
+
Only proceed to create sales materials when the user explicitly requests it.
|
| 120 |
+
Work together with the user to update the outcome of the sales material.
|
| 121 |
+
"""
|
| 122 |
+
prompt_template = ChatPromptTemplate.from_messages(
|
| 123 |
+
[
|
| 124 |
+
("system", prompt_message),
|
| 125 |
+
MessagesPlaceholder(variable_name="chat_history"),
|
| 126 |
+
("user", "{input}"),
|
| 127 |
+
MessagesPlaceholder(variable_name="agent_scratchpad"),
|
| 128 |
+
]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Create Langchain Agent with specific model and temperature
|
| 132 |
+
try:
|
| 133 |
llm = ChatOpenAI(model="gpt-4o", temperature=0.5)
|
| 134 |
+
llm_with_tools = llm.bind_tools(tools)
|
| 135 |
+
except Exception as e:
|
| 136 |
+
logger.error(f"Error creating Langchain Agent: {e}")
|
| 137 |
+
st.error(f"Error creating Langchain Agent: {e}")
|
| 138 |
+
st.stop()
|
| 139 |
+
|
| 140 |
+
# Define the agent pipeline to handle the conversation flow
|
| 141 |
+
try:
|
| 142 |
+
agent = (
|
| 143 |
+
{
|
| 144 |
+
"input": lambda x: x["input"],
|
| 145 |
+
"agent_scratchpad": lambda x: format_to_openai_tool_messages(x["intermediate_steps"]),
|
| 146 |
+
"chat_history": lambda x: x["chat_history"],
|
| 147 |
+
}
|
| 148 |
+
| prompt_template
|
| 149 |
+
| llm_with_tools
|
| 150 |
+
| OpenAIToolsAgentOutputParser()
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Instantiate an AgentExecutor to execute the defined agent pipeline
|
| 154 |
+
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
| 155 |
+
except Exception as e:
|
| 156 |
+
logger.error(f"Error defining agent pipeline: {e}")
|
| 157 |
+
st.error(f"Error defining agent pipeline: {e}")
|
| 158 |
+
st.stop()
|
| 159 |
+
|
| 160 |
+
# Initialize chat history
|
| 161 |
+
chat_history = []
|
| 162 |
+
|
| 163 |
+
def chatbot_response(message, history):
|
| 164 |
+
try:
|
| 165 |
+
output = agent_executor.invoke({"input": message, "chat_history": chat_history})
|
| 166 |
+
chat_history.extend([HumanMessage(content=message), AIMessage(content=output["output"])])
|
| 167 |
+
return output["output"]
|
| 168 |
+
except Exception as e:
|
| 169 |
+
logger.error(f"Error generating chatbot response: {e}")
|
| 170 |
+
return "Error occurred during response generation"
|
| 171 |
+
|
| 172 |
+
# Streamlit app
|
| 173 |
+
st.title("Instant Insight-2-Action")
|
| 174 |
+
|
| 175 |
+
# User input
|
| 176 |
+
user_input = st.text_input("You:", "")
|
| 177 |
+
|
| 178 |
+
if st.button("Submit"):
|
| 179 |
+
if user_input:
|
| 180 |
+
response = chatbot_response(user_input, chat_history)
|
| 181 |
+
st.write("AI:", response)
|
| 182 |
+
else:
|
| 183 |
+
st.warning("Please enter a message.")
|