or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

agents-tools.mdcallbacks-monitoring.mdchains-workflows.mddocument-processing.mdindex.mdmemory-context.md

agents-tools.mddocs/

0

# Agents and Tools

1

2

AI agents that can reason about which tools to use and when to use them. Agents leverage Large Language Models to make decisions about tool selection and execution, enabling autonomous task completion across various domains.

3

4

## Capabilities

5

6

### Agent Creation and Execution

7

8

Initialize and run agents with tools and language models. Agents can handle complex multi-step tasks by reasoning about tool usage.

9

10

```python { .api }

11

def initialize_agent(

12

tools: List[BaseTool],

13

llm: BaseLanguageModel,

14

agent: Optional[str] = None,

15

callback_manager: Optional[BaseCallbackManager] = None,

16

agent_path: Optional[str] = None,

17

agent_kwargs: Optional[dict] = None,

18

**kwargs: Any

19

) -> AgentExecutor:

20

"""

21

Initialize an agent with tools and LLM.

22

23

**Deprecated since 0.1.0**: Use newer agent creation functions like

24

create_openai_functions_agent, create_react_agent, etc. instead.

25

Removal planned for version 1.0.

26

27

Parameters:

28

- tools: List of tools the agent can use

29

- llm: Language model for agent reasoning

30

- agent: Agent type (ZERO_SHOT_REACT_DESCRIPTION, etc.)

31

- callback_manager: Callback handler for monitoring

32

- agent_kwargs: Additional agent configuration

33

34

Returns:

35

AgentExecutor instance

36

"""

37

38

class AgentExecutor:

39

"""Execute agent actions with tools and handle iterations."""

40

41

def __init__(

42

self,

43

agent: BaseAgent,

44

tools: List[BaseTool],

45

callback_manager: Optional[BaseCallbackManager] = None,

46

verbose: bool = False,

47

return_intermediate_steps: bool = False,

48

max_iterations: Optional[int] = 15,

49

**kwargs: Any

50

): ...

51

52

def run(self, input: str) -> str:

53

"""Run agent with string input, return string output."""

54

55

def invoke(self, input: dict) -> dict:

56

"""Invoke agent with dict input, return dict output."""

57

58

def stream(self, input: dict):

59

"""Stream agent execution steps."""

60

```

61

62

### Agent Types

63

64

Different agent architectures for various use cases and reasoning patterns.

65

66

```python { .api }

67

class AgentType:

68

"""Enumeration of available agent types."""

69

ZERO_SHOT_REACT_DESCRIPTION: str = "zero-shot-react-description"

70

REACT_DOCSTORE: str = "react-docstore"

71

SELF_ASK_WITH_SEARCH: str = "self-ask-with-search"

72

CONVERSATIONAL_REACT_DESCRIPTION: str = "conversational-react-description"

73

CHAT_ZERO_SHOT_REACT_DESCRIPTION: str = "chat-zero-shot-react-description"

74

CHAT_CONVERSATIONAL_REACT_DESCRIPTION: str = "chat-conversational-react-description"

75

STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION: str = "structured-chat-zero-shot-react-description"

76

OPENAI_FUNCTIONS: str = "openai-functions"

77

OPENAI_MULTI_FUNCTIONS: str = "openai-multi-functions"

78

79

class ZeroShotAgent:

80

"""Zero-shot ReAct agent for tool usage."""

81

82

@classmethod

83

def create_prompt(

84

cls,

85

tools: List[BaseTool],

86

prefix: str = None,

87

suffix: str = None,

88

format_instructions: str = None,

89

**kwargs: Any

90

) -> PromptTemplate: ...

91

92

class ConversationalAgent:

93

"""Conversational agent with memory."""

94

95

@classmethod

96

def create_prompt(

97

cls,

98

tools: List[BaseTool],

99

prefix: str = None,

100

suffix: str = None,

101

**kwargs: Any

102

) -> PromptTemplate: ...

103

104

class ReActTextWorldAgent:

105

"""ReAct agent for text-based environments."""

106

107

class StructuredChatAgent:

108

"""Agent for structured chat with complex tool inputs."""

109

```

110

111

### Modern Agent Creation Functions

112

113

Newer functional approach for creating specific agent types with better control and configuration.

114

115

```python { .api }

116

def create_openai_functions_agent(

117

llm: BaseLanguageModel,

118

tools: List[BaseTool],

119

prompt: BasePromptTemplate

120

) -> Runnable:

121

"""Create OpenAI Functions agent."""

122

123

def create_openai_tools_agent(

124

llm: BaseLanguageModel,

125

tools: List[BaseTool],

126

prompt: BasePromptTemplate

127

) -> Runnable:

128

"""Create OpenAI Tools agent."""

129

130

def create_react_agent(

131

llm: BaseLanguageModel,

132

tools: List[BaseTool],

133

prompt: BasePromptTemplate

134

) -> Runnable:

135

"""Create ReAct agent."""

136

137

def create_structured_chat_agent(

138

llm: BaseLanguageModel,

139

tools: List[BaseTool],

140

prompt: BasePromptTemplate

141

) -> Runnable:

142

"""Create structured chat agent."""

143

144

def create_tool_calling_agent(

145

llm: BaseLanguageModel,

146

tools: List[BaseTool],

147

prompt: BasePromptTemplate

148

) -> Runnable:

149

"""Create tool calling agent."""

150

151

def create_xml_agent(

152

llm: BaseLanguageModel,

153

tools: List[BaseTool],

154

prompt: BasePromptTemplate

155

) -> Runnable:

156

"""Create XML-based agent."""

157

```

158

159

### Agent Base Classes

160

161

Core agent abstractions and interfaces.

162

163

```python { .api }

164

class BaseAgent:

165

"""Base agent class."""

166

167

def plan(

168

self,

169

intermediate_steps: List[Tuple[AgentAction, str]],

170

callbacks: Optional[Callbacks] = None,

171

**kwargs: Any

172

) -> Union[AgentAction, AgentFinish]: ...

173

174

@property

175

def input_keys(self) -> List[str]: ...

176

177

@property

178

def return_values(self) -> List[str]: ...

179

180

class BaseSingleActionAgent(BaseAgent):

181

"""Base single action agent."""

182

183

class BaseMultiActionAgent(BaseAgent):

184

"""Base multi-action agent."""

185

186

class LLMSingleActionAgent(BaseSingleActionAgent):

187

"""LLM-powered single action agent."""

188

189

def __init__(

190

self,

191

llm_chain: LLMChain,

192

output_parser: AgentOutputParser,

193

stop: List[str] = None,

194

**kwargs: Any

195

): ...

196

```

197

198

### Tool System

199

200

Tools that agents can use to interact with external systems and perform actions.

201

202

```python { .api }

203

from langchain_core.tools import BaseTool, Tool, StructuredTool, tool

204

205

class BaseTool:

206

"""Base tool class."""

207

name: str

208

description: str

209

210

def run(self, tool_input: str) -> str:

211

"""Run the tool with string input."""

212

213

def invoke(self, input: Union[str, dict]) -> Any:

214

"""Invoke the tool with input."""

215

216

class Tool(BaseTool):

217

"""Simple tool wrapper."""

218

219

def __init__(

220

self,

221

name: str,

222

func: Callable,

223

description: str,

224

**kwargs: Any

225

): ...

226

227

class StructuredTool(BaseTool):

228

"""Tool with structured input schema."""

229

230

@classmethod

231

def from_function(

232

cls,

233

func: Callable,

234

name: str = None,

235

description: str = None,

236

**kwargs: Any

237

) -> "StructuredTool": ...

238

239

def tool(

240

*args: Union[str, Callable],

241

return_direct: bool = False,

242

args_schema: Type[BaseModel] = None,

243

infer_schema: bool = True

244

) -> Callable:

245

"""

246

Decorator to create tools from functions.

247

248

Parameters:

249

- return_direct: Return tool output directly to user

250

- args_schema: Pydantic model for input validation

251

- infer_schema: Automatically infer schema from function

252

"""

253

```

254

255

### Agent Toolkits

256

257

Pre-built collections of tools for specific domains and use cases.

258

259

```python { .api }

260

def create_vectorstore_agent(

261

llm: BaseLanguageModel,

262

toolkit: VectorStoreToolkit,

263

callback_manager: Optional[BaseCallbackManager] = None,

264

prefix: str = None,

265

verbose: bool = False,

266

**kwargs: Any

267

) -> AgentExecutor:

268

"""Create agent for vector store operations."""

269

270

def create_vectorstore_router_agent(

271

llm: BaseLanguageModel,

272

toolkit: VectorStoreRouterToolkit,

273

callback_manager: Optional[BaseCallbackManager] = None,

274

prefix: str = None,

275

verbose: bool = False,

276

**kwargs: Any

277

) -> AgentExecutor:

278

"""Create routing agent for multiple vector stores."""

279

```

280

281

### Agent Utilities

282

283

Helper classes and functions for agent operations.

284

285

```python { .api }

286

class AgentExecutorIterator:

287

"""Iterator for stepping through agent execution."""

288

289

def __init__(self, agent_executor: AgentExecutor, inputs: dict, **kwargs): ...

290

291

def __iter__(self): ...

292

293

def __next__(self) -> AgentAction: ...

294

295

class AgentOutputParser:

296

"""Parse agent outputs into actions or finish."""

297

298

def parse(self, text: str) -> Union[AgentAction, AgentFinish]: ...

299

300

class AgentAction:

301

"""Represents an action for agent to take."""

302

tool: str

303

tool_input: Union[str, dict]

304

log: str

305

306

class AgentFinish:

307

"""Represents final result from agent."""

308

return_values: dict

309

log: str

310

311

def load_agent(config: dict, **kwargs: Any) -> AgentExecutor:

312

"""Load agent from configuration."""

313

```

314

315

## Usage Examples

316

317

### Basic Agent with Tools

318

319

```python

320

from langchain.agents import initialize_agent, AgentType

321

from langchain_community.tools import DuckDuckGoSearchRun, Calculator

322

from langchain_openai import OpenAI

323

324

# Create tools

325

search = DuckDuckGoSearchRun()

326

calculator = Calculator()

327

tools = [search, calculator]

328

329

# Create LLM

330

llm = OpenAI(temperature=0)

331

332

# Initialize agent

333

agent = initialize_agent(

334

tools,

335

llm,

336

agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,

337

verbose=True

338

)

339

340

# Run agent

341

result = agent.run("What is the population of Tokyo multiplied by 2?")

342

```

343

344

### Custom Tool Creation

345

346

```python

347

from langchain_core.tools import tool

348

349

@tool

350

def get_current_weather(location: str) -> str:

351

"""Get current weather for a location."""

352

# Implementation would call weather API

353

return f"Weather in {location}: Sunny, 22°C"

354

355

# Use with agent

356

tools = [get_current_weather]

357

agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION)

358

result = agent.run("What's the weather like in Paris?")

359

```

360

361

### Structured Tool with Schema

362

363

```python

364

from langchain_core.tools import StructuredTool

365

from pydantic import BaseModel, Field

366

367

class WeatherInput(BaseModel):

368

location: str = Field(description="City name")

369

units: str = Field(default="celsius", description="Temperature units")

370

371

def get_weather(location: str, units: str = "celsius") -> str:

372

return f"Weather in {location}: 22°{units[0].upper()}"

373

374

weather_tool = StructuredTool.from_function(

375

func=get_weather,

376

name="weather",

377

description="Get weather information",

378

args_schema=WeatherInput

379

)

380

```