在本节中,我们将授予阿尔弗雷德访问网络的权利,使他能够找到最新的新闻和全球动态。此外,他还将能够访问天气数据以及Hugging Face模型下载统计信息,从而能够就相关话题进行有意义的对话。
为您的智能体提供网络访问权限
请记住,我们希望阿尔弗雷德能够成为一个真正的文艺复兴式主持人,拥有对世界的深刻了解。
为此,我们需要确保阿尔弗雷德能够获取关于世界的最新新闻和信息。
让我们先为阿尔弗雷德创建一个网络搜索工具吧!
smolagents
from smolagents import DuckDuckGoSearchTool
# Initialize the DuckDuckGo search tool
search_tool = DuckDuckGoSearchTool()
# Example usage
results = search_tool("Who's the current President of France?")
print(results)
预期输出:
The current President of France in Emmanuel Macron.
llama-index
from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec
from llama_index.core.tools import FunctionTool
# Initialize the DuckDuckGo search tool
tool_spec = DuckDuckGoSearchToolSpec()
search_tool = FunctionTool.from_defaults(tool_spec.duckduckgo_full_search)
# Example usage
response = search_tool("Who's the current President of France?")
print(response.raw_output[-1]['body'])
预期输出:
The President of the French Republic is the head of state of France. The current President is Emmanuel Macron since 14 May 2017 defeating Marine Le Pen in the second round of the presidential election on 7 May 2017. List of French presidents (Fifth Republic) N° Portrait Name ...
langgraph
from langchain_community.tools import DuckDuckGoSearchRun
search_tool = DuckDuckGoSearchRun()
results = search_tool.invoke("Who's the current President of France?")
print(results)
预期输出:
Emmanuel Macron (born December 21, 1977, Amiens, France) is a French banker and politician who was elected president of France in 2017...
创建自定义工具以获取天气信息以安排烟花表演
完美的庆典会在晴朗的天空中燃放烟花,我们需要确保烟花不会因恶劣天气而取消。
让我们创建一个自定义工具,用于调用外部天气API并获取指定位置的天气信息。
[!TIP] 为了简单起见,我们在示例中使用了一个虚拟的天气 API。如果您想使用真实的天气 API,可以实现一个使用 OpenWeatherMap API 的天气工具。 单元1.
smolagents
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):
# Dummy weather data
weather_conditions = [
{"condition": "Rainy", "temp_c": 15},
{"condition": "Clear", "temp_c": 25},
{"condition": "Windy", "temp_c": 20}
]
# Randomly select a weather condition
data = random.choice(weather_conditions)
return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C"
# Initialize the tool
weather_info_tool = WeatherInfoTool()
llama-index
import random
from llama_index.core.tools import FunctionTool
def get_weather_info(location: str) -> str:
"""Fetches dummy weather information for a given location."""
# Dummy weather data
weather_conditions = [
{"condition": "Rainy", "temp_c": 15},
{"condition": "Clear", "temp_c": 25},
{"condition": "Windy", "temp_c": 20}
]
# Randomly select a weather condition
data = random.choice(weather_conditions)
return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C"
# Initialize the tool
weather_info_tool = FunctionTool.from_defaults(get_weather_info)
langgraph
from langchain_core.tools import Tool
import random
def get_weather_info(location: str) -> str:
"""Fetches dummy weather information for a given location."""
# Dummy weather data
weather_conditions = [
{"condition": "Rainy", "temp_c": 15},
{"condition": "Clear", "temp_c": 25},
{"condition": "Windy", "temp_c": 20}
]
# Randomly select a weather condition
data = random.choice(weather_conditions)
return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C"
# Initialize the tool
weather_info_tool = Tool(
name="get_weather_info",
func=get_weather_info,
description="Fetches dummy weather information for a given location."
)
为有影响力的 AI 开发者创建枢纽统计工具
出席这场晚宴的都有AI领域的顶尖人物。阿尔弗雷德希望通过讨论他们最受欢迎的模型、数据集以及应用领域来给他们留下深刻印象。我们将创建一个工具,该工具可以根据用户名从Hugging Face Hub获取模型统计信息。
smolagents
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:
# List models from the specified author, sorted by downloads
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)}"
# Initialize the tool
hub_stats_tool = HubStatsTool()
# Example usage
print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook
预期输出:
The most downloaded model by facebook is facebook/esmfold_v1 with 12,544,550 downloads.
llama-index
import random
from llama_index.core.tools import FunctionTool
from huggingface_hub import list_models
def get_hub_stats(author: str) -> str:
"""Fetches the most downloaded model from a specific author on the Hugging Face Hub."""
try:
# List models from the specified author, sorted by downloads
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)}"
# Initialize the tool
hub_stats_tool = FunctionTool.from_defaults(get_hub_stats)
# Example usage
print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook
预期输出:
The most downloaded model by facebook is facebook/esmfold_v1 with 12,544,550 downloads.
langgraph
from langchain_core.tools import Tool
from huggingface_hub import list_models
def get_hub_stats(author: str) -> str:
"""Fetches the most downloaded model from a specific author on the Hugging Face Hub."""
try:
# List models from the specified author, sorted by downloads
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)}"
# Initialize the tool
hub_stats_tool = Tool(
name="get_hub_stats",
func=get_hub_stats,
description="Fetches the most downloaded model from a specific author on the Hugging Face Hub."
)
# Example usage
print(hub_stats_tool.invoke("facebook")) # Example: Get the most downloaded model by Facebook
预期输出:
The most downloaded model by facebook is facebook/esmfold_v1 with 13,109,861 downloads.
通过 Hub 统计工具,Alfred 现在可以通过讨论其最受欢迎的模型来给有影响力的 AI 开发者留下深刻印象。
将工具与 Alfred 集成
现在我们已经拥有了所有工具,接下来将它们整合到 Alfred 的智能体中:
smolagents
from smolagents import CodeAgent, InferenceClientModel
# Initialize the Hugging Face model
model = InferenceClientModel()
# Create Alfred with all the tools
alfred = CodeAgent(
tools=[search_tool, weather_info_tool, hub_stats_tool],
model=model
)
# Example query Alfred might receive during the gala
response = alfred.run("What is Facebook and what's their most popular model?")
print("🎩 Alfred's Response:")
print(response)
预期输出:
🎩 Alfred's Response:
Facebook is a social networking website where users can connect, share information, and interact with others. The most downloaded model by Facebook on the Hugging Face Hub is ESMFold_v1.
llama-index
from llama_index.core.agent.workflow import AgentWorkflow
from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
# Initialize the Hugging Face model
llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct")
# Create Alfred with all the tools
alfred = AgentWorkflow.from_tools_or_functions(
[search_tool, weather_info_tool, hub_stats_tool],
llm=llm
)
# Example query Alfred might receive during the gala
response = await alfred.run("What is Facebook and what's their most popular model?")
print("🎩 Alfred's Response:")
print(response)
预期输出:
🎩 Alfred's Response:
Facebook is a social networking service and technology company based in Menlo Park, California. It was founded by Mark Zuckerberg and allows people to create profiles, connect with friends and family, share photos and videos, and join groups based on shared interests. The most popular model by Facebook on the Hugging Face Hub is `facebook/esmfold_v1` with 13,109,861 downloads.
langgraph
from typing import TypedDict, Annotated
from langgraph.graph.message import add_messages
from langchain_core.messages import AnyMessage, HumanMessage, AIMessage
from langgraph.prebuilt import ToolNode
from langgraph.graph import START, StateGraph
from langgraph.prebuilt import tools_condition
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
# Generate the chat interface, including the tools
llm = HuggingFaceEndpoint(
repo_id="Qwen/Qwen2.5-Coder-32B-Instruct",
huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,
)
chat = ChatHuggingFace(llm=llm, verbose=True)
tools = [search_tool, weather_info_tool, hub_stats_tool]
chat_with_tools = chat.bind_tools(tools)
# Generate the AgentState and Agent graph
class AgentState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
def assistant(state: AgentState):
return {
"messages": [chat_with_tools.invoke(state["messages"])],
}
## The graph
builder = StateGraph(AgentState)
# Define nodes: these do the work
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))
# Define edges: these determine how the control flow moves
builder.add_edge(START, "assistant")
builder.add_conditional_edges(
"assistant",
# If the latest message requires a tool, route to tools
# Otherwise, provide a direct response
tools_condition,
)
builder.add_edge("tools", "assistant")
alfred = builder.compile()
messages = [HumanMessage(content="Who is Facebook and what's their most popular model?")]
response = alfred.invoke({"messages": messages})
print("🎩 Alfred's Response:")
print(response['messages'][-1].content)
预期输出:
🎩 Alfred's Response:
Facebook is a social media company known for its social networking site, Facebook, as well as other services like Instagram and WhatsApp. The most downloaded model by Facebook on the Hugging Face Hub is facebook/esmfold_v1 with 13,202,321 downloads.
小结
通过整合这些工具,Alfred现在能够处理各种任务,从网络搜索到天气更新以及模型统计信息。这确保了它成为庆典上最信息丰富且引人注目的主持人。
[!TIP] 尝试实现一个工具,用于获取特定主题的最新新闻。
完成后,在智能体中实现你的自定义工具。
tools.py文件。