Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,11 +16,9 @@ from langchain_text_splitters import CharacterTextSplitter
|
|
| 16 |
import serpapi
|
| 17 |
import requests
|
| 18 |
|
| 19 |
-
# Initialize logging
|
| 20 |
logging.basicConfig(level=logging.INFO)
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
-
|
| 23 |
-
# Load environment variables
|
| 24 |
load_dotenv()
|
| 25 |
|
| 26 |
# Define and validate API keys
|
|
@@ -31,7 +29,6 @@ if not openai_api_key or not serper_api_key:
|
|
| 31 |
logger.error("API keys are not set properly.")
|
| 32 |
raise ValueError("API keys for OpenAI and SERPER must be set in the .env file.")
|
| 33 |
|
| 34 |
-
# Initialize OpenAI client
|
| 35 |
openai.api_key = openai_api_key
|
| 36 |
|
| 37 |
# Load knowledge base
|
|
@@ -53,7 +50,7 @@ knowledge_base = load_knowledge_base()
|
|
| 53 |
embeddings = OpenAIEmbeddings()
|
| 54 |
db = FAISS.from_documents(knowledge_base, embeddings)
|
| 55 |
|
| 56 |
-
# Define search
|
| 57 |
def search_knowledge_base(query):
|
| 58 |
try:
|
| 59 |
output = db.similarity_search(query)
|
|
@@ -62,21 +59,14 @@ def search_knowledge_base(query):
|
|
| 62 |
logger.error(f"Error searching knowledge base: {e}")
|
| 63 |
return ["Error occurred during knowledge base search"]
|
| 64 |
|
| 65 |
-
# SERPER API Google Search function
|
| 66 |
def google_search(query):
|
| 67 |
try:
|
| 68 |
search_client = serpapi.Client(api_key=serper_api_key)
|
| 69 |
-
results = search_client.search({
|
| 70 |
-
"engine": "google",
|
| 71 |
-
"q": query,
|
| 72 |
-
})
|
| 73 |
snippets = [result["snippet"] for result in results.get("organic_results", [])]
|
| 74 |
return snippets
|
| 75 |
-
except requests.exceptions.HTTPError as http_err:
|
| 76 |
-
logger.error(f"HTTP error occurred: {http_err}")
|
| 77 |
-
return ["HTTP error occurred during Google search"]
|
| 78 |
except Exception as e:
|
| 79 |
-
logger.error(f"
|
| 80 |
return ["Error occurred during Google search"]
|
| 81 |
|
| 82 |
# RAG response function
|
|
@@ -107,10 +97,10 @@ tools = [knowledge_base_tool, google_search_tool]
|
|
| 107 |
|
| 108 |
# Create the prompt template
|
| 109 |
prompt_message = """
|
| 110 |
-
Act as an expert copywriter who specializes in
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
"""
|
| 115 |
|
| 116 |
prompt_template = ChatPromptTemplate.from_messages([
|
|
@@ -140,7 +130,7 @@ agent = (
|
|
| 140 |
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
| 141 |
|
| 142 |
# Streamlit app
|
| 143 |
-
st.title("
|
| 144 |
|
| 145 |
# Initialize chat history
|
| 146 |
if 'chat_history' not in st.session_state:
|
|
@@ -152,7 +142,7 @@ for message in st.session_state.chat_history:
|
|
| 152 |
st.markdown(message["content"])
|
| 153 |
|
| 154 |
# Chat input
|
| 155 |
-
if prompt := st.chat_input("
|
| 156 |
# Add user message to chat history
|
| 157 |
st.session_state.chat_history.append({"role": "user", "content": prompt})
|
| 158 |
|
|
@@ -168,15 +158,12 @@ if prompt := st.chat_input("Type your message here..."):
|
|
| 168 |
try:
|
| 169 |
# Generate response using the agent executor
|
| 170 |
output = agent_executor.invoke({
|
| 171 |
-
"input": prompt,
|
| 172 |
"chat_history": st.session_state.chat_history
|
| 173 |
})
|
| 174 |
full_response = output["output"]
|
| 175 |
|
| 176 |
-
# Display the response
|
| 177 |
-
for chunk in full_response.split():
|
| 178 |
-
full_response += chunk + " "
|
| 179 |
-
message_placeholder.markdown(full_response + "▌")
|
| 180 |
message_placeholder.markdown(full_response)
|
| 181 |
except Exception as e:
|
| 182 |
logger.error(f"Error generating response: {e}")
|
|
|
|
| 16 |
import serpapi
|
| 17 |
import requests
|
| 18 |
|
| 19 |
+
# Initialize logging and load environment variables
|
| 20 |
logging.basicConfig(level=logging.INFO)
|
| 21 |
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
| 22 |
load_dotenv()
|
| 23 |
|
| 24 |
# Define and validate API keys
|
|
|
|
| 29 |
logger.error("API keys are not set properly.")
|
| 30 |
raise ValueError("API keys for OpenAI and SERPER must be set in the .env file.")
|
| 31 |
|
|
|
|
| 32 |
openai.api_key = openai_api_key
|
| 33 |
|
| 34 |
# Load knowledge base
|
|
|
|
| 50 |
embeddings = OpenAIEmbeddings()
|
| 51 |
db = FAISS.from_documents(knowledge_base, embeddings)
|
| 52 |
|
| 53 |
+
# Define search functions
|
| 54 |
def search_knowledge_base(query):
|
| 55 |
try:
|
| 56 |
output = db.similarity_search(query)
|
|
|
|
| 59 |
logger.error(f"Error searching knowledge base: {e}")
|
| 60 |
return ["Error occurred during knowledge base search"]
|
| 61 |
|
|
|
|
| 62 |
def google_search(query):
|
| 63 |
try:
|
| 64 |
search_client = serpapi.Client(api_key=serper_api_key)
|
| 65 |
+
results = search_client.search({"engine": "google", "q": query})
|
|
|
|
|
|
|
|
|
|
| 66 |
snippets = [result["snippet"] for result in results.get("organic_results", [])]
|
| 67 |
return snippets
|
|
|
|
|
|
|
|
|
|
| 68 |
except Exception as e:
|
| 69 |
+
logger.error(f"Error in Google search: {e}")
|
| 70 |
return ["Error occurred during Google search"]
|
| 71 |
|
| 72 |
# RAG response function
|
|
|
|
| 97 |
|
| 98 |
# Create the prompt template
|
| 99 |
prompt_message = """
|
| 100 |
+
Act as an expert copywriter who specializes in identifying and explaining trust builders for companies.
|
| 101 |
+
Focus on finding and detailing trust builders for the specified company or topic.
|
| 102 |
+
Organize the trust builders into categories such as Vision, Development, Benefit, Competence, Stability, and Relationship.
|
| 103 |
+
Provide specific examples and data points when available to support each trust builder.
|
| 104 |
"""
|
| 105 |
|
| 106 |
prompt_template = ChatPromptTemplate.from_messages([
|
|
|
|
| 130 |
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
| 131 |
|
| 132 |
# Streamlit app
|
| 133 |
+
st.title("Trust Builders Finder")
|
| 134 |
|
| 135 |
# Initialize chat history
|
| 136 |
if 'chat_history' not in st.session_state:
|
|
|
|
| 142 |
st.markdown(message["content"])
|
| 143 |
|
| 144 |
# Chat input
|
| 145 |
+
if prompt := st.chat_input("Enter a company name or topic to find trust builders"):
|
| 146 |
# Add user message to chat history
|
| 147 |
st.session_state.chat_history.append({"role": "user", "content": prompt})
|
| 148 |
|
|
|
|
| 158 |
try:
|
| 159 |
# Generate response using the agent executor
|
| 160 |
output = agent_executor.invoke({
|
| 161 |
+
"input": f"{prompt}",
|
| 162 |
"chat_history": st.session_state.chat_history
|
| 163 |
})
|
| 164 |
full_response = output["output"]
|
| 165 |
|
| 166 |
+
# Display the response
|
|
|
|
|
|
|
|
|
|
| 167 |
message_placeholder.markdown(full_response)
|
| 168 |
except Exception as e:
|
| 169 |
logger.error(f"Error generating response: {e}")
|