-
Notifications
You must be signed in to change notification settings - Fork 670
Expand file tree
/
Copy pathagent_service.py
More file actions
2269 lines (1964 loc) · 87.9 KB
/
Copy pathagent_service.py
File metadata and controls
2269 lines (1964 loc) · 87.9 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 asyncio
import json
import logging
import os
import uuid
from collections import deque
from typing import Callable, Optional, Dict
from fastapi import Header, Request
from fastapi.responses import JSONResponse, StreamingResponse
from nexent.core.agents.run_agent import agent_run
from nexent.memory.memory_service import clear_memory, add_memory_in_levels
from jinja2 import Template
from agents.agent_run_manager import agent_run_manager
from agents.create_agent_info import create_agent_run_info, create_tool_config_list
from agents.preprocess_manager import preprocess_manager
from services.agent_version_service import publish_version_impl
from utils.prompt_template_utils import normalize_prompt_generate_template_content
from consts.const import MEMORY_SEARCH_START_MSG, MEMORY_SEARCH_DONE_MSG, MEMORY_SEARCH_FAIL_MSG, TOOL_TYPE_MAPPING, \
LANGUAGE, MESSAGE_ROLE, MODEL_CONFIG_MAPPING, CAN_EDIT_ALL_USER_ROLES, PERMISSION_EDIT, PERMISSION_READ, PERMISSION_PRIVATE
from consts.exceptions import MemoryPreparationException
from consts.agent_unavailable_reasons import AgentUnavailableReason
from consts.model import (
AgentInfoRequest,
AgentRequest,
AgentNameBatchCheckRequest,
AgentNameBatchRegenerateRequest,
ExportAndImportAgentInfo,
ExportAndImportDataFormat,
MCPInfo,
SkillInstanceInfoRequest,
ToolInstanceInfoRequest,
ToolSourceEnum, ModelConnectStatusEnum
)
from database.agent_db import (
create_agent,
delete_agent_by_id,
delete_agent_relationship,
delete_related_agent,
insert_related_agent,
query_all_agent_info_by_tenant_id,
query_sub_agents_id_list,
search_agent_id_by_agent_name,
search_agent_info_by_agent_id,
search_blank_sub_agent_by_main_agent_id,
update_agent,
update_related_agents,
clear_agent_new_mark
)
from database import a2a_agent_db
from database.model_management_db import get_model_by_model_id, get_model_id_by_display_name
from database.remote_mcp_db import get_mcp_server_by_name_and_tenant
from database.tool_db import (
check_tool_is_available,
create_or_update_tool_by_tool_info,
delete_tools_by_agent_id,
query_all_enabled_tool_instances,
query_all_tools,
query_tool_instances_by_id,
query_tool_instances_by_agent_id,
search_tools_for_sub_agent
)
from database import skill_db
from database.agent_version_db import query_version_list
from database.group_db import query_group_ids_by_user
from database.user_tenant_db import get_user_tenant_by_user_id
from database.a2a_agent_db import get_server_agent_ids
from services.prompt_template_service import (
SYSTEM_PROMPT_TEMPLATE_ID,
SYSTEM_PROMPT_TEMPLATE_NAME,
get_prompt_template_summary,
)
from utils.str_utils import convert_list_to_string, convert_string_to_list
from services.conversation_management_service import save_conversation_assistant, save_conversation_user
from services.memory_config_service import build_memory_context
from utils.auth_utils import get_current_user_info, get_user_language
from utils.config_utils import tenant_config_manager
from utils.memory_utils import build_memory_config
from utils.thread_utils import submit
from utils.prompt_template_utils import get_prompt_generate_prompt_template
from utils.llm_utils import call_llm_for_system_prompt
# Monitoring utilities: expose monitoring context for downstream observers
from nexent.monitor import set_monitoring_context
# Import monitoring utilities
from utils.monitoring import monitoring_manager
logger = logging.getLogger(__name__)
# -------------------------------------------------------------
# Internal helper functions
# -------------------------------------------------------------
def _resolve_user_tenant_language(
authorization: str,
http_request: Request | None = None,
user_id: str | None = None,
tenant_id: str | None = None,
):
"""Resolve user_id, tenant_id, language with optional overrides.
If user_id and tenant_id are provided, do not parse from authorization again.
"""
if user_id is None or tenant_id is None:
return get_current_user_info(authorization, http_request)
else:
return user_id, tenant_id, get_user_language(http_request)
def _get_user_group_ids(user_id: str, tenant_id: str) -> str:
"""
Get user's group IDs as a comma-separated string.
Args:
user_id: User ID
tenant_id: Tenant ID
Returns:
Comma-separated string of group IDs
"""
try:
group_ids = query_group_ids_by_user(user_id)
return convert_list_to_string(group_ids)
except Exception as e:
logger.warning(
f"Failed to get user groups for user {user_id}: {str(e)}")
return ""
def _resolve_model_with_fallback(
model_display_name: str | None,
exported_model_id: str | None,
model_label: str,
tenant_id: str
) -> str | None:
"""
Resolve model_id from model_display_name with fallback to quick config LLM model.
Args:
model_display_name: Display name of the model to lookup
exported_model_id: Original model_id from export (for logging only)
model_label: Label for logging (e.g., "Model", "Business logic model")
tenant_id: Tenant ID for model lookup
Returns:
Resolved model_id or None if not found and no fallback available
"""
if not model_display_name:
return None
# Try to find model by display name in current tenant
resolved_id = get_model_id_by_display_name(model_display_name, tenant_id)
if resolved_id:
logger.info(
f"{model_label} '{model_display_name}' found in tenant {tenant_id}, "
f"mapped to model_id: {resolved_id} (exported model_id was: {exported_model_id})")
return resolved_id
# Model not found, try fallback to quick config LLM model
logger.warning(
f"{model_label} '{model_display_name}' (exported model_id: {exported_model_id}) "
f"not found in tenant {tenant_id}, falling back to quick config LLM model.")
quick_config_model = tenant_config_manager.get_model_config(
key=MODEL_CONFIG_MAPPING["llm"],
tenant_id=tenant_id
)
if quick_config_model:
fallback_id = quick_config_model.get("model_id")
logger.info(
f"Using quick config LLM model for {model_label.lower()}: "
f"{quick_config_model.get('display_name')} (model_id: {fallback_id})")
return fallback_id
logger.warning(f"No quick config LLM model found for tenant {tenant_id}")
return None
def _normalize_language_key(language: str) -> str:
normalized = (language or "").lower()
if normalized.startswith(LANGUAGE["ZH"]):
return LANGUAGE["ZH"]
return LANGUAGE["EN"]
def _render_prompt_template(template_str: str, **context) -> str:
if not template_str:
return ""
try:
return Template(template_str).render(**context).strip()
except Exception as exc:
logger.warning(f"Failed to render prompt template: {exc}")
return template_str
def _format_existing_values(values: set[str], language: str) -> str:
if not values:
return "无" if _normalize_language_key(language) == LANGUAGE["ZH"] else "None"
return ", ".join(sorted(values))
def _check_agent_value_duplicate(
field_key: str,
value: str,
tenant_id: str,
exclude_agent_id: int | None = None,
agents_cache: list[dict] | None = None
) -> bool:
if not value:
return False
if agents_cache is None:
agents_cache = query_all_agent_info_by_tenant_id(tenant_id)
for agent in agents_cache:
if exclude_agent_id and agent.get("agent_id") == exclude_agent_id:
continue
if agent.get(field_key) == value:
return True
return False
def _check_agent_name_duplicate(
name: str,
tenant_id: str,
exclude_agent_id: int | None = None,
agents_cache: list[dict] | None = None
) -> bool:
return _check_agent_value_duplicate(
"name",
name,
tenant_id=tenant_id,
exclude_agent_id=exclude_agent_id,
agents_cache=agents_cache
)
def _check_agent_display_name_duplicate(
display_name: str,
tenant_id: str,
exclude_agent_id: int | None = None,
agents_cache: list[dict] | None = None
) -> bool:
return _check_agent_value_duplicate(
"display_name",
display_name,
tenant_id=tenant_id,
exclude_agent_id=exclude_agent_id,
agents_cache=agents_cache
)
def _generate_unique_value_with_suffix(
base_value: str,
*,
tenant_id: str,
duplicate_check_fn: Callable[..., bool],
agents_cache: list[dict] | None = None,
exclude_agent_id: int | None = None,
max_suffix_attempts: int = 100
) -> str:
counter = 1
while counter <= max_suffix_attempts:
candidate = f"{base_value}_{counter}"
if not duplicate_check_fn(
candidate,
tenant_id=tenant_id,
exclude_agent_id=exclude_agent_id,
agents_cache=agents_cache
):
return candidate
counter += 1
raise ValueError("Failed to generate unique value after max attempts")
def _generate_unique_agent_name_with_suffix(
base_value: str,
tenant_id: str,
agents_cache: list[dict] | None = None,
exclude_agent_id: int | None = None
) -> str:
return _generate_unique_value_with_suffix(
base_value,
tenant_id=tenant_id,
duplicate_check_fn=_check_agent_name_duplicate,
agents_cache=agents_cache,
exclude_agent_id=exclude_agent_id
)
def _generate_unique_display_name_with_suffix(
base_value: str,
tenant_id: str,
agents_cache: list[dict] | None = None,
exclude_agent_id: int | None = None
) -> str:
return _generate_unique_value_with_suffix(
base_value,
tenant_id=tenant_id,
duplicate_check_fn=_check_agent_display_name_duplicate,
agents_cache=agents_cache,
exclude_agent_id=exclude_agent_id
)
def _regenerate_agent_value_with_llm(
*,
original_value: str,
existing_values: list[str],
task_description: str,
model_id: int,
tenant_id: str,
language: str,
system_prompt_key: str,
user_prompt_key: str,
default_system_prompt: str,
default_user_prompt_builder: Callable[[dict], str],
fallback_fn: Callable[[str], str],
prompt_template_id: Optional[int] = None,
user_id: Optional[str] = None,
) -> str:
"""
Shared helper to regenerate agent-related values with an LLM.
"""
if user_id is not None:
from services.prompt_template_service import resolve_prompt_generate_template
prompt_template = resolve_prompt_generate_template(
tenant_id=tenant_id,
user_id=user_id,
language=language,
prompt_template_id=prompt_template_id,
)
else:
prompt_template = normalize_prompt_generate_template_content(
get_prompt_generate_prompt_template(language)
)
system_prompt = _render_prompt_template(
prompt_template.get(system_prompt_key, ""),
original_value=original_value
)
user_prompt_template = prompt_template.get(user_prompt_key, "")
value_set = {value for value in existing_values if value}
context = {
"task_description": task_description or "",
"original_value": original_value,
"existing_values": _format_existing_values(value_set, language)
}
user_prompt = _render_prompt_template(user_prompt_template, **context)
if not system_prompt:
system_prompt = default_system_prompt
if not user_prompt:
user_prompt = default_user_prompt_builder(context)
max_attempts = 5
last_error: Exception | None = None
for attempt in range(1, max_attempts + 1):
try:
regenerated_value = call_llm_for_system_prompt(
model_id=model_id,
user_prompt=user_prompt,
system_prompt=system_prompt,
callback=None,
tenant_id=tenant_id
)
candidate = (regenerated_value or "").strip().splitlines()[0].strip()
if candidate in value_set:
raise ValueError(f"Generated duplicate value '{candidate}'")
return candidate
except Exception as exc:
last_error = exc
logger.warning(
f"Attempt {attempt}/{max_attempts} to regenerate value failed: {exc}"
)
logger.error(
"Failed to regenerate agent value with LLM after maximum retries",
exc_info=last_error
)
return fallback_fn(original_value)
def _regenerate_agent_name_with_llm(
original_name: str,
existing_names: list[str],
task_description: str,
model_id: int,
tenant_id: str,
language: str = LANGUAGE["ZH"],
agents_cache: list[dict] | None = None,
exclude_agent_id: int | None = None,
prompt_template_id: Optional[int] = None,
user_id: Optional[str] = None,
) -> str:
return _regenerate_agent_value_with_llm(
original_value=original_name,
existing_values=existing_names,
task_description=task_description,
model_id=model_id,
tenant_id=tenant_id,
language=language,
system_prompt_key="agent_name_regenerate_system_prompt",
user_prompt_key="agent_name_regenerate_user_prompt",
default_system_prompt=(
"You refine agent variable names so that they stay close to the "
"original meaning and remain unique within the tenant."
),
default_user_prompt_builder=lambda ctx: (
f"### Task Description:\n{ctx['task_description']}\n\n"
f"### Original Name:\n{ctx['original_value']}\n\n"
f"### Existing Names:\n{ctx['existing_values']}\n\n"
"Generate a concise Python variable name that keeps the same "
"meaning and does not duplicate the existing names. Return only "
"the variable name."
),
fallback_fn=lambda base_value: _generate_unique_agent_name_with_suffix(
base_value,
tenant_id=tenant_id,
agents_cache=agents_cache,
exclude_agent_id=exclude_agent_id
),
prompt_template_id=prompt_template_id,
user_id=user_id,
)
def _regenerate_agent_display_name_with_llm(
original_display_name: str,
existing_display_names: list[str],
task_description: str,
model_id: int,
tenant_id: str,
language: str = LANGUAGE["ZH"],
agents_cache: list[dict] | None = None,
exclude_agent_id: int | None = None,
prompt_template_id: Optional[int] = None,
user_id: Optional[str] = None,
) -> str:
return _regenerate_agent_value_with_llm(
original_value=original_display_name,
existing_values=existing_display_names,
task_description=task_description,
model_id=model_id,
tenant_id=tenant_id,
language=language,
system_prompt_key="agent_display_name_regenerate_system_prompt",
user_prompt_key="agent_display_name_regenerate_user_prompt",
default_system_prompt=(
"You refine agent display names so they remain unique, concise, "
"and aligned with the agent's capability."
),
default_user_prompt_builder=lambda ctx: (
f"### Task Description:\n{ctx['task_description']}\n\n"
f"### Original Display Name:\n{ctx['original_value']}\n\n"
f"### Existing Display Names:\n{ctx['existing_values']}\n\n"
"Generate a new display name that keeps the same meaning but does "
"not duplicate existing names. Return only the display name."
),
fallback_fn=lambda base_value: _generate_unique_display_name_with_suffix(
base_value,
tenant_id=tenant_id,
agents_cache=agents_cache,
exclude_agent_id=exclude_agent_id
),
prompt_template_id=prompt_template_id,
user_id=user_id,
)
async def check_agent_name_conflict_batch_impl(
request: AgentNameBatchCheckRequest,
authorization: str
) -> list[dict]:
"""
Batch check name/display_name duplication for multiple agents.
"""
_, tenant_id, _ = get_current_user_info(authorization)
agents_cache = query_all_agent_info_by_tenant_id(tenant_id)
results: list[dict] = []
for item in request.items:
if not item.name:
results.append({
"name_conflict": False,
"display_name_conflict": False,
"conflict_agents": []
})
continue
conflicts: list[dict] = []
name_conflict = False
display_name_conflict = False
for agent in agents_cache:
if item.agent_id and agent.get("agent_id") == item.agent_id:
continue
matches_name = item.name and agent.get("name") == item.name
matches_display = item.display_name and agent.get(
"display_name") == item.display_name
if matches_name:
name_conflict = True
if matches_display:
display_name_conflict = True
if matches_name or matches_display:
conflicts.append({
"name": agent.get("name"),
"display_name": agent.get("display_name"),
})
results.append({
"name_conflict": name_conflict,
"display_name_conflict": display_name_conflict,
"conflict_agents": conflicts
})
return results
async def regenerate_agent_name_batch_impl(
request: AgentNameBatchRegenerateRequest,
authorization: str
) -> list[dict]:
"""
Batch regenerate agent name/display_name with LLM (or suffix fallback).
"""
_, tenant_id, _ = get_current_user_info(authorization)
agents_cache = query_all_agent_info_by_tenant_id(tenant_id)
existing_names = [agent.get("name") for agent in agents_cache if agent.get("name")]
existing_display_names = [agent.get("display_name") for agent in agents_cache if agent.get("display_name")]
# Always use tenant quick-config LLM model
quick_config_model = tenant_config_manager.get_model_config(
key=MODEL_CONFIG_MAPPING["llm"],
tenant_id=tenant_id
)
resolved_model_id = quick_config_model.get("model_id") if quick_config_model else None
if not resolved_model_id:
raise ValueError("No available model for regeneration. Please configure an LLM model first.")
results: list[dict] = []
# Use local mutable caches to avoid regenerated duplicates in the same batch
name_set = set(existing_names)
display_name_set = set(existing_display_names)
for item in request.items:
agent_name = item.name or ""
agent_display_name = item.display_name or ""
task_description = item.task_description or ""
exclude_agent_id = item.agent_id
# Regenerate name if duplicate and non-empty
if agent_name and _check_agent_name_duplicate(
agent_name, tenant_id, agents_cache=agents_cache, exclude_agent_id=exclude_agent_id
):
try:
agent_name = await asyncio.to_thread(
_regenerate_agent_name_with_llm,
original_name=agent_name,
existing_names=list(name_set),
task_description=task_description,
model_id=resolved_model_id,
tenant_id=tenant_id,
language=LANGUAGE["ZH"],
agents_cache=agents_cache,
exclude_agent_id=exclude_agent_id
)
except Exception as e:
logger.error(f"Failed to regenerate agent name with LLM: {str(e)}, using fallback")
agent_name = _generate_unique_agent_name_with_suffix(
agent_name,
tenant_id=tenant_id,
agents_cache=agents_cache,
exclude_agent_id=exclude_agent_id
)
# Regenerate display_name if duplicate and non-empty
if agent_display_name and _check_agent_display_name_duplicate(
agent_display_name, tenant_id, agents_cache=agents_cache, exclude_agent_id=exclude_agent_id
):
try:
agent_display_name = await asyncio.to_thread(
_regenerate_agent_display_name_with_llm,
original_display_name=agent_display_name,
existing_display_names=list(display_name_set),
task_description=task_description,
model_id=resolved_model_id,
tenant_id=tenant_id,
language=LANGUAGE["ZH"],
agents_cache=agents_cache,
exclude_agent_id=exclude_agent_id
)
except Exception as e:
logger.error(f"Failed to regenerate agent display_name with LLM: {str(e)}, using fallback")
agent_display_name = _generate_unique_display_name_with_suffix(
agent_display_name,
tenant_id=tenant_id,
agents_cache=agents_cache,
exclude_agent_id=exclude_agent_id
)
# Track regenerated names to avoid duplicates within batch
if agent_name:
name_set.add(agent_name)
if agent_display_name:
display_name_set.add(agent_display_name)
results.append({
"name": agent_name,
"display_name": agent_display_name
})
return results
async def _stream_agent_chunks(
agent_request: "AgentRequest",
user_id: str,
tenant_id: str,
agent_run_info,
memory_ctx,
):
"""Yield SSE chunks from agent_run while persisting messages & cleanup.
This utility centralizes the common streaming logic used by both
generate_stream_with_memory and generate_stream_no_memory so that the code
is easier to maintain and less error-prone.
"""
local_messages = []
captured_final_answer = None
try:
async for chunk in agent_run(agent_run_info):
local_messages.append(chunk)
# Try to capture the final answer as it streams by in order to start memory addition
try:
data = json.loads(chunk)
if data.get("type") == "final_answer":
captured_final_answer = data.get("content")
except Exception:
pass
yield f"data: {chunk}\n\n"
except Exception as run_exc:
logger.error(f"Agent run error: {str(run_exc)}")
# Emit an error chunk and terminate the stream immediately
error_payload = json.dumps(
{"type": "error", "content": str(run_exc)}, ensure_ascii=False)
yield f"data: {error_payload}\n\n"
finally:
# Persist assistant messages for non-debug runs
if not agent_request.is_debug:
save_messages(
agent_request,
target=MESSAGE_ROLE["ASSISTANT"],
messages=local_messages,
tenant_id=tenant_id,
user_id=user_id,
)
# Always unregister the run to release resources
agent_run_manager.unregister_agent_run(
agent_request.conversation_id, user_id)
# Schedule memory addition in background to avoid blocking SSE termination
async def _add_memory_background():
try:
# Skip if memory recording is disabled
if not getattr(memory_ctx.user_config, "memory_switch", False):
return
# Use the captured final answer during streaming; observer queue was drained
final_answer_local = captured_final_answer
if not final_answer_local:
return
# Determine allowed memory levels
levels_local = {"agent", "user_agent"}
if memory_ctx.user_config.agent_share_option == "never":
levels_local.discard("agent")
if memory_ctx.agent_id in getattr(memory_ctx.user_config, "disable_agent_ids", []):
levels_local.discard("agent")
if memory_ctx.agent_id in getattr(memory_ctx.user_config, "disable_user_agent_ids", []):
levels_local.discard("user_agent")
if not levels_local:
return
mem_messages_local = [
{"role": MESSAGE_ROLE["USER"],
"content": agent_run_info.query},
{"role": MESSAGE_ROLE["ASSISTANT"],
"content": final_answer_local},
]
add_result_local = await add_memory_in_levels(
messages=mem_messages_local,
memory_config=memory_ctx.memory_config,
tenant_id=memory_ctx.tenant_id,
user_id=memory_ctx.user_id,
agent_id=memory_ctx.agent_id,
memory_levels=list(levels_local),
)
items_local = add_result_local.get("results", [])
logger.info(f"Memory addition completed: {items_local}")
except Exception as bg_e:
logger.error(
f"Unexpected error during background memory addition: {bg_e}")
try:
# Create and store the background task to avoid warnings
background_task = asyncio.create_task(_add_memory_background())
# Add done callback to handle any exceptions that might occur
background_task.add_done_callback(lambda t: t.exception() if t.exception() else None)
except Exception as schedule_err:
logger.error(
f"Failed to schedule background memory addition: {schedule_err}")
def get_enable_tool_id_by_agent_id(agent_id: int, tenant_id: str):
all_tool_instance = query_all_enabled_tool_instances(
agent_id=agent_id, tenant_id=tenant_id)
enable_tool_id_set = set()
for tool_instance in all_tool_instance:
if tool_instance["enabled"]:
enable_tool_id_set.add(tool_instance["tool_id"])
return list(enable_tool_id_set)
async def get_creating_sub_agent_id_service(tenant_id: str, user_id: str = None) -> int:
"""
first find the blank sub agent, if it exists, it means the agent was created before, but exited prematurely;
if it does not exist, create a new one
"""
sub_agent_id = search_blank_sub_agent_by_main_agent_id(tenant_id=tenant_id)
if sub_agent_id:
return sub_agent_id
else:
return create_agent(agent_info={"enabled": False}, tenant_id=tenant_id, user_id=user_id)["agent_id"]
async def get_agent_info_impl(agent_id: int, tenant_id: str, version_no: int = 0):
try:
agent_info = search_agent_info_by_agent_id(agent_id, tenant_id, version_no)
except Exception as e:
logger.error(f"Failed to get agent info: {str(e)}")
raise ValueError(f"Failed to get agent info: {str(e)}")
try:
tool_info = search_tools_for_sub_agent(
agent_id=agent_id, tenant_id=tenant_id)
agent_info["tools"] = tool_info
except Exception as e:
logger.error(f"Failed to get agent tools: {str(e)}")
agent_info["tools"] = []
try:
sub_agent_id_list = query_sub_agents_id_list(
main_agent_id=agent_id, tenant_id=tenant_id)
agent_info["sub_agent_id_list"] = sub_agent_id_list
except Exception as e:
logger.error(f"Failed to get sub agent id list: {str(e)}")
agent_info["sub_agent_id_list"] = []
if agent_info["model_id"] is not None:
model_info = get_model_by_model_id(agent_info["model_id"])
agent_info["model_name"] = model_info.get("display_name", None) if model_info is not None else None
else:
agent_info["model_name"] = None
# Get business logic model display name from model_id
if agent_info.get("business_logic_model_id") is not None:
business_logic_model_info = get_model_by_model_id(agent_info["business_logic_model_id"])
agent_info["business_logic_model_name"] = business_logic_model_info.get("display_name", None) if business_logic_model_info is not None else None
elif "business_logic_model_name" not in agent_info:
agent_info["business_logic_model_name"] = None
if not agent_info.get("prompt_template_id"):
agent_info["prompt_template_id"] = SYSTEM_PROMPT_TEMPLATE_ID
if not agent_info.get("prompt_template_name"):
agent_info["prompt_template_name"] = SYSTEM_PROMPT_TEMPLATE_NAME
if agent_info.get("group_ids") is not None:
agent_info["group_ids"] = convert_string_to_list(agent_info.get("group_ids"))
# Check agent availability
is_available, unavailable_reasons = check_agent_availability(
agent_id=agent_id,
tenant_id=tenant_id,
agent_info=agent_info
)
agent_info["is_available"] = is_available
agent_info["unavailable_reasons"] = unavailable_reasons
return agent_info
async def get_creating_sub_agent_info_impl(authorization: str = Header(None)):
user_id, tenant_id, _ = get_current_user_info(authorization)
try:
sub_agent_id = await get_creating_sub_agent_id_service(tenant_id, user_id)
except Exception as e:
logger.error(f"Failed to get creating sub agent id: {str(e)}")
raise ValueError(f"Failed to get creating sub agent id: {str(e)}")
try:
agent_info = search_agent_info_by_agent_id(
agent_id=sub_agent_id, tenant_id=tenant_id)
except Exception as e:
logger.error(f"Failed to get sub agent info: {str(e)}")
raise ValueError(f"Failed to get sub agent info: {str(e)}")
try:
enable_tool_id_list = get_enable_tool_id_by_agent_id(
sub_agent_id, tenant_id)
except Exception as e:
logger.error(f"Failed to get sub agent enable tool id list: {str(e)}")
raise ValueError(
f"Failed to get sub agent enable tool id list: {str(e)}")
return {"agent_id": sub_agent_id,
"name": agent_info.get("name"),
"display_name": agent_info.get("display_name"),
"description": agent_info.get("description"),
"enable_tool_id_list": enable_tool_id_list,
"model_name": agent_info["model_name"],
"model_id": agent_info.get("model_id"),
"max_steps": agent_info["max_steps"],
"business_description": agent_info["business_description"],
"duty_prompt": agent_info.get("duty_prompt"),
"constraint_prompt": agent_info.get("constraint_prompt"),
"few_shots_prompt": agent_info.get("few_shots_prompt"),
"sub_agent_id_list": query_sub_agents_id_list(main_agent_id=sub_agent_id, tenant_id=tenant_id)}
async def update_agent_info_impl(request: AgentInfoRequest, authorization: str = Header(None)):
user_id, tenant_id, _ = get_current_user_info(authorization)
prompt_template_id, prompt_template_name = get_prompt_template_summary(
template_id=request.prompt_template_id,
tenant_id=tenant_id,
user_id=user_id,
)
# If agent_id is None, create a new agent; otherwise, update existing
agent_id: Optional[int] = request.agent_id
try:
if agent_id is None:
# Create agent - automatically set group_ids to current user's groups
user_group_ids = _get_user_group_ids(user_id, tenant_id)
created = create_agent(agent_info={
"name": request.name,
"display_name": request.display_name,
"description": request.description,
"business_description": request.business_description,
"author": request.author,
"model_id": request.model_id,
"model_name": request.model_name,
"business_logic_model_id": request.business_logic_model_id,
"business_logic_model_name": request.business_logic_model_name,
"prompt_template_id": prompt_template_id,
"prompt_template_name": prompt_template_name,
"max_steps": request.max_steps,
"provide_run_summary": request.provide_run_summary,
"duty_prompt": request.duty_prompt,
"constraint_prompt": request.constraint_prompt,
"few_shots_prompt": request.few_shots_prompt,
"enabled": request.enabled if request.enabled is not None else True,
"group_ids": convert_list_to_string(request.group_ids) if request.group_ids else user_group_ids,
"ingroup_permission": request.ingroup_permission
}, tenant_id=tenant_id, user_id=user_id)
agent_id = created["agent_id"]
else:
# Update agent
request.prompt_template_id = prompt_template_id
request.prompt_template_name = prompt_template_name
update_agent(agent_id, request, user_id)
except Exception as e:
logger.error(f"Failed to update agent info: {str(e)}")
raise ValueError(f"Failed to update agent info: {str(e)}")
# Handle enabled tools saving when provided
try:
if request.enabled_tool_ids is not None and agent_id is not None:
enabled_set = set(request.enabled_tool_ids)
# Query existing tool instances for this agent
existing_instances = query_tool_instances_by_agent_id(
agent_id, tenant_id)
# Handle unselected tool(already exist instance)→ enabled=False
for instance in existing_instances:
inst_tool_id = instance.get("tool_id")
if inst_tool_id is not None and inst_tool_id not in enabled_set:
create_or_update_tool_by_tool_info(
tool_info=ToolInstanceInfoRequest(
tool_id=inst_tool_id,
agent_id=agent_id,
params=instance.get("params", {}),
enabled=False
),
tenant_id=tenant_id,
user_id=user_id
)
# Handle selected tool → enabled=True(create or update)
for tool_id in enabled_set:
# Keep existing params if any
existing_instance = next(
(inst for inst in existing_instances
if inst.get("tool_id") == tool_id),
None
)
params = (existing_instance or {}).get("params", {})
create_or_update_tool_by_tool_info(
tool_info=ToolInstanceInfoRequest(
tool_id=tool_id,
agent_id=agent_id,
params=params,
enabled=True,
),
tenant_id=tenant_id,
user_id=user_id
)
except Exception as e:
logger.error(f"Failed to update agent tools: {str(e)}")
raise ValueError(f"Failed to update agent tools: {str(e)}")
# Handle enabled skills saving when provided
try:
if request.enabled_skill_ids is not None and agent_id is not None:
enabled_set = set(request.enabled_skill_ids)
# Query existing skill instances for this agent
existing_instances = skill_db.query_skill_instances_by_agent_id(
agent_id, tenant_id)
# Handle unselected skill (already exist instance) -> enabled=False
for instance in existing_instances:
inst_skill_id = instance.get("skill_id")
if inst_skill_id is not None and inst_skill_id not in enabled_set:
skill_db.create_or_update_skill_by_skill_info(
skill_info=SkillInstanceInfoRequest(
skill_id=inst_skill_id,
agent_id=agent_id,
skill_description=instance.get("skill_description"),
skill_content=instance.get("skill_content"),
enabled=False
),
tenant_id=tenant_id,
user_id=user_id
)
# Handle selected skill -> enabled=True (create or update)
for skill_id in enabled_set:
# Keep existing skill_description and skill_content if any
existing_instance = next(
(inst for inst in existing_instances
if inst.get("skill_id") == skill_id),
None
)
skill_description = (existing_instance or {}).get("skill_description")
skill_content = (existing_instance or {}).get("skill_content")
skill_db.create_or_update_skill_by_skill_info(
skill_info=SkillInstanceInfoRequest(
skill_id=skill_id,
agent_id=agent_id,
skill_description=skill_description,
skill_content=skill_content,
enabled=True,
),
tenant_id=tenant_id,
user_id=user_id
)
except Exception as e:
logger.error(f"Failed to update agent skills: {str(e)}")
raise ValueError(f"Failed to update agent skills: {str(e)}")
# Handle related agents saving when provided
try:
if request.related_agent_ids is not None and agent_id is not None:
related_agent_ids = request.related_agent_ids
# Check for circular dependencies using BFS
search_list = deque(related_agent_ids)
agent_id_set = set()
while len(search_list):
left_ele = search_list.popleft()
if left_ele == agent_id:
raise ValueError("Circular dependency detected: Agent cannot be related to itself or create circular calls")
if left_ele in agent_id_set:
continue
else:
agent_id_set.add(left_ele)
sub_ids = query_sub_agents_id_list(
main_agent_id=left_ele, tenant_id=tenant_id)
search_list.extend(sub_ids)
# Update related agents
update_related_agents(