rnrahate007 commited on
Commit
9c1ded2
·
verified ·
1 Parent(s): 4dfd646

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -29
app.py CHANGED
@@ -2,25 +2,24 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
- import time
6
 
7
- # --- New Imports for Tool-Calling Agent ---
8
  from langchain_google_genai import ChatGoogleGenerativeAI
9
  from langchain_community.tools import DuckDuckGoSearchRun
10
- from langchain.agents import AgentExecutor, create_tool_calling_agent
11
- from langchain_core.prompts import ChatPromptTemplate
12
 
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
 
16
- # --- Refactored Gemini Agent Definition ---
17
  class GeminiAgent:
18
  def __init__(self):
19
  api_key = os.getenv("GEMINI_API_KEY")
20
  if not api_key:
21
  raise ValueError("GEMINI_API_KEY not set")
22
 
23
- # Initialize Gemini 2.5 Flash for fast, accurate tool calling
24
  self.llm = ChatGoogleGenerativeAI(
25
  model="gemini-2.5-flash",
26
  temperature=0,
@@ -31,38 +30,33 @@ class GeminiAgent:
31
  self.search_tool = DuckDuckGoSearchRun()
32
  self.tools = [self.search_tool]
33
 
34
- # Define the Agentic Prompt
35
- prompt = ChatPromptTemplate.from_messages([
36
- ("system", """You are an expert assistant for the GAIA benchmark.
37
- You must use your tools to find accurate, up-to-date information before answering.
38
- Do not guess. If you need to perform math, search for the formula or calculation.
39
- Provide ONLY a short, factual answer (e.g., a specific number, name, or exact phrase).
40
- No explanations, just the direct answer."""),
41
- ("human", "{input}"),
42
- ("placeholder", "{agent_scratchpad}"),
43
- ])
44
 
45
- # Create the Tool Calling Agent and Executor
46
- self.agent = create_tool_calling_agent(self.llm, self.tools, prompt)
47
- self.agent_executor = AgentExecutor(
48
- agent=self.agent,
49
- tools=self.tools,
50
- verbose=True, # Set to False to reduce logs
51
- max_iterations=5, # Prevent infinite loops
52
- handle_parsing_errors=True
53
  )
54
 
55
- print("Gemini Tool-Calling Agent initialized with Gemini 2.5 Flash")
56
 
57
  def __call__(self, question: str) -> str:
58
  print(f"Agent processing question: {question[:50]}...")
59
 
60
  try:
61
- # We no longer need time.sleep(6) because Gemini 2.5 Flash handles rate limits better,
62
- # and the agent executor handles the pacing of tool calls natively.
63
- response = self.agent_executor.invoke({"input": question})
 
64
 
65
- answer = response.get("output", "").strip()
 
66
 
67
  if not answer:
68
  answer = "0"
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
 
5
 
6
+ # --- Updated Imports for Modern LangChain (v1.0+) ---
7
  from langchain_google_genai import ChatGoogleGenerativeAI
8
  from langchain_community.tools import DuckDuckGoSearchRun
9
+ from langgraph.prebuilt import create_react_agent
10
+ from langchain_core.messages import SystemMessage
11
 
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
+ # --- Modern LangGraph Gemini Agent ---
16
  class GeminiAgent:
17
  def __init__(self):
18
  api_key = os.getenv("GEMINI_API_KEY")
19
  if not api_key:
20
  raise ValueError("GEMINI_API_KEY not set")
21
 
22
+ # Initialize Gemini 2.5 Flash
23
  self.llm = ChatGoogleGenerativeAI(
24
  model="gemini-2.5-flash",
25
  temperature=0,
 
30
  self.search_tool = DuckDuckGoSearchRun()
31
  self.tools = [self.search_tool]
32
 
33
+ # Define the System Prompt
34
+ system_prompt = """You are an expert assistant for the GAIA benchmark.
35
+ You must use your tools to find accurate, up-to-date information before answering.
36
+ Do not guess. If you need to perform math, search for the formula or calculation.
37
+ Provide ONLY a short, factual answer (e.g., a specific number, name, or exact phrase).
38
+ No explanations, just the direct answer."""
 
 
 
 
39
 
40
+ # Create the LangGraph Agent (replaces AgentExecutor)
41
+ self.agent_executor = create_react_agent(
42
+ self.llm,
43
+ self.tools,
44
+ state_modifier=SystemMessage(content=system_prompt)
 
 
 
45
  )
46
 
47
+ print("LangGraph Agent initialized with Gemini 2.5 Flash")
48
 
49
  def __call__(self, question: str) -> str:
50
  print(f"Agent processing question: {question[:50]}...")
51
 
52
  try:
53
+ # LangGraph expects input formatted as a list of messages
54
+ response = self.agent_executor.invoke({
55
+ "messages": [("user", question)]
56
+ })
57
 
58
+ # The final answer is the content of the last message in the sequence
59
+ answer = response["messages"][-1].content.strip()
60
 
61
  if not answer:
62
  answer = "0"