JoseferEins commited on
Commit
7a40ff8
·
verified ·
1 Parent(s): a9ded72

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -23
app.py CHANGED
@@ -14,12 +14,102 @@ 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
  """
@@ -35,6 +125,9 @@ def get_current_time_in_timezone(timezone: str) -> str:
35
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
36
 
37
 
 
 
 
38
  @tool
39
  def get_cultural_info(topic: str) -> str:
40
  """
@@ -45,7 +138,6 @@ def get_cultural_info(topic: str) -> str:
45
  A short summary text from Wikipedia for the specified topic.
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
@@ -55,9 +147,8 @@ def get_cultural_info(topic: str) -> str:
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:
@@ -78,52 +169,45 @@ def get_cultural_info(topic: str) -> str:
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
 
@@ -139,10 +223,7 @@ agent = CodeAgent(
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()
 
14
  import yaml
15
  import os
16
 
17
+ from tools.final_answer import FinalAnswerTool # Adjust import path if needed
18
 
19
  ########################################
20
+ # UTILITY FUNCTION:
21
+ # Restructure Europeana JSON response
22
  ########################################
23
+ def restructure_europeana_response(europeana_json: dict) -> str:
24
+ """
25
+ Takes a Europeana Search API JSON response and returns a
26
+ simplified string summary, focusing on child-friendly information.
27
+ """
28
+ # Check if Europe's response is successful
29
+ if not europeana_json.get("success"):
30
+ return f"Oops! There was a problem with Europeana: {europeana_json.get('error', 'Unknown error')}"
31
+
32
+ items = europeana_json.get("items", [])
33
+ if not items:
34
+ return "Sorry, I couldn’t find anything on Europeana for that topic!"
35
+
36
+ # Build a short list of results
37
+ result_lines = []
38
+ for idx, item in enumerate(items, start=1):
39
+ # Try to get a title
40
+ title_list = item.get("title") or []
41
+ if not title_list:
42
+ # fallback: check dcTitleLangAware if "title" is missing
43
+ dc_title_lang = item.get("dcTitleLangAware", {})
44
+ if dc_title_lang:
45
+ first_lang = next(iter(dc_title_lang))
46
+ title_list = dc_title_lang[first_lang]
47
+ title_str = title_list[0] if title_list else "[No title found]"
48
+
49
+ # Provider (museum/institution)
50
+ provider_list = item.get("dataProvider") or []
51
+ provider_str = provider_list[0] if provider_list else "Unknown provider"
52
+
53
+ # Object type (IMAGE, VIDEO, TEXT, SOUND, etc.)
54
+ obj_type = item.get("type") or "Unknown type"
55
+
56
+ # A short description
57
+ desc_list = item.get("dcDescription") or []
58
+ desc_str = desc_list[0] if desc_list else "No description available."
59
+
60
+ # Year (if present)
61
+ year_list = item.get("year") or []
62
+ year_str = year_list[0] if year_list else "N/A"
63
+
64
+ # Construct a child-friendly summary
65
+ # Feel free to reword for an even more "kid-friendly" vibe
66
+ summary_text = (
67
+ f"{idx}) **Title**: {title_str}\n"
68
+ f" **Where it’s from**: {provider_str}\n"
69
+ f" **Type of item**: {obj_type}\n"
70
+ f" **Approx. Year**: {year_str}\n"
71
+ f" **Fun Fact/Description**: {desc_str}\n"
72
+ )
73
+ result_lines.append(summary_text)
74
+
75
+ # Combine the lines into a single string
76
+ intro = "Here are some cool things I found in Europeana:\n"
77
+ return intro + "\n".join(result_lines)
78
+
79
+ ########################################
80
+ # EUROPEANA TOOL
81
+ ########################################
82
+ EUROPEANA_API_KEY = "YOUR_EUROPEANA_API_KEY" # <-- Replace with your real key!
83
+
84
+ @tool
85
+ def query_europeana(query: str) -> str:
86
+ """
87
+ A tool that queries the Europeana Search API for a given query
88
+ and returns up to 5 results in a kid-friendly summary.
89
+ """
90
+ endpoint = "https://api.europeana.eu/record/v2/search.json"
91
+ params = {
92
+ "query": query,
93
+ "wskey": EUROPEANA_API_KEY,
94
+ "rows": 5,
95
+ }
96
+ try:
97
+ response = requests.get(endpoint, params=params)
98
+ data = response.json()
99
+
100
+ if response.status_code != 200:
101
+ return f"Oops, something went wrong: {data.get('error', 'Unknown HTTP error')}"
102
+
103
+ # Use our restructure function for a nice summary
104
+ return restructure_europeana_response(data)
105
 
106
+ except Exception as e:
107
+ return f"Error calling Europeana API: {str(e)}"
108
+
109
+
110
+ ########################################
111
+ # TIME TOOL
112
+ ########################################
113
  @tool
114
  def get_current_time_in_timezone(timezone: str) -> str:
115
  """
 
125
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
126
 
127
 
128
+ ########################################
129
+ # WIKIPEDIA CULTURAL INFO
130
+ ########################################
131
  @tool
132
  def get_cultural_info(topic: str) -> str:
133
  """
 
138
  A short summary text from Wikipedia for the specified topic.
139
  """
140
  try:
 
141
  url = (
142
  "https://en.wikipedia.org/w/api.php?"
143
  "action=query&prop=extracts&exintro&explaintext&format=json&titles=" + topic
 
147
 
148
  pages = data.get("query", {}).get("pages", {})
149
  if not pages:
150
+ return f"I couldn't find anything on Wikipedia for '{topic}'."
151
 
 
152
  page_id = next(iter(pages))
153
  page_content = pages[page_id]
154
  if "missing" in page_content:
 
169
  ########################################
170
  final_answer = FinalAnswerTool()
171
 
 
172
  ########################################
173
+ # MODEL
174
  ########################################
175
  model = HfApiModel(
176
  max_tokens=1024,
177
  temperature=0.5,
178
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct', # or your chosen HF endpoint
179
  custom_role_conversions=None
180
  )
181
 
182
  ########################################
183
+ # OPTIONAL: IMAGE GENERATION TOOL
184
  ########################################
 
185
  try:
186
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
187
  except Exception as e:
188
  print("Error loading text-to-image tool:", e)
189
  image_generation_tool = None
190
 
 
191
  ########################################
192
+ # PROMPT TEMPLATES (for kids style)
193
  ########################################
 
 
194
  this_dir = os.path.dirname(os.path.abspath(__file__))
195
  prompts_path = os.path.join(this_dir, "prompts.yaml")
 
196
  with open(prompts_path, 'r', encoding='utf-8') as stream:
197
  prompt_templates = yaml.safe_load(stream)
198
 
 
199
  ########################################
200
  # BUILD THE AGENT
201
  ########################################
202
  tools_list = [
203
+ final_answer,
204
  DuckDuckGoSearchTool(),
205
  VisitWebpageTool(),
206
  get_current_time_in_timezone,
207
+ get_cultural_info,
208
+ query_europeana, # <--- Our new Europeana tool
209
  ]
210
 
 
211
  if image_generation_tool:
212
  tools_list.append(image_generation_tool)
213
 
 
223
  prompt_templates=prompt_templates
224
  )
225
 
 
 
 
 
226
  if __name__ == "__main__":
227
+ # (OPTIONAL) Launch Gradio Chat UI
228
  from Gradio_UI import GradioUI
229
  GradioUI(agent).launch()