节将为 Alfred 赋予网络访问能力,使其能够获取实时新闻与全球资讯。 同时还将集成天气数据和 Hugging Face Hub 模型下载统计功能,帮助其进行时效性话题交流。
请记住,我们希望 Alfred 能够展现出一位真正的文艺复兴主持人的风采,并对世界有着深刻的了解。
为此,我们需要确保 Alfred 能够获取有关世界的最新新闻和信息。
让我们从为 Alfred 创建一个网络搜索工具开始吧!
from smolagents import DuckDuckGoSearchTool
# 初始化 DuckDuckGo 搜索工具
search_tool = DuckDuckGoSearchTool()
# 示例用法
results = search_tool("Who's the current President of France?")
print(results)预期输出:
法国现任总统为 Emmanuel Macron。
完美的庆典应该在晴朗的天空下燃放烟花,我们需要确保烟花不会因为恶劣天气而取消。
让我们创建一个自定义工具,用于调用外部天气 API 并获取指定位置的天气信息。
from smolagents import Tool
import random
class WeatherInfoTool(Tool):
name = "weather_info"
description = "Fetches dummy weather information for a given location."
inputs = {
"location": {
"type": "string",
"description": "The location to get weather information for."
}
}
output_type = "string"
def forward(self, location: str):
# 虚拟天气数据
weather_conditions = [
{"condition": "Rainy", "temp_c": 15},
{"condition": "Clear", "temp_c": 25},
{"condition": "Windy", "temp_c": 20}
]
# 随机选择一种天气状况
data = random.choice(weather_conditions)
return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C"
# 初始化工具
weather_info_tool = WeatherInfoTool()出席此次盛会的都是 AI 开发者的精英。Alfred 希望通过讨论他们最受欢迎的模型、数据集和空间来给他们留下深刻印象。我们将创建一个工具,根据用户名从 Hugging Face Hub 获取模型统计数据。
from smolagents import Tool
from huggingface_hub import list_models
class HubStatsTool(Tool):
name = "hub_stats"
description = "Fetches the most downloaded model from a specific author on the Hugging Face Hub."
inputs = {
"author": {
"type": "string",
"description": "The username of the model author/organization to find models from."
}
}
output_type = "string"
def forward(self, author: str):
try:
# 列出指定作者的模型,按下载次数排序
models = list(list_models(author=author, sort="downloads", direction=-1, limit=1))
if models:
model = models[0]
return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads."
else:
return f"No models found for author {author}."
except Exception as e:
return f"Error fetching models for {author}: {str(e)}"
# 初始化工具
hub_stats_tool = HubStatsTool()
# 示例用法
print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook预期输出:
Facebook 下载次数最多的模型是 facebook/esmfold_v1,下载次数为 12,544,550 次。借助 Hub Stats 工具,Alfred 现在可以通过讨论他们最受欢迎的模型来打动有影响力的 AI 开发者。
现在我们已经拥有了所有工具,让我们将它们集成到 Alfred 的智能体中:
from smolagents import CodeAgent, InferenceClientModel
# 初始化 Hugging Face 模型
model = InferenceClientModel()
# 使用所有工具创建 Alfred
alfred = CodeAgent(
tools=[search_tool, weather_info_tool, hub_stats_tool],
model=model
)
# Alfred 在庆典期间可能会收到的示例查询
response = alfred.run("What is Facebook and what's their most popular model?")
print("🎩 Alfred's Response:")
print(response)预期输出:
🎩 Alfred's Response:
Facebook 是一个社交网站,用户可以在这里互相联系、分享信息并互动。Facebook 在 Hugging Face Hub 上下载次数最多的模型是 ESMFold_v1。通过集成这些工具,Alfred 现在可以处理各种任务,从网页搜索到天气更新和模型统计。这确保他始终是晚会上最了解情况、最有魅力的主持人。
完成后,在 tools.py 文件中实现您的自定义工具。