-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathreact_agent.py
More file actions
1619 lines (1479 loc) · 71.4 KB
/
react_agent.py
File metadata and controls
1619 lines (1479 loc) · 71.4 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
import argparse
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
import json
import os
import re
import signal
import sys
import threading
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Type
from openai import OpenAI, APIError, APIConnectionError, APITimeoutError
import tiktoken
from agent_base.base import BaseAgent
from agent_base.console_utils import ConsoleEventPrinter
from agent_base.context_compact import compact_messages, should_compact_messages
from agent_base.model_profiles import resolve_model_profile
from agent_base.provider_compat import apply_sampling_params
from agent_base.prompt import composed_system_prompt
from agent_base.session_state import AgentSessionState, CompactionRecord, persist_session_state, resolve_session_state_path
from agent_base.trace_utils import FlatTraceWriter
from agent_base.tools.custom import build_custom_tool_map
from agent_base.tools.tooling import normalize_workspace_root
from agent_base.tools.tool_extra import StrReplaceEditor
from agent_base.tools.tool_file import Edit, Glob, Grep, Read, ReadImage, ReadPDF, Write
from agent_base.tools.tool_runtime import Bash, TerminalInterrupt, TerminalKill, TerminalRead, TerminalStart, TerminalWrite
from agent_base.tools.tool_user import AskUser
from agent_base.tools.tool_web import ScholarSearch, WebFetch, WebSearch
from agent_base.utils import (
MissingRequiredEnvError,
append_saved_image_paths_to_prompt,
env_flag,
image_input_content_parts,
load_default_dotenvs,
read_role_prompt_files,
require_required_env,
safe_jsonable,
stage_image_file_for_input,
)
import datetime
import random
import time
AVAILABLE_TOOLS = [
Glob(),
Grep(),
Read(),
ReadPDF(),
ReadImage(),
Write(),
Edit(),
Bash(),
WebSearch(),
ScholarSearch(),
WebFetch(),
AskUser(),
TerminalStart(),
TerminalWrite(),
TerminalRead(),
TerminalInterrupt(),
TerminalKill(),
]
AVAILABLE_TOOL_MAP = {tool.name: tool for tool in AVAILABLE_TOOLS}
OPTIONAL_TOOLS = [
StrReplaceEditor(),
]
OPTIONAL_TOOL_MAP = {tool.name: tool for tool in OPTIONAL_TOOLS}
ALL_TOOL_MAP = {**AVAILABLE_TOOL_MAP, **OPTIONAL_TOOL_MAP}
DEFAULT_IMAGE_TOKEN_ESTIMATE = 1536
DEFAULT_MODEL_NAME = "gpt-5.4"
DEFAULT_MAX_LLM_CALLS = 100
DEFAULT_MAX_ROUNDS = 100
DEFAULT_MAX_RUNTIME_SECONDS = 150 * 60
DEFAULT_MAX_OUTPUT_TOKENS = 10000
DEFAULT_MAX_INPUT_TOKENS = 320000
DEFAULT_MAX_RETRIES = 10
DEFAULT_TEMPERATURE = 0.6
DEFAULT_TOP_P = 0.95
DEFAULT_PRESENCE_PENALTY = 1.1
DEFAULT_LLM_TIMEOUT_SECONDS = 600.0
MAX_PARALLEL_READ_TOOL_CALLS = 3
PARALLEL_READ_TOOL_NAMES = frozenset(
{
"Glob",
"Grep",
"Read",
"ReadImage",
"WebSearch",
"ScholarSearch",
"WebFetch",
}
)
def default_model_name() -> str:
return os.environ.get("MODEL_NAME", DEFAULT_MODEL_NAME).strip() or DEFAULT_MODEL_NAME
class LLMHardTimeoutError(TimeoutError):
pass
@contextmanager
def llm_hard_timeout(timeout_seconds: float):
if (
timeout_seconds <= 0
or threading.current_thread() is not threading.main_thread()
or not hasattr(signal, "SIGALRM")
):
yield
return
def _handle_timeout(signum, frame):
raise LLMHardTimeoutError(f"LLM request exceeded hard timeout of {timeout_seconds:.1f}s")
previous_handler = signal.getsignal(signal.SIGALRM)
previous_timer = signal.getitimer(signal.ITIMER_REAL)
signal.signal(signal.SIGALRM, _handle_timeout)
signal.setitimer(signal.ITIMER_REAL, timeout_seconds)
try:
yield
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, previous_handler)
if previous_timer[0] > 0:
signal.setitimer(signal.ITIMER_REAL, previous_timer[0], previous_timer[1])
def today_date():
return datetime.date.today().strftime("%Y-%m-%d")
def max_llm_calls_per_run() -> int:
return int(os.getenv("MAX_LLM_CALL_PER_RUN", str(DEFAULT_MAX_LLM_CALLS)))
def max_agent_rounds() -> int:
return int(os.getenv("MAX_AGENT_ROUNDS", str(DEFAULT_MAX_ROUNDS)))
def max_agent_runtime_seconds() -> int:
return int(os.getenv("MAX_AGENT_RUNTIME_SECONDS", str(DEFAULT_MAX_RUNTIME_SECONDS)))
def llm_max_output_tokens() -> int:
return int(os.getenv("LLM_MAX_OUTPUT_TOKENS", str(DEFAULT_MAX_OUTPUT_TOKENS)))
def remaining_runtime_seconds(runtime_deadline: Optional[float]) -> Optional[float]:
if runtime_deadline is None:
return None
return runtime_deadline - time.time()
def debug_enabled() -> bool:
return env_flag("DEBUG_AGENT")
def assistant_text_content(content: Any) -> str:
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
text_parts: list[str] = []
for part in content:
if isinstance(part, dict) and part.get("type") == "text":
text_parts.append(str(part.get("text", "")))
else:
text_parts.append(str(part))
return "".join(text_parts)
return str(content)
def message_trace_text(content: Any) -> str:
if isinstance(content, str):
return content
if not isinstance(content, list):
return str(content)
text_parts: list[str] = []
for part in content:
if not isinstance(part, dict):
text_parts.append(str(part))
continue
part_type = part.get("type")
if part_type == "text":
text_parts.append(str(part.get("text", "")))
elif part_type == "image_url":
image_url = part.get("image_url", {})
url = image_url.get("url", "") if isinstance(image_url, dict) else ""
url_text = str(url)
if url_text.startswith("data:image/"):
url_text = url_text.split(",", 1)[0] + ",...(base64 omitted)"
text_parts.append(f"[image_url: {url_text}]")
else:
text_parts.append(str(part))
return "\n".join(text for text in text_parts if text)
def _message_has_image_content(message: dict[str, Any]) -> bool:
content = message.get("content")
return isinstance(content, list) and any(isinstance(part, dict) and part.get("type") == "image_url" for part in content)
def _last_assistant_message_index(messages: Sequence[dict[str, Any]]) -> int:
for index in range(len(messages) - 1, -1, -1):
if isinstance(messages[index], dict) and messages[index].get("role") == "assistant":
return index
return -1
def _image_reference_summary(part: dict[str, Any]) -> str:
image_url = part.get("image_url", {})
url = image_url.get("url", "") if isinstance(image_url, dict) else ""
url_text = str(url)
if url_text.startswith("data:image/"):
return url_text.split(",", 1)[0] + ",...(base64 omitted)"
elif len(url_text) > 180:
return url_text[:180] + "...(truncated)"
return url_text or "unavailable"
def _image_path_hint_from_text(text: str) -> str:
patterns = (
r"\[User-provided image saved at ([^\]\n]+)\]",
r"Local image path:\s*([^\n]+)",
)
for pattern in patterns:
match = re.search(pattern, text)
if match:
return match.group(1).strip()
return ""
def _omitted_image_part_text(part: dict[str, Any], *, saved_path_hint: str = "") -> str:
url_text = _image_reference_summary(part)
path_text = f" Saved local path: {saved_path_hint}." if saved_path_hint else ""
return (
"[Previous image omitted from this model request to avoid repeatedly resending image bytes. "
f"Original image reference: {url_text}. "
f"{path_text} "
"The nearby conversation text or tool metadata records saved local paths when available; "
"use ReadImage on the saved path if visual details are needed again.]"
)
def _replace_image_parts_with_text(content: Any, *, message_index: int) -> tuple[Any, list[dict[str, Any]]]:
if not isinstance(content, list):
return content, []
replacement: list[Any] = []
omitted_images: list[dict[str, Any]] = []
image_index = 0
last_text_path_hint = ""
for part in content:
if isinstance(part, dict) and part.get("type") == "text":
path_hint = _image_path_hint_from_text(str(part.get("text", "")))
if path_hint:
last_text_path_hint = path_hint
if isinstance(part, dict) and part.get("type") == "image_url":
omitted_images.append(
{
"message_index": message_index,
"image_index": image_index,
"reference_summary": _image_reference_summary(part),
"saved_path_hint": last_text_path_hint,
}
)
replacement.append({"type": "text", "text": _omitted_image_part_text(part, saved_path_hint=last_text_path_hint)})
else:
replacement.append(safe_jsonable(part))
if isinstance(part, dict) and part.get("type") == "image_url":
image_index += 1
return replacement, omitted_images
def prepare_messages_for_llm(messages: Sequence[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Return request messages with old image bytes replaced by text references.
Image content parts are only needed immediately after they enter the
conversation. Older image parts stay represented as text so the agent can
re-read saved paths with ReadImage without resending the image every round.
"""
last_assistant_index = _last_assistant_message_index(messages)
request_messages: list[dict[str, Any]] = []
omitted_images: list[dict[str, Any]] = []
for index, raw_message in enumerate(messages):
message = safe_jsonable(raw_message)
if not isinstance(message, dict):
request_messages.append({"role": "user", "content": str(message)})
continue
if index <= last_assistant_index and _message_has_image_content(message):
message = dict(message)
message["content"], message_omitted_images = _replace_image_parts_with_text(
message.get("content"),
message_index=index,
)
omitted_images.extend(message_omitted_images)
request_messages.append(message)
image_aging = {
"omitted_image_count": len(omitted_images),
"omitted_images": omitted_images,
}
return request_messages, image_aging
def assistant_reasoning_content(message: Any) -> Optional[Any]:
if hasattr(message, "model_dump"):
try:
dumped = safe_jsonable(message.model_dump())
if isinstance(dumped, dict) and "reasoning_content" in dumped:
return dumped.get("reasoning_content")
except Exception:
pass
model_extra = getattr(message, "model_extra", None)
if isinstance(model_extra, dict) and "reasoning_content" in model_extra:
return safe_jsonable(model_extra.get("reasoning_content"))
raw_reasoning = getattr(message, "reasoning_content", None)
if raw_reasoning is None:
return None
return safe_jsonable(raw_reasoning)
def assistant_has_meaningful_text(content: Any) -> bool:
return bool(assistant_text_content(content).strip())
def input_tokens_from_usage(usage: Any) -> Optional[int]:
if not isinstance(usage, dict):
return None
for key in ("prompt_tokens", "input_tokens"):
value = usage.get(key)
if isinstance(value, int):
return value
return None
def llm_call_trace_payload(
*,
request_messages: Sequence[dict[str, Any]],
image_aging: Optional[dict[str, Any]] = None,
response: Any,
model_name: str,
native_tools: Sequence[dict[str, Any]],
) -> dict[str, Any]:
payload = {
"model_name": model_name,
"request_messages": safe_jsonable(list(request_messages)),
"tools_enabled": bool(native_tools),
"native_tools": safe_jsonable(list(native_tools)),
"response": safe_jsonable(response),
}
if image_aging and int(image_aging.get("omitted_image_count", 0) or 0) > 0:
payload["image_aging"] = safe_jsonable(image_aging)
return payload
def compaction_trace_payload(
*,
trigger_reason: str,
outcome: Any,
) -> dict[str, Any]:
return {
"trigger_reason": trigger_reason,
"status": getattr(outcome, "status", ""),
"error": getattr(outcome, "error", ""),
"prior_token_estimate": getattr(outcome, "prior_token_estimate", 0),
"new_token_estimate": getattr(outcome, "new_token_estimate", 0),
"compacted_group_count": getattr(outcome, "compacted_group_count", 0),
"kept_group_count": getattr(outcome, "kept_group_count", 0),
"existing_memory_text": getattr(outcome, "existing_memory_text", ""),
"summary_request": safe_jsonable(getattr(outcome, "summary_request", []) or []),
"summary_response": safe_jsonable(getattr(outcome, "summary_response", {}) or {}),
"summary_text": getattr(outcome, "summary_text", ""),
"pre_messages": safe_jsonable(getattr(outcome, "pre_messages", []) or []),
"post_messages": safe_jsonable(getattr(outcome, "post_messages", []) or []),
}
def legacy_protocol_error(content: str) -> Optional[str]:
stripped = content.lstrip()
if stripped.startswith("<tool_call>"):
return "assistant emitted deprecated text <tool_call> protocol"
if stripped.startswith("<tool_response>"):
return "assistant emitted deprecated text <tool_response> protocol"
if stripped.startswith("<think>"):
return "assistant emitted deprecated text <think> protocol"
if stripped.startswith("<answer>"):
return "assistant emitted deprecated text <answer> protocol"
return None
def tool_schema(tool: Any) -> dict[str, Any]:
return {
"type": "function",
"function": {
"name": tool.name,
"description": tool.description,
"parameters": tool.parameters,
},
}
def resolved_tool_names(function_list: Optional[Sequence[str]]) -> list[str]:
if function_list is None:
return list(AVAILABLE_TOOL_MAP.keys())
resolved: list[str] = []
for raw_name in function_list:
name = str(raw_name).strip()
if name:
resolved.append(name)
return resolved
def available_tool_schemas(function_list: Optional[Sequence[str]] = None) -> list[dict[str, Any]]:
names = resolved_tool_names(function_list)
unknown_tools = [name for name in names if name not in ALL_TOOL_MAP]
if unknown_tools:
raise ValueError(f"Unknown tools requested: {unknown_tools}")
return [tool_schema(ALL_TOOL_MAP[name]) for name in names]
def resolve_extra_tool_names(extra_tools: Optional[Sequence[str]]) -> list[str]:
resolved: list[str] = []
for raw_name in extra_tools or []:
name = str(raw_name).strip()
if not name:
continue
if name not in OPTIONAL_TOOL_MAP:
raise ValueError(f"Unknown extra tool requested: {name}")
if name not in resolved:
resolved.append(name)
return resolved
def default_tool_names(*, include_ask_user: bool = True, extra_tools: Optional[Sequence[str]] = None) -> list[str]:
names = [name for name in AVAILABLE_TOOL_MAP if include_ask_user or name != "AskUser"]
for name in resolve_extra_tool_names(extra_tools):
if name not in names:
names.append(name)
return names
def normalized_tool_call(tool_call: Any) -> dict[str, Any]:
return {
"id": getattr(tool_call, "id", ""),
"type": "function",
"function": {
"name": tool_call.function.name,
"arguments": tool_call.function.arguments,
},
}
def tool_result_message_content(result: Any) -> str:
if isinstance(result, dict) and result.get("kind") == "image_tool_result":
return str(result.get("text", "")).strip() or "ReadImage returned no metadata."
if isinstance(result, (dict, list)):
return json.dumps(safe_jsonable(result), ensure_ascii=False)
return str(result)
def model_supports_runtime_image_parts(model_name: str) -> bool:
normalized = str(model_name or "").strip().casefold()
if "deepseek" in normalized:
return False
return True
def image_context_message(result: Any, model_name: str) -> Optional[dict[str, Any]]:
if not isinstance(result, dict) or result.get("kind") != "image_tool_result":
return None
image_url = str(result.get("image_url", "")).strip()
if not image_url and model_supports_runtime_image_parts(model_name):
return None
metadata_text = str(result.get("text", "")).strip()
text = (
"Runtime image context from ReadImage.\n"
"Use the attached image as evidence produced by that tool call when deciding the next step or final result.\n"
"Do not assume that all required tool work is complete merely because an image is attached."
)
if metadata_text:
text += "\n\nReadImage metadata:\n" + metadata_text
if not model_supports_runtime_image_parts(model_name):
text += (
"\n\nThis model endpoint does not accept runtime image content parts, so only the "
"ReadImage metadata is forwarded in conversation history. Do not invent visual details "
"that are not supported by the metadata."
)
return {"role": "user", "content": text}
return {
"role": "user",
"content": [
{"type": "text", "text": text},
{"type": "image_url", "image_url": {"url": image_url, "detail": "auto"}},
],
}
def api_tool_message(tool_call_id: str, result: Any) -> dict[str, Any]:
return {
"role": "tool",
"tool_call_id": tool_call_id,
"content": tool_result_message_content(result),
}
def assistant_history_message(
*,
content: Any,
tool_calls: Optional[list[dict[str, Any]]] = None,
reasoning_content: Optional[Any] = None,
raw_message: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
if isinstance(raw_message, dict):
message = safe_jsonable(raw_message)
if isinstance(message, dict):
message["role"] = "assistant"
if content is not None or "content" not in message:
message["content"] = content
if tool_calls and "tool_calls" not in message:
message["tool_calls"] = tool_calls
elif "tool_calls" in message and not message.get("tool_calls"):
message.pop("tool_calls", None)
if reasoning_content is not None and "reasoning_content" not in message:
message["reasoning_content"] = reasoning_content
elif "reasoning_content" in message and message.get("reasoning_content") is None:
message.pop("reasoning_content", None)
return message
message: dict[str, Any] = {"role": "assistant", "content": content}
if tool_calls:
message["tool_calls"] = tool_calls
if reasoning_content is not None:
message["reasoning_content"] = reasoning_content
return message
def assistant_retry_history_message(
*,
content: Any,
reasoning_content: Optional[Any] = None,
) -> Optional[dict[str, Any]]:
if reasoning_content is None and not assistant_has_meaningful_text(content):
return None
# For retry/correction branches, preserve a replay-safe assistant history
# message without tool calls so provider-specific reasoning state is not
# lost while avoiding invalid unfinished tool-call history.
return assistant_history_message(
content=assistant_text_content(content),
reasoning_content=reasoning_content,
)
def parse_tool_arguments_list(tool_calls: list[dict[str, Any]]) -> list[Any]:
def _maybe_parse_nested_json(raw: Any) -> Any:
if not isinstance(raw, str):
return raw
try:
parsed = json.loads(raw)
except (TypeError, ValueError):
return raw
if isinstance(parsed, str):
nested_text = parsed.strip()
if nested_text.startswith("{") or nested_text.startswith("["):
try:
return json.loads(nested_text)
except (TypeError, ValueError):
return parsed
return parsed
parsed_arguments: list[Any] = []
for tool_call in tool_calls:
function_block = tool_call.get("function", {}) if isinstance(tool_call, dict) else {}
tool_arguments_raw = function_block.get("arguments", {})
parsed = _maybe_parse_nested_json(tool_arguments_raw)
parsed_arguments.append(safe_jsonable(parsed))
return parsed_arguments
def image_trace_paths(result: Any) -> list[str]:
if not isinstance(result, dict) or result.get("kind") != "image_tool_result":
return []
path = str(result.get("path", "")).strip()
return [path] if path else []
def image_context_trace_text(result: Any) -> str:
if not isinstance(result, dict) or result.get("kind") != "image_tool_result":
return ""
metadata_text = str(result.get("text", "")).strip()
text = (
"Runtime image context from ReadImage.\n"
"Use the attached image as evidence produced by that tool call when deciding the next step or final result.\n"
"Do not assume that all required tool work is complete merely because an image is attached."
)
if metadata_text:
text += "\n\nReadImage metadata:\n" + metadata_text
return text
def default_llm_config(model_name: Optional[str] = None) -> dict:
selected_model = str(model_name or "").strip() or default_model_name()
return {
"model": selected_model,
"api_key": os.environ.get("API_KEY", "EMPTY"),
"api_base": os.environ.get("API_BASE"),
"timeout_seconds": float(os.environ.get("LLM_TIMEOUT_SECONDS", str(DEFAULT_LLM_TIMEOUT_SECONDS))),
"generate_cfg": {
"max_input_tokens": int(os.environ.get("MAX_INPUT_TOKENS", str(DEFAULT_MAX_INPUT_TOKENS))),
"max_output_tokens": int(os.environ.get("LLM_MAX_OUTPUT_TOKENS", str(DEFAULT_MAX_OUTPUT_TOKENS))),
"max_retries": int(os.environ.get("LLM_MAX_RETRIES", str(DEFAULT_MAX_RETRIES))),
"temperature": float(os.environ.get("TEMPERATURE", str(DEFAULT_TEMPERATURE))),
"top_p": float(os.environ.get("TOP_P", str(DEFAULT_TOP_P))),
"presence_penalty": float(os.environ.get("PRESENCE_PENALTY", str(DEFAULT_PRESENCE_PENALTY))),
},
}
def execute_tool_by_name(tool_map: dict[str, Any], tool_name: str, tool_args: Any, **kwargs):
if tool_name not in tool_map:
return f"Error: Tool {tool_name} not found"
tool = tool_map[tool_name]
if tool_name == "ReadImage" and hasattr(tool, "call_for_llm"):
return tool.call_for_llm(tool_args, **kwargs)
return tool.call(tool_args, **kwargs)
def can_parallelize_tool_name(tool_name: str) -> bool:
return tool_name in PARALLEL_READ_TOOL_NAMES
def tool_execution_batches(tool_names: Sequence[str]) -> list[list[int]]:
batches: list[list[int]] = []
read_batch: list[int] = []
for index, tool_name in enumerate(tool_names):
if can_parallelize_tool_name(tool_name):
read_batch.append(index)
continue
if read_batch:
batches.append(read_batch)
read_batch = []
batches.append([index])
if read_batch:
batches.append(read_batch)
return batches
def normalized_image_inputs(images: Optional[str | Path | Sequence[str | Path]]) -> list[str | Path]:
if images is None:
return []
if isinstance(images, (str, Path)):
return [images]
if isinstance(images, Sequence) and not isinstance(images, (str, bytes)):
return list(images)
raise ValueError("images must be a path or a sequence of paths.")
class MultiTurnReactAgent(BaseAgent):
def __init__(
self,
function_list: Optional[List[str]] = None,
llm: Optional[Dict] = None,
trace_dir: Optional[str] = None,
role_prompt: Optional[str] = None,
workspace_root: Optional[str] = None,
custom_tools: Optional[Sequence[Any]] = None,
max_llm_calls: Optional[int] = None,
max_rounds: Optional[int] = None,
max_runtime_seconds: Optional[int] = None,
):
if not isinstance(llm, dict):
raise ValueError("llm must be a dict configuration.")
custom_tool_map = build_custom_tool_map(custom_tools)
conflicting_tools = [name for name in custom_tool_map if name in ALL_TOOL_MAP]
if conflicting_tools:
raise ValueError(f"Custom tool names conflict with built-in tools: {conflicting_tools}")
tool_registry = {**ALL_TOOL_MAP, **custom_tool_map}
requested_tools = self.resolve_function_list(function_list)
if requested_tools is None:
requested_tools = list(AVAILABLE_TOOL_MAP.keys())
for tool_name in custom_tool_map:
if tool_name not in requested_tools:
requested_tools.append(tool_name)
duplicate_tools: list[str] = []
seen_tools: set[str] = set()
for tool_name in requested_tools:
if tool_name in seen_tools and tool_name not in duplicate_tools:
duplicate_tools.append(tool_name)
seen_tools.add(tool_name)
if duplicate_tools:
raise ValueError(f"Duplicate tools requested: {duplicate_tools}")
unknown_tools = [tool for tool in requested_tools if tool not in tool_registry]
if unknown_tools:
raise ValueError(f"Unknown tools requested: {unknown_tools}")
if "model" not in llm or not str(llm["model"]).strip():
raise ValueError('llm["model"] must be a non-empty string.')
if "generate_cfg" not in llm or not isinstance(llm["generate_cfg"], dict):
raise ValueError('llm["generate_cfg"] must be a dict.')
self.tool_map = {tool_name: tool_registry[tool_name] for tool_name in requested_tools}
self.tool_names = list(self.tool_map.keys())
self.model = str(llm["model"])
self.llm_generate_cfg = llm["generate_cfg"]
self.trace_dir = Path(trace_dir) if trace_dir else None
self.trace_path: Optional[Path] = None
self.session_state_path: Optional[Path] = None
self.role_prompt = self.resolve_role_prompt(role_prompt)
self.workspace_root = normalize_workspace_root(workspace_root) if workspace_root else None
self.max_llm_calls = int(max_llm_calls) if max_llm_calls is not None else max_llm_calls_per_run()
self.max_rounds = int(max_rounds) if max_rounds is not None else max_agent_rounds()
self.max_runtime_seconds = (
int(max_runtime_seconds) if max_runtime_seconds is not None else max_agent_runtime_seconds()
)
if self.max_rounds <= 0:
raise ValueError("max_rounds must be > 0.")
self._native_tools = [tool_schema(self.tool_map[tool_name]) for tool_name in self.tool_names]
self._encoding = tiktoken.get_encoding("cl100k_base")
self._native_tools_token_estimate = len(
self._encoding.encode(json.dumps(self._native_tools, ensure_ascii=False))
)
self._llm_timeout_seconds = float(
llm.get("timeout_seconds", os.getenv("LLM_TIMEOUT_SECONDS", str(DEFAULT_LLM_TIMEOUT_SECONDS)))
)
self._llm_api_key = str(llm.get("api_key") or os.environ.get("API_KEY", "EMPTY"))
api_base = str(llm.get("api_base") or os.environ.get("API_BASE", "")).strip()
self._llm_api_base = api_base or None
self._llm_client = (
OpenAI(
api_key=self._llm_api_key,
base_url=self._llm_api_base,
timeout=self._llm_timeout_seconds,
)
if self._llm_api_base
else None
)
def _call_chat_completion(
self,
msgs,
*,
include_native_tools: bool,
max_tries=10,
runtime_deadline: Optional[float] = None,
max_output_tokens: Optional[int] = None,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
presence_penalty: Optional[float] = None,
) -> dict[str, Any]:
max_tries = int(self.llm_generate_cfg.get("max_retries", max_tries))
if self._llm_client is None or not self._llm_api_base:
return {"status": "error", "error": "llm api error: API_BASE is not set."}
base_sleep_time = 1
last_error = "unknown llm error"
for attempt in range(max_tries):
remaining = remaining_runtime_seconds(runtime_deadline)
if remaining is not None and remaining <= 0:
last_error = "agent runtime limit reached before llm call could complete"
break
try:
if debug_enabled():
print(f"--- Attempting to call the service, try {attempt + 1}/{max_tries} ---")
request_timeout = (
min(self._llm_timeout_seconds, max(remaining, 0.001))
if remaining is not None
else self._llm_timeout_seconds
)
request_client = self._llm_client.with_options(timeout=request_timeout)
request_kwargs = dict(
model=self.model,
messages=msgs,
max_tokens=int(
max_output_tokens
if max_output_tokens is not None
else self.llm_generate_cfg.get("max_output_tokens", llm_max_output_tokens())
),
)
apply_sampling_params(
request_kwargs,
model_name=self.model,
temperature=(
temperature if temperature is not None else self.llm_generate_cfg.get("temperature", 0.6)
),
top_p=top_p if top_p is not None else self.llm_generate_cfg.get("top_p", 0.95),
presence_penalty=(
presence_penalty
if presence_penalty is not None
else self.llm_generate_cfg.get("presence_penalty", 1.1)
),
)
if include_native_tools and self._native_tools:
request_kwargs["tools"] = self._native_tools
request_kwargs["tool_choice"] = "auto"
request_kwargs["parallel_tool_calls"] = True
with llm_hard_timeout(request_timeout):
chat_response = request_client.chat.completions.create(**request_kwargs)
choice = chat_response.choices[0]
message = choice.message
content = message.content
tool_calls = [normalized_tool_call(tool_call) for tool_call in (message.tool_calls or [])]
reasoning_content = assistant_reasoning_content(message)
raw_message = safe_jsonable(message.model_dump()) if hasattr(message, "model_dump") else None
usage = safe_jsonable(chat_response.usage.model_dump()) if getattr(chat_response, "usage", None) else None
if assistant_has_meaningful_text(content) or tool_calls:
if debug_enabled():
print("--- Service call successful, received a valid response ---")
return {
"status": "ok",
"finish_reason": choice.finish_reason,
"content": content,
"tool_calls": tool_calls,
"reasoning_content": reasoning_content,
"raw_message": raw_message,
"usage": usage,
}
else:
last_error = "empty response from llm api"
if debug_enabled():
print(f"Warning: Attempt {attempt + 1} received an empty response.")
except (APIError, APIConnectionError, APITimeoutError, LLMHardTimeoutError) as e:
last_error = str(e)
if debug_enabled():
print(f"Error: Attempt {attempt + 1} failed with an API or network error: {e}")
if attempt < max_tries - 1:
sleep_time = base_sleep_time * (2 ** attempt) + random.uniform(0, 1)
sleep_time = min(sleep_time, 30)
remaining = remaining_runtime_seconds(runtime_deadline)
if remaining is not None:
if remaining <= 0:
last_error = "agent runtime limit reached before llm retry could complete"
break
sleep_time = min(sleep_time, remaining)
if debug_enabled():
print(f"Retrying in {sleep_time:.2f} seconds...")
if sleep_time > 0:
time.sleep(sleep_time)
else:
if debug_enabled():
print("Error: All retry attempts have been exhausted. The call has failed.")
return {"status": "error", "error": f"llm api error: {last_error}"}
def call_llm_api(self, msgs, max_tries=10, runtime_deadline: Optional[float] = None) -> dict[str, Any]:
return self._call_chat_completion(
msgs,
include_native_tools=True,
max_tries=max_tries,
runtime_deadline=runtime_deadline,
)
def call_compaction_api(
self,
msgs,
*,
runtime_deadline: Optional[float] = None,
max_output_tokens: Optional[int] = None,
) -> dict[str, Any]:
return self._call_chat_completion(
msgs,
include_native_tools=False,
max_tries=3,
runtime_deadline=runtime_deadline,
max_output_tokens=max_output_tokens,
temperature=0.0,
top_p=1.0,
presence_penalty=0.0,
)
def count_tokens(self, messages, *, include_tool_schema: bool = True):
image_token_estimate = int(os.getenv("IMAGE_PART_TOKEN_ESTIMATE", str(DEFAULT_IMAGE_TOKEN_ESTIMATE)))
token_count = self._native_tools_token_estimate if include_tool_schema else 0
for message in messages:
token_count += len(self._encoding.encode(message.get("role", "")))
content = message.get("content", "")
if isinstance(content, str):
token_count += len(self._encoding.encode(content))
elif isinstance(content, list):
for part in content:
if not isinstance(part, dict):
token_count += len(self._encoding.encode(str(part)))
continue
if part.get("type") == "text":
token_count += len(self._encoding.encode(str(part.get("text", ""))))
elif part.get("type") == "image_url":
token_count += image_token_estimate
else:
token_count += len(self._encoding.encode(str(part)))
else:
token_count += len(self._encoding.encode(str(content)))
tool_calls = message.get("tool_calls")
if isinstance(tool_calls, list) and tool_calls:
token_count += len(self._encoding.encode(json.dumps(tool_calls, ensure_ascii=False)))
reasoning_content = message.get("reasoning_content")
if isinstance(reasoning_content, str) and reasoning_content:
token_count += len(self._encoding.encode(reasoning_content))
elif reasoning_content is not None:
token_count += len(
self._encoding.encode(json.dumps(safe_jsonable(reasoning_content), ensure_ascii=False))
)
return token_count
def run(
self,
prompt: str,
workspace_root: Optional[str] = None,
images: Optional[str | Path | Sequence[str | Path]] = None,
) -> str:
"""Run the agent on one prompt and return only the final result text."""
resolved_workspace_root = normalize_workspace_root(
workspace_root if workspace_root is not None else self.workspace_root
)
run_prompt = prompt
initial_content_parts: list[dict[str, Any]] = []
saved_image_paths: list[str] = []
for image_index, image_path in enumerate(normalized_image_inputs(images)):
saved_path, data_url = stage_image_file_for_input(
image_path,
workspace_root=resolved_workspace_root,
image_index=image_index,
)
saved_image_paths.append(saved_path)
initial_content_parts.extend(image_input_content_parts(data_url, saved_path))
if saved_image_paths:
run_prompt = append_saved_image_paths_to_prompt(prompt, saved_image_paths)
return self._run_session(
run_prompt,
workspace_root=str(resolved_workspace_root),
initial_content_parts=initial_content_parts or None,
)["result_text"]
def _run_session(
self,
prompt: str,
workspace_root: Optional[str] = None,
event_callback: Optional[Callable[[dict[str, Any]], None]] = None,
initial_content_parts: Optional[Sequence[dict[str, Any]]] = None,
prior_messages: Optional[Sequence[dict[str, Any]]] = None,
interrupt_event: Optional[threading.Event] = None,
) -> dict:
"""Internal execution path with trace data for tests and debugging."""
if not isinstance(prompt, str) or not prompt.strip():
raise ValueError("prompt must be a non-empty string.")
prompt_text = prompt.strip()
resolved_workspace_root = normalize_workspace_root(
workspace_root if workspace_root is not None else self.workspace_root
)
start_time = time.time()
trace_dir = self.trace_dir
cur_date = today_date()
extra_blocks = [self.role_prompt] if self.role_prompt else None
system_prompt = composed_system_prompt(current_date=str(cur_date), extra_blocks=extra_blocks)
user_content = (
f"Current workspace root: {resolved_workspace_root}\n"
"Relative local file paths resolve from the workspace root.\n\n"
f"Prompt:\n{prompt_text}"
)
if initial_content_parts is not None:
if not isinstance(initial_content_parts, Sequence) or isinstance(initial_content_parts, (str, bytes)):
raise ValueError("initial_content_parts must be a sequence of OpenAI-style content part dicts.")
safe_initial_parts = safe_jsonable(list(initial_content_parts))
if not isinstance(safe_initial_parts, list) or not all(isinstance(part, dict) for part in safe_initial_parts):
raise ValueError("initial_content_parts must contain only dict content parts.")
user_content: Any = [{"type": "text", "text": user_content}, *safe_initial_parts]
continuing_conversation = prior_messages is not None
if continuing_conversation:
if not isinstance(prior_messages, Sequence) or isinstance(prior_messages, (str, bytes)):
raise ValueError("prior_messages must be a sequence of message dicts.")
safe_prior_messages = safe_jsonable(list(prior_messages))
if not isinstance(safe_prior_messages, list) or not all(isinstance(message, dict) for message in safe_prior_messages):
raise ValueError("prior_messages must contain only dict messages.")
messages = list(safe_prior_messages)
if not messages or messages[0].get("role") != "system":
messages.insert(0, {"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": user_content})
else:
messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_content}]
max_llm_calls = self.max_llm_calls
max_input_tokens = int(self.llm_generate_cfg.get("max_input_tokens", DEFAULT_MAX_INPUT_TOKENS))
max_output_tokens = int(self.llm_generate_cfg.get("max_output_tokens", llm_max_output_tokens()))
compact_trigger_tokens = self.llm_generate_cfg.get("compact_trigger_tokens")
if compact_trigger_tokens is None:
compact_trigger_tokens = os.getenv("AUTO_COMPACT_TRIGGER_TOKENS", "128k")
model_profile = resolve_model_profile(
self.model,
configured_max_input_tokens=max_input_tokens,
configured_max_output_tokens=max_output_tokens,
compact_trigger_tokens=compact_trigger_tokens,
)
agent_runtime_limit = self.max_runtime_seconds
runtime_deadline = start_time + agent_runtime_limit
num_llm_calls_available = max_llm_calls
round_index = 0
trace_writer = FlatTraceWriter(
trace_dir=trace_dir,
model_name=self.model,