AI Agents with Hugging Face smolagents
Adel Nehme
VP of AI Curriculum, DataCamp
Function Tools (@tool
decorator)
Class-Based Tools (Tool
subclass)
from smolagents import Tool class ToolName(Tool): name = "tool_name"
description = "Clear description for the agent"
inputs = { "parameter_name": {"type": "parameter_type", "description": "Parameter purpose"} } output_type = "string"
def __init__(self, custom_parameters): super().__init__() self.custom_attribute = custom_parameters
def forward(self, parameter_name): # Agent calls this method return "processed output"
class RecipeSearchTool(Tool): name = "recipe_search" description = "Search cooking documentation for recipes, techniques, and meal planning information" inputs = { "query": {"type": "string", "description": "Natural language cooking query"} } output_type = "string"
def __init__(self, vectorstore, k=6): super().__init__() self.vectorstore = vectorstore self.k = k
def forward(self, query): docs = self.vectorstore.similarity_search(query, k=self.k) return "\n\n".join(doc.page_content for doc in docs) or "Nothing found."
# Initialize the retrieval tool
recipe_search = RecipeSearchTool(vector_store)
agent = CodeAgent(
tools=[recipe_search],
model=model,
instructions="Search thoroughly to provide complete recipe answers.
If initial results seem incomplete, try different search terms.",
verbosity_level=1,
max_steps=8
)
Query: How do I cook salmon with herbs using professional techniques?
[Step 1] Search "salmon herbs cooking techniques"...
[Step 2] Search "professional salmon preparation"...
[Final Answer]
"Pat fillets dry, season with herbs, and:
AI Agents with Hugging Face smolagents