-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathastr_main_agent.py
More file actions
1642 lines (1468 loc) · 62.8 KB
/
Copy pathastr_main_agent.py
File metadata and controls
1642 lines (1468 loc) · 62.8 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
from __future__ import annotations
import asyncio
import copy
import datetime
import json
import os
import platform
import zoneinfo
from collections.abc import Coroutine
from dataclasses import dataclass, field
from pathlib import Path
from astrbot.core import logger
from astrbot.core.agent.handoff import HandoffTool
from astrbot.core.agent.mcp_client import MCPTool
from astrbot.core.agent.message import TextPart
from astrbot.core.agent.tool import ToolSet
from astrbot.core.astr_agent_context import AgentContextWrapper, AstrAgentContext
from astrbot.core.astr_agent_hooks import MAIN_AGENT_HOOKS
from astrbot.core.astr_agent_run_util import AgentRunner
from astrbot.core.astr_agent_tool_exec import FunctionToolExecutor
from astrbot.core.astr_main_agent_resources import (
CHATUI_SPECIAL_DEFAULT_PERSONA_PROMPT,
LIVE_MODE_SYSTEM_PROMPT,
LLM_SAFETY_MODE_SYSTEM_PROMPT,
SANDBOX_MODE_PROMPT,
TOOL_CALL_PROMPT,
TOOL_CALL_PROMPT_SKILLS_LIKE_MODE,
)
from astrbot.core.conversation_mgr import Conversation
from astrbot.core.message.components import File, Image, Record, Reply, Video
from astrbot.core.persona_error_reply import (
extract_persona_custom_error_message_from_persona,
set_persona_custom_error_message_on_event,
)
from astrbot.core.platform.astr_message_event import AstrMessageEvent
from astrbot.core.provider import Provider
from astrbot.core.provider.entities import ProviderRequest
from astrbot.core.provider.register import llm_tools
from astrbot.core.skills.skill_manager import (
SkillInfo,
SkillManager,
build_skills_prompt,
)
from astrbot.core.star.context import Context
from astrbot.core.star.star import star_registry
from astrbot.core.star.star_handler import star_map
from astrbot.core.tools.computer_tools import (
AnnotateExecutionTool,
BrowserBatchExecTool,
BrowserExecTool,
CreateSkillCandidateTool,
CreateSkillPayloadTool,
CuaKeyboardTypeTool,
CuaMouseClickTool,
CuaScreenshotTool,
EvaluateSkillCandidateTool,
ExecuteShellTool,
FileDownloadTool,
FileEditTool,
FileReadTool,
FileUploadTool,
FileWriteTool,
GetExecutionHistoryTool,
GetSkillPayloadTool,
GrepTool,
ListSkillCandidatesTool,
ListSkillReleasesTool,
LocalPythonTool,
PromoteSkillCandidateTool,
PythonTool,
RollbackSkillReleaseTool,
RunBrowserSkillTool,
SyncSkillReleaseTool,
normalize_umo_for_workspace,
)
from astrbot.core.tools.cron_tools import FutureTaskTool
from astrbot.core.tools.knowledge_base_tools import (
KnowledgeBaseQueryTool,
retrieve_knowledge_base,
)
from astrbot.core.tools.message_tools import SendMessageToUserTool
from astrbot.core.tools.web_search_tools import (
BaiduWebSearchTool,
BochaWebSearchTool,
BraveWebSearchTool,
ExaGetContentsTool,
ExaWebSearchTool,
FirecrawlExtractWebPageTool,
FirecrawlWebSearchTool,
TavilyExtractWebPageTool,
TavilyWebSearchTool,
normalize_legacy_web_search_config,
)
from astrbot.core.utils.astrbot_path import (
get_astrbot_system_tmp_path,
get_astrbot_workspaces_path,
)
from astrbot.core.utils.file_extract import extract_file_moonshotai
from astrbot.core.utils.llm_metadata import LLM_METADATAS
from astrbot.core.utils.media_utils import (
IMAGE_COMPRESS_DEFAULT_MAX_SIZE,
IMAGE_COMPRESS_DEFAULT_QUALITY,
compress_image,
)
from astrbot.core.utils.quoted_message.settings import (
SETTINGS as DEFAULT_QUOTED_MESSAGE_SETTINGS,
)
from astrbot.core.utils.quoted_message.settings import (
QuotedMessageParserSettings,
)
from astrbot.core.utils.quoted_message_parser import (
extract_quoted_message_images,
extract_quoted_message_text,
)
from astrbot.core.utils.string_utils import normalize_and_dedupe_strings
LLM_ERROR_MESSAGE_EXTRA_KEY = "_llm_error_message"
WEEKDAY_NAMES = (
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
)
WEB_SEARCH_CITATION_TOOL_NAMES = frozenset(
{
"web_search_baidu",
"web_search_tavily",
"web_search_bocha",
"web_search_brave",
"web_search_exa",
}
)
WEB_SEARCH_CITATION_PROMPT = (
"Always cite web search results you rely on. "
"Index is a unique identifier for each search result. "
"Use the exact citation format <ref>index</ref> (e.g. <ref>abcd.3</ref>) "
"after the sentence that uses the information. Do not invent citations."
)
@dataclass(slots=True)
class MainAgentBuildConfig:
"""The main agent build configuration.
Most of the configs can be found in the cmd_config.json"""
tool_call_timeout: int
"""The timeout (in seconds) for a tool call.
When the tool call exceeds this time,
a timeout error as a tool result will be returned.
"""
tool_schema_mode: str = "full"
"""The tool schema mode, can be 'full' or 'skills-like'."""
provider_wake_prefix: str = ""
"""The wake prefix for the provider. If the user message does not start with this prefix,
the main agent will not be triggered."""
streaming_response: bool = True
"""Whether to use streaming response."""
sanitize_context_by_modalities: bool = False
"""Whether to sanitize the context based on the provider's supported modalities.
This will remove unsupported message types(e.g. image) from the context to prevent issues."""
kb_agentic_mode: bool = False
"""Whether to use agentic mode for knowledge base retrieval.
This will inject the knowledge base query tool into the main agent's toolset to allow dynamic querying."""
file_extract_enabled: bool = False
"""Whether to enable file content extraction for uploaded files."""
file_extract_prov: str = "moonshotai"
"""The file extraction provider."""
file_extract_msh_api_key: str = ""
"""The API key for Moonshot AI file extraction provider."""
context_limit_reached_strategy: str = "truncate_by_turns"
"""The strategy to handle context length limit reached."""
llm_compress_instruction: str = ""
"""The instruction for compression in llm_compress strategy."""
llm_compress_keep_recent_ratio: float = 0.15
"""Percent of current context tokens to keep as exact recent context during llm_compress strategy."""
llm_compress_provider_id: str = ""
"""The provider ID for the LLM used in context compression."""
max_context_length: int = 50
"""The maximum number of turns to keep in context. -1 means no limit.
This enforce max turns before compression"""
dequeue_context_length: int = 10
"""The number of oldest turns to remove when context length limit is reached."""
fallback_max_context_tokens: int = 128000
"""Fallback max context tokens. When max_context_tokens is 0 and the model is not in LLM_METADATAS, use this value."""
llm_safety_mode: bool = True
"""This will inject healthy and safe system prompt into the main agent,
to prevent LLM output harmful information"""
safety_mode_strategy: str = "system_prompt"
computer_use_runtime: str = "local"
"""The runtime for agent computer use: none, local, or sandbox."""
sandbox_cfg: dict = field(default_factory=dict)
add_cron_tools: bool = True
"""This will add cron job management tools to the main agent for proactive cron job execution."""
provider_settings: dict = field(default_factory=dict)
subagent_orchestrator: dict = field(default_factory=dict)
timezone: str | None = None
max_quoted_fallback_images: int = 20
"""Maximum number of images injected from quoted-message fallback extraction."""
@dataclass(slots=True)
class MainAgentBuildResult:
agent_runner: AgentRunner
provider_request: ProviderRequest
provider: Provider
reset_coro: Coroutine | None = None
def _set_llm_error_message(event: AstrMessageEvent, message: str) -> None:
event.set_extra(LLM_ERROR_MESSAGE_EXTRA_KEY, message)
def _select_provider(
event: AstrMessageEvent, plugin_context: Context
) -> Provider | None:
"""Select chat provider for the event."""
sel_provider = event.get_extra("selected_provider")
if sel_provider and isinstance(sel_provider, str):
provider = plugin_context.get_provider_by_id(sel_provider)
if provider is None:
logger.error("未找到指定的提供商: %s。", sel_provider)
_set_llm_error_message(
event,
f"LLM 请求失败:未找到指定的提供商 `{sel_provider}`。请检查提供商配置或重新选择可用模型。",
)
return None
if not isinstance(provider, Provider):
logger.error(
"选择的提供商类型无效(%s),跳过 LLM 请求处理。", type(provider)
)
_set_llm_error_message(
event,
f"LLM 请求失败:选择的提供商类型无效({type(provider).__name__}),已跳过本次请求。",
)
return None
return provider
try:
return plugin_context.get_using_provider(umo=event.unified_msg_origin)
except ValueError as exc:
logger.error("Error occurred while selecting provider: %s", exc)
_set_llm_error_message(event, f"LLM 请求失败:{exc}")
return None
async def _get_session_conv(
event: AstrMessageEvent, plugin_context: Context
) -> Conversation:
conv_mgr = plugin_context.conversation_manager
umo = event.unified_msg_origin
cid = await conv_mgr.get_curr_conversation_id(umo)
if not cid:
cid = await conv_mgr.new_conversation(umo, event.get_platform_id())
conversation = await conv_mgr.get_conversation(umo, cid)
if not conversation:
cid = await conv_mgr.new_conversation(umo, event.get_platform_id())
conversation = await conv_mgr.get_conversation(umo, cid)
if not conversation:
raise RuntimeError("无法创建新的对话。")
return conversation
async def _apply_kb(
event: AstrMessageEvent,
req: ProviderRequest,
plugin_context: Context,
config: MainAgentBuildConfig,
) -> None:
if not config.kb_agentic_mode:
if req.prompt is None or not req.prompt.strip():
return
try:
kb_result = await retrieve_knowledge_base(
query=req.prompt,
umo=event.unified_msg_origin,
context=plugin_context,
)
if not kb_result:
return
req.extra_user_content_parts.append(
TextPart(
text=f"[Related Knowledge Base Results]:\n{kb_result}",
).mark_as_temp()
)
except Exception as exc: # noqa: BLE001
logger.error("Error occurred while retrieving knowledge base: %s", exc)
else:
if req.func_tool is None:
req.func_tool = ToolSet()
req.func_tool.add_tool(
plugin_context.get_llm_tool_manager().get_builtin_tool(
KnowledgeBaseQueryTool
)
)
async def _apply_file_extract(
event: AstrMessageEvent,
req: ProviderRequest,
config: MainAgentBuildConfig,
) -> None:
file_paths = []
file_names = []
for comp in event.message_obj.message:
if isinstance(comp, File):
file_paths.append(await comp.get_file())
file_names.append(comp.name)
elif isinstance(comp, Reply) and comp.chain:
for reply_comp in comp.chain:
if isinstance(reply_comp, File):
file_paths.append(await reply_comp.get_file())
file_names.append(reply_comp.name)
if not file_paths:
return
if not req.prompt:
req.prompt = "总结一下文件里面讲了什么?"
if config.file_extract_prov == "moonshotai":
if not config.file_extract_msh_api_key:
logger.error("Moonshot AI API key for file extract is not set")
return
file_contents = await asyncio.gather(
*[
extract_file_moonshotai(
file_path,
config.file_extract_msh_api_key,
)
for file_path in file_paths
]
)
else:
logger.error("Unsupported file extract provider: %s", config.file_extract_prov)
return
for file_content, file_name in zip(file_contents, file_names):
req.contexts.append(
{
"role": "system",
"content": (
"File Extract Results of user uploaded files:\n"
f"{file_content}\nFile Name: {file_name or 'Unknown'}"
),
},
)
def _apply_prompt_prefix(req: ProviderRequest, cfg: dict) -> None:
prefix = cfg.get("prompt_prefix")
if not prefix:
return
if "{{prompt}}" in prefix:
req.prompt = prefix.replace("{{prompt}}", req.prompt)
else:
req.prompt = f"{prefix}{req.prompt}"
def _get_workspace_path_for_umo(umo: str) -> Path:
normalized_umo = normalize_umo_for_workspace(umo)
return Path(get_astrbot_workspaces_path()) / normalized_umo
def _apply_workspace_extra_prompt(
event: AstrMessageEvent,
req: ProviderRequest,
) -> None:
extra_prompt_path = _get_workspace_path_for_umo(event.unified_msg_origin) / (
"EXTRA_PROMPT.md"
)
if not extra_prompt_path.is_file():
return
try:
extra_prompt = extra_prompt_path.read_text(encoding="utf-8").strip()
except Exception as exc: # noqa: BLE001
logger.warning(
"Failed to read workspace extra prompt for umo=%s from %s: %s",
event.unified_msg_origin,
extra_prompt_path,
exc,
)
return
if not extra_prompt:
return
req.system_prompt = (
f"{req.system_prompt or ''}\n"
"[Workspace Extra Prompt]\n"
"The following instructions are loaded from the current workspace "
"`EXTRA_PROMPT.md` file.\n"
f"{extra_prompt}\n"
)
def _apply_local_env_tools(req: ProviderRequest, plugin_context: Context) -> None:
if req.func_tool is None:
req.func_tool = ToolSet()
tool_mgr = plugin_context.get_llm_tool_manager()
req.func_tool.add_tool(tool_mgr.get_builtin_tool(ExecuteShellTool))
req.func_tool.add_tool(tool_mgr.get_builtin_tool(LocalPythonTool))
req.func_tool.add_tool(tool_mgr.get_builtin_tool(FileReadTool))
req.func_tool.add_tool(tool_mgr.get_builtin_tool(FileWriteTool))
req.func_tool.add_tool(tool_mgr.get_builtin_tool(FileEditTool))
req.func_tool.add_tool(tool_mgr.get_builtin_tool(GrepTool))
req.system_prompt = f"{req.system_prompt or ''}\n{_build_local_mode_prompt()}\n"
def _build_local_mode_prompt() -> str:
system_name = platform.system() or "Unknown"
shell_hint = (
"The runtime shell is Windows Command Prompt (cmd.exe). "
"Use cmd-compatible commands and do not assume Unix commands like cat/ls/grep are available."
if system_name.lower() == "windows"
else "The runtime shell is Unix-like. Use POSIX-compatible shell commands."
)
return (
"You have access to the host local environment and can execute shell commands and Python code. "
f"Current operating system: {system_name}. "
f"{shell_hint}"
)
def _filter_skills_for_current_config(
skills: list[SkillInfo],
cfg: dict,
) -> list[SkillInfo]:
plugin_set = cfg.get("plugin_set", ["*"])
allowed_plugins = (
None
if not isinstance(plugin_set, list) or "*" in plugin_set
else {str(name) for name in plugin_set}
)
plugin_by_root_dir = {
metadata.root_dir_name: metadata
for metadata in star_registry
if metadata.root_dir_name
}
filtered: list[SkillInfo] = []
for skill in skills:
if skill.source_type != "plugin":
filtered.append(skill)
continue
plugin = plugin_by_root_dir.get(skill.plugin_name)
if not plugin or not plugin.activated:
continue
if plugin.reserved or allowed_plugins is None:
filtered.append(skill)
continue
if plugin.name is not None and plugin.name in allowed_plugins:
filtered.append(skill)
return filtered
async def _ensure_persona_and_skills(
req: ProviderRequest,
cfg: dict,
plugin_context: Context,
event: AstrMessageEvent,
) -> None:
"""Ensure persona and skills are applied to the request's system prompt or user prompt."""
if not req.conversation:
return
(
persona_id,
persona,
_,
use_webchat_special_default,
) = await plugin_context.persona_manager.resolve_selected_persona(
umo=event.unified_msg_origin,
conversation_persona_id=req.conversation.persona_id,
platform_name=event.get_platform_name(),
provider_settings=cfg,
)
set_persona_custom_error_message_on_event(
event, extract_persona_custom_error_message_from_persona(persona)
)
if req.system_prompt is None:
req.system_prompt = ""
if persona:
# Inject persona system prompt
if prompt := persona["prompt"]:
req.system_prompt += f"\n# Persona Instructions\n\n{prompt}\n"
if begin_dialogs := copy.deepcopy(persona.get("_begin_dialogs_processed")):
req.contexts[:0] = begin_dialogs
elif use_webchat_special_default:
req.system_prompt += CHATUI_SPECIAL_DEFAULT_PERSONA_PROMPT
# Inject skills prompt
runtime = cfg.get("computer_use_runtime", "local")
skill_manager = SkillManager()
skills = skill_manager.list_skills(active_only=True, runtime=runtime)
skills = _filter_skills_for_current_config(skills, cfg)
workspace_skills = []
if runtime == "local" and not event.get_group_id():
workspace_skills = skill_manager.list_workspace_skills(
_get_workspace_path_for_umo(event.unified_msg_origin)
)
if skills or workspace_skills:
if persona and persona.get("skills") is not None:
if not persona["skills"]:
skills = []
else:
allowed = set(persona["skills"])
skills = [skill for skill in skills if skill.name in allowed]
if workspace_skills and (not persona or persona.get("skills") != []):
skills_by_name = {skill.name: skill for skill in skills}
for skill in workspace_skills:
skills_by_name[skill.name] = skill
skills = [skills_by_name[name] for name in sorted(skills_by_name)]
if skills:
req.system_prompt += f"\n{build_skills_prompt(skills)}\n"
if runtime == "none":
req.system_prompt += (
"User has not enabled the Computer Use feature. "
"You cannot use shell or Python to perform skills. "
"If you need to use these capabilities, ask the user to enable Computer Use in the AstrBot WebUI -> Config."
)
tmgr = plugin_context.get_llm_tool_manager()
# inject toolset in the persona
if (persona and persona.get("tools") is None) or not persona:
persona_toolset = tmgr.get_full_tool_set()
for tool in list(persona_toolset):
if not tool.active:
persona_toolset.remove_tool(tool.name)
else:
persona_toolset = ToolSet()
if persona["tools"]:
for tool_name in persona["tools"]:
tool = tmgr.get_func(tool_name)
if tool and tool.active:
persona_toolset.add_tool(tool)
if not req.func_tool:
req.func_tool = persona_toolset
else:
req.func_tool.merge(persona_toolset)
# sub agents integration
orch_cfg = plugin_context.get_config().get("subagent_orchestrator", {})
so = plugin_context.subagent_orchestrator
if orch_cfg.get("main_enable", False) and so:
remove_dup = bool(orch_cfg.get("remove_main_duplicate_tools", False))
assigned_tools: set[str] = set()
agents = orch_cfg.get("agents", [])
if isinstance(agents, list):
for a in agents:
if not isinstance(a, dict):
continue
if a.get("enabled", True) is False:
continue
persona_tools = None
pid = a.get("persona_id")
if pid:
persona = plugin_context.persona_manager.get_persona_v3_by_id(pid)
if persona is not None:
persona_tools = persona.get("tools")
tools = a.get("tools", [])
if persona_tools is not None:
tools = persona_tools
if tools is None:
assigned_tools.update(
[
tool.name
for tool in tmgr.func_list
if not isinstance(tool, HandoffTool)
]
)
continue
if not isinstance(tools, list):
continue
for t in tools:
name = str(t).strip()
if name:
assigned_tools.add(name)
if req.func_tool is None:
req.func_tool = ToolSet()
# add subagent handoff tools
for tool in so.handoffs:
req.func_tool.add_tool(tool)
# check duplicates
if remove_dup:
handoff_names = {tool.name for tool in so.handoffs}
for tool_name in assigned_tools:
if tool_name in handoff_names:
continue
req.func_tool.remove_tool(tool_name)
router_prompt = (
plugin_context.get_config()
.get("subagent_orchestrator", {})
.get("router_system_prompt", "")
).strip()
if router_prompt:
req.system_prompt += f"\n{router_prompt}\n"
try:
event.trace.record(
"sel_persona",
persona_id=persona_id,
persona_toolset=persona_toolset.names(),
)
except Exception:
pass
async def _request_img_caption(
provider_id: str,
cfg: dict,
image_urls: list[str],
plugin_context: Context,
) -> str:
prov = plugin_context.get_provider_by_id(provider_id)
if prov is None:
raise ValueError(
f"Cannot get image caption because provider `{provider_id}` is not exist.",
)
if not isinstance(prov, Provider):
raise ValueError(
f"Cannot get image caption because provider `{provider_id}` is not a valid Provider, it is {type(prov)}.",
)
img_cap_prompt = cfg.get(
"image_caption_prompt",
"Please describe the image.",
)
logger.debug("Processing image caption with provider: %s", provider_id)
llm_resp = await prov.text_chat(
prompt=img_cap_prompt,
image_urls=image_urls,
)
return llm_resp.completion_text
async def _ensure_img_caption(
event: AstrMessageEvent,
req: ProviderRequest,
cfg: dict,
plugin_context: Context,
image_caption_provider: str,
) -> None:
try:
compressed_urls = []
for url in req.image_urls:
compressed_url = await _compress_image_for_provider(url, cfg)
compressed_urls.append(compressed_url)
if _is_generated_compressed_image_path(url, compressed_url):
event.track_temporary_local_file(compressed_url)
caption = await _request_img_caption(
image_caption_provider,
cfg,
compressed_urls,
plugin_context,
)
if caption:
req.extra_user_content_parts.append(
TextPart(text=f"<image_caption>{caption}</image_caption>")
)
req.image_urls = []
except Exception as exc: # noqa: BLE001
logger.error("处理图片描述失败: %s", exc)
req.extra_user_content_parts.append(TextPart(text="[Image Captioning Failed]"))
finally:
req.image_urls = []
def _append_quoted_image_attachment(req: ProviderRequest, image_path: str) -> None:
req.extra_user_content_parts.append(
TextPart(text=f"[Image Attachment in quoted message: path {image_path}]")
)
def _append_audio_attachment(req: ProviderRequest, audio_path: str) -> None:
req.extra_user_content_parts.append(
TextPart(text=f"[Audio Attachment: path {audio_path}]")
)
def _append_quoted_audio_attachment(req: ProviderRequest, audio_path: str) -> None:
req.extra_user_content_parts.append(
TextPart(text=f"[Audio Attachment in quoted message: path {audio_path}]")
)
async def _append_video_attachment(
req: ProviderRequest,
video: Video,
*,
quoted: bool = False,
) -> None:
try:
video_path = await video.convert_to_file_path()
except Exception as exc: # noqa: BLE001
if quoted:
logger.debug(
"Quoted video attachment is not locally resolvable, preserving ref: %s",
exc,
)
video_ref = video.path or video.url or video.file or ""
ref_name = os.path.basename(video_ref.split("?", 1)[0].rstrip("/"))
req.extra_user_content_parts.append(
TextPart(
text=(
"[Video Attachment in quoted message: "
f"name {ref_name or 'video'}, ref {video_ref}]"
)
)
)
else:
logger.error("Error processing video attachment: %s", exc)
return
video_name = os.path.basename(video_path)
if quoted:
text = (
f"[Video Attachment in quoted message: "
f"name {video_name}, path {video_path}]"
)
else:
text = f"[Video Attachment: name {video_name}, path {video_path}]"
req.extra_user_content_parts.append(TextPart(text=text))
def _get_quoted_message_parser_settings(
provider_settings: dict[str, object] | None,
) -> QuotedMessageParserSettings:
if not isinstance(provider_settings, dict):
return DEFAULT_QUOTED_MESSAGE_SETTINGS
overrides = provider_settings.get("quoted_message_parser")
if not isinstance(overrides, dict):
return DEFAULT_QUOTED_MESSAGE_SETTINGS
return DEFAULT_QUOTED_MESSAGE_SETTINGS.with_overrides(overrides)
def _get_image_compress_args(
provider_settings: dict[str, object] | None,
) -> tuple[bool, int, int]:
if not isinstance(provider_settings, dict):
return True, IMAGE_COMPRESS_DEFAULT_MAX_SIZE, IMAGE_COMPRESS_DEFAULT_QUALITY
enabled = provider_settings.get("image_compress_enabled", True)
if not isinstance(enabled, bool):
enabled = True
raw_options = provider_settings.get("image_compress_options", {})
options = raw_options if isinstance(raw_options, dict) else {}
max_size = options.get("max_size", IMAGE_COMPRESS_DEFAULT_MAX_SIZE)
if not isinstance(max_size, int):
max_size = IMAGE_COMPRESS_DEFAULT_MAX_SIZE
max_size = max(max_size, 1)
quality = options.get("quality", IMAGE_COMPRESS_DEFAULT_QUALITY)
if not isinstance(quality, int):
quality = IMAGE_COMPRESS_DEFAULT_QUALITY
quality = min(max(quality, 1), 100)
return enabled, max_size, quality
async def _compress_image_for_provider(
url_or_path: str,
provider_settings: dict[str, object] | None,
) -> str:
try:
enabled, max_size, quality = _get_image_compress_args(provider_settings)
if not enabled:
return url_or_path
return await compress_image(url_or_path, max_size=max_size, quality=quality)
except Exception as exc: # noqa: BLE001
logger.error("Image compression failed: %s", exc)
return url_or_path
def _is_generated_compressed_image_path(
original_path: str,
compressed_path: str | None,
) -> bool:
if not compressed_path or compressed_path == original_path:
return False
if compressed_path.startswith("http") or compressed_path.startswith("data:image"):
return False
return os.path.exists(compressed_path)
async def _process_quote_message(
event: AstrMessageEvent,
req: ProviderRequest,
img_cap_prov_id: str,
plugin_context: Context,
quoted_message_settings: QuotedMessageParserSettings = DEFAULT_QUOTED_MESSAGE_SETTINGS,
config: MainAgentBuildConfig | None = None,
main_provider_supports_image: bool = False,
skip_quote_image_caption: bool = False,
) -> None:
quote = None
for comp in event.message_obj.message:
if isinstance(comp, Reply):
quote = comp
break
if not quote:
return
content_parts = []
sender_info = f"({quote.sender_nickname}): " if quote.sender_nickname else ""
message_str = (
await extract_quoted_message_text(
event,
quote,
settings=quoted_message_settings,
)
or quote.message_str
or "[Empty Text]"
)
content_parts.append(f"{sender_info}{message_str}")
image_seg = None
if quote.chain:
for comp in quote.chain:
if isinstance(comp, Image):
image_seg = comp
break
if image_seg:
if skip_quote_image_caption:
logger.debug(
"Skipping quote image captioning because image captioning already handled this request."
)
elif main_provider_supports_image:
logger.debug(
"Skipping quote image captioning because the main provider supports image input."
)
elif not img_cap_prov_id:
logger.debug(
"No dedicated image caption provider configured. "
"Skipping quote image captioning."
)
else:
try:
prov = None
path = None
compress_path = None
prov = plugin_context.get_provider_by_id(img_cap_prov_id)
if prov is None:
prov = plugin_context.get_using_provider(event.unified_msg_origin)
if prov and isinstance(prov, Provider):
path = await image_seg.convert_to_file_path()
compress_path = await _compress_image_for_provider(
path,
config.provider_settings if config else None,
)
if path and _is_generated_compressed_image_path(
path, compress_path
):
event.track_temporary_local_file(compress_path)
llm_resp = await prov.text_chat(
prompt="Please describe the image content.",
image_urls=[compress_path],
)
if llm_resp.completion_text:
content_parts.append(
f"[Image Caption in quoted message]: {llm_resp.completion_text}"
)
else:
logger.warning("No provider found for image captioning in quote.")
except BaseException as exc:
logger.error("处理引用图片失败: %s", exc)
finally:
if (
compress_path
and compress_path != path
and os.path.exists(compress_path)
):
try:
os.remove(compress_path)
except Exception as exc: # noqa: BLE001
logger.warning(
"Fail to remove temporary compressed image: %s", exc
)
quoted_content = "\n".join(content_parts)
quoted_text = f"<Quoted Message>\n{quoted_content}\n</Quoted Message>"
req.extra_user_content_parts.append(TextPart(text=quoted_text))
def _append_system_reminders(
event: AstrMessageEvent,
req: ProviderRequest,
cfg: dict,
timezone: str | None,
) -> None:
system_parts: list[str] = []
if cfg.get("identifier"):
user_id = event.message_obj.sender.user_id
user_nickname = event.message_obj.sender.nickname
system_parts.append(f"User ID: {user_id}, Nickname: {user_nickname}")
if cfg.get("group_name_display") and event.message_obj.group_id:
if not event.message_obj.group:
logger.error(
"Group name display enabled but group object is None. Group ID: %s",
event.message_obj.group_id,
)
else:
group_name = event.message_obj.group.group_name
if group_name:
system_parts.append(f"Group name: {group_name}")
if cfg.get("datetime_system_prompt"):
now = None
if timezone:
try:
now = datetime.datetime.now(zoneinfo.ZoneInfo(timezone))
except Exception as exc: # noqa: BLE001
logger.error("时区设置错误: %s, 使用本地时区", exc)
if now is None:
now = datetime.datetime.now().astimezone()
current_time = now.strftime("%Y-%m-%d %H:%M (%Z)")
weekday = WEEKDAY_NAMES[now.weekday()]
system_parts.append(f"Current datetime: {current_time}, Weekday: {weekday}")
if system_parts:
system_content = (
"<system_reminder>" + "\n".join(system_parts) + "</system_reminder>"
)
req.extra_user_content_parts.append(TextPart(text=system_content))
async def _decorate_llm_request(
event: AstrMessageEvent,
req: ProviderRequest,
plugin_context: Context,
config: MainAgentBuildConfig,
provider: Provider | None = None,
) -> None:
cfg = config.provider_settings or plugin_context.get_config(
umo=event.unified_msg_origin
).get("provider_settings", {})
_apply_prompt_prefix(req, cfg)
main_provider_supports_image = provider is not None and _provider_supports_modality(
provider, "image"
)
img_cap_prov_id: str = cfg.get("default_image_caption_provider_id") or ""
quote_images_already_captioned = False
if req.conversation:
await _ensure_persona_and_skills(req, cfg, plugin_context, event)
if img_cap_prov_id and req.image_urls and not main_provider_supports_image:
await _ensure_img_caption(
event,
req,
cfg,
plugin_context,
img_cap_prov_id,
)
quote_images_already_captioned = True
quoted_message_settings = _get_quoted_message_parser_settings(cfg)
await _process_quote_message(
event,
req,
img_cap_prov_id,
plugin_context,
quoted_message_settings,
config,
main_provider_supports_image=main_provider_supports_image,
skip_quote_image_caption=quote_images_already_captioned,
)
tz = config.timezone
if tz is None:
tz = plugin_context.get_config().get("timezone")
_append_system_reminders(event, req, cfg, tz)
_apply_workspace_extra_prompt(event, req)
def _plugin_tool_fix(event: AstrMessageEvent, req: ProviderRequest) -> None:
"""根据事件中的插件设置,过滤请求中的工具列表。
注意:没有 handler_module_path 的工具(如 MCP 工具)会被保留,
因为它们不属于任何插件,不应被插件过滤逻辑影响。
"""
if event.plugins_name is not None and req.func_tool:
new_tool_set = ToolSet()