or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

agents.mdchains.mddocument-loaders.mdembeddings.mdexperimental.mdindex.mdmemory.mdoutput-parsers.mdretrievers.mdtools.mdutilities.md
tile.json

tools.mddocs/

0

# Tools and Tool Calling

1

2

Built-in and custom tools that agents can use to interact with external systems, APIs, databases, and perform various operations. Tools provide the interface between language models and the external world.

3

4

## Capabilities

5

6

### Base Tool Classes

7

8

Foundation classes for creating and using tools in LangChain applications.

9

10

```typescript { .api }

11

/**

12

* Base tool class - all tools inherit from this

13

*/

14

abstract class Tool {

15

/** Name of the tool */

16

name: string;

17

18

/** Description of what the tool does */

19

description: string;

20

21

/** Whether to return tool output directly */

22

returnDirect?: boolean;

23

24

/** Whether to enable verbose logging */

25

verbose?: boolean;

26

27

/** Callback handlers for tool execution */

28

callbacks?: BaseCallbackHandler[];

29

30

/** Execute the tool with string input */

31

abstract _call(arg: string, runManager?: CallbackManagerForToolRun): Promise<string>;

32

33

/** Public interface to call the tool */

34

call(arg: string, config?: RunnableConfig): Promise<string>;

35

36

/** Invoke the tool (Runnable interface) */

37

invoke(input: string, config?: RunnableConfig): Promise<string>;

38

}

39

40

/**

41

* Structured tool with schema validation

42

*/

43

abstract class StructuredTool extends Tool {

44

/** Zod schema for input validation */

45

abstract schema: ZodSchema<any>;

46

47

/** Execute the tool with structured input */

48

abstract _call(arg: any, runManager?: CallbackManagerForToolRun): Promise<string>;

49

50

/** Call with structured input and validation */

51

call(arg: any, config?: RunnableConfig): Promise<string>;

52

}

53

```

54

55

### Dynamic Tools

56

57

Tools created at runtime with custom functionality.

58

59

```typescript { .api }

60

/**

61

* Dynamically created tool with string input

62

*/

63

class DynamicTool extends Tool {

64

constructor(fields: DynamicToolInput);

65

66

/** The function to execute */

67

func: (input: string, runManager?: CallbackManagerForToolRun) => Promise<string> | string;

68

69

_call(input: string, runManager?: CallbackManagerForToolRun): Promise<string>;

70

}

71

72

/**

73

* Dynamic tool with structured input and schema validation

74

*/

75

class DynamicStructuredTool<T extends ZodTypeAny = ZodTypeAny> extends StructuredTool {

76

constructor(fields: DynamicStructuredToolInput<T>);

77

78

/** Zod schema for input validation */

79

schema: T;

80

81

/** The function to execute with structured input */

82

func: (input: TypeOf<T>, runManager?: CallbackManagerForToolRun) => Promise<string> | string;

83

84

_call(input: TypeOf<T>, runManager?: CallbackManagerForToolRun): Promise<string>;

85

}

86

```

87

88

**Usage Examples:**

89

90

```typescript

91

import { DynamicTool, DynamicStructuredTool } from "langchain/tools";

92

import { z } from "zod";

93

94

// Simple dynamic tool

95

const calculatorTool = new DynamicTool({

96

name: "calculator",

97

description: "Calculate mathematical expressions. Input should be a valid math expression.",

98

func: async (input: string) => {

99

try {

100

const result = eval(input);

101

return result.toString();

102

} catch (error) {

103

return `Error: ${error.message}`;

104

}

105

}

106

});

107

108

// Structured tool with validation

109

const weatherTool = new DynamicStructuredTool({

110

name: "get_weather",

111

description: "Get current weather for a city",

112

schema: z.object({

113

city: z.string().describe("The city name"),

114

units: z.enum(["celsius", "fahrenheit"]).optional().default("celsius")

115

}),

116

func: async ({ city, units }) => {

117

// Mock weather API call

118

const temp = units === "celsius" ? "22°C" : "72°F";

119

return `Current weather in ${city}: ${temp}, partly cloudy`;

120

}

121

});

122

123

// Using the tools

124

const result1 = await calculatorTool.call("2 + 3 * 4");

125

const result2 = await weatherTool.call({ city: "New York", units: "fahrenheit" });

126

```

127

128

### Built-in Tools

129

130

Pre-implemented tools for common operations.

131

132

```typescript { .api }

133

/**

134

* Tool for listing JSON object keys

135

*/

136

class JsonListKeysTool extends Tool {

137

constructor();

138

name: "json_list_keys_tool";

139

description: "Can be used to list all keys at the top level of a json object. Input is a valid json object.";

140

_call(input: string): Promise<string>;

141

}

142

143

/**

144

* Tool for getting values from JSON objects

145

*/

146

class JsonGetValueTool extends Tool {

147

constructor(jsonSpec?: JsonSpec);

148

name: "json_get_value_tool";

149

description: string;

150

_call(input: string): Promise<string>;

151

}

152

153

/**

154

* Tool for making HTTP GET requests

155

*/

156

class RequestsGetTool extends Tool {

157

constructor(headers?: Record<string, string>, maxOutputLength?: number);

158

name: "requests_get";

159

description: "A portal to the internet. Use this when you need to get specific content from a website.";

160

headers: Record<string, string>;

161

maxOutputLength: number;

162

_call(input: string): Promise<string>;

163

}

164

165

/**

166

* Tool for making HTTP POST requests

167

*/

168

class RequestsPostTool extends Tool {

169

constructor(headers?: Record<string, string>, maxOutputLength?: number);

170

name: "requests_post";

171

description: "Use this when you want to POST to a website.";

172

headers: Record<string, string>;

173

maxOutputLength: number;

174

_call(input: string): Promise<string>;

175

}

176

177

/**

178

* Tool for vector store question answering

179

*/

180

class VectorStoreQATool extends Tool {

181

constructor(name: string, description: string, fields: VectorStoreQAToolFields);

182

vectorStore: VectorStoreInterface;

183

llm: BaseLanguageModelInterface;

184

_call(input: string): Promise<string>;

185

}

186

187

/**

188

* Tool for reading files from filesystem

189

*/

190

class ReadFileTool extends Tool {

191

constructor();

192

name: "read_file";

193

description: "Read file from disk";

194

_call(input: string): Promise<string>;

195

}

196

197

/**

198

* Tool for writing files to filesystem

199

*/

200

class WriteFileTool extends Tool {

201

constructor();

202

name: "write_file";

203

description: "Write file to disk";

204

_call(input: string): Promise<string>;

205

}

206

```

207

208

**Usage Example:**

209

210

```typescript

211

import {

212

JsonListKeysTool,

213

JsonGetValueTool,

214

RequestsGetTool

215

} from "langchain/tools";

216

217

const jsonListTool = new JsonListKeysTool();

218

const jsonGetTool = new JsonGetValueTool();

219

const httpTool = new RequestsGetTool({

220

"User-Agent": "LangChain Agent"

221

});

222

223

// List keys in JSON

224

const jsonData = '{"name": "Alice", "age": 30, "city": "New York"}';

225

const keys = await jsonListTool.call(jsonData);

226

// Result: "name, age, city"

227

228

// Get specific value

229

const name = await jsonGetTool.call('{"json_object": ' + jsonData + ', "key": "name"}');

230

// Result: "Alice"

231

232

// Make HTTP request

233

const webpage = await httpTool.call("https://api.github.com/users/octocat");

234

```

235

236

### Tool Formatting and Conversion

237

238

Utilities for converting tools to different formats, especially for LLM function calling.

239

240

```typescript { .api }

241

/**

242

* Convert tool to OpenAI function format

243

*/

244

function formatToOpenAIFunction(tool: StructuredToolInterface): FunctionDefinition;

245

246

/**

247

* Convert tool to OpenAI tool format

248

*/

249

function formatToOpenAITool(tool: StructuredToolInterface): ToolDefinition;

250

251

/**

252

* Render tool names and descriptions in plain text

253

*/

254

function renderTextDescription(

255

tools: (StructuredToolInterface | ToolDefinition)[]

256

): string;

257

258

/**

259

* Render tool names, descriptions, and arguments schema

260

*/

261

function renderTextDescriptionAndArgs(

262

tools: (StructuredToolInterface | ToolDefinition)[]

263

): string;

264

```

265

266

**Usage Example:**

267

268

```typescript

269

import {

270

formatToOpenAIFunction,

271

formatToOpenAITool,

272

renderTextDescription

273

} from "langchain/tools";

274

import { DynamicStructuredTool } from "langchain/tools";

275

import { z } from "zod";

276

277

const weatherTool = new DynamicStructuredTool({

278

name: "get_weather",

279

description: "Get weather for a city",

280

schema: z.object({

281

city: z.string(),

282

units: z.enum(["celsius", "fahrenheit"]).default("celsius")

283

}),

284

func: async ({ city, units }) => `Weather in ${city}: 22°${units[0]}`

285

});

286

287

// Convert to OpenAI function format

288

const openAIFunction = formatToOpenAIFunction(weatherTool);

289

console.log(openAIFunction);

290

// {

291

// name: "get_weather",

292

// description: "Get weather for a city",

293

// parameters: { type: "object", properties: {...}, required: [...] }

294

// }

295

296

// Convert to OpenAI tool format

297

const openAITool = formatToOpenAITool(weatherTool);

298

console.log(openAITool);

299

// {

300

// type: "function",

301

// function: { name: "get_weather", description: "...", parameters: {...} }

302

// }

303

304

// Render as text description

305

const textDescription = renderTextDescription([weatherTool]);

306

console.log(textDescription);

307

// "get_weather: Get weather for a city"

308

```

309

310

### Specialized Tools

311

312

Domain-specific tools for particular use cases.

313

314

```typescript { .api }

315

/**

316

* Tool for SQL database operations

317

*/

318

class QuerySqlTool extends Tool {

319

constructor(db: SqlDatabase);

320

name: "query_sql_db";

321

description: "Input to this tool is a detailed and correct SQL query, output is a result from the database.";

322

db: SqlDatabase;

323

_call(input: string): Promise<string>;

324

}

325

326

/**

327

* Tool for SQL database schema information

328

*/

329

class InfoSqlTool extends Tool {

330

constructor(db: SqlDatabase);

331

name: "sql_db_schema";

332

description: "Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.";

333

db: SqlDatabase;

334

_call(input: string): Promise<string>;

335

}

336

337

/**

338

* Tool for listing SQL database tables

339

*/

340

class ListTablesSqlTool extends Tool {

341

constructor(db: SqlDatabase);

342

name: "sql_db_list_tables";

343

description: "Input is an empty string, output is a comma separated list of tables in the database.";

344

db: SqlDatabase;

345

_call(input: string): Promise<string>;

346

}

347

348

/**

349

* Tool for SQL query checking

350

*/

351

class QueryCheckerTool extends Tool {

352

constructor(db: SqlDatabase, llm: BaseLanguageModelInterface);

353

name: "sql_db_query_checker";

354

description: "Use this tool to double check if your query is correct before executing it.";

355

db: SqlDatabase;

356

llm: BaseLanguageModelInterface;

357

_call(input: string): Promise<string>;

358

}

359

```

360

361

### Web Browser Tools

362

363

Tools for web browsing and content extraction.

364

365

```typescript { .api }

366

/**

367

* Tool for web browsing operations

368

*/

369

class WebBrowser extends Tool {

370

constructor(fields: WebBrowserArgs);

371

name: "web_browser";

372

description: "A web browser that can navigate to URLs and extract content.";

373

374

_call(input: string): Promise<string>;

375

}

376

377

interface WebBrowserArgs {

378

model: BaseLanguageModelInterface;

379

embeddings: EmbeddingsInterface;

380

headers?: Record<string, string>;

381

axiosConfig?: AxiosRequestConfig;

382

}

383

```

384

385

### Retriever Tools

386

387

Tools that wrap retrievers for use in agent workflows.

388

389

```typescript { .api }

390

/**

391

* Create a tool from a retriever

392

*/

393

function createRetrieverTool(

394

retriever: BaseRetrieverInterface,

395

input: CreateRetrieverToolInput

396

): DynamicTool;

397

398

interface CreateRetrieverToolInput {

399

name: string;

400

description: string;

401

}

402

```

403

404

**Usage Example:**

405

406

```typescript

407

import { createRetrieverTool } from "langchain/tools/retriever";

408

import { MemoryVectorStore } from "langchain/vectorstores/memory";

409

import { OpenAIEmbeddings } from "@langchain/openai";

410

411

const vectorStore = new MemoryVectorStore(new OpenAIEmbeddings());

412

const retriever = vectorStore.asRetriever();

413

414

const retrieverTool = createRetrieverTool(retriever, {

415

name: "search_documents",

416

description: "Search through uploaded documents to find relevant information"

417

});

418

419

const result = await retrieverTool.call("What is the company policy on remote work?");

420

```

421

422

### Chain Tools (Deprecated)

423

424

Legacy tool for wrapping chains - use DynamicTool instead.

425

426

```typescript { .api }

427

/**

428

* @deprecated Use DynamicTool instead

429

* Tool that wraps a chain for use by agents

430

*/

431

class ChainTool extends Tool {

432

constructor(fields: ChainToolInput);

433

434

/** The chain to execute */

435

chain: BaseChain;

436

437

/** Whether to return the full chain output */

438

returnDirect?: boolean;

439

440

_call(input: string): Promise<string>;

441

}

442

```

443

444

## Types

445

446

### Tool Input Types

447

448

```typescript { .api }

449

interface ToolParams {

450

name: string;

451

description: string;

452

returnDirect?: boolean;

453

verbose?: boolean;

454

callbacks?: BaseCallbackHandler[];

455

}

456

457

interface DynamicToolInput extends ToolParams {

458

func: (input: string, runManager?: CallbackManagerForToolRun) => Promise<string> | string;

459

}

460

461

interface DynamicStructuredToolInput<T extends ZodTypeAny = ZodTypeAny> extends ToolParams {

462

schema: T;

463

func: (input: TypeOf<T>, runManager?: CallbackManagerForToolRun) => Promise<string> | string;

464

}

465

466

interface ChainToolInput extends ToolParams {

467

chain: BaseChain;

468

}

469

```

470

471

### JSON Tool Types

472

473

```typescript { .api }

474

interface JsonSpec {

475

/** JSON schema type */

476

type: string;

477

/** Object properties */

478

properties?: Record<string, JsonSpec>;

479

/** Array items schema */

480

items?: JsonSpec;

481

/** Required properties */

482

required?: string[];

483

/** Additional metadata */

484

description?: string;

485

}

486

487

type JsonObject = Record<string, Json>;

488

type Json = string | number | boolean | null | Json[] | JsonObject;

489

```

490

491

### Vector Store Tool Types

492

493

```typescript { .api }

494

interface VectorStoreQAToolFields {

495

vectorStore: VectorStoreInterface;

496

llm: BaseLanguageModelInterface;

497

returnSourceDocuments?: boolean;

498

}

499

```

500

501

### OpenAI Tool Format Types

502

503

```typescript { .api }

504

interface FunctionDefinition {

505

name: string;

506

description?: string;

507

parameters?: {

508

type: "object";

509

properties: Record<string, any>;

510

required?: string[];

511

};

512

}

513

514

interface ToolDefinition {

515

type: "function";

516

function: FunctionDefinition;

517

}

518

```

519

520

### Web Browser Types

521

522

```typescript { .api }

523

interface WebBrowserArgs {

524

model: BaseLanguageModelInterface;

525

embeddings: EmbeddingsInterface;

526

headers?: Record<string, string>;

527

axiosConfig?: AxiosRequestConfig;

528

}

529

```

530

531

### Tool Execution Types

532

533

```typescript { .api }

534

interface CallbackManagerForToolRun extends BaseCallbackManager {

535

handleToolStart?(

536

tool: { name: string },

537

input: string,

538

runId?: string,

539

parentRunId?: string,

540

tags?: string[],

541

metadata?: Record<string, unknown>

542

): Promise<void>;

543

544

handleToolEnd?(output: string, runId?: string): Promise<void>;

545

546

handleToolError?(error: Error, runId?: string): Promise<void>;

547

}

548

549

interface RunnableConfig {

550

tags?: string[];

551

metadata?: Record<string, unknown>;

552

callbacks?: BaseCallbackHandler[];

553

runName?: string;

554

runId?: string;

555

configurable?: Record<string, any>;

556

}

557

```

558

559

## Tool Creation Patterns

560

561

### Custom Tool Creation

562

563

```typescript

564

// Simple function-based tool

565

const customTool = new DynamicTool({

566

name: "random_number",

567

description: "Generate a random number between 1 and max (default 100)",

568

func: async (input: string) => {

569

const max = parseInt(input) || 100;

570

return Math.floor(Math.random() * max + 1).toString();

571

}

572

});

573

574

// Structured tool with validation

575

const structuredTool = new DynamicStructuredTool({

576

name: "send_email",

577

description: "Send an email to a recipient",

578

schema: z.object({

579

to: z.string().email().describe("Recipient email address"),

580

subject: z.string().describe("Email subject"),

581

body: z.string().describe("Email body content")

582

}),

583

func: async ({ to, subject, body }) => {

584

// Email sending logic here

585

console.log(`Sending email to ${to}: ${subject}`);

586

return `Email sent successfully to ${to}`;

587

}

588

});

589

```

590

591

### Tool Error Handling

592

593

```typescript

594

const robustTool = new DynamicTool({

595

name: "api_call",

596

description: "Make API call with error handling",

597

func: async (input: string) => {

598

try {

599

const response = await fetch(input);

600

if (!response.ok) {

601

throw new Error(`HTTP ${response.status}: ${response.statusText}`);

602

}

603

return await response.text();

604

} catch (error) {

605

return `Error: ${error instanceof Error ? error.message : 'Unknown error'}`;

606

}

607

}

608

});

609

```