Miguel Figueiredo Marques commited on
Commit
1079dc5
·
1 Parent(s): 453c536

add openai

Browse files
Files changed (2) hide show
  1. app.py +18 -18
  2. requirements.txt +2 -2
app.py CHANGED
@@ -13,7 +13,7 @@ from dotenv import load_dotenv
13
 
14
  from langchain_core.messages import SystemMessage, HumanMessage
15
  from langchain_core.tools import tool
16
- from langchain_groq import ChatGroq
17
  from langgraph.graph import START, StateGraph, MessagesState
18
  from langgraph.prebuilt import ToolNode, tools_condition
19
 
@@ -21,12 +21,12 @@ load_dotenv()
21
 
22
  # --- Constants ---
23
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
24
- # Main reasoning + tool-calling model (Groq free tier). Swap if a model is retired.
25
- MODEL_NAME = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
26
- # Vision model for image questions (best-effort; update id if Groq retires it).
27
- VISION_MODEL = os.getenv("GROQ_VISION_MODEL", "meta-llama/llama-4-scout-17b-16e-instruct")
28
- # Seconds to pause between questions to stay under Groq free-tier rate limits.
29
- PER_QUESTION_DELAY = float(os.getenv("PER_QUESTION_DELAY", "3"))
30
 
31
  SYSTEM_PROMPT = (
32
  "You are a precise general AI assistant solving questions from the GAIA benchmark. "
@@ -62,7 +62,7 @@ def web_search(query: str) -> str:
62
  for r in res.get("results", []):
63
  out.append(
64
  f'<result title="{r.get("title", "")}" url="{r.get("url", "")}">\n'
65
- f'{r.get("content", "")}\n</result>'
66
  )
67
  return "\n\n---\n\n".join(out) if out else "No results found."
68
  except Exception as e:
@@ -79,7 +79,7 @@ def wiki_search(query: str) -> str:
79
  from langchain_community.document_loaders import WikipediaLoader
80
  docs = WikipediaLoader(query=query, load_max_docs=2).load()
81
  return "\n\n---\n\n".join(
82
- f'<Document source="{d.metadata.get("source", "")}">\n{d.page_content[:4000]}\n</Document>'
83
  for d in docs
84
  ) or "No Wikipedia results."
85
  except Exception as e:
@@ -142,7 +142,7 @@ def read_file(path: str) -> str:
142
  return f"Excel {df.shape[0]} rows x {df.shape[1]} cols. Columns: {list(df.columns)}\n\n{df.head(20).to_string()}"
143
  with open(path, "r", encoding="utf-8", errors="replace") as f:
144
  content = f.read()
145
- return content[:8000] + ("\n...[truncated]" if len(content) > 8000 else "")
146
  except Exception as e:
147
  return f"read_file error: {e}"
148
 
@@ -155,12 +155,12 @@ def transcribe_audio(path: str) -> str:
155
  Args:
156
  path: The local path to the audio file."""
157
  try:
158
- from groq import Groq
159
- client = Groq()
160
  with open(path, "rb") as f:
161
  tr = client.audio.transcriptions.create(
162
  file=(os.path.basename(path), f.read()),
163
- model="whisper-large-v3",
164
  )
165
  return tr.text
166
  except Exception as e:
@@ -175,8 +175,8 @@ def analyze_image(path: str, question: str) -> str:
175
  path: The local path to the image file.
176
  question: What you want to know about the image."""
177
  try:
178
- from groq import Groq
179
- client = Groq()
180
  with open(path, "rb") as f:
181
  b64 = base64.b64encode(f.read()).decode()
182
  ext = (os.path.splitext(path)[1].lstrip(".") or "png").lower()
@@ -211,7 +211,7 @@ TOOLS = [
211
 
212
  def build_graph():
213
  """Build a simple assistant <-> tools LangGraph agent."""
214
- llm = ChatGroq(model=MODEL_NAME, temperature=0, max_tokens=4096)
215
  llm_with_tools = llm.bind_tools(TOOLS, tool_choice="auto")
216
 
217
  def assistant(state: MessagesState):
@@ -268,7 +268,7 @@ class BasicAgent:
268
  # Retries exhausted — fall back to a direct no-tools LLM call
269
  print("Tool calls keep failing; falling back to direct LLM (no tools).")
270
  try:
271
- llm = ChatGroq(model=MODEL_NAME, temperature=0, max_tokens=4096)
272
  direct = llm.invoke(messages)
273
  answer = extract_final_answer(direct.content)
274
  print(f"Fallback returning: {answer[:120]}")
@@ -428,7 +428,7 @@ def build_demo():
428
  """
429
  **Instructions:**
430
 
431
- 1. Set the `GROQ_API_KEY` and `TAVILY_API_KEY` secrets in this Space (Settings → Secrets).
432
  2. Log in to your Hugging Face account using the button below.
433
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, submit, and see the score.
434
 
 
13
 
14
  from langchain_core.messages import SystemMessage, HumanMessage
15
  from langchain_core.tools import tool
16
+ from langchain_openai import ChatOpenAI
17
  from langgraph.graph import START, StateGraph, MessagesState
18
  from langgraph.prebuilt import ToolNode, tools_condition
19
 
 
21
 
22
  # --- Constants ---
23
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
24
+ # Main reasoning + tool-calling model.
25
+ MODEL_NAME = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
26
+ # Vision model for image questions (gpt-4o-mini supports vision natively).
27
+ VISION_MODEL = os.getenv("OPENAI_VISION_MODEL", "gpt-4o-mini")
28
+ # Seconds to pause between questions (OpenAI limits are generous; 1s is enough).
29
+ PER_QUESTION_DELAY = float(os.getenv("PER_QUESTION_DELAY", "1"))
30
 
31
  SYSTEM_PROMPT = (
32
  "You are a precise general AI assistant solving questions from the GAIA benchmark. "
 
62
  for r in res.get("results", []):
63
  out.append(
64
  f'<result title="{r.get("title", "")}" url="{r.get("url", "")}">\n'
65
+ f'{r.get("content", "")[:500]}\n</result>'
66
  )
67
  return "\n\n---\n\n".join(out) if out else "No results found."
68
  except Exception as e:
 
79
  from langchain_community.document_loaders import WikipediaLoader
80
  docs = WikipediaLoader(query=query, load_max_docs=2).load()
81
  return "\n\n---\n\n".join(
82
+ f'<Document source="{d.metadata.get("source", "")}">\n{d.page_content[:2000]}\n</Document>'
83
  for d in docs
84
  ) or "No Wikipedia results."
85
  except Exception as e:
 
142
  return f"Excel {df.shape[0]} rows x {df.shape[1]} cols. Columns: {list(df.columns)}\n\n{df.head(20).to_string()}"
143
  with open(path, "r", encoding="utf-8", errors="replace") as f:
144
  content = f.read()
145
+ return content[:4000] + ("\n...[truncated]" if len(content) > 4000 else "")
146
  except Exception as e:
147
  return f"read_file error: {e}"
148
 
 
155
  Args:
156
  path: The local path to the audio file."""
157
  try:
158
+ import openai
159
+ client = openai.OpenAI()
160
  with open(path, "rb") as f:
161
  tr = client.audio.transcriptions.create(
162
  file=(os.path.basename(path), f.read()),
163
+ model="whisper-1",
164
  )
165
  return tr.text
166
  except Exception as e:
 
175
  path: The local path to the image file.
176
  question: What you want to know about the image."""
177
  try:
178
+ import openai
179
+ client = openai.OpenAI()
180
  with open(path, "rb") as f:
181
  b64 = base64.b64encode(f.read()).decode()
182
  ext = (os.path.splitext(path)[1].lstrip(".") or "png").lower()
 
211
 
212
  def build_graph():
213
  """Build a simple assistant <-> tools LangGraph agent."""
214
+ llm = ChatOpenAI(model=MODEL_NAME, temperature=0, max_tokens=1024)
215
  llm_with_tools = llm.bind_tools(TOOLS, tool_choice="auto")
216
 
217
  def assistant(state: MessagesState):
 
268
  # Retries exhausted — fall back to a direct no-tools LLM call
269
  print("Tool calls keep failing; falling back to direct LLM (no tools).")
270
  try:
271
+ llm = ChatOpenAI(model=MODEL_NAME, temperature=0, max_tokens=1024)
272
  direct = llm.invoke(messages)
273
  answer = extract_final_answer(direct.content)
274
  print(f"Fallback returning: {answer[:120]}")
 
428
  """
429
  **Instructions:**
430
 
431
+ 1. Set the `OPENAI_API_KEY` and `TAVILY_API_KEY` secrets in this Space (Settings → Secrets).
432
  2. Log in to your Hugging Face account using the button below.
433
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run the agent, submit, and see the score.
434
 
requirements.txt CHANGED
@@ -3,9 +3,9 @@ requests
3
  python-dotenv
4
  langchain-core
5
  langchain-community
6
- langchain-groq
7
  langgraph
8
- groq
9
  tavily-python
10
  wikipedia
11
  arxiv
 
3
  python-dotenv
4
  langchain-core
5
  langchain-community
6
+ langchain-openai
7
  langgraph
8
+ openai
9
  tavily-python
10
  wikipedia
11
  arxiv