-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathagents.py
More file actions
1814 lines (1626 loc) · 79 KB
/
agents.py
File metadata and controls
1814 lines (1626 loc) · 79 KB
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding=utf-8
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import importlib
import json
import os
import tempfile
import textwrap
import time
import warnings
from abc import ABC, abstractmethod
from collections.abc import Callable, Generator
from concurrent.futures import ThreadPoolExecutor, as_completed
from contextvars import copy_context
from dataclasses import dataclass
from logging import getLogger
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Type, TypeAlias, TypedDict, Union
import yaml
from huggingface_hub import create_repo, metadata_update, snapshot_download, upload_folder
from jinja2 import StrictUndefined, Template
from rich.console import Group
from rich.live import Live
from rich.markdown import Markdown
from rich.panel import Panel
from rich.rule import Rule
from rich.text import Text
if TYPE_CHECKING:
import PIL.Image
from .agent_types import AgentAudio, AgentImage, handle_agent_output_types
from .default_tools import TOOL_MAPPING, FinalAnswerTool
from .local_python_executor import BASE_BUILTIN_MODULES, LocalPythonExecutor, PythonExecutor, fix_final_answer_code
from .memory import (
ActionStep,
AgentMemory,
CallbackRegistry,
FinalAnswerStep,
MemoryStep,
PlanningStep,
SystemPromptStep,
TaskStep,
Timing,
ToolCall,
)
from .models import (
CODEAGENT_RESPONSE_FORMAT,
MODEL_REGISTRY,
ChatMessage,
ChatMessageStreamDelta,
ChatMessageToolCall,
MessageRole,
Model,
agglomerate_stream_deltas,
parse_json_if_needed,
)
from .monitoring import (
YELLOW_HEX,
AgentLogger,
LogLevel,
Monitor,
TokenUsage,
)
from .remote_executors import BlaxelExecutor, DockerExecutor, E2BExecutor, ModalExecutor, WasmExecutor
from .tools import BaseTool, Tool, validate_tool_arguments
from .utils import (
AgentError,
AgentExecutionError,
AgentGenerationError,
AgentMaxStepsError,
AgentParsingError,
AgentToolCallError,
AgentToolExecutionError,
create_agent_gradio_app_template,
extract_code_from_text,
is_valid_name,
make_init_file,
parse_code_blobs,
truncate_content,
)
logger = getLogger(__name__)
def populate_template(template: str, variables: dict[str, Any]) -> str:
compiled_template = Template(template, undefined=StrictUndefined)
try:
return compiled_template.render(**variables)
except Exception as e:
raise Exception(f"Error during jinja template rendering: {type(e).__name__}: {e}")
@dataclass
class ActionOutput:
output: Any
is_final_answer: bool
@dataclass
class ToolOutput:
id: str
output: Any
is_final_answer: bool
observation: str
tool_call: ToolCall
class PlanningPromptTemplate(TypedDict):
"""
Prompt templates for the planning step.
Args:
plan (`str`): Initial plan prompt.
update_plan_pre_messages (`str`): Update plan pre-messages prompt.
update_plan_post_messages (`str`): Update plan post-messages prompt.
"""
initial_plan: str
update_plan_pre_messages: str
update_plan_post_messages: str
class ManagedAgentPromptTemplate(TypedDict):
"""
Prompt templates for the managed agent.
Args:
task (`str`): Task prompt.
report (`str`): Report prompt.
"""
task: str
report: str
class FinalAnswerPromptTemplate(TypedDict):
"""
Prompt templates for the final answer.
Args:
pre_messages (`str`): Pre-messages prompt.
post_messages (`str`): Post-messages prompt.
"""
pre_messages: str
post_messages: str
class PromptTemplates(TypedDict):
"""
Prompt templates for the agent.
Args:
system_prompt (`str`): System prompt.
planning ([`~agents.PlanningPromptTemplate`]): Planning prompt templates.
managed_agent ([`~agents.ManagedAgentPromptTemplate`]): Managed agent prompt templates.
final_answer ([`~agents.FinalAnswerPromptTemplate`]): Final answer prompt templates.
"""
system_prompt: str
planning: PlanningPromptTemplate
managed_agent: ManagedAgentPromptTemplate
final_answer: FinalAnswerPromptTemplate
EMPTY_PROMPT_TEMPLATES = PromptTemplates(
system_prompt="",
planning=PlanningPromptTemplate(
initial_plan="",
update_plan_pre_messages="",
update_plan_post_messages="",
),
managed_agent=ManagedAgentPromptTemplate(task="", report=""),
final_answer=FinalAnswerPromptTemplate(pre_messages="", post_messages=""),
)
@dataclass
class RunResult:
"""Holds extended information about an agent run.
Attributes:
output (Any | None): The final output of the agent run, if available.
state (Literal["success", "max_steps_error"]): The final state of the agent after the run.
steps (list[dict]): The agent's memory, as a list of steps.
token_usage (TokenUsage | None): Count of tokens used during the run.
timing (Timing): Timing details of the agent run: start time, end time, duration.
messages (list[dict]): The agent's memory, as a list of messages.
<Deprecated version="1.22.0">
Parameter 'messages' is deprecated and will be removed in version 1.25. Please use 'steps' instead.
</Deprecated>
"""
output: Any | None
state: Literal["success", "max_steps_error"]
steps: list[dict]
token_usage: TokenUsage | None
timing: Timing
def __init__(self, output=None, state=None, steps=None, token_usage=None, timing=None, messages=None):
# Handle deprecated 'messages' parameter
if messages is not None:
if steps is not None:
raise ValueError("Cannot specify both 'messages' and 'steps' parameters. Use 'steps' instead.")
warnings.warn(
"Parameter 'messages' is deprecated and will be removed in version 1.25. Please use 'steps' instead.",
FutureWarning,
stacklevel=2,
)
steps = messages
# Initialize with dataclass fields
self.output = output
self.state = state
self.steps = steps
self.token_usage = token_usage
self.timing = timing
@property
def messages(self):
"""Backward compatibility property that returns steps."""
warnings.warn(
"Parameter 'messages' is deprecated and will be removed in version 1.25. Please use 'steps' instead.",
FutureWarning,
stacklevel=2,
)
return self.steps
def dict(self):
return {
"output": self.output,
"state": self.state,
"steps": self.steps,
"token_usage": self.token_usage.dict() if self.token_usage is not None else None,
"timing": self.timing.dict(),
}
StreamEvent: TypeAlias = Union[
ChatMessageStreamDelta,
ChatMessageToolCall,
ActionOutput,
ToolCall,
ToolOutput,
PlanningStep,
ActionStep,
FinalAnswerStep,
]
class MultiStepAgent(ABC):
"""
Agent class that solves the given task step by step, using the ReAct framework:
While the objective is not reached, the agent will perform a cycle of action (given by the LLM) and observation (obtained from the environment).
Args:
tools (`list[Tool]`): [`Tool`]s that the agent can use.
model (`Callable[[list[dict[str, str]]], ChatMessage]`): Model that will generate the agent's actions.
prompt_templates ([`~agents.PromptTemplates`], *optional*): Prompt templates.
instructions (`str`, *optional*): Custom instructions for the agent, will be inserted in the system prompt.
max_steps (`int`, default `20`): Maximum number of steps the agent can take to solve the task.
add_base_tools (`bool`, default `False`): Whether to add the base tools to the agent's tools.
verbosity_level (`LogLevel`, default `LogLevel.INFO`): Level of verbosity of the agent's logs.
managed_agents (`list`, *optional*): Managed agents that the agent can call.
step_callbacks (`list[Callable]` | `dict[Type[MemoryStep], Callable | list[Callable]]`, *optional*): Callbacks that will be called at each step.
planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
name (`str`, *optional*): Necessary for a managed agent only - the name by which this agent can be called.
description (`str`, *optional*): Necessary for a managed agent only - the description of this agent.
provide_run_summary (`bool`, *optional*): Whether to provide a run summary when called as a managed agent.
final_answer_checks (`list[Callable]`, *optional*): List of validation functions to run before accepting a final answer.
Each function should:
- Take the final answer, the agent's memory, and the agent itself as arguments.
- Return a boolean indicating whether the final answer is valid.
return_full_result (`bool`, default `False`): Whether to return the full [`RunResult`] object or just the final answer output from the agent run.
"""
def __init__(
self,
tools: list[Tool],
model: Model,
prompt_templates: PromptTemplates | None = None,
instructions: str | None = None,
max_steps: int = 20,
add_base_tools: bool = False,
verbosity_level: LogLevel = LogLevel.INFO,
managed_agents: list | None = None,
step_callbacks: list[Callable] | dict[Type[MemoryStep], Callable | list[Callable]] | None = None,
planning_interval: int | None = None,
name: str | None = None,
description: str | None = None,
provide_run_summary: bool = False,
final_answer_checks: list[Callable] | None = None,
return_full_result: bool = False,
logger: AgentLogger | None = None,
):
self.agent_name = self.__class__.__name__
self.model = model
self.prompt_templates = prompt_templates or EMPTY_PROMPT_TEMPLATES
if prompt_templates is not None:
missing_keys = set(EMPTY_PROMPT_TEMPLATES.keys()) - set(prompt_templates.keys())
assert not missing_keys, (
f"Some prompt templates are missing from your custom `prompt_templates`: {missing_keys}"
)
for key, value in EMPTY_PROMPT_TEMPLATES.items():
if isinstance(value, dict):
for subkey in value.keys():
assert key in prompt_templates.keys() and (subkey in prompt_templates[key].keys()), (
f"Some prompt templates are missing from your custom `prompt_templates`: {subkey} under {key}"
)
self.max_steps = max_steps
self.step_number = 0
self.planning_interval = planning_interval
self.state: dict[str, Any] = {}
self.name = self._validate_name(name)
self.description = description
self.provide_run_summary = provide_run_summary
self.final_answer_checks = final_answer_checks if final_answer_checks is not None else []
self.return_full_result = return_full_result
self.instructions = instructions
self._setup_managed_agents(managed_agents)
self._setup_tools(tools, add_base_tools)
self._validate_tools_and_managed_agents(tools, managed_agents)
self.task: str | None = None
self.memory = AgentMemory(self.system_prompt)
if logger is None:
self.logger = AgentLogger(level=verbosity_level)
else:
self.logger = logger
self.monitor = Monitor(self.model, self.logger)
self._setup_step_callbacks(step_callbacks)
self.stream_outputs = False
@property
def system_prompt(self) -> str:
return self.initialize_system_prompt()
@system_prompt.setter
def system_prompt(self, value: str):
raise AttributeError(
"""The 'system_prompt' property is read-only. Use 'self.prompt_templates["system_prompt"]' instead."""
)
def _validate_name(self, name: str | None) -> str | None:
if name is not None and not is_valid_name(name):
raise ValueError(f"Agent name '{name}' must be a valid Python identifier and not a reserved keyword.")
return name
def _setup_managed_agents(self, managed_agents: list | None = None) -> None:
"""Setup managed agents with proper logging."""
self.managed_agents = {}
if managed_agents:
assert all(agent.name and agent.description for agent in managed_agents), (
"All managed agents need both a name and a description!"
)
self.managed_agents = {agent.name: agent for agent in managed_agents}
# Ensure managed agents can be called as tools by the model: set their inputs and output_type
for agent in self.managed_agents.values():
agent.inputs = {
"task": {"type": "string", "description": "Long detailed description of the task."},
"additional_args": {
"type": "object",
"description": "Dictionary of extra inputs to pass to the managed agent, e.g. images, dataframes, or any other contextual data it may need.",
"nullable": True,
},
}
agent.output_type = "string"
def _setup_tools(self, tools, add_base_tools):
assert all(isinstance(tool, BaseTool) for tool in tools), (
"All elements must be instance of BaseTool (or a subclass)"
)
self.tools = {tool.name: tool for tool in tools}
if add_base_tools:
self.tools.update(
{
name: cls()
for name, cls in TOOL_MAPPING.items()
if name != "python_interpreter" or self.__class__.__name__ == "ToolCallingAgent"
}
)
self.tools.setdefault("final_answer", FinalAnswerTool())
def _validate_tools_and_managed_agents(self, tools, managed_agents):
tool_and_managed_agent_names = [tool.name for tool in tools]
if managed_agents is not None:
tool_and_managed_agent_names += [agent.name for agent in managed_agents]
if self.name:
tool_and_managed_agent_names.append(self.name)
if len(tool_and_managed_agent_names) != len(set(tool_and_managed_agent_names)):
raise ValueError(
"Each tool or managed_agent should have a unique name! You passed these duplicate names: "
f"{[name for name in tool_and_managed_agent_names if tool_and_managed_agent_names.count(name) > 1]}"
)
def _setup_step_callbacks(self, step_callbacks):
# Initialize step callbacks registry
self.step_callbacks = CallbackRegistry()
if step_callbacks:
# Register callbacks list only for ActionStep for backward compatibility
if isinstance(step_callbacks, list):
for callback in step_callbacks:
self.step_callbacks.register(ActionStep, callback)
# Register callbacks dict for specific step classes
elif isinstance(step_callbacks, dict):
for step_cls, callbacks in step_callbacks.items():
if not isinstance(callbacks, list):
callbacks = [callbacks]
for callback in callbacks:
self.step_callbacks.register(step_cls, callback)
else:
raise ValueError("step_callbacks must be a list or a dict")
# Register monitor update_metrics only for ActionStep for backward compatibility
self.step_callbacks.register(ActionStep, self.monitor.update_metrics)
def run(
self,
task: str,
stream: bool = False,
reset: bool = True,
images: list["PIL.Image.Image"] | None = None,
additional_args: dict | None = None,
max_steps: int | None = None,
return_full_result: bool | None = None,
) -> Any | RunResult:
"""
Run the agent for the given task.
Args:
task (`str`): Task to perform.
stream (`bool`): Whether to run in streaming mode.
If `True`, returns a generator that yields each step as it is executed. You must iterate over this generator to process the individual steps (e.g., using a for loop or `next()`).
If `False`, executes all steps internally and returns only the final answer after completion.
reset (`bool`): Whether to reset the conversation or keep it going from previous run.
images (`list[PIL.Image.Image]`, *optional*): Image(s) objects.
additional_args (`dict`, *optional*): Any other variables that you want to pass to the agent run, for instance images or dataframes. Give them clear names!
max_steps (`int`, *optional*): Maximum number of steps the agent can take to solve the task. if not provided, will use the agent's default value.
return_full_result (`bool`, *optional*): Whether to return the full [`RunResult`] object or just the final answer output.
If `None` (default), the agent's `self.return_full_result` setting is used.
Example:
```py
from smolagents import CodeAgent
agent = CodeAgent(tools=[])
agent.run("What is the result of 2 power 3.7384?")
```
"""
max_steps = max_steps or self.max_steps
self.task = task
self.interrupt_switch = False
if additional_args:
self.state.update(additional_args)
self.task += f"""
You have been provided with these additional arguments, that you can access directly using the keys as variables:
{str(additional_args)}."""
self.memory.system_prompt = SystemPromptStep(system_prompt=self.system_prompt)
if reset:
self.memory.reset()
self.monitor.reset()
self.logger.log_task(
content=self.task.strip(),
subtitle=f"{type(self.model).__name__} - {(self.model.model_id if hasattr(self.model, 'model_id') else '')}",
level=LogLevel.INFO,
title=self.name if hasattr(self, "name") else None,
)
self.memory.steps.append(TaskStep(task=self.task, task_images=images))
if getattr(self, "python_executor", None):
self.python_executor.send_variables(variables=self.state)
self.python_executor.send_tools({**self.tools, **self.managed_agents})
if stream:
# The steps are returned as they are executed through a generator to iterate on.
return self._run_stream(task=self.task, max_steps=max_steps, images=images)
run_start_time = time.time()
steps = list(self._run_stream(task=self.task, max_steps=max_steps, images=images))
# Outputs are returned only at the end. We only look at the last step.
assert isinstance(steps[-1], FinalAnswerStep)
output = steps[-1].output
return_full_result = return_full_result if return_full_result is not None else self.return_full_result
if return_full_result:
total_input_tokens = 0
total_output_tokens = 0
correct_token_usage = True
for step in self.memory.steps:
if isinstance(step, (ActionStep, PlanningStep)):
if step.token_usage is None:
correct_token_usage = False
break
else:
total_input_tokens += step.token_usage.input_tokens
total_output_tokens += step.token_usage.output_tokens
if correct_token_usage:
token_usage = TokenUsage(input_tokens=total_input_tokens, output_tokens=total_output_tokens)
else:
token_usage = None
if self.memory.steps and isinstance(getattr(self.memory.steps[-1], "error", None), AgentMaxStepsError):
state = "max_steps_error"
else:
state = "success"
step_dicts = self.memory.get_full_steps()
return RunResult(
output=output,
token_usage=token_usage,
steps=step_dicts,
timing=Timing(start_time=run_start_time, end_time=time.time()),
state=state,
)
return output
def _run_stream(
self, task: str, max_steps: int, images: list["PIL.Image.Image"] | None = None
) -> Generator[ActionStep | PlanningStep | FinalAnswerStep | ChatMessageStreamDelta]:
self.step_number = 1
returned_final_answer = False
while not returned_final_answer and self.step_number <= max_steps:
if self.interrupt_switch:
raise AgentError("Agent interrupted.", self.logger)
# Run a planning step if scheduled
if self.planning_interval is not None and (
self.step_number == 1 or (self.step_number - 1) % self.planning_interval == 0
):
planning_start_time = time.time()
planning_step = None
for element in self._generate_planning_step(
task, is_first_step=len(self.memory.steps) == 1, step=self.step_number
): # Don't use the attribute step_number here, because there can be steps from previous runs
yield element
planning_step = element
assert isinstance(planning_step, PlanningStep) # Last yielded element should be a PlanningStep
planning_end_time = time.time()
planning_step.timing = Timing(
start_time=planning_start_time,
end_time=planning_end_time,
)
self._finalize_step(planning_step)
self.memory.steps.append(planning_step)
# Start action step!
action_step_start_time = time.time()
action_step = ActionStep(
step_number=self.step_number,
timing=Timing(start_time=action_step_start_time),
observations_images=images,
)
self.logger.log_rule(f"Step {self.step_number}", level=LogLevel.INFO)
try:
for output in self._step_stream(action_step):
# Yield all
yield output
if isinstance(output, ActionOutput) and output.is_final_answer:
final_answer = output.output
self.logger.log(
Text(f"Final answer: {final_answer}", style=f"bold {YELLOW_HEX}"),
level=LogLevel.INFO,
)
if self.final_answer_checks:
self._validate_final_answer(final_answer)
returned_final_answer = True
action_step.is_final_answer = True
except AgentGenerationError as e:
# Agent generation errors are not caused by a Model error but an implementation error: so we should raise them and exit.
raise e
except AgentError as e:
# Other AgentError types are caused by the Model, so we should log them and iterate.
action_step.error = e
finally:
self._finalize_step(action_step)
self.memory.steps.append(action_step)
yield action_step
self.step_number += 1
if not returned_final_answer and self.step_number == max_steps + 1:
final_answer = self._handle_max_steps_reached(task)
yield action_step
final_answer_step = FinalAnswerStep(handle_agent_output_types(final_answer))
self._finalize_step(final_answer_step)
yield final_answer_step
def _validate_final_answer(self, final_answer: Any):
for check_function in self.final_answer_checks:
try:
assert check_function(final_answer, self.memory, agent=self)
except Exception as e:
raise AgentError(f"Check {check_function.__name__} failed with error: {e}", self.logger)
def _finalize_step(self, memory_step: ActionStep | PlanningStep | FinalAnswerStep):
if not isinstance(memory_step, FinalAnswerStep):
memory_step.timing.end_time = time.time()
self.step_callbacks.callback(memory_step, agent=self)
def _handle_max_steps_reached(self, task: str) -> Any:
action_step_start_time = time.time()
final_answer = self.provide_final_answer(task)
final_memory_step = ActionStep(
step_number=self.step_number,
error=AgentMaxStepsError("Reached max steps.", self.logger),
timing=Timing(start_time=action_step_start_time, end_time=time.time()),
token_usage=final_answer.token_usage,
)
final_memory_step.action_output = final_answer.content
self._finalize_step(final_memory_step)
self.memory.steps.append(final_memory_step)
return final_answer.content
def _generate_planning_step(
self, task, is_first_step: bool, step: int
) -> Generator[ChatMessageStreamDelta | PlanningStep]:
start_time = time.time()
if is_first_step:
input_messages = [
ChatMessage(
role=MessageRole.USER,
content=[
{
"type": "text",
"text": populate_template(
self.prompt_templates["planning"]["initial_plan"],
variables={"task": task, "tools": self.tools, "managed_agents": self.managed_agents},
),
}
],
)
]
if self.stream_outputs and hasattr(self.model, "generate_stream"):
plan_message_content = ""
output_stream = self.model.generate_stream(input_messages, stop_sequences=["<end_plan>"]) # type: ignore
input_tokens, output_tokens = 0, 0
with Live("", console=self.logger.console, vertical_overflow="visible") as live:
for event in output_stream:
if event.content is not None:
plan_message_content += event.content
live.update(Markdown(plan_message_content))
if event.token_usage:
input_tokens = event.token_usage.input_tokens
output_tokens += event.token_usage.output_tokens
yield event
else:
plan_message = self.model.generate(input_messages, stop_sequences=["<end_plan>"])
plan_message_content = plan_message.content
input_tokens, output_tokens = 0, 0
if plan_message.token_usage:
input_tokens = plan_message.token_usage.input_tokens
output_tokens = plan_message.token_usage.output_tokens
plan = textwrap.dedent(
f"""Here are the facts I know and the plan of action that I will follow to solve the task:\n```\n{plan_message_content}\n```"""
)
else:
# Summary mode removes the system prompt and previous planning messages output by the model.
# Removing previous planning messages avoids influencing too much the new plan.
memory_messages = self.write_memory_to_messages(summary_mode=True)
plan_update_pre = ChatMessage(
role=MessageRole.SYSTEM,
content=[
{
"type": "text",
"text": populate_template(
self.prompt_templates["planning"]["update_plan_pre_messages"], variables={"task": task}
),
}
],
)
plan_update_post = ChatMessage(
role=MessageRole.USER,
content=[
{
"type": "text",
"text": populate_template(
self.prompt_templates["planning"]["update_plan_post_messages"],
variables={
"task": task,
"tools": self.tools,
"managed_agents": self.managed_agents,
"remaining_steps": (self.max_steps - step),
},
),
}
],
)
input_messages = [plan_update_pre] + memory_messages + [plan_update_post]
if self.stream_outputs and hasattr(self.model, "generate_stream"):
plan_message_content = ""
input_tokens, output_tokens = 0, 0
with Live("", console=self.logger.console, vertical_overflow="visible") as live:
for event in self.model.generate_stream(
input_messages,
stop_sequences=["<end_plan>"],
): # type: ignore
if event.content is not None:
plan_message_content += event.content
live.update(Markdown(plan_message_content))
if event.token_usage:
input_tokens = event.token_usage.input_tokens
output_tokens += event.token_usage.output_tokens
yield event
else:
plan_message = self.model.generate(input_messages, stop_sequences=["<end_plan>"])
plan_message_content = plan_message.content
input_tokens, output_tokens = 0, 0
if plan_message.token_usage:
input_tokens = plan_message.token_usage.input_tokens
output_tokens = plan_message.token_usage.output_tokens
plan = textwrap.dedent(
f"""I still need to solve the task I was given:\n```\n{self.task}\n```\n\nHere are the facts I know and my new/updated plan of action to solve the task:\n```\n{plan_message_content}\n```"""
)
log_headline = "Initial plan" if is_first_step else "Updated plan"
self.logger.log(Rule(f"[bold]{log_headline}", style="orange"), Text(plan), level=LogLevel.INFO)
yield PlanningStep(
model_input_messages=input_messages,
plan=plan,
model_output_message=ChatMessage(role=MessageRole.ASSISTANT, content=plan_message_content),
token_usage=TokenUsage(input_tokens=input_tokens, output_tokens=output_tokens),
timing=Timing(start_time=start_time, end_time=time.time()),
)
@abstractmethod
def initialize_system_prompt(self) -> str:
"""To be implemented in child classes"""
...
def interrupt(self):
"""Interrupts the agent execution."""
self.interrupt_switch = True
def write_memory_to_messages(
self,
summary_mode: bool = False,
) -> list[ChatMessage]:
"""
Reads past llm_outputs, actions, and observations or errors from the memory into a series of messages
that can be used as input to the LLM. Adds a number of keywords (such as PLAN, error, etc) to help
the LLM.
"""
messages = self.memory.system_prompt.to_messages(summary_mode=summary_mode)
for memory_step in self.memory.steps:
messages.extend(memory_step.to_messages(summary_mode=summary_mode))
return messages
def _step_stream(
self, memory_step: ActionStep
) -> Generator[ChatMessageStreamDelta | ToolCall | ToolOutput | ActionOutput]:
"""
Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
Yields ChatMessageStreamDelta during the run if streaming is enabled.
At the end, yields either None if the step is not final, or the final answer.
"""
raise NotImplementedError("This method should be implemented in child classes")
def step(self, memory_step: ActionStep) -> Any:
"""
Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
Returns either None if the step is not final, or the final answer.
"""
return list(self._step_stream(memory_step))[-1]
def extract_action(self, model_output: str, split_token: str) -> tuple[str, str]:
"""
Parse action from the LLM output
Args:
model_output (`str`): Output of the LLM
split_token (`str`): Separator for the action. Should match the example in the system prompt.
"""
try:
split = model_output.split(split_token)
rationale, action = (
split[-2],
split[-1],
) # NOTE: using indexes starting from the end solves for when you have more than one split_token in the output
except Exception:
raise AgentParsingError(
f"No '{split_token}' token provided in your output.\nYour output:\n{model_output}\n. Be sure to include an action, prefaced with '{split_token}'!",
self.logger,
)
return rationale.strip(), action.strip()
def provide_final_answer(self, task: str) -> ChatMessage:
"""
Provide the final answer to the task, based on the logs of the agent's interactions.
Args:
task (`str`): Task to perform.
images (`list[PIL.Image.Image]`, *optional*): Image(s) objects.
Returns:
`str`: Final answer to the task.
"""
messages = [
ChatMessage(
role=MessageRole.SYSTEM,
content=[
{
"type": "text",
"text": self.prompt_templates["final_answer"]["pre_messages"],
}
],
)
]
messages += self.write_memory_to_messages()[1:]
messages.append(
ChatMessage(
role=MessageRole.USER,
content=[
{
"type": "text",
"text": populate_template(
self.prompt_templates["final_answer"]["post_messages"], variables={"task": task}
),
}
],
)
)
try:
chat_message: ChatMessage = self.model.generate(messages)
return chat_message
except Exception as e:
return ChatMessage(
role=MessageRole.ASSISTANT,
content=[{"type": "text", "text": f"Error in generating final LLM output: {e}"}],
)
def visualize(self):
"""Creates a rich tree visualization of the agent's structure."""
self.logger.visualize_agent_tree(self)
def replay(self, detailed: bool = False):
"""Prints a pretty replay of the agent's steps.
Args:
detailed (bool, optional): If True, also displays the memory at each step. Defaults to False.
Careful: will increase log length exponentially. Use only for debugging.
"""
self.memory.replay(self.logger, detailed=detailed)
def __call__(self, task: str, **kwargs):
"""Adds additional prompting for the managed agent, runs it, and wraps the output.
This method is called only by a managed agent.
"""
full_task = populate_template(
self.prompt_templates["managed_agent"]["task"],
variables=dict(name=self.name, task=task),
)
result = self.run(full_task, **kwargs)
if isinstance(result, RunResult):
report = result.output
else:
report = result
answer = populate_template(
self.prompt_templates["managed_agent"]["report"], variables=dict(name=self.name, final_answer=report)
)
if self.provide_run_summary:
answer += "\n\nFor more detail, find below a summary of this agent's work:\n<summary_of_work>\n"
for message in self.write_memory_to_messages(summary_mode=True):
content = message.content
answer += "\n" + truncate_content(str(content)) + "\n---"
answer += "\n</summary_of_work>"
return answer
def save(self, output_dir: str | Path, relative_path: str | None = None):
"""
Saves the relevant code files for your agent. This will copy the code of your agent in `output_dir` as well as autogenerate:
- a `tools` folder containing the logic for each of the tools under `tools/{tool_name}.py`.
- a `managed_agents` folder containing the logic for each of the managed agents.
- an `agent.json` file containing a dictionary representing your agent.
- a `prompt.yaml` file containing the prompt templates used by your agent.
- an `app.py` file providing a UI for your agent when it is exported to a Space with `agent.push_to_hub()`
- a `requirements.txt` containing the names of the modules used by your tool (as detected when inspecting its
code)
Args:
output_dir (`str` or `Path`): The folder in which you want to save your agent.
"""
make_init_file(output_dir)
# Recursively save managed agents
if self.managed_agents:
make_init_file(os.path.join(output_dir, "managed_agents"))
for agent_name, agent in self.managed_agents.items():
agent_suffix = f"managed_agents.{agent_name}"
if relative_path:
agent_suffix = relative_path + "." + agent_suffix
agent.save(os.path.join(output_dir, "managed_agents", agent_name), relative_path=agent_suffix)
class_name = self.__class__.__name__
# Save tools to different .py files
for tool in self.tools.values():
make_init_file(os.path.join(output_dir, "tools"))
tool.save(os.path.join(output_dir, "tools"), tool_file_name=tool.name, make_gradio_app=False)
# Save prompts to yaml
yaml_prompts = yaml.safe_dump(
self.prompt_templates,
default_style="|", # This forces block literals for all strings
default_flow_style=False,
width=float("inf"),
sort_keys=False,
allow_unicode=True,
indent=2,
)
with open(os.path.join(output_dir, "prompts.yaml"), "w", encoding="utf-8") as f:
f.write(yaml_prompts)
# Save agent dictionary to json
agent_dict = self.to_dict()
agent_dict["tools"] = [tool.name for tool in self.tools.values()]
agent_dict["managed_agents"] = {agent.name: agent.__class__.__name__ for agent in self.managed_agents.values()}
with open(os.path.join(output_dir, "agent.json"), "w", encoding="utf-8") as f:
json.dump(agent_dict, f, indent=4)
# Save requirements
with open(os.path.join(output_dir, "requirements.txt"), "w", encoding="utf-8") as f:
f.writelines(f"{r}\n" for r in agent_dict["requirements"])
# Make agent.py file with Gradio UI
agent_name = f"agent_{self.name}" if getattr(self, "name", None) else "agent"
managed_agent_relative_path = relative_path + "." if relative_path is not None else ""
app_template = create_agent_gradio_app_template()
# Render the app.py file from Jinja2 template
app_text = app_template.render(
{
"agent_name": agent_name,
"class_name": class_name,
"agent_dict": agent_dict,
"tools": self.tools,
"managed_agents": self.managed_agents,
"managed_agent_relative_path": managed_agent_relative_path,
}
)
with open(os.path.join(output_dir, "app.py"), "w", encoding="utf-8") as f:
f.write(app_text + "\n") # Append newline at the end
def to_dict(self) -> dict[str, Any]:
"""Convert the agent to a dictionary representation.
Returns:
`dict`: Dictionary representation of the agent.
"""
# TODO: handle serializing step_callbacks and final_answer_checks
for attr in ["final_answer_checks", "step_callbacks"]:
if getattr(self, attr, None):
self.logger.log(f"This agent has {attr}: they will be ignored by this method.", LogLevel.INFO)
tool_dicts = [tool.to_dict() for tool in self.tools.values()]
tool_requirements = {req for tool in self.tools.values() for req in tool.to_dict()["requirements"]}
managed_agents_requirements = {
req for managed_agent in self.managed_agents.values() for req in managed_agent.to_dict()["requirements"]
}
requirements = tool_requirements | managed_agents_requirements
if hasattr(self, "authorized_imports"):
requirements.update(
{package.split(".")[0] for package in self.authorized_imports if package not in BASE_BUILTIN_MODULES}
)
agent_dict = {
"class": self.__class__.__name__,
"tools": tool_dicts,
"model": {
"class": self.model.__class__.__name__,
"data": self.model.to_dict(),
},
"managed_agents": [managed_agent.to_dict() for managed_agent in self.managed_agents.values()],
"prompt_templates": self.prompt_templates,