jwa91 commited on
Commit
68bf79b
·
verified ·
1 Parent(s): e8d4494

Update app.py: feat: add trivia question tool and integrate with CodeAgent

Browse files

### Added
- Implemented `get_trivia_question` tool to fetch random trivia questions from Open Trivia Database.
- Integrated the new tool into the `CodeAgent` for use in the system.

### Changed
- Removed placeholder tool `my_cutom_tool` and replaced it with `get_trivia_question`.
- Updated imports: added `random` for randomizing question type in `get_trivia_question`.

### Fixed
- N/A

### Notes
- Trivia questions now support predefined categories and require difficulty level.
- Question type (`multiple` or `boolean`) is randomly selected.

Files changed (1) hide show
  1. app.py +66 -20
app.py CHANGED
@@ -1,49 +1,96 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
 
 
6
  from tools.final_answer import FinalAnswerTool
7
 
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
- def my_cutom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
  Args:
16
- arg1: the first argument
17
- arg2: the second argument
 
 
 
 
 
 
 
 
 
 
 
 
18
  """
19
- return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @tool
22
  def get_current_time_in_timezone(timezone: str) -> str:
23
  """A tool that fetches the current local time in a specified timezone.
 
24
  Args:
25
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
26
  """
27
  try:
28
- # Create timezone object
29
  tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
  return f"The current local time in {timezone} is: {local_time}"
33
  except Exception as e:
34
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
36
-
37
  final_answer = FinalAnswerTool()
38
  model = HfApiModel(
39
- max_tokens=2096,
40
- temperature=0.5,
41
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
42
- custom_role_conversions=None,
43
  )
44
 
45
-
46
- # Import tool from Hub
47
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
48
 
49
  with open("prompts.yaml", 'r') as stream:
@@ -51,7 +98,7 @@ with open("prompts.yaml", 'r') as stream:
51
 
52
  agent = CodeAgent(
53
  model=model,
54
- tools=[final_answer], ## add your tools here (don't remove final answer)
55
  max_steps=6,
56
  verbosity_level=1,
57
  grammar=None,
@@ -61,5 +108,4 @@ agent = CodeAgent(
61
  prompt_templates=prompt_templates
62
  )
63
 
64
-
65
- GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
+ import random
7
+
8
  from tools.final_answer import FinalAnswerTool
9
 
10
  from Gradio_UI import GradioUI
11
 
 
12
  @tool
13
+ def get_trivia_question(category: str, difficulty: str) -> str:
14
+ """Fetches a random trivia question from the Open Trivia Database.
15
+
16
  Args:
17
+ category: The category of the question. Must be one of:
18
+ - 'General Knowledge'
19
+ - 'Books'
20
+ - 'Film'
21
+ - 'Music'
22
+ - 'Video Games'
23
+ - 'Computers'
24
+ - 'Mathematics'
25
+ - 'Mythology'
26
+ - 'Sports'
27
+ difficulty: The difficulty level of the question. Must be 'easy', 'medium', or 'hard'.
28
+
29
+ Returns:
30
+ A formatted trivia question with possible answers.
31
  """
32
+ category_map = {
33
+ "General Knowledge": 9,
34
+ "Books": 10,
35
+ "Film": 11,
36
+ "Music": 12,
37
+ "Video Games": 15,
38
+ "Computers": 18,
39
+ "Mathematics": 19,
40
+ "Mythology": 20,
41
+ "Sports": 21
42
+ }
43
+ if category not in category_map:
44
+ return f"Invalid category. Must be one of: {', '.join(category_map.keys())}"
45
+ if difficulty not in ["easy", "medium", "hard"]:
46
+ return "Invalid difficulty. Must be 'easy', 'medium', or 'hard'."
47
+ question_type = random.choice(["multiple", "boolean"])
48
+ params = {
49
+ "amount": 1,
50
+ "category": category_map[category],
51
+ "difficulty": difficulty,
52
+ "type": question_type
53
+ }
54
+ response = requests.get("https://opentdb.com/api.php", params=params)
55
+ if response.status_code != 200:
56
+ return "An error occurred while fetching a trivia question."
57
+ data = response.json()
58
+ if data["response_code"] != 0:
59
+ return "No question found for the given criteria."
60
+ question_data = data["results"][0]
61
+ question = question_data["question"]
62
+ correct_answer = question_data["correct_answer"]
63
+ incorrect_answers = question_data["incorrect_answers"]
64
+ if question_type == "multiple":
65
+ options = incorrect_answers + [correct_answer]
66
+ random.shuffle(options)
67
+ options_text = "\n".join([f"- {opt}" for opt in options])
68
+ return f"Trivia Question: {question}\n\nPossible answers:\n{options_text}\n\nWhat is your answer?"
69
+ else:
70
+ return f"Trivia Question: {question}\n\nAnswer: True or False?"
71
 
72
  @tool
73
  def get_current_time_in_timezone(timezone: str) -> str:
74
  """A tool that fetches the current local time in a specified timezone.
75
+
76
  Args:
77
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
78
  """
79
  try:
 
80
  tz = pytz.timezone(timezone)
 
81
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
82
  return f"The current local time in {timezone} is: {local_time}"
83
  except Exception as e:
84
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
85
 
 
86
  final_answer = FinalAnswerTool()
87
  model = HfApiModel(
88
+ max_tokens=2096,
89
+ temperature=0.5,
90
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
91
+ custom_role_conversions=None,
92
  )
93
 
 
 
94
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
95
 
96
  with open("prompts.yaml", 'r') as stream:
 
98
 
99
  agent = CodeAgent(
100
  model=model,
101
+ tools=[final_answer, get_trivia_question, get_current_time_in_timezone],
102
  max_steps=6,
103
  verbosity_level=1,
104
  grammar=None,
 
108
  prompt_templates=prompt_templates
109
  )
110
 
111
+ GradioUI(agent).launch()