Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,31 +5,42 @@ from langchain_community.tools.tavily_search import TavilySearchResults
|
|
| 5 |
from langchain_openai import ChatOpenAI
|
| 6 |
import streamlit as st
|
| 7 |
|
| 8 |
-
# set
|
| 9 |
-
os.
|
| 10 |
-
os.
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
|
|
|
| 14 |
|
| 15 |
-
#
|
|
|
|
|
|
|
|
|
|
| 16 |
tools = [TavilySearchResults(max_results=1)]
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
#
|
| 22 |
agent = create_openai_tools_agent(llm, tools, prompt)
|
| 23 |
|
| 24 |
-
#
|
| 25 |
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
st.title(
|
| 29 |
-
input = st.text_input('What do you want to know?')
|
| 30 |
|
| 31 |
-
|
| 32 |
-
if input:
|
| 33 |
-
response=agent_executor.invoke({"input": {input}})
|
| 34 |
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from langchain_openai import ChatOpenAI
|
| 6 |
import streamlit as st
|
| 7 |
|
| 8 |
+
# Securely set API keys (e.g., in a .streamlit/secrets.toml file or environment variables)
|
| 9 |
+
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
|
| 10 |
+
TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')
|
| 11 |
|
| 12 |
+
if not OPENAI_API_KEY or not TAVILY_API_KEY:
|
| 13 |
+
st.error("API keys for OpenAI and Tavily are not set. Please configure them properly.")
|
| 14 |
+
st.stop()
|
| 15 |
|
| 16 |
+
# Create GPT-3.5 instance
|
| 17 |
+
llm = ChatOpenAI(model_name="gpt-4o", temperature=0.7, max_tokens=4096)
|
| 18 |
+
|
| 19 |
+
# Use Tavily as the tool for web searching
|
| 20 |
tools = [TavilySearchResults(max_results=1)]
|
| 21 |
|
| 22 |
+
# Retrieve the agent prompt from LangChain Hub
|
| 23 |
+
try:
|
| 24 |
+
prompt = hub.pull("hwchase17/openai-tools-agent")
|
| 25 |
+
except Exception as e:
|
| 26 |
+
st.error(f"Failed to load prompt from hub: {e}")
|
| 27 |
+
st.stop()
|
| 28 |
|
| 29 |
+
# Construct the OpenAI tools agent
|
| 30 |
agent = create_openai_tools_agent(llm, tools, prompt)
|
| 31 |
|
| 32 |
+
# Create the agent executor by passing in the agent and tools
|
| 33 |
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
| 34 |
|
| 35 |
+
# Build the Streamlit web app
|
| 36 |
+
st.title("ChatGPT with Web Search")
|
|
|
|
| 37 |
|
| 38 |
+
user_input = st.text_input("What do you want to know?")
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
# Process input and display response
|
| 41 |
+
if user_input:
|
| 42 |
+
try:
|
| 43 |
+
response = agent_executor.invoke({"input": user_input})
|
| 44 |
+
st.write(response.get("output", "No output received. Please try again."))
|
| 45 |
+
except Exception as e:
|
| 46 |
+
st.error(f"Error processing your request: {e}")
|