JoseferEins commited on
Commit
a9ded72
·
verified ·
1 Parent(s): 66bf097

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -49
app.py CHANGED
@@ -1,44 +1,40 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, GoogleSearchTool, VisitWebpageTool, HfApiModel,load_tool,tool
 
 
 
 
 
 
 
 
 
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
- from tools.final_answer import FinalAnswerTool
7
- import matplotlib.pyplot as plt
8
- import numpy as np
9
- from Gradio_UI import GradioUI
10
-
11
 
12
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
13
- @tool
14
- def my_cutom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
15
- #Keep this format for the description / args / args description but feel free to modify the tool
16
- """A tool that does nothing yet
17
- Args:
18
- arg1: the first argument
19
- arg2: the second argument
20
- """
21
- return "What magic will you build ?"
22
 
 
 
 
23
 
24
  @tool
25
  def get_current_time_in_timezone(timezone: str) -> str:
26
- """A tool that fetches the current local time in a specified timezone.
 
27
  Args:
28
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
29
  """
30
  try:
31
- # Create timezone object
32
  tz = pytz.timezone(timezone)
33
- # Get current time in that timezone
34
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
35
  return f"The current local time in {timezone} is: {local_time}"
36
  except Exception as e:
37
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
38
 
39
- #########################################################################
40
- # NEW TOOL: GET CULTURAL INFO (via Wikipedia)
41
- #########################################################################
42
  @tool
43
  def get_cultural_info(topic: str) -> str:
44
  """
@@ -50,24 +46,20 @@ def get_cultural_info(topic: str) -> str:
50
  """
51
  try:
52
  # Query the Wikipedia API for an extract
53
- # Using the "summary" approach with 'exintro' to get the first paragraph
54
  url = (
55
  "https://en.wikipedia.org/w/api.php?"
56
  "action=query&prop=extracts&exintro&explaintext&format=json&titles=" + topic
57
  )
58
  response = requests.get(url)
59
  data = response.json()
60
-
61
- # Extract the page data
62
  pages = data.get("query", {}).get("pages", {})
63
  if not pages:
64
  return f"No Wikipedia pages found for topic: {topic}"
65
 
66
- # Wikipedia returns a dictionary keyed by page ID
67
  page_id = next(iter(pages))
68
  page_content = pages[page_id]
69
-
70
- # Check for missing page or missing extract
71
  if "missing" in page_content:
72
  return f"No page found on Wikipedia for topic: {topic}"
73
 
@@ -79,42 +71,78 @@ def get_cultural_info(topic: str) -> str:
79
 
80
  except Exception as e:
81
  return f"Error retrieving cultural info for '{topic}': {str(e)}"
82
- #########################################################################
83
 
84
 
 
 
 
85
  final_answer = FinalAnswerTool()
 
 
 
 
 
86
  model = HfApiModel(
87
- max_tokens=2096,
88
- temperature=0.5,
89
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
90
- custom_role_conversions=None,
91
  )
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- # Import tool from Hub
95
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
96
 
97
- with open("prompts.yaml", 'r') as stream:
98
- prompt_templates = yaml.safe_load(stream)
99
-
 
 
 
 
 
 
 
 
 
 
 
 
100
  agent = CodeAgent(
101
  model=model,
102
- tools=[
103
- final_answer,
104
- DuckDuckGoSearchTool(),
105
- VisitWebpageTool(),
106
- get_current_time_in_timezone,
107
- get_cultural_info, # <-- Our new cultural info tool
108
- image_generation_tool
109
- ],
110
  max_steps=6,
111
  verbosity_level=1,
112
  grammar=None,
113
  planning_interval=None,
114
- name=None,
115
- description=None,
116
  prompt_templates=prompt_templates
117
  )
118
 
119
 
120
- GradioUI(agent).launch()
 
 
 
 
 
 
1
+ # kids_museum_agent.py
2
+
3
+ from smolagents import (
4
+ CodeAgent,
5
+ DuckDuckGoSearchTool,
6
+ VisitWebpageTool,
7
+ HfApiModel,
8
+ load_tool,
9
+ tool
10
+ )
11
  import datetime
12
  import requests
13
  import pytz
14
  import yaml
15
+ import os
 
 
 
 
16
 
17
+ from tools.final_answer import FinalAnswerTool # Adjust import if you store final_answer differently
 
 
 
 
 
 
 
 
 
18
 
19
+ ########################################
20
+ # TOOLS
21
+ ########################################
22
 
23
  @tool
24
  def get_current_time_in_timezone(timezone: str) -> str:
25
+ """
26
+ A tool that fetches the current local time in a specified timezone.
27
  Args:
28
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
29
  """
30
  try:
 
31
  tz = pytz.timezone(timezone)
 
32
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
33
  return f"The current local time in {timezone} is: {local_time}"
34
  except Exception as e:
35
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
36
 
37
+
 
 
38
  @tool
39
  def get_cultural_info(topic: str) -> str:
40
  """
 
46
  """
47
  try:
48
  # Query the Wikipedia API for an extract
 
49
  url = (
50
  "https://en.wikipedia.org/w/api.php?"
51
  "action=query&prop=extracts&exintro&explaintext&format=json&titles=" + topic
52
  )
53
  response = requests.get(url)
54
  data = response.json()
55
+
 
56
  pages = data.get("query", {}).get("pages", {})
57
  if not pages:
58
  return f"No Wikipedia pages found for topic: {topic}"
59
 
60
+ # The keys in 'pages' are page IDs
61
  page_id = next(iter(pages))
62
  page_content = pages[page_id]
 
 
63
  if "missing" in page_content:
64
  return f"No page found on Wikipedia for topic: {topic}"
65
 
 
71
 
72
  except Exception as e:
73
  return f"Error retrieving cultural info for '{topic}': {str(e)}"
 
74
 
75
 
76
+ ########################################
77
+ # FINAL ANSWER TOOL (REQUIRED)
78
+ ########################################
79
  final_answer = FinalAnswerTool()
80
+
81
+
82
+ ########################################
83
+ # MODEL (choose whichever model/endpoint you prefer)
84
+ ########################################
85
  model = HfApiModel(
86
+ max_tokens=1024,
87
+ temperature=0.5,
88
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct', # or any other model ID / HF endpoint
89
+ custom_role_conversions=None
90
  )
91
 
92
+ ########################################
93
+ # LOAD ANY OPTIONAL TOOLS FROM HUB (e.g. text-to-image)
94
+ ########################################
95
+ # NOTE: If you want to see if it works, you can skip or keep it
96
+ try:
97
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
98
+ except Exception as e:
99
+ print("Error loading text-to-image tool:", e)
100
+ image_generation_tool = None
101
+
102
+
103
+ ########################################
104
+ # PROMPT TEMPLATES
105
+ ########################################
106
+ # We read from prompts.yaml. Make sure you have a prompts.yaml in the same folder.
107
+ # It can contain specialized instructions for your "kid-friendly" museum agent.
108
+ this_dir = os.path.dirname(os.path.abspath(__file__))
109
+ prompts_path = os.path.join(this_dir, "prompts.yaml")
110
+
111
+ with open(prompts_path, 'r', encoding='utf-8') as stream:
112
+ prompt_templates = yaml.safe_load(stream)
113
 
 
 
114
 
115
+ ########################################
116
+ # BUILD THE AGENT
117
+ ########################################
118
+ tools_list = [
119
+ final_answer, # Important: must remain in the tools
120
+ DuckDuckGoSearchTool(),
121
+ VisitWebpageTool(),
122
+ get_current_time_in_timezone,
123
+ get_cultural_info
124
+ ]
125
+
126
+ # If the image_generation_tool loaded successfully, add it:
127
+ if image_generation_tool:
128
+ tools_list.append(image_generation_tool)
129
+
130
  agent = CodeAgent(
131
  model=model,
132
+ tools=tools_list,
 
 
 
 
 
 
 
133
  max_steps=6,
134
  verbosity_level=1,
135
  grammar=None,
136
  planning_interval=None,
137
+ name="KidsMuseumAgent",
138
+ description="A friendly museum assistant that explains art, history, and culture in kid-friendly language.",
139
  prompt_templates=prompt_templates
140
  )
141
 
142
 
143
+ ########################################
144
+ # (OPTIONAL) GRADIO UI LAUNCH
145
+ ########################################
146
+ if __name__ == "__main__":
147
+ from Gradio_UI import GradioUI
148
+ GradioUI(agent).launch()