meart commited on
Commit
3f0b461
·
verified ·
1 Parent(s): d49e9f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -168
app.py CHANGED
@@ -1,83 +1,31 @@
1
  import os
2
- import sys
3
  import json
4
  import requests
5
- import streamlit as st
6
  from typing import Dict, List, Any, Optional, Union
7
  from langchain_core.prompts import ChatPromptTemplate
8
- from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
9
  from langchain.agents import AgentExecutor, create_openai_tools_agent
10
- from langchain_core.tools import tool, BaseTool
11
  from langchain_openai import ChatOpenAI
12
  from langchain_core.messages import AIMessage, HumanMessage
13
- import youtube_transcript_api
14
  from youtube_transcript_api import YouTubeTranscriptApi
15
  from youtube_transcript_api.formatters import TextFormatter
16
  import re
17
 
18
- # Streamlit app configuration - only run if imported by Streamlit
19
- if 'streamlit' in sys.modules:
20
- st.set_page_config(page_title="GAIA Agent", page_icon="🤖", layout="wide")
21
- st.title("🤖 GAIA Agent")
22
-
23
- # Environment variables setup - safely handle secrets
24
- try:
25
- # Try to access Streamlit secrets if available
26
- OPENAI_API_KEY = os.environ.get("OPENAI_TEST", "")
27
- if not OPENAI_API_KEY and hasattr(st, "secrets"):
28
- try:
29
- OPENAI_API_KEY = st.secrets.get("OPENAI_TEST", "")
30
- except:
31
- pass
32
-
33
- SERPER_API_KEY = os.environ.get("SERPER_API_KEY", "")
34
- if not SERPER_API_KEY and hasattr(st, "secrets"):
35
- try:
36
- SERPER_API_KEY = st.secrets.get("SERPER_API_KEY", "")
37
- except:
38
- pass
39
-
40
- MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
41
- if not MODEL_NAME and hasattr(st, "secrets"):
42
- try:
43
- MODEL_NAME = st.secrets.get("MODEL_NAME", "gpt-4o-mini")
44
- except:
45
- MODEL_NAME = "gpt-4o-mini"
46
-
47
- except Exception as e:
48
- # Fallback to environment variables only
49
- OPENAI_API_KEY = os.environ.get("OPENAI_TEST", "")
50
- SERPER_API_KEY = os.environ.get("SERPER_API_KEY", "")
51
- MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
52
 
53
- # Initialize the LLM with cache handling
54
  def get_llm():
55
  """Initialize the LLM"""
56
- try:
57
- # Use cache_resource if in Streamlit
58
- if 'streamlit' in sys.modules and hasattr(st, 'cache_resource'):
59
- @st.cache_resource
60
- def cached_llm():
61
- return ChatOpenAI(
62
- model=MODEL_NAME,
63
- temperature=0.1,
64
- api_key=OPENAI_API_KEY
65
- )
66
- return cached_llm()
67
- else:
68
- return ChatOpenAI(
69
- model=MODEL_NAME,
70
- temperature=0.1,
71
- api_key=OPENAI_API_KEY
72
- )
73
- except Exception as e:
74
- print(f"Error initializing LLM: {str(e)}")
75
- # Return a basic version as fallback
76
- return ChatOpenAI(
77
- model=MODEL_NAME,
78
- temperature=0.1,
79
- api_key=OPENAI_API_KEY
80
- )
81
 
82
  # Tools for the agent
83
  @tool
@@ -161,12 +109,6 @@ def extract_youtube_transcript(youtube_url: str) -> str:
161
 
162
  return f"YouTube Video Transcript:\n\n{formatted_transcript}"
163
 
164
- except youtube_transcript_api.NoTranscriptFound:
165
- return "No transcript is available for this video."
166
- except youtube_transcript_api.TranscriptsDisabled:
167
- return "Transcripts are disabled for this video."
168
- except youtube_transcript_api.VideoUnavailable:
169
- return "The video is unavailable or private."
170
  except Exception as e:
171
  return f"Error extracting transcript: {str(e)}"
172
 
@@ -230,46 +172,18 @@ agent_prompt = ChatPromptTemplate.from_messages([
230
  # Create the agent
231
  def get_agent_executor():
232
  """Initialize and return the agent executor"""
233
- try:
234
- # Use cache_resource if in Streamlit
235
- if 'streamlit' in sys.modules and hasattr(st, 'cache_resource'):
236
- @st.cache_resource
237
- def cached_executor():
238
- llm = get_llm()
239
- agent = create_openai_tools_agent(llm, tools, agent_prompt)
240
- return AgentExecutor(
241
- agent=agent,
242
- tools=tools,
243
- verbose=True,
244
- handle_parsing_errors=True,
245
- max_iterations=5,
246
- early_stopping_method="force"
247
- )
248
- return cached_executor()
249
- else:
250
- llm = get_llm()
251
- agent = create_openai_tools_agent(llm, tools, agent_prompt)
252
- return AgentExecutor(
253
- agent=agent,
254
- tools=tools,
255
- verbose=True,
256
- handle_parsing_errors=True,
257
- max_iterations=5,
258
- early_stopping_method="force"
259
- )
260
- except Exception as e:
261
- print(f"Error initializing agent executor: {str(e)}")
262
- # Return a basic version directly
263
- llm = get_llm()
264
- agent = create_openai_tools_agent(llm, tools, agent_prompt)
265
- return AgentExecutor(
266
- agent=agent,
267
- tools=tools,
268
- verbose=True,
269
- handle_parsing_errors=True,
270
- max_iterations=5,
271
- early_stopping_method="force"
272
- )
273
 
274
  # Main function to handle input and generate responses
275
  def process_input(user_input: str) -> str:
@@ -289,74 +203,30 @@ def process_input(user_input: str) -> str:
289
  except Exception as e:
290
  return f"Error processing your request: {str(e)}"
291
 
292
- # Streamlit UI - only run if in Streamlit environment
293
- if 'streamlit' in sys.modules:
294
- try:
295
- st.write("""
296
- This agent is designed to pass the GAIA benchmark with at least a 30% score.
297
- It uses OpenAI's gpt-4o-mini model, Google search via Serper API, and can parse YouTube video content.
298
- """)
299
-
300
- # Check if API keys are set
301
- if not OPENAI_API_KEY:
302
- st.warning("⚠️ OpenAI API key (OPENAI_TEST) is not set. Please add it to your environment variables.")
303
- if not SERPER_API_KEY:
304
- st.warning("⚠️ Serper API key is not set. Please add it to your environment variables.")
305
-
306
- # User input
307
- user_query = st.text_area("Enter your question or task:", height=100)
308
-
309
- if st.button("Submit"):
310
- if user_query:
311
- with st.spinner("Thinking..."):
312
- # Process the query
313
- response = process_input(user_query)
314
-
315
- # Display response
316
- st.markdown("### Response:")
317
- st.write(response)
318
- else:
319
- st.warning("Please enter a question or task.")
320
- except Exception as e:
321
- st.error(f"Error in the Streamlit UI: {str(e)}")
322
-
323
- # Determine if running in Streamlit
324
- def is_streamlit_running():
325
- """Check if running in Streamlit environment"""
326
- # Check if streamlit is imported
327
- is_streamlit_imported = 'streamlit' in sys.modules
328
-
329
- # Check the process name (typically streamlit run app.py)
330
- process_name = os.environ.get("_", "")
331
- is_streamlit_process = "streamlit" in process_name if process_name else False
332
-
333
- return is_streamlit_imported and is_streamlit_process
334
-
335
- # For testing purposes outside of Streamlit
336
  def main():
337
  """
338
  Main function to demonstrate the agent's capabilities.
339
  """
340
- print("GAIA Agent initialized. Enter 'exit' to quit.")
341
- print(f"Using model: {MODEL_NAME}")
342
-
343
  if not OPENAI_API_KEY:
344
- print("WARNING: OpenAI API key (OPENAI_TEST) is not set.")
345
  if not SERPER_API_KEY:
346
- print("WARNING: Serper API key is not set.")
 
 
 
347
 
348
  while True:
349
- user_input = input("\nUser: ")
350
 
351
  if user_input.lower() == 'exit':
352
- print("Exiting the agent.")
353
  break
354
 
 
355
  response = process_input(user_input)
356
- print(f"\nAgent: {response}")
357
 
358
- if __name__ == "__main__" and not is_streamlit_running():
359
- try:
360
- main()
361
- except Exception as e:
362
- print(f"Error running in CLI mode: {str(e)}")
 
1
  import os
 
2
  import json
3
  import requests
4
+ import sys
5
  from typing import Dict, List, Any, Optional, Union
6
  from langchain_core.prompts import ChatPromptTemplate
7
+ from langchain_core.output_parsers import StrOutputParser
8
  from langchain.agents import AgentExecutor, create_openai_tools_agent
9
+ from langchain_core.tools import tool
10
  from langchain_openai import ChatOpenAI
11
  from langchain_core.messages import AIMessage, HumanMessage
 
12
  from youtube_transcript_api import YouTubeTranscriptApi
13
  from youtube_transcript_api.formatters import TextFormatter
14
  import re
15
 
16
+ # Environment variables setup
17
+ OPENAI_API_KEY = os.environ.get("OPENAI_TEST", "")
18
+ SERPER_API_KEY = os.environ.get("SERPER_API_KEY", "")
19
+ MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ # Initialize the LLM
22
  def get_llm():
23
  """Initialize the LLM"""
24
+ return ChatOpenAI(
25
+ model=MODEL_NAME,
26
+ temperature=0.1,
27
+ api_key=OPENAI_API_KEY
28
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  # Tools for the agent
31
  @tool
 
109
 
110
  return f"YouTube Video Transcript:\n\n{formatted_transcript}"
111
 
 
 
 
 
 
 
112
  except Exception as e:
113
  return f"Error extracting transcript: {str(e)}"
114
 
 
172
  # Create the agent
173
  def get_agent_executor():
174
  """Initialize and return the agent executor"""
175
+ llm = get_llm()
176
+ agent = create_openai_tools_agent(llm, tools, agent_prompt)
177
+
178
+ # Create the agent executor
179
+ return AgentExecutor(
180
+ agent=agent,
181
+ tools=tools,
182
+ verbose=True,
183
+ handle_parsing_errors=True,
184
+ max_iterations=5,
185
+ early_stopping_method="force"
186
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
  # Main function to handle input and generate responses
189
  def process_input(user_input: str) -> str:
 
203
  except Exception as e:
204
  return f"Error processing your request: {str(e)}"
205
 
206
+ # Main function for GAIA benchmark
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  def main():
208
  """
209
  Main function to demonstrate the agent's capabilities.
210
  """
211
+ # Environment check
 
 
212
  if not OPENAI_API_KEY:
213
+ print("⚠️ WARNING: OpenAI API key (OPENAI_TEST) is not set.")
214
  if not SERPER_API_KEY:
215
+ print("⚠️ WARNING: Serper API key is not set.")
216
+
217
+ print("GAIA Agent initialized. Using model:", MODEL_NAME)
218
+ print("Enter your questions or 'exit' to quit.")
219
 
220
  while True:
221
+ user_input = input("\nQuery: ")
222
 
223
  if user_input.lower() == 'exit':
224
+ print("Exiting.")
225
  break
226
 
227
+ print("\nProcessing...")
228
  response = process_input(user_input)
229
+ print(f"\nResponse: {response}")
230
 
231
+ if __name__ == "__main__":
232
+ main()