Crowe Basetool

Crowe BaseTool

Overview Crowe BaseTool is a unified tool execution and schema management framework designed for AI-powered workflows. It streamlines function calling, schema conversion, and tool execution across providers like OpenAI and Anthropic, with built-in validation, caching, and error handling.


Key Capabilities

  • Function → AI Schema Instantly convert Python functions to standardized function-calling schemas.

  • Multi-Provider Schema Support Validate and convert between OpenAI, Anthropic, and other AI provider formats.

  • Execution Engine Run tools sequentially or in parallel with robust error handling and automatic retries.

  • Pydantic Integration Manage, validate, and serialize Pydantic models with ease.

  • Auto Execution Detect and execute tools directly from API responses.

  • Performance-Ready Caching system for repeated calls to boost speed and reduce cost.


Initialization Parameters

Parameter
Type
Default
Description

verbose

bool

None

Enable detailed logs.

base_models

List[BaseModel]

None

Pydantic models to manage.

autocheck

bool

None

Enable schema and type validation.

auto_execute_tool

bool

None

Auto-run tools from responses.

tools

List[Callable]

None

Functions to register as tools.

tool_system_prompt

str

None

Custom system prompt for tools.

function_map

Dict[str, Callable]

None

Map of function names to callables.

list_of_dicts

List[Dict]

None

Pre-defined schema dictionaries.


Core Methods

  • Schema Conversion

    • func_to_dict() → Convert Python functions into AI tool schemas.

    • base_model_to_dict() / multi_base_models_to_dict() → Pydantic → AI schema.

    • convert_schema_between_providers() → Cross-provider schema translation.

  • Execution

    • execute_tool() → Run tool with input validation.

    • dynamic_run() → Auto-detect input type and execute.

    • execute_tool_from_text() → Run tools from JSON strings.

  • Validation & Inspection

    • check_func_if_have_docs() → Ensure functions are documented.

    • check_func_if_have_type_hints() → Verify type hints.

    • validate_function_schema() → Confirm schema compliance.

  • Automation

    • execute_function_calls_from_api_response() → Parse and run API function calls.

    • detect_api_response_format() → Identify API provider response type.

BaseTool — Method Highlights


func_to_dict

Convert any Python function into an OpenAI function calling schema. Useful for exposing local functions directly to an AI model.

from swarms.tools.base_tool import BaseTool

def add_numbers(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

tool = BaseTool(verbose=True)
schema = tool.func_to_dict(add_numbers)
print(schema)
# {'type': 'function', 'function': {'name': 'add_numbers', 'description': 'Add two numbers together.', 'parameters': {...}}}

load_params_from_func_for_pybasemodel

Automatically generate Pydantic model parameters from a function for type-safe input validation.

from swarms.tools.base_tool import BaseTool

def calculate_area(length: float, width: float) -> float:
    """Calculate area of a rectangle."""
    return length * width

tool = BaseTool()
processed_func = tool.load_params_from_func_for_pybasemodel(calculate_area)

result = processed_func(5.0, 3.0)
print(result)  # 15.0

base_model_to_dict

Convert a Pydantic BaseModel to an AI-callable schema.

from pydantic import BaseModel
from swarms.tools.base_tool import BaseTool

class UserInfo(BaseModel):
    name: str
    age: int
    email: str

tool = BaseTool()
schema = tool.base_model_to_dict(UserInfo)
print(schema)

multi_base_models_to_dict

Merge multiple Pydantic models into a single schema.

from pydantic import BaseModel
from swarms.tools.base_tool import BaseTool

class User(BaseModel):
    name: str
    age: int

class Product(BaseModel):
    name: str
    price: float

tool = BaseTool()
schemas = tool.multi_base_models_to_dict([User, Product])
print(schemas)

dict_to_openai_schema_str

Convert a schema dictionary into a string for OpenAI function calling.

from swarms.tools.base_tool import BaseTool

my_dict = {
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get weather information",
        "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}
    }
}

tool = BaseTool()
schema_str = tool.dict_to_openai_schema_str(my_dict)
print(schema_str)

multi_dict_to_openai_schema_str

Combine multiple schema dictionaries into one string.

from swarms.tools.base_tool import BaseTool

dict1 = {"type": "function", "function": {"name": "func1", "description": "Function 1"}}
dict2 = {"type": "function", "function": {"name": "func2", "description": "Function 2"}}

tool = BaseTool()
schema_str = tool.multi_dict_to_openai_schema_str([dict1, dict2])
print(schema_str)

execute_tool

Execute a tool based on a JSON response string (name + parameters).

from swarms.tools.base_tool import BaseTool

def greet(name: str) -> str:
    """Greet a person by name."""
    return f"Hello, {name}!"

tool = BaseTool(tools=[greet])

response = '{"name": "greet", "parameters": {"name": "Alice"}}'
result = tool.execute_tool(response)
print(result)  # "Hello, Alice!"

detect_tool_input_type

Detect the input category to choose the right processing path: "Pydantic" | "Dictionary" | "Function" | "Unknown".

from swarms.tools.base_tool import BaseTool
from pydantic import BaseModel

class MyModel(BaseModel):
    value: int

def my_function():
    return "ok"

tool = BaseTool()

print(tool.detect_tool_input_type(MyModel))        # "Pydantic"
print(tool.detect_tool_input_type(my_function))    # "Function"
print(tool.detect_tool_input_type({"k": "v"}))     # "Dictionary"
print(tool.detect_tool_input_type(42))             # "Unknown"

dynamic_run

Auto-detect the input type (Pydantic class, dict schema, or function) and do the right thing (e.g., return schema string or execute).

from swarms.tools.base_tool import BaseTool

def multiply(x: int, y: int) -> int:
    """Multiply two numbers."""
    return x * y

tool = BaseTool(auto_execute_tool=False)

schema_or_result = tool.dynamic_run(multiply)
print(type(schema_or_result), schema_or_result)  # typically a schema string

execute_tool_by_name

Find a registered tool by name and execute it with JSON parameters.

from swarms.tools.base_tool import BaseTool

def calculate_sum(a: int, b: int) -> int:
    """Calculate sum of two numbers."""
    return a + b

tool = BaseTool(function_map={"calculate_sum": calculate_sum})
result = tool.execute_tool_by_name("calculate_sum", '{"a": 5, "b": 3}')
print(result)  # 8

execute_tool_from_text

Parse a JSON tool-call string ({"name": "...","parameters": {...}}) and execute it.

from swarms.tools.base_tool import BaseTool

def divide(x: float, y: float) -> float:
    """Divide x by y."""
    return x / y

tool = BaseTool(function_map={"divide": divide})
text = '{"name": "divide", "parameters": {"x": 10, "y": 2}}'
print(tool.execute_tool_from_text(text))  # 5.0

check_str_for_functions_valid

Validate if a string is JSON and the function name exists in the function map.

from swarms.tools.base_tool import BaseTool

def test_func():
    return "ok"

tool = BaseTool(function_map={"test_func": test_func})

valid_output = '{"type":"function","function":{"name":"test_func"}}'
print(tool.check_str_for_functions_valid(valid_output))  # True

invalid_output = '{"type":"function","function":{"name":"missing"}}'
print(tool.check_str_for_functions_valid(invalid_output))  # False

convert_funcs_into_tools

Convert all functions in tools into internal OpenAI-style tool format, populating function_map.

from swarms.tools.base_tool import BaseTool

def func1(x: int) -> int:
    """Function 1."""
    return x * 2

def func2(y: str) -> str:
    """Function 2."""
    return y.upper()

tool = BaseTool(tools=[func1, func2])
tool.convert_funcs_into_tools()
print(sorted(tool.function_map.keys()))  # ['func1', 'func2']

convert_tool_into_openai_schema

Export all registered tools as a combined OpenAI function-calling schema.

from swarms.tools.base_tool import BaseTool

def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

def subtract(a: int, b: int) -> int:
    """Subtract b from a."""
    return a - b

tool = BaseTool(tools=[add, subtract])
schema = tool.convert_tool_into_openai_schema()
print(schema)  # dict with 'type': 'function' entries for add/subtract

check_func_if_have_docs

Ensure a function has a docstring. (Implementations may return True or raise a specific error if missing.)

from swarms.tools.base_tool import BaseTool

def documented_func():
    """This function has documentation."""
    return "ok"

def undocumented_func():
    return "nope"

tool = BaseTool()
print(tool.check_func_if_have_docs(documented_func))  # True

# Depending on implementation, the next line may raise ToolDocumentationError:
# tool.check_func_if_have_docs(undocumented_func)

check_func_if_have_type_hints

Ensure a function has proper type hints. (Implementations may return True or raise a specific error if missing.)

from swarms.tools.base_tool import BaseTool

def typed_func(x: int) -> str:
    """A typed function."""
    return str(x)

def untyped_func(x):
    """An untyped function."""
    return str(x)

tool = BaseTool()
print(tool.check_func_if_have_type_hints(typed_func))  # True

# Depending on implementation, may raise ToolTypeHintError:
# tool.check_func_if_have_type_hints(untyped_func)

find_function_name

Find a function by name in the registered tool set.

from swarms.tools.base_tool import BaseTool

def my_function():
    """My function."""
    return "hello"

tool = BaseTool(tools=[my_function])
found = tool.find_function_name("my_function")
print(found is my_function)  # True

function_to_dict

Convert a function into a dictionary representation (name, docstring, params).

from swarms.tools.base_tool import BaseTool

def example_func(param: str) -> str:
    """Example function."""
    return param

tool = BaseTool()
func_dict = tool.function_to_dict(example_func)
print(func_dict)  # {'name': 'example_func', 'description': 'Example function.', 'parameters': {...}}

multiple_functions_to_dict

Convert a list of functions into a list of dict representations.

from swarms.tools.base_tool import BaseTool

def func1(x: int) -> int:
    """Function 1."""
    return x

def func2(y: str) -> str:
    """Function 2."""
    return y

tool = BaseTool()
func_dicts = tool.multiple_functions_to_dict([func1, func2])
print(func_dicts)  # [{'name': 'func1', ...}, {'name': 'func2', ...}]

execute_function_with_dict

Execute a function using a dictionary of parameters. Useful when arguments are produced by a model or parsed from JSON.

from swarms.tools.base_tool import BaseTool

def power(base: int, exponent: int) -> int:
    """Calculate base to the power of exponent."""
    return base ** exponent

tool = BaseTool(tools=[power])

# Provide params as a dict; specify the function by name
result = tool.execute_function_with_dict({"base": 2, "exponent": 3}, "power")
print(result)  # 8

execute_multiple_functions_with_dict

Execute multiple functions from a list of parameter dictionaries (optionally specify names if auto-detection isn’t used).

from swarms.tools.base_tool import BaseTool

def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

tool = BaseTool(tools=[add, multiply])

results = tool.execute_multiple_functions_with_dict(
    [{"a": 1, "b": 2}, {"a": 3, "b": 4}],
    ["add", "multiply"]
)
print(results)  # [3, 12]

validate_function_schema

Validate a function schema for a target provider ("openai", "anthropic", "generic", or "auto").

from swarms.tools.base_tool import BaseTool

openai_schema = {
    "type": "function",
    "function": {
        "name": "add_numbers",
        "description": "Add two numbers",
        "parameters": {
            "type": "object",
            "properties": {
                "a": {"type": "integer"},
                "b": {"type": "integer"}
            },
            "required": ["a", "b"]
        }
    }
}

tool = BaseTool()
is_valid = tool.validate_function_schema(openai_schema, provider="openai")
print(is_valid)  # True (if valid)

get_schema_provider_format

Detect the provider format of a given schema dict.

from swarms.tools.base_tool import BaseTool

openai_schema = {
    "type": "function",
    "function": {"name": "test", "description": "Test function"}
}

tool = BaseTool()
provider = tool.get_schema_provider_format(openai_schema)
print(provider)  # "openai"

convert_schema_between_providers

Convert a function schema between providers (e.g., OpenAI → Anthropic).

from swarms.tools.base_tool import BaseTool

openai_schema = {
    "type": "function",
    "function": {
        "name": "test_func",
        "description": "Test function",
        "parameters": {"type": "object", "properties": {}}
    }
}

tool = BaseTool()
anthropic_schema = tool.convert_schema_between_providers(openai_schema, "anthropic")
print(anthropic_schema)
# e.g. {"name": "test_func", "description": "Test function", "input_schema": {...}}

execute_function_calls_from_api_response

Auto-detect and execute function calls embedded in OpenAI/Anthropic responses. Can run sequentially or in parallel.

from swarms.tools.base_tool import BaseTool

def get_weather(city: str) -> str:
    """Get weather for a city."""
    return f"Weather in {city}: Sunny, 25°C"

# Simulated OpenAI-style response with a tool call
openai_response = {
    "choices": [{
        "message": {
            "tool_calls": [{
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "arguments": '{"city": "New York"}'
                },
                "id": "call_123"
            }]
        }
    }]
}

tool = BaseTool(tools=[get_weather])

# Execute discovered tool calls
results = tool.execute_function_calls_from_api_response(
    api_response=openai_response,
    sequential=True,       # or False for parallel
    max_workers=4,
    return_as_string=True  # pretty formatted strings
)

print(results)
# ["Function 'get_weather' result:\nWeather in New York: Sunny, 25°C"]

detect_api_response_format

Detect whether a response looks like OpenAI, Anthropic, generic, or unknown.

from swarms.tools.base_tool import BaseTool

openai_response = {"choices": [{"message": {"tool_calls": []}}]}
anthropic_response = {"content": [{"type": "tool_use", "name": "test", "input": {}}]}

tool = BaseTool()
print(tool.detect_api_response_format(openai_response))   # "openai"
print(tool.detect_api_response_format(anthropic_response))# "anthropic"

Exception Classes

Custom exceptions for precise error handling:

  • BaseToolError — Base class for all BaseTool-related errors

  • ToolValidationError — Schema/tool validation failed

  • ToolExecutionError — Tool execution failed

  • ToolNotFoundError — Requested tool not found

  • FunctionSchemaError — Failed during schema conversion

  • ToolDocumentationError — Missing/invalid function docstring

  • ToolTypeHintError — Missing/invalid type hints

Example handling:

from swarms.tools.base_tool import BaseTool, ToolNotFoundError

tool = BaseTool(function_map={})
try:
    tool.execute_tool_by_name("no_such_function", "{}")
except ToolNotFoundError as e:
    print(f"Not found: {e}")

Usage Tips

  • Provide docstrings and type hints for every function to enable clean schemas and validation.

  • Use verbose=True during development to surface detailed logs.

  • Pre-fill function_map for direct name-based execution.

  • Validate schemas before sending them to different providers.

  • Use parallel execution for high-throughput batches.

  • Catch specific BaseTool exceptions for robust error handling.

Last updated