bako96 commited on
Commit
11d5988
·
verified ·
1 Parent(s): ae7a494

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -50
app.py CHANGED
@@ -1,69 +1,229 @@
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_custom_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
 
39
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
-
42
- model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
 
 
 
 
 
 
 
 
 
47
  )
48
 
 
 
49
 
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
 
53
- with open("prompts.yaml", 'r') as stream:
54
- prompt_templates = yaml.safe_load(stream)
55
-
56
- agent = CodeAgent(
57
- model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
- max_steps=6,
60
- verbosity_level=1,
61
- grammar=None,
62
- planning_interval=None,
63
- name=None,
64
- description=None,
65
- prompt_templates=prompt_templates
66
- )
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, tool
2
+ import re
3
+ from typing import Dict, Any, List
4
+ import json
 
5
  from tools.final_answer import FinalAnswerTool
6
 
 
 
 
7
  @tool
8
+ def search_youtuber(youtuber_name: str) -> Dict[str, Any]:
9
+ """
10
+ Searches for information about a YouTuber using DuckDuckGo.
11
+
12
  Args:
13
+ youtuber_name: Name of the YouTuber to search for
14
+
15
+ Returns:
16
+ Dictionary containing search results about the YouTuber
17
  """
18
+ search_tool = DuckDuckGoSearchTool()
19
+
20
+ # First search for the YouTuber's channel
21
+ channel_results = search_tool.run(f"{youtuber_name} youtube channel")
22
+
23
+ # Then search for more specific information
24
+ stats_results = search_tool.run(f"{youtuber_name} youtube stats subscribers")
25
+
26
+ # Search for recent content/news
27
+ content_results = search_tool.run(f"{youtuber_name} recent videos content")
28
+
29
+ # Search for background information
30
+ background_results = search_tool.run(f"{youtuber_name} youtube background history")
31
+
32
+ return {
33
+ "channel_results": channel_results,
34
+ "stats_results": stats_results,
35
+ "content_results": content_results,
36
+ "background_results": background_results
37
+ }
38
 
39
  @tool
40
+ def extract_youtube_info(search_results: Dict[str, Any]) -> Dict[str, Any]:
41
+ """
42
+ Extracts relevant YouTuber information from search results.
43
+
44
  Args:
45
+ search_results: Dictionary containing search results
46
+
47
+ Returns:
48
+ Dictionary containing extracted YouTuber information
49
  """
50
+ # Extract channel URL
51
+ channel_url = None
52
+ for result in search_results.get("channel_results", []):
53
+ if "youtube.com/channel/" in result.get("url", "") or "youtube.com/c/" in result.get("url", "") or "youtube.com/@" in result.get("url", ""):
54
+ channel_url = result.get("url")
55
+ break
56
+
57
+ # Extract subscriber count and other stats
58
+ subscriber_count = None
59
+ view_count = None
60
+ for result in search_results.get("stats_results", []):
61
+ desc = result.get("desc", "")
62
+ # Look for subscriber patterns like "10M subscribers" or "10 million subscribers"
63
+ sub_match = re.search(r"(\d+(?:\.\d+)?[KMB]?)\s+subscribers", desc, re.IGNORECASE)
64
+ if sub_match:
65
+ subscriber_count = sub_match.group(1)
66
+
67
+ # Look for view patterns
68
+ view_match = re.search(r"(\d+(?:\.\d+)?[KMB]?)\s+views", desc, re.IGNORECASE)
69
+ if view_match:
70
+ view_count = view_match.group(1)
71
+
72
+ # Extract recent videos/content
73
+ recent_videos = []
74
+ for result in search_results.get("content_results", []):
75
+ if "video" in result.get("desc", "").lower() or "upload" in result.get("desc", "").lower():
76
+ recent_videos.append({
77
+ "title": result.get("title"),
78
+ "url": result.get("url"),
79
+ "description": result.get("desc")
80
+ })
81
+ if len(recent_videos) >= 3:
82
+ break
83
+
84
+ # Extract background information
85
+ background_info = []
86
+ for result in search_results.get("background_results", []):
87
+ if "started" in result.get("desc", "").lower() or "began" in result.get("desc", "").lower() or "history" in result.get("desc", "").lower():
88
+ background_info.append({
89
+ "title": result.get("title"),
90
+ "url": result.get("url"),
91
+ "description": result.get("desc")
92
+ })
93
+ if len(background_info) >= 2:
94
+ break
95
+
96
+ return {
97
+ "channel_url": channel_url,
98
+ "subscriber_count": subscriber_count,
99
+ "view_count": view_count,
100
+ "recent_videos": recent_videos,
101
+ "background_info": background_info,
102
+ "raw_results": {
103
+ "channel": search_results.get("channel_results", [])[:3],
104
+ "stats": search_results.get("stats_results", [])[:3],
105
+ "content": search_results.get("content_results", [])[:3],
106
+ "background": search_results.get("background_results", [])[:3]
107
+ }
108
+ }
109
 
110
+ @tool
111
+ def format_youtuber_profile(youtuber_name: str, info: Dict[str, Any]) -> str:
112
+ """
113
+ Formats YouTuber information with proper citations.
114
+
115
+ Args:
116
+ youtuber_name: Name of the YouTuber
117
+ info: Dictionary containing YouTuber information
118
+
119
+ Returns:
120
+ Formatted information with citations
121
+ """
122
+ raw_results = info.get("raw_results", {})
123
+
124
+ result = f"# {youtuber_name} - YouTube Creator Profile\n\n"
125
+
126
+ # Channel information
127
+ result += "## Channel Information\n"
128
+ if info.get("channel_url"):
129
+ result += f"- **Channel URL:** [{info.get('channel_url')}]({info.get('channel_url')}) \n"
130
+
131
+ if info.get("subscriber_count"):
132
+ result += f"- **Subscribers:** {info.get('subscriber_count')} \n"
133
+
134
+ if info.get("view_count"):
135
+ result += f"- **Views:** {info.get('view_count')} \n"
136
+
137
+ # Add channel source citation
138
+ if raw_results.get("channel") and len(raw_results.get("channel")) > 0:
139
+ source = raw_results.get("channel")[0]
140
+ result += f"\n: [{source.get('title')}]({source.get('url')})\n"
141
+
142
+ # Add stats source citation
143
+ if raw_results.get("stats") and len(raw_results.get("stats")) > 0:
144
+ source = raw_results.get("stats")[0]
145
+ result += f": [{source.get('title')}]({source.get('url')})\n"
146
+
147
+ # Recent content
148
+ if info.get("recent_videos") and len(info.get("recent_videos")) > 0:
149
+ result += "\n## Recent Content\n"
150
+ for i, video in enumerate(info.get("recent_videos")):
151
+ result += f"- **{video.get('title')}** $CITE_{3+i}\n"
152
+ result += f" {video.get('description')}\n"
153
+ result += f" [Link]({video.get('url')})\n\n"
154
+
155
+ # Content citations
156
+ for i, source in enumerate(raw_results.get("content", [])[:len(info.get("recent_videos", []))]):
157
+ result += f"$CITE_{3+i}: [{source.get('title')}]({source.get('url')})\n"
158
+
159
+ # Background information
160
+ if info.get("background_info") and len(info.get("background_info")) > 0:
161
+ result += "\n## Background & History\n"
162
+ cite_start = 3 + len(info.get("recent_videos", []))
163
+ for i, bg in enumerate(info.get("background_info")):
164
+ result += f"- **{bg.get('title')}** $CITE_{cite_start+i}\n"
165
+ result += f" {bg.get('description')}\n\n"
166
+
167
+ # Background citations
168
+ cite_start = 3 + len(info.get("recent_videos", []))
169
+ for i, source in enumerate(raw_results.get("background", [])[:len(info.get("background_info", []))]):
170
+ result += f"$CITE_{cite_start+i}: [{source.get('title')}]({source.get('url')})\n"
171
+
172
+ return result
173
 
174
+ # Create the specialized YouTuber information agent
175
+ search_tool = DuckDuckGoSearchTool()
176
  final_answer = FinalAnswerTool()
177
 
178
+ youtuber_info_agent = CodeAgent(
179
+ model=HfApiModel(
180
+ max_tokens=2048,
181
+ temperature=0.3,
182
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
183
+ ),
184
+ tools=[
185
+ search_tool,
186
+ search_youtuber,
187
+ extract_youtube_info,
188
+ format_youtuber_profile,
189
+ final_answer
190
+ ],
191
+ max_steps=8,
192
+ verbosity_level=1,
193
+ name="YouTuberInfoAgent",
194
+ description="A specialized agent that finds and provides information about YouTubers using DuckDuckGo search with proper citations."
195
  )
196
 
197
+ # Example prompt template
198
+ system_prompt = """You are a specialized YouTuber information agent. Your task is to find and provide detailed information about YouTube creators when given a YouTuber's name.
199
 
200
+ ALWAYS include multiple distinct sources in your response, at LEAST 3-4, by $CITE_id at the end of each information part, like , .
 
201
 
202
+ Follow these steps:
203
+ 1. Search for the YouTuber using the search_youtuber tool
204
+ 2. Extract relevant information using the extract_youtube_info tool
205
+ 3. Format the information with proper citations using the format_youtuber_profile tool
206
+ 4. Present the information to the user in a well-organized format
 
 
 
 
 
 
 
 
 
207
 
208
+ Always verify the information before presenting it and indicate if certain information couldn't be retrieved.
209
+ """
210
+
211
+ # Add the agent to a Gradio UI
212
+ from gradio import Interface
213
+
214
+ def process_request(youtuber_name):
215
+ response = youtuber_info_agent.run(
216
+ system_prompt=system_prompt,
217
+ user_prompt=f"Please provide information about the YouTuber: {youtuber_name}"
218
+ )
219
+ return response
220
+
221
+ interface = Interface(
222
+ fn=process_request,
223
+ inputs="text",
224
+ outputs="markdown",
225
+ title="YouTuber Information Agent",
226
+ description="Enter a YouTuber's name to get information about them with proper citations."
227
+ )
228
 
229
+ interface.launch()