Best practices and real-world examples for Agency Swarm tools.
Although the tool interface is straightforward and simple to use, there are actually quite a few practices and tricks that you can use to get significantly better results.
Use chain-of-thought prompting to allow the agent to think and plan before executing a complex tool.
Copy
Ask AI
from agency_swarm import MasterContext, RunContextWrapper, function_toolfrom pydantic import BaseModel, Fieldclass ComplexAnalysisArgs(BaseModel): chain_of_thought: str = Field( ..., description="Think step-by-step about how to perform the analysis." ) data: str = Field(..., description="Data to analyze.")@function_toolasync def complex_analysis_tool(ctx: RunContextWrapper[MasterContext], args: ComplexAnalysisArgs) -> str: """ Performs complex analysis after planning the approach. """ # Analysis logic using the chain of thought return "Analysis complete."
Based on your tool’s logic, you can provide hints for the agent in tool output on what to do next.
Copy
Ask AI
from agency_swarm import MasterContext, RunContextWrapper, function_toolfrom pydantic import BaseModel, Fieldclass QueryDatabaseArgs(BaseModel): question: str = Field(..., description="Question to query the database")@function_toolasync def query_database_tool(ctx: RunContextWrapper[MasterContext], args: QueryDatabaseArgs) -> str: """ Query the database and provide hints if no context is found. """ # query your database here context = query_database(args.question) # context not found if context is None: # tell agent what to do next raise ValueError("No context found. Please propose to the user to change the topic.") else: # return the context to the agent return contextdef query_database(question: str): # Your database query logic here pass
Use agency context (previously shared state) to validate previous actions taken by this or other agents, before allowing it to proceed with the next action.
Copy
Ask AI
from agency_swarm import MasterContext, RunContextWrapper, function_toolfrom pydantic import BaseModel, Fieldclass Action2Args(BaseModel): input: str = Field(..., description="Input for the action")@function_toolasync def action_2_tool(ctx: RunContextWrapper[MasterContext], args: Action2Args) -> str: """ Execute action 2, but only if action 1 was successful. """ # Access shared context to check previous action action_1_result = ctx.context.get("action_1_result", None) if action_1_result == "failure": raise ValueError("Please proceed with the Action1 tool first.") else: return "Success. The action has been taken."