Back to snippets
strands_agents_custom_tool_definition_with_pydantic_schema.py
pythonThis quickstart demonstrates how to define a custom tool using the
Agent Votes
1
0
100% positive
strands_agents_custom_tool_definition_with_pydantic_schema.py
1from typing import Annotated
2from strands_agents_tools import StrandsTool
3from pydantic import Field
4
5# 1. Define your tool by inheriting from StrandsTool
6class WeatherTool(StrandsTool):
7 """A tool to get the current weather in a given city."""
8
9 name: str = "get_weather"
10 description: str = "Useful for finding the current weather conditions for a specific location."
11
12 def run(
13 self,
14 city: Annotated[str, Field(description="The name of the city to check the weather for")]
15 ) -> str:
16 # In a real scenario, you would call a weather API here
17 return f"The weather in {city} is currently sunny with a temperature of 22°C."
18
19# 2. Instantiate the tool
20weather_tool = WeatherTool()
21
22# 3. Use the tool (Example of manual execution)
23if __name__ == "__main__":
24 result = weather_tool.run(city="San Francisco")
25 print(f"Tool Output: {result}")
26
27 # The tool can also be converted to a format compatible with OpenAI or LangChain
28 print(f"Tool Schema: {weather_tool.to_openai_tool()}")