Simplify Your Bedrock Converse API Integration with the bedrock-tools Python Library
I wrote this post to introduce bedrock-tools, a Python library I wrote to streamline the integration of custom Python functions with the Amazon Bedrock Converse API for building conversational AI agents and applications. The library minimizes boilerplate code, automates type handling by generating JSON schemas from function annotations, and manages tool invocation and exception handling seamlessly. By enabling developers to define tools as simple Python functions, bedrock-tools simplifies the development process, allowing a focus on core application functionality.
frombedrock_toolsimport BedrockTools
# define native functions as tools (using type annotations)defadd_numbers(a: int, b: int) -> int:
"""Add two numbers together."""return a + b
defgreet(name: str) -> str:
"""Greet a person by name."""returnf"Hello, {name}!"defget_weather(city: str, state: str) -> dict:
"""Get the weather for a location."""return {
"city": city,
"state": state,
"temperature": "75°F",
"condition": "Partly Cloudy",
}
# setuptools = BedrockTools()
tools.add_function(add_numbers)
tools.add_function(greet)
tools.add_function(get_weather)
# Use the config in your Bedrock Converse API callresponse = bedrock.converse(
modelId=model_id,
toolConfig=tools.get_tool_config()
messages=messages,
)
# When you receive a toolUse from the API, invoke the toolif"toolUse"in content_block:
tool_results.append(tools.invoke(content_block["toolUse"]))
message = {"role": "user", "content": tool_results}