Skip to content

Conversation

@majiayu000
Copy link

Summary

Add support for using callable class instances and bound methods as tools in beta_tool. This enables a more natural pattern for tools that need access to instance state or context.

Changes

  • Added _normalize_callable() helper function that extracts the bound __call__ method from callable class instances
  • Modified BaseFunctionTool.__init__ to normalize callables before processing
  • Added tests for callable class instances and bound methods

Usage

Callable class instance:

class FetchProduct:
    def __init__(self, ctx: dict):
        self.ctx = ctx
    
    def __call__(self, product_id: int) -> str:
        """Fetch a product by ID."""
        return f"Product {product_id} from {self.ctx['session']}"

instance = FetchProduct({"session": "test"})
tool = beta_tool(instance, name="fetch_product")

Bound method:

class WeatherService:
    def __init__(self, api_key: str):
        self.api_key = api_key
    
    def get_weather(self, location: str) -> str:
        """Get weather for a location."""
        return f"Weather in {location}"

service = WeatherService("secret-key")
tool = beta_tool(service.get_weather, name="weather")

Closes #1087

Test plan

  • Added unit tests for callable class instances
  • Added unit tests for bound methods
  • Verified existing function tests still pass
  • Ran ./scripts/lint - all checks pass
  • Ran ./scripts/test tests/lib/tools/test_functions.py - 23 tests pass

Add support for using callable class instances (objects with __call__
method) and bound methods as tools in beta_tool. This enables a more
natural pattern for tools that need access to instance state or context.

Previously, only plain functions could be used with beta_tool. Now users
can pass:
- Callable class instances: beta_tool(MyCallableClass(ctx))
- Bound methods: beta_tool(instance.method)

The implementation normalizes callable instances by extracting their
bound __call__ method, which ensures the schema doesn't include 'self'
and the method is properly bound when called.

Closes anthropics#1087

Signed-off-by: majiayu000 <1835304752@qq.com>
@majiayu000 majiayu000 requested a review from a team as a code owner January 5, 2026 14:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant