jesusgj commited on
Commit
8cf27dc
·
1 Parent(s): 903af12

Created agent.py

Browse files
Files changed (2) hide show
  1. agent.py +73 -0
  2. app.py +72 -4
agent.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import os
4
+ import re
5
+ import requests
6
+ from smolagents import CodeAgent, ToolCallingAgent, WebSearchTool, tool
7
+ from smolagents.models.huggingface import HuggingFaceModel
8
+ from dotenv import load_dotenv
9
+ from markdownify import markdownify
10
+ from requests.exceptions import RequestException
11
+
12
+ def initialize_agent():
13
+ # Load environment variables from .env file
14
+ load_dotenv()
15
+
16
+ # 1. Load the model
17
+ # Make sure to set HF_TOKEN in your Hugging Face Space secrets
18
+ model_name = "HuggingFaceH4/zephyr-7b-beta"
19
+ try:
20
+ model = HuggingFaceModel(model=model_name, token=os.environ.get("HF_TOKEN"))
21
+ except Exception as e:
22
+ print(f"Error loading model: {e}")
23
+ model = None
24
+
25
+ # 2. Define the tools
26
+ @tool
27
+ def visit_webpage(url: str) -> str:
28
+ """Visits a webpage at the given URL and returns its content as a markdown string.
29
+
30
+ Args:
31
+ url: The URL of the webpage to visit.
32
+
33
+ Returns:
34
+ The content of the webpage converted to Markdown, or an error message if the request fails.
35
+ """
36
+ try:
37
+ # Send a GET request to the URL
38
+ response = requests.get(url)
39
+ response.raise_for_status() # Raise an exception for bad status codes
40
+
41
+ # Convert the HTML content to Markdown
42
+ markdown_content = markdownify(response.text).strip()
43
+
44
+ # Remove multiple line breaks
45
+ markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
46
+
47
+ return markdown_content
48
+
49
+ except RequestException as e:
50
+ return f"Error fetching the webpage: {str(e)}"
51
+ except Exception as e:
52
+ return f"An unexpected error occurred: {str(e)}"
53
+
54
+ # 3. Define the agents
55
+ if model:
56
+ web_agent = ToolCallingAgent(
57
+ tools=[WebSearchTool(), visit_webpage],
58
+ model=model,
59
+ max_steps=10,
60
+ name="web_search_agent",
61
+ description="Runs web searches for you.",
62
+ )
63
+
64
+ manager_agent = CodeAgent(
65
+ tools=[],
66
+ model=model,
67
+ managed_agents=[web_agent],
68
+ additional_authorized_imports=["time", "numpy", "pandas"],
69
+ )
70
+ return manager_agent
71
+ else:
72
+ return None
73
+
app.py CHANGED
@@ -1,7 +1,75 @@
1
  import gradio as gr
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import requests
3
+ from agent import initialize_agent
4
 
5
+ # 1. Initialize the agent
6
+ manager_agent = initialize_agent()
7
 
8
+ # 2. Define the API URL
9
+ API_URL = "https://gaia-benchmark-dev.hf.space"
10
+
11
+ # 3. Gradio interface
12
+ def run_evaluation(hf_username, space_url):
13
+ if not manager_agent:
14
+ return "Agent could not be initialized. Please check the model and token."
15
+ if not hf_username or not space_url:
16
+ return "Please provide your Hugging Face username and Space URL."
17
+
18
+ try:
19
+ # Get questions
20
+ print("Fetching questions...")
21
+ response = requests.get(f"{API_URL}/questions")
22
+ response.raise_for_status()
23
+ questions = response.json()
24
+ print(f"Found {len(questions)} questions.")
25
+
26
+ # Run agent on questions
27
+ answers = []
28
+ for i, question in enumerate(questions):
29
+ prompt = question["question"]
30
+ print(f"Answering question {i+1}/{len(questions)}: {prompt}")
31
+ try:
32
+ answer = manager_agent.run(prompt)
33
+ answers.append({"question_id": question["id"], "answer": answer})
34
+ print(f"Got answer: {answer}")
35
+ except Exception as e:
36
+ print(f"Error running agent on question {question['id']}: {e}")
37
+ answers.append({"question_id": question["id"], "answer": "Error: Could not generate an answer."})
38
+
39
+ # Submit answers
40
+ print("Submitting answers...")
41
+ submission_response = requests.post(
42
+ f"{API_URL}/submit",
43
+ json={
44
+ "hf_username": hf_username,
45
+ "answers": answers,
46
+ "space_url": space_url
47
+ }
48
+ )
49
+ submission_response.raise_for_status()
50
+ print("Submission successful!")
51
+ return submission_response.json()
52
+ except requests.exceptions.RequestException as e:
53
+ print(f"An error occurred: {e}")
54
+ return f"An error occurred: {e}"
55
+ except Exception as e:
56
+ print(f"An unexpected error occurred: {e}")
57
+ return f"An unexpected error occurred: {e}"
58
+
59
+ with gr.Blocks() as demo:
60
+ gr.Markdown("# GAIA Benchmark Evaluation with smolagent")
61
+ gr.Markdown("Enter your Hugging Face username and the URL of your Space to submit your agent's answers to the GAIA benchmark.")
62
+ with gr.Row():
63
+ hf_username_input = gr.Textbox(label="Hugging Face Username")
64
+ space_url_input = gr.Textbox(label="Hugging Face Space URL")
65
+ run_button = gr.Button("Run Evaluation")
66
+ output = gr.JSON()
67
+
68
+ run_button.click(
69
+ run_evaluation,
70
+ inputs=[hf_username_input, space_url_input],
71
+ outputs=output
72
+ )
73
+
74
+ if __name__ == "__main__":
75
+ demo.launch()