@tool("search", return_direct=True)
def search_api(query: str) -> str:
# Searches the API for the query.
return
from swarms.models import OpenAIChat
from swarms.structs import Flow
from swarms.tools import tool
api_key = ""
# Initialize the language model, this model can be swapped out with Anthropic, ETC, Huggingface Models like Mistral, ETC
llm = OpenAIChat(
openai_api_key=api_key,
temperature=0.5,
max_tokens=3000,
)
# Tool usage example
@tool
def search_api(query: str):
"""Search the web with this tool"""
pass
# Initialize the flow
flow = Flow(llm=llm, max_loops=5, dashboard=True, tools=[search_api])
out = flow.run("Generate a 10,000 word blog on health and wellness.")
print(out)
Learn how the worker uses tool: https://github.com/kyegomez/swarms/blob/master/swarms/agents/agent.py
tool
DocumentationDecorator Functionality:
The tool
decorator can be used in several ways, based on the arguments passed to it. It supports transforming simple functions, asynchronous functions, or objects implementing a Runnable
interface into a tool.
Arguments Handling:
*args
: This is a variable argument list allowing different types of inputs (string, Callable
, or Runnable
).return_direct
: If set to True
, the tool returns directly without continuing the loop in which it's running.args_schema
: An optional Pydantic model (BaseModel
) for validating input arguments to the tool.infer_schema
: If True
, the tool attempts to infer the argument schema from the function signature.Tool Creation:
Runnable
object, it wraps its invocation methods (ainvoke
for async, invoke
for sync) into a tool.StructuredTool.from_function
if infer_schema
is True
or creates a basic Tool
otherwise.Schema Inference:
infer_schema
is True
, the decorator infers the input schema for the tool based on the function's signature.run()
method.Error Handling:
infer_schema
is False
, the function must have a docstring to provide a description.Simple Function as a Tool:
@tool
def search_api(query: str) -> str:
# Function body
Named Tool with Direct Return:
@tool("search", return_direct=True)
def search_api(query: str) -> str:
# Function body
Using Runnable:
@tool("runnable_tool")
class MyRunnable(Runnable):
# Implementation of Runnable
This kind of tool creation is particularly useful in systems where you need modular, reusable components that can be plugged into different parts of an application, especially in scenarios involving asynchronous operations, agent-based simulations, or complex workflows requiring structured input/output handling.
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too