or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

batches.mdbeta.mdclient-initialization.mderrors.mdindex.mdmessages.mdmodels.mdplatform-clients.mdstreaming.mdtools-builtin.mdtools-decorators.mdtools-function.mdtools-memory.mdtools-runners.mdtools.mdtypes.md

tools.mddocs/

0

# Tool Calling

1

2

Tool calling enables Claude to interact with external functions and APIs by generating structured tool use requests that your application can execute. The Anthropic Python SDK provides decorators, function wrappers, and automatic execution loops to simplify tool integration.

3

4

## Package Information

5

6

- **Package Name**: anthropic

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install anthropic`

10

11

## Core Imports

12

13

```python

14

from anthropic import Anthropic, beta_tool, beta_async_tool

15

from anthropic.lib.tools import (

16

BetaToolRunner,

17

BetaAsyncToolRunner,

18

BetaStreamingToolRunner,

19

BetaAsyncStreamingToolRunner,

20

BetaFunctionTool,

21

BetaAsyncFunctionTool,

22

BetaAbstractMemoryTool,

23

BetaAsyncAbstractMemoryTool,

24

)

25

```

26

27

## Basic Usage

28

29

### Defining Tools with Decorators

30

31

```python

32

from anthropic import Anthropic, beta_tool

33

34

# Define a simple tool using the decorator

35

@beta_tool

36

def get_weather(location: str, unit: str = "fahrenheit") -> str:

37

"""Get the current weather for a location.

38

39

Args:

40

location: The city and state, e.g. "San Francisco, CA"

41

unit: Temperature unit (fahrenheit or celsius)

42

"""

43

# Your weather API logic here

44

return f"The weather in {location} is 72°{unit[0].upper()}"

45

46

# Use the tool with Claude

47

client = Anthropic()

48

message = client.beta.messages.create(

49

model="claude-3-5-sonnet-20241022",

50

max_tokens=1024,

51

tools=[get_weather.to_dict()],

52

messages=[{"role": "user", "content": "What's the weather in Paris?"}]

53

)

54

55

# Check if Claude wants to use the tool

56

if message.stop_reason == "tool_use":

57

tool_use_block = next(block for block in message.content if block.type == "tool_use")

58

result = get_weather.call(tool_use_block.input)

59

print(result)

60

```

61

62

### Automatic Tool Execution with Tool Runner

63

64

```python

65

from anthropic import Anthropic, beta_tool

66

67

@beta_tool

68

def calculate(operation: str, x: float, y: float) -> str:

69

"""Perform mathematical calculations.

70

71

Args:

72

operation: The operation to perform (add, subtract, multiply, divide)

73

x: First number

74

y: Second number

75

"""

76

operations = {

77

"add": x + y,

78

"subtract": x - y,

79

"multiply": x * y,

80

"divide": x / y if y != 0 else "Error: Division by zero"

81

}

82

return str(operations.get(operation, "Unknown operation"))

83

84

client = Anthropic()

85

86

# Tool runner automatically executes tools and continues the conversation

87

runner = client.beta.messages.tool_runner(

88

model="claude-3-5-sonnet-20241022",

89

max_tokens=1024,

90

tools=[calculate],

91

messages=[{"role": "user", "content": "What is 125 times 49?"}]

92

)

93

94

# Get the final message after all tool calls complete

95

final_message = runner.until_done()

96

print(final_message.content[0].text)

97

```

98

99

## Architecture

100

101

The tool calling system consists of several layers:

102

103

- **Decorators**: `beta_tool` and `beta_async_tool` convert Python functions into tool definitions with automatic schema generation from type hints and docstrings

104

- **Function Tool Classes**: `BetaFunctionTool` and `BetaAsyncFunctionTool` wrap functions and handle validation, schema creation, and execution

105

- **Builtin Tool Classes**: `BetaBuiltinFunctionTool` and `BetaAsyncBuiltinFunctionTool` provide abstract interfaces for built-in tools like memory

106

- **Tool Runners**: `BetaToolRunner`, `BetaStreamingToolRunner`, and their async variants implement automatic tool execution loops

107

- **Memory Tools**: `BetaAbstractMemoryTool` and `BetaAsyncAbstractMemoryTool` enable custom memory backend implementations

108

109

This design enables both manual tool handling (full control) and automatic tool execution (convenience), supporting synchronous, asynchronous, and streaming workflows.

110

111

## Capabilities

112

113

### Tool Decorators

114

115

Convert Python functions into tool definitions with automatic schema inference from type hints and docstrings.

116

117

```python { .api }

118

def beta_tool(

119

func: Callable[..., str | Iterable[BetaContent]] | None = None,

120

*,

121

name: str | None = None,

122

description: str | None = None,

123

input_schema: dict | type[BaseModel] | None = None

124

) -> BetaFunctionTool | Callable[[Callable], BetaFunctionTool]:

125

"""

126

Decorator to create a function tool with automatic schema generation.

127

128

Args:

129

func: The function to convert into a tool (when used without parentheses)

130

name: Custom tool name (defaults to function name)

131

description: Tool description (defaults to function docstring)

132

input_schema: Custom JSON schema or Pydantic model for parameters

133

134

Returns:

135

BetaFunctionTool instance or decorator function

136

"""

137

138

def beta_async_tool(

139

func: Callable[..., Coroutine[Any, Any, str | Iterable[BetaContent]]] | None = None,

140

*,

141

name: str | None = None,

142

description: str | None = None,

143

input_schema: dict | type[BaseModel] | None = None

144

) -> BetaAsyncFunctionTool | Callable[[Callable], BetaAsyncFunctionTool]:

145

"""

146

Decorator to create an async function tool with automatic schema generation.

147

148

Args:

149

func: The async function to convert into a tool

150

name: Custom tool name (defaults to function name)

151

description: Tool description (defaults to function docstring)

152

input_schema: Custom JSON schema or Pydantic model for parameters

153

154

Returns:

155

BetaAsyncFunctionTool instance or decorator function

156

"""

157

```

158

159

[Tool Decorators](./tools-decorators.md)

160

161

### Function Tool Classes

162

163

Wrapper classes that handle function-based tools, including validation, schema generation, and execution.

164

165

```python { .api }

166

class BetaFunctionTool:

167

"""

168

Synchronous function tool wrapper.

169

170

Attributes:

171

func: The wrapped function

172

name: Tool name sent to the API

173

description: Tool description

174

input_schema: JSON schema for tool parameters

175

"""

176

def __init__(

177

self,

178

func: Callable[..., str | Iterable[BetaContent]],

179

*,

180

name: str | None = None,

181

description: str | None = None,

182

input_schema: dict | type[BaseModel] | None = None

183

) -> None: ...

184

185

def to_dict(self) -> ToolParam: ...

186

def call(self, input: object) -> str | Iterable[BetaContent]: ...

187

188

class BetaAsyncFunctionTool:

189

"""

190

Asynchronous function tool wrapper.

191

192

Attributes:

193

func: The wrapped async function

194

name: Tool name sent to the API

195

description: Tool description

196

input_schema: JSON schema for tool parameters

197

"""

198

def __init__(

199

self,

200

func: Callable[..., Coroutine[Any, Any, str | Iterable[BetaContent]]],

201

*,

202

name: str | None = None,

203

description: str | None = None,

204

input_schema: dict | type[BaseModel] | None = None

205

) -> None: ...

206

207

def to_dict(self) -> ToolParam: ...

208

async def call(self, input: object) -> str | Iterable[BetaContent]: ...

209

```

210

211

[Function Tools](./tools-function.md)

212

213

### Builtin Tool Classes

214

215

Abstract base classes for implementing built-in tool types with custom behavior.

216

217

```python { .api }

218

class BetaBuiltinFunctionTool(ABC):

219

"""

220

Abstract base class for synchronous built-in tools.

221

"""

222

@abstractmethod

223

def to_dict(self) -> BetaToolUnionParam: ...

224

225

@abstractmethod

226

def call(self, input: object) -> str | Iterable[BetaContent]: ...

227

228

@property

229

def name(self) -> str: ...

230

231

class BetaAsyncBuiltinFunctionTool(ABC):

232

"""

233

Abstract base class for asynchronous built-in tools.

234

"""

235

@abstractmethod

236

def to_dict(self) -> BetaToolUnionParam: ...

237

238

@abstractmethod

239

async def call(self, input: object) -> str | Iterable[BetaContent]: ...

240

241

@property

242

def name(self) -> str: ...

243

```

244

245

[Builtin Tools](./tools-builtin.md)

246

247

### Tool Runner Classes

248

249

Automatic tool execution loops that handle the request-response cycle with Claude, including tool calls and result processing.

250

251

```python { .api }

252

class BetaToolRunner:

253

"""

254

Synchronous tool runner with automatic execution loop.

255

256

Iterates through messages, automatically executing tools when Claude

257

requests them and sending results back until completion.

258

"""

259

def until_done(self) -> ParsedBetaMessage[ResponseFormatT]: ...

260

def generate_tool_call_response(self) -> BetaMessageParam | None: ...

261

def set_messages_params(

262

self,

263

params: ParseMessageCreateParamsBase[ResponseFormatT]

264

| Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]]

265

) -> None: ...

266

def append_messages(self, *messages: BetaMessageParam | ParsedBetaMessage[ResponseFormatT]) -> None: ...

267

268

class BetaAsyncToolRunner:

269

"""

270

Asynchronous tool runner with automatic execution loop.

271

"""

272

async def until_done(self) -> ParsedBetaMessage[ResponseFormatT]: ...

273

async def generate_tool_call_response(self) -> BetaMessageParam | None: ...

274

def set_messages_params(

275

self,

276

params: ParseMessageCreateParamsBase[ResponseFormatT]

277

| Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]]

278

) -> None: ...

279

def append_messages(self, *messages: BetaMessageParam | ParsedBetaMessage[ResponseFormatT]) -> None: ...

280

281

class BetaStreamingToolRunner:

282

"""

283

Streaming synchronous tool runner that yields MessageStream objects.

284

285

Each iteration yields a stream for one turn of the conversation.

286

"""

287

def until_done(self) -> ParsedBetaMessage[ResponseFormatT]: ...

288

def generate_tool_call_response(self) -> BetaMessageParam | None: ...

289

def set_messages_params(

290

self,

291

params: ParseMessageCreateParamsBase[ResponseFormatT]

292

| Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]]

293

) -> None: ...

294

def append_messages(self, *messages: BetaMessageParam | ParsedBetaMessage[ResponseFormatT]) -> None: ...

295

296

class BetaAsyncStreamingToolRunner:

297

"""

298

Streaming asynchronous tool runner that yields AsyncMessageStream objects.

299

"""

300

async def until_done(self) -> ParsedBetaMessage[ResponseFormatT]: ...

301

async def generate_tool_call_response(self) -> BetaMessageParam | None: ...

302

def set_messages_params(

303

self,

304

params: ParseMessageCreateParamsBase[ResponseFormatT]

305

| Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]]

306

) -> None: ...

307

def append_messages(self, *messages: BetaMessageParam | ParsedBetaMessage[ResponseFormatT]) -> None: ...

308

```

309

310

[Tool Runners](./tools-runners.md)

311

312

### Memory Tool Classes

313

314

Abstract base classes for implementing custom memory backends that Claude can use to store and retrieve information across conversations.

315

316

```python { .api }

317

class BetaAbstractMemoryTool(BetaBuiltinFunctionTool):

318

"""

319

Abstract base class for synchronous memory tool implementations.

320

321

Subclass this to create custom memory storage solutions

322

(e.g., database, cloud storage, encrypted files).

323

"""

324

def __init__(self, *, cache_control: BetaCacheControlEphemeralParam | None = None) -> None: ...

325

326

@abstractmethod

327

def view(self, command: BetaMemoryTool20250818ViewCommand) -> str | Iterable[BetaContent]: ...

328

329

@abstractmethod

330

def create(self, command: BetaMemoryTool20250818CreateCommand) -> str | Iterable[BetaContent]: ...

331

332

@abstractmethod

333

def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> str | Iterable[BetaContent]: ...

334

335

@abstractmethod

336

def insert(self, command: BetaMemoryTool20250818InsertCommand) -> str | Iterable[BetaContent]: ...

337

338

@abstractmethod

339

def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> str | Iterable[BetaContent]: ...

340

341

@abstractmethod

342

def rename(self, command: BetaMemoryTool20250818RenameCommand) -> str | Iterable[BetaContent]: ...

343

344

def clear_all_memory(self) -> str | Iterable[BetaContent]: ...

345

346

class BetaAsyncAbstractMemoryTool(BetaAsyncBuiltinFunctionTool):

347

"""

348

Abstract base class for asynchronous memory tool implementations.

349

"""

350

def __init__(self, *, cache_control: BetaCacheControlEphemeralParam | None = None) -> None: ...

351

352

@abstractmethod

353

async def view(self, command: BetaMemoryTool20250818ViewCommand) -> str | Iterable[BetaContent]: ...

354

355

@abstractmethod

356

async def create(self, command: BetaMemoryTool20250818CreateCommand) -> str | Iterable[BetaContent]: ...

357

358

@abstractmethod

359

async def str_replace(self, command: BetaMemoryTool20250818StrReplaceCommand) -> str | Iterable[BetaContent]: ...

360

361

@abstractmethod

362

async def insert(self, command: BetaMemoryTool20250818InsertCommand) -> str | Iterable[BetaContent]: ...

363

364

@abstractmethod

365

async def delete(self, command: BetaMemoryTool20250818DeleteCommand) -> str | Iterable[BetaContent]: ...

366

367

@abstractmethod

368

async def rename(self, command: BetaMemoryTool20250818RenameCommand) -> str | Iterable[BetaContent]: ...

369

370

async def clear_all_memory(self) -> str | Iterable[BetaContent]: ...

371

```

372

373

[Memory Tools](./tools-memory.md)

374

375

## Types

376

377

### Tool Result Type

378

379

```python { .api }

380

BetaFunctionToolResultType = str | Iterable[BetaContent]

381

```

382

383

The return type for tool functions. Can be either a simple string or an iterable of content blocks for complex responses.

384

385

### Tool Union Types

386

387

```python { .api }

388

BetaRunnableTool = BetaFunctionTool[Any] | BetaBuiltinFunctionTool

389

BetaAsyncRunnableTool = BetaAsyncFunctionTool[Any] | BetaAsyncBuiltinFunctionTool

390

```

391

392

Union types representing all tools that can be executed by tool runners.

393