1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
| from typing import Any, Dict, List, Optional, Sequence, Union
from langchain_core.agents import AgentAction, AgentFinish, AgentStep
from langchain_core.tools import BaseTool
from langchain.agents.agent import BaseSingleActionAgent, BaseMultiActionAgent
class AgentExecutor(Chain):
"""使用工具的Agent。
AgentExecutor负责运行Agent并管理其与工具的交互。
它实现了Agent的推理-行动循环,包括:
1. 调用Agent进行推理
2. 执行Agent选择的工具
3. 将工具结果反馈给Agent
4. 重复直到Agent决定停止
设计特点:
1. 灵活的Agent接口:支持单动作和多动作Agent
2. 工具管理:统一的工具调用和错误处理
3. 执行控制:迭代限制、时间限制、早停策略
4. 可观测性:完整的回调和追踪支持
"""
agent: Union[BaseSingleActionAgent, BaseMultiActionAgent, Runnable]
"""要运行的Agent,用于在执行循环的每个步骤创建计划并确定要采取的行动。"""
tools: Sequence[BaseTool]
"""Agent可以调用的有效工具。"""
return_intermediate_steps: bool = False
"""是否在最终输出之外还返回Agent的中间步骤轨迹。"""
max_iterations: Optional[int] = 15
"""结束执行循环之前要采取的最大步骤数。
设置为'None'可能导致无限循环。"""
max_execution_time: Optional[float] = None
"""在执行循环中花费的最大墙钟时间量。"""
early_stopping_method: str = "force"
"""如果Agent从未返回`AgentFinish`,用于早停的方法。
可以是'force'或'generate'。
`"force"`返回一个字符串,说明它因为遇到时间或迭代限制而停止。
`"generate"`最后一次调用Agent的LLM Chain,
基于之前的步骤生成最终答案。"""
handle_parsing_errors: Union[bool, str, Callable[[OutputParserException], str]] = (
False
)
"""如何处理Agent输出解析器引发的错误。
默认为`False`,会抛出错误。
如果为`true`,错误将作为观察发送回LLM。
如果为字符串,字符串本身将作为观察发送给LLM。
如果为可调用函数,函数将以异常作为参数调用,
函数的结果将作为观察传递给Agent。"""
trim_intermediate_steps: Union[
int,
Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]],
] = -1
"""如何修剪传递给Agent的中间步骤。
如果为int,将保留最后N个步骤。
如果为callable,将调用该函数来修剪步骤。"""
def __init__(
self,
agent: Union[BaseSingleActionAgent, BaseMultiActionAgent, Runnable],
tools: Sequence[BaseTool],
callback_manager: Optional[BaseCallbackManager] = None,
**kwargs: Any,
):
"""初始化AgentExecutor。
Args:
agent: 要使用的Agent。
tools: 工具列表。
callback_manager: 回调管理器。
**kwargs: 额外参数。
"""
super().__init__(**kwargs)
self.agent = agent
self.tools = tools
# 验证工具名称唯一性
tool_names = [tool.name for tool in tools]
if len(tool_names) != len(set(tool_names)):
raise ValueError("工具名称必须唯一")
@property
def input_keys(self) -> List[str]:
"""返回期望的输入键。"""
return self.agent.input_keys
@property
def output_keys(self) -> List[str]:
"""返回输出键。"""
if self.return_intermediate_steps:
return self.agent.return_values + ["intermediate_steps"]
else:
return self.agent.return_values
def _should_continue(self, iterations: int, time_elapsed: float) -> bool:
"""检查是否应该继续执行循环。
Args:
iterations: 当前迭代次数。
time_elapsed: 已经过的时间。
Returns:
是否应该继续。
"""
if self.max_iterations is not None and iterations >= self.max_iterations:
return False
if (
self.max_execution_time is not None
and time_elapsed >= self.max_execution_time
):
return False
return True
def _call(
self,
inputs: Dict[str, str],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
"""运行文本并获取Agent响应。
Args:
inputs: 输入字典。
run_manager: 回调管理器。
Returns:
包含Agent输出的字典。
"""
# 构建工具名称到工具的映射,便于查找
name_to_tool_map = {tool.name: tool for tool in self.tools}
# 为日志记录构建从每个工具到颜色的映射
color_mapping = get_color_mapping(
[tool.name for tool in self.tools],
excluded_colors=["green", "red"],
)
intermediate_steps: List[Tuple[AgentAction, str]] = []
# 开始跟踪迭代次数和经过的时间
iterations = 0
time_elapsed = 0.0
start_time = time.time()
# 现在进入Agent循环(直到它返回某些东西)
while self._should_continue(iterations, time_elapsed):
next_step_output = self._take_next_step(
name_to_tool_map,
color_mapping,
inputs,
intermediate_steps,
run_manager=run_manager,
)
if isinstance(next_step_output, AgentFinish):
return self._return(
next_step_output,
intermediate_steps,
run_manager=run_manager,
)
intermediate_steps.extend(next_step_output)
if len(next_step_output) == 1:
next_step_action = next_step_output[0]
# 查看工具是否应该直接返回
tool_return = self._get_tool_return(next_step_action)
if tool_return is not None:
return self._return(
tool_return,
intermediate_steps,
run_manager=run_manager,
)
iterations += 1
time_elapsed = time.time() - start_time
output = self._return(
self._get_action_agent().return_stopped_response(
self.early_stopping_method, intermediate_steps
),
intermediate_steps,
run_manager=run_manager,
)
return output
def _take_next_step(
self,
name_to_tool_map: Dict[str, BaseTool],
color_mapping: Dict[str, str],
inputs: Dict[str, str],
intermediate_steps: List[Tuple[AgentAction, str]],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:
"""采取单个步骤在Agent循环中。
这包括:
1. 调用Agent规划下一个动作
2. 执行该动作
3. 返回结果
Args:
name_to_tool_map: 工具名称到工具的映射。
color_mapping: 工具到颜色的映射。
inputs: 用户输入。
intermediate_steps: 到目前为止的中间步骤。
run_manager: 回调管理器。
Returns:
AgentFinish或步骤列表。
"""
try:
# 修剪中间步骤
intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)
# 调用Agent规划
output = self.agent.plan(
intermediate_steps,
callbacks=run_manager.get_child() if run_manager else None,
**inputs,
)
except OutputParserException as e:
if isinstance(self.handle_parsing_errors, bool):
raise_error = not self.handle_parsing_errors
else:
raise_error = False
if raise_error:
raise ValueError(
"Agent输出解析出错。"
"请传递`handle_parsing_errors=True`以自动处理这些错误。"
) from e
text = str(e)
if isinstance(self.handle_parsing_errors, bool):
if e.send_to_llm:
observation = str(e.observation)
text = str(e.llm_output)
else:
observation = "解析LLM输出时出现无效格式"
elif isinstance(self.handle_parsing_errors, str):
observation = self.handle_parsing_errors
elif callable(self.handle_parsing_errors):
observation = self.handle_parsing_errors(e)
else:
raise ValueError("Got unexpected type of `handle_parsing_errors`")
output = AgentAction("_Exception", observation, text)
# 如果Agent返回AgentFinish,则完成
if isinstance(output, AgentFinish):
return output
actions: List[AgentAction]
if isinstance(output, AgentAction):
actions = [output]
else:
actions = output
result = []
for agent_action in actions:
if run_manager:
run_manager.on_agent_action(agent_action, color="green")
# 否则我们查找工具并运行它
if agent_action.tool in name_to_tool_map:
tool = name_to_tool_map[agent_action.tool]
return_direct = tool.return_direct
color = color_mapping[agent_action.tool]
tool_run_kwargs = self.agent.tool_run_logging_kwargs()
if return_direct:
tool_run_kwargs["llm_prefix"] = ""
# 执行工具
observation = tool.run(
agent_action.tool_input,
verbose=self.verbose,
color=color,
callbacks=run_manager.get_child() if run_manager else None,
**tool_run_kwargs,
)
else:
tool_run_kwargs = self.agent.tool_run_logging_kwargs()
observation = InvalidTool().run(
{
"requested_tool_name": agent_action.tool,
"available_tool_names": list(name_to_tool_map.keys()),
},
verbose=self.verbose,
color=None,
callbacks=run_manager.get_child() if run_manager else None,
**tool_run_kwargs,
)
result.append((agent_action, observation))
return result
def _prepare_intermediate_steps(
self, steps: List[Tuple[AgentAction, str]]
) -> List[Tuple[AgentAction, str]]:
"""准备中间步骤以传递给Agent。
这可能涉及修剪步骤以保持在上下文长度限制内。
Args:
steps: 原始中间步骤。
Returns:
处理后的中间步骤。
"""
if isinstance(self.trim_intermediate_steps, int):
if self.trim_intermediate_steps == -1:
# 不修剪
return steps
else:
# 保留最后N个步骤
return steps[-self.trim_intermediate_steps :]
elif callable(self.trim_intermediate_steps):
# 使用自定义函数修剪
return self.trim_intermediate_steps(steps)
else:
raise ValueError(
f"Got unexpected type of `trim_intermediate_steps`: "
f"{type(self.trim_intermediate_steps)}"
)
def _return(
self,
output: AgentFinish,
intermediate_steps: List[Tuple[AgentAction, str]],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
"""返回Agent的输出。
Args:
output: Agent的最终输出。
intermediate_steps: 中间步骤列表。
run_manager: 回调管理器。
Returns:
格式化的输出字典。
"""
if run_manager:
run_manager.on_agent_finish(output, color="green", verbose=self.verbose)
final_output = output.return_values
if self.return_intermediate_steps:
final_output["intermediate_steps"] = intermediate_steps
return final_output
def _get_tool_return(
self, next_step_output: Tuple[AgentAction, str]
) -> Optional[AgentFinish]:
"""检查工具是否应该直接返回。
Args:
next_step_output: 下一步输出。
Returns:
如果工具应该直接返回,则返回AgentFinish,否则返回None。
"""
agent_action, observation = next_step_output
name_to_tool_map = {tool.name: tool for tool in self.tools}
if agent_action.tool in name_to_tool_map:
if name_to_tool_map[agent_action.tool].return_direct:
return AgentFinish(
{self.agent.return_values[0]: observation},
"",
)
return None
async def _acall(
self,
inputs: Dict[str, str],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
"""异步运行Agent。"""
name_to_tool_map = {tool.name: tool for tool in self.tools}
color_mapping = get_color_mapping(
[tool.name for tool in self.tools],
excluded_colors=["green", "red"],
)
intermediate_steps: List[Tuple[AgentAction, str]] = []
iterations = 0
time_elapsed = 0.0
start_time = time.time()
while self._should_continue(iterations, time_elapsed):
next_step_output = await self._atake_next_step(
name_to_tool_map,
color_mapping,
inputs,
intermediate_steps,
run_manager=run_manager,
)
if isinstance(next_step_output, AgentFinish):
return self._return(
next_step_output,
intermediate_steps,
run_manager=run_manager,
)
intermediate_steps.extend(next_step_output)
if len(next_step_output) == 1:
next_step_action = next_step_output[0]
tool_return = self._get_tool_return(next_step_action)
if tool_return is not None:
return self._return(
tool_return,
intermediate_steps,
run_manager=run_manager,
)
iterations += 1
time_elapsed = time.time() - start_time
output = self._return(
self._get_action_agent().return_stopped_response(
self.early_stopping_method, intermediate_steps
),
intermediate_steps,
run_manager=run_manager,
)
return output
async def _atake_next_step(
self,
name_to_tool_map: Dict[str, BaseTool],
color_mapping: Dict[str, str],
inputs: Dict[str, str],
intermediate_steps: List[Tuple[AgentAction, str]],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:
"""异步采取下一步。"""
try:
intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)
# 调用Agent规划
output = await self.agent.aplan(
intermediate_steps,
callbacks=run_manager.get_child() if run_manager else None,
**inputs,
)
except OutputParserException as e:
# 错误处理逻辑与同步版本相同
if isinstance(self.handle_parsing_errors, bool):
raise_error = not self.handle_parsing_errors
else:
raise_error = False
if raise_error:
raise ValueError(
"Agent输出解析出错。"
"请传递`handle_parsing_errors=True`以自动处理这些错误。"
) from e
text = str(e)
if isinstance(self.handle_parsing_errors, bool):
if e.send_to_llm:
observation = str(e.observation)
text = str(e.llm_output)
else:
observation = "解析LLM输出时出现无效格式"
elif isinstance(self.handle_parsing_errors, str):
observation = self.handle_parsing_errors
elif callable(self.handle_parsing_errors):
observation = self.handle_parsing_errors(e)
else:
raise ValueError("Got unexpected type of `handle_parsing_errors`")
output = AgentAction("_Exception", observation, text)
if isinstance(output, AgentFinish):
return output
actions: List[AgentAction]
if isinstance(output, AgentAction):
actions = [output]
else:
actions = output
result = []
for agent_action in actions:
if run_manager:
await run_manager.on_agent_action(agent_action, color="green")
if agent_action.tool in name_to_tool_map:
tool = name_to_tool_map[agent_action.tool]
return_direct = tool.return_direct
color = color_mapping[agent_action.tool]
tool_run_kwargs = self.agent.tool_run_logging_kwargs()
if return_direct:
tool_run_kwargs["llm_prefix"] = ""
# 异步执行工具
observation = await tool.arun(
agent_action.tool_input,
verbose=self.verbose,
color=color,
callbacks=run_manager.get_child() if run_manager else None,
**tool_run_kwargs,
)
else:
tool_run_kwargs = self.agent.tool_run_logging_kwargs()
observation = await InvalidTool().arun(
{
"requested_tool_name": agent_action.tool,
"available_tool_names": list(name_to_tool_map.keys()),
},
verbose=self.verbose,
color=None,
callbacks=run_manager.get_child() if run_manager else None,
**tool_run_kwargs,
)
result.append((agent_action, observation))
return result
@property
def _chain_type(self) -> str:
return "agent_executor"
|