-
Notifications
You must be signed in to change notification settings - Fork 576
/
Copy pathagent.py
1751 lines (1627 loc) · 56.7 KB
/
agent.py
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 json
import logging
import re
from datetime import datetime, timezone
from typing import Annotated, Any, Dict, List, Optional
import yaml
from epyxid import XID
from fastapi import HTTPException
from pydantic import BaseModel, ConfigDict, constr, field_validator, model_validator
from pydantic import Field as PydanticField
from pydantic.json_schema import SkipJsonSchema
from sqlalchemy import (
BigInteger,
Boolean,
Column,
DateTime,
Float,
Identity,
Integer,
String,
func,
select,
)
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
from models.base import Base
from models.db import get_session
from models.skill import SkillConfig
logger = logging.getLogger(__name__)
class AgentAutonomous(BaseModel):
"""Autonomous agent configuration."""
id: Annotated[
str,
PydanticField(description="Unique identifier for the autonomous configuration"),
]
name: Annotated[
Optional[str],
PydanticField(
default=None, description="Display name of the autonomous configuration"
),
]
description: Annotated[
Optional[str],
PydanticField(
default=None, description="Description of the autonomous configuration"
),
]
minutes: Annotated[
Optional[int],
PydanticField(
default=None,
description="Interval in minutes between operations, mutually exclusive with cron",
),
]
cron: Annotated[
Optional[str],
PydanticField(
default=None,
description="Cron expression for scheduling operations, mutually exclusive with minutes",
),
]
prompt: Annotated[
str,
PydanticField(description="Special prompt used during autonomous operation"),
]
enabled: Annotated[
Optional[bool],
PydanticField(
default=True, description="Whether the autonomous configuration is enabled"
),
]
@field_validator("id")
@classmethod
def validate_id(cls, v: str) -> str:
if not v:
raise ValueError("id cannot be empty")
if len(v.encode()) > 20:
raise ValueError("id must be at most 20 bytes")
if not re.match(r"^[a-z0-9-]+$", v):
raise ValueError(
"id must contain only lowercase letters, numbers, and dashes"
)
return v
@field_validator("name")
@classmethod
def validate_name(cls, v: Optional[str]) -> Optional[str]:
if v is not None and len(v.encode()) > 50:
raise ValueError("name must be at most 50 bytes")
return v
@field_validator("description")
@classmethod
def validate_description(cls, v: Optional[str]) -> Optional[str]:
if v is not None and len(v.encode()) > 200:
raise ValueError("description must be at most 200 bytes")
return v
@field_validator("prompt")
@classmethod
def validate_prompt(cls, v: Optional[str]) -> Optional[str]:
if v is not None and len(v.encode()) > 2000:
raise ValueError("prompt must be at most 2000 bytes")
return v
@model_validator(mode="after")
def validate_schedule(self) -> "AgentAutonomous":
if self.minutes is None and self.cron is None:
raise ValueError("either minutes or cron must have a value")
return self
class AgentTable(Base):
"""Agent table db model."""
__tablename__ = "agents"
id = Column(
String,
primary_key=True,
comment="Unique identifier for the agent. Must be URL-safe, containing only lowercase letters, numbers, and hyphens",
)
number = Column(
BigInteger,
Identity(start=1, increment=1),
nullable=False,
comment="Auto-incrementing number assigned by the system for easy reference",
)
name = Column(
String,
nullable=True,
comment="Display name of the agent",
)
slug = Column(
String,
nullable=True,
comment="Slug of the agent, used for URL generation",
)
ticker = Column(
String,
nullable=True,
comment="Ticker symbol of the agent",
)
token_address = Column(
String,
nullable=True,
comment="Token address of the agent",
)
purpose = Column(
String,
nullable=True,
comment="Purpose or role of the agent",
)
personality = Column(
String,
nullable=True,
comment="Personality traits of the agent",
)
principles = Column(
String,
nullable=True,
comment="Principles or values of the agent",
)
owner = Column(
String,
nullable=True,
comment="Owner identifier of the agent, used for access control",
)
upstream_id = Column(
String,
nullable=True,
comment="External reference ID for idempotent operations",
)
# AI part
model = Column(
String,
nullable=True,
default="gpt-4o-mini",
comment="AI model identifier to be used by this agent for processing requests. Available models: gpt-4o, gpt-4o-mini, chatgpt-4o-latest, deepseek-chat, deepseek-reasoner, grok-2",
)
prompt = Column(
String,
nullable=True,
comment="Base system prompt that defines the agent's behavior and capabilities",
)
prompt_append = Column(
String,
nullable=True,
comment="Additional system prompt that has higher priority than the base prompt",
)
temperature = Column(
Float,
nullable=True,
default=0.7,
comment="AI model temperature parameter controlling response randomness (0.0~1.0)",
)
frequency_penalty = Column(
Float,
nullable=True,
default=0.0,
comment="Frequency penalty for the AI model, a higher value penalizes new tokens based on their existing frequency in the chat history (-2.0~2.0)",
)
presence_penalty = Column(
Float,
nullable=True,
default=0.0,
comment="Presence penalty for the AI model, a higher value penalizes new tokens based on whether they appear in the chat history (-2.0~2.0)",
)
# autonomous mode
autonomous = Column(
JSONB,
nullable=True,
comment="Autonomous agent configurations",
)
autonomous_enabled = Column(
Boolean,
nullable=True,
default=False,
comment="Whether the agent can operate autonomously without user input",
)
autonomous_minutes = Column(
Integer,
nullable=True,
default=240,
comment="Interval in minutes between autonomous operations when enabled",
)
autonomous_prompt = Column(
String,
nullable=True,
comment="Special prompt used during autonomous operation mode",
)
# skills
skills = Column(
JSONB,
nullable=True,
comment="Dict of skills and their corresponding configurations",
)
# if cdp_enabled, agent will have a cdp wallet
cdp_enabled = Column(
Boolean,
nullable=True,
default=False,
comment="Whether CDP (Crestal Development Platform) integration is enabled",
)
cdp_skills = Column(
ARRAY(String),
nullable=True,
comment="List of CDP skills available to this agent",
)
cdp_network_id = Column(
String,
nullable=True,
default="base-mainnet",
comment="Network identifier for CDP integration",
)
# if goat_enabled, will load goat skills
crossmint_config = Column(
JSONB,
nullable=True,
comment="Dict of Crossmint wallet configurations",
)
goat_enabled = Column(
Boolean,
nullable=True,
default=False,
comment="Whether GOAT integration is enabled",
)
goat_skills = Column(
JSONB,
nullable=True,
comment="Dict of GOAT skills and their corresponding configurations",
)
# if twitter_enabled, the twitter_entrypoint will be enabled, twitter_config will be checked
twitter_entrypoint_enabled = Column(
Boolean,
nullable=True,
default=False,
comment="Whether the agent can receive events from Twitter",
)
twitter_config = Column(
JSONB,
nullable=True,
comment="This configuration will be used for entrypoint only",
)
# twitter skills require config, but not require twitter_enabled flag.
# As long as twitter_skills is not empty, the corresponding skills will be loaded.
twitter_skills = Column(
ARRAY(String),
nullable=True,
comment="List of Twitter-specific skills available to this agent",
)
# if telegram_entrypoint_enabled, the telegram_entrypoint_enabled will be enabled, telegram_config will be checked
telegram_entrypoint_enabled = Column(
Boolean,
nullable=True,
default=False,
comment="Whether the agent can receive events from Telegram",
)
telegram_config = Column(
JSONB,
nullable=True,
comment="Telegram integration configuration settings",
)
# telegram skills not used for now
telegram_skills = Column(
ARRAY(String),
nullable=True,
comment="List of Telegram-specific skills available to this agent",
)
# skills have no category
common_skills = Column(
ARRAY(String),
nullable=True,
comment="List of general-purpose skills available to this agent",
)
# if enso_enabled, the enso skillset will be enabled, enso_config will be checked
enso_enabled = Column(
Boolean,
nullable=True,
default=False,
comment="Whether Enso integration is enabled",
)
# enso skills
enso_skills = Column(
ARRAY(String),
nullable=True,
comment="List of Enso-specific skills available to this agent",
)
enso_config = Column(
JSONB,
nullable=True,
comment="Enso integration configuration settings",
)
# Acolyt skills
acolyt_skills = Column(
ARRAY(String),
nullable=True,
comment="List of Acolyt-specific skills available to this agent",
)
acolyt_config = Column(
JSONB,
nullable=True,
comment="Acolyt integration configuration settings",
)
# Allora skills
allora_skills = Column(
ARRAY(String),
nullable=True,
comment="List of Allora-specific skills available to this agent",
)
allora_config = Column(
JSONB,
nullable=True,
comment="Allora integration configuration settings",
)
# ELFA skills
elfa_skills = Column(
ARRAY(String),
nullable=True,
comment="List of Elfa-specific skills available to this agent",
)
elfa_config = Column(
JSONB,
nullable=True,
comment="Elfa integration configuration settings",
)
# auto timestamp
created_at = Column(
DateTime(timezone=True),
nullable=False,
server_default=func.now(),
comment="Timestamp when the agent was created",
)
updated_at = Column(
DateTime(timezone=True),
nullable=False,
server_default=func.now(),
onupdate=lambda: datetime.now(timezone.utc),
comment="Timestamp when the agent was last updated",
)
class AgentUpdate(BaseModel):
"""Agent update model."""
name: Annotated[
Optional[str],
PydanticField(
default=None,
description="Display name of the agent",
),
]
slug: Annotated[
Optional[str],
PydanticField(
default=None,
description="Slug of the agent, used for URL generation",
),
]
ticker: Annotated[
Optional[str],
PydanticField(
default=None,
description="Ticker symbol of the agent",
),
]
token_address: Annotated[
Optional[str],
PydanticField(
default=None,
description="Token address of the agent",
),
]
purpose: Annotated[
Optional[str],
PydanticField(
default=None,
description="Purpose or role of the agent",
),
]
personality: Annotated[
Optional[str],
PydanticField(
default=None,
description="Personality traits of the agent",
),
]
principles: Annotated[
Optional[str],
PydanticField(
default=None,
description="Principles or values of the agent",
),
]
owner: Annotated[
Optional[str],
PydanticField(
default=None,
description="Owner identifier of the agent, used for access control",
),
]
upstream_id: Annotated[
Optional[str],
PydanticField(
default=None,
index=True,
description="External reference ID for idempotent operations",
),
]
# AI part
model: Annotated[
Optional[str],
PydanticField(
default="gpt-4o-mini",
description="AI model identifier to be used by this agent for processing requests. Available models: gpt-4o, gpt-4o-mini, chatgpt-4o-latest, deepseek-chat, deepseek-reasoner, grok-2",
),
]
prompt: Annotated[
Optional[str],
PydanticField(
default=None,
description="Base system prompt that defines the agent's behavior and capabilities",
),
]
prompt_append: Annotated[
Optional[str],
PydanticField(
default=None,
description="Additional system prompt that has higher priority than the base prompt",
),
]
temperature: Annotated[
Optional[float],
PydanticField(
default=0.7,
description="AI model temperature parameter controlling response randomness (0.0~1.0)",
),
]
frequency_penalty: Annotated[
Optional[float],
PydanticField(
default=0.0,
description="Frequency penalty for the AI model, a higher value penalizes new tokens based on their existing frequency in the chat history (-2.0~2.0)",
),
]
presence_penalty: Annotated[
Optional[float],
PydanticField(
default=0.0,
description="Presence penalty for the AI model, a higher value penalizes new tokens based on whether they appear in the chat history (-2.0~2.0)",
),
]
# autonomous mode
autonomous: Annotated[
Optional[List[AgentAutonomous]],
PydanticField(
default=None,
description=(
"Autonomous agent configurations.\n"
"autonomous:\n"
" - id: a\n"
" name: TestA\n"
" minutes: 1\n"
" prompt: |-\n"
" Say hello [sequence], use number for sequence.\n"
" - id: b\n"
" name: TestB\n"
' cron: "0/3 * * * *"\n'
" prompt: |-\n"
" Say hi [sequence], use number for sequence.\n"
),
),
]
autonomous_enabled: Annotated[
Optional[bool],
PydanticField(
default=False,
deprecated="Please use autonomous instead",
description="Whether the agent can operate autonomously without user input",
),
]
autonomous_minutes: Annotated[
Optional[int],
PydanticField(
default=240,
deprecated="Please use autonomous instead",
description="Interval in minutes between autonomous operations when enabled",
),
]
autonomous_prompt: Annotated[
Optional[str],
PydanticField(
default=None,
deprecated="Please use autonomous instead",
description="Special prompt used during autonomous operation mode",
),
]
# skills
skills: Annotated[
Optional[Dict[str, SkillConfig]],
PydanticField(
default=None,
description="Dict of skills and their corresponding configurations",
),
]
# if cdp_enabled, agent will have a cdp wallet
cdp_enabled: Annotated[
Optional[bool],
PydanticField(
default=False,
description="Whether CDP (Crestal Development Platform) integration is enabled",
),
]
cdp_skills: Annotated[
Optional[List[str]],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="List of CDP skills available to this agent",
),
]
cdp_network_id: Annotated[
Optional[str],
PydanticField(
default="base-mainnet",
description="Network identifier for CDP integration",
),
]
# if goat_enabled, will load goat skills
crossmint_config: Annotated[
Optional[dict],
PydanticField(
default=None,
description="Dict of Crossmint wallet configurations",
),
]
goat_enabled: Annotated[
Optional[bool],
PydanticField(
default=False,
description="Whether GOAT integration is enabled",
),
]
goat_skills: Annotated[
Optional[dict],
PydanticField(
default=None,
description="Dict of GOAT skills and their corresponding configurations",
),
]
# if twitter_enabled, the twitter_entrypoint will be enabled, twitter_config will be checked
twitter_entrypoint_enabled: Annotated[
Optional[bool],
PydanticField(
default=False,
description="Whether the agent can receive events from Twitter",
),
]
twitter_config: Annotated[
Optional[dict],
PydanticField(
default=None,
description="This configuration will be used for entrypoint only",
),
]
# twitter skills require config, but not require twitter_enabled flag.
# As long as twitter_skills is not empty, the corresponding skills will be loaded.
twitter_skills: Annotated[
Optional[List[str]],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="List of Twitter-specific skills available to this agent",
),
]
# if telegram_entrypoint_enabled, the telegram_entrypoint_enabled will be enabled, telegram_config will be checked
telegram_entrypoint_enabled: Annotated[
Optional[bool],
PydanticField(
default=False,
description="Whether the agent can receive events from Telegram",
),
]
telegram_config: Annotated[
Optional[dict],
PydanticField(
default=None,
description="Telegram integration configuration settings",
),
]
# telegram skills not used for now
telegram_skills: Annotated[
Optional[List[str]],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="List of Telegram-specific skills available to this agent",
),
]
# skills have no category
common_skills: Annotated[
Optional[List[str]],
PydanticField(
default=None,
description="List of general-purpose skills available to this agent",
),
]
# if enso_enabled, the enso skillset will be enabled, enso_config will be checked
enso_enabled: Annotated[
Optional[bool],
PydanticField(
default=False,
description="Whether Enso integration is enabled",
),
]
# enso skills
enso_skills: Annotated[
Optional[List[str]],
PydanticField(
default=None,
deprecated="Please use enso_enabled instead",
description="List of Enso-specific skills available to this agent",
),
]
enso_config: Annotated[
Optional[dict],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="Enso integration configuration settings",
),
]
# Acolyt skills
acolyt_skills: Annotated[
Optional[List[str]],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="List of Acolyt-specific skills available to this agent",
),
]
acolyt_config: Annotated[
Optional[dict],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="Acolyt integration configuration settings",
),
]
# Allora skills
allora_skills: Annotated[
Optional[List[str]],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="List of Allora-specific skills available to this agent",
),
]
allora_config: Annotated[
Optional[dict],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="Allora integration configuration settings",
),
]
# ELFA skills
elfa_skills: Annotated[
Optional[List[str]],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="List of Elfa-specific skills available to this agent",
),
]
elfa_config: Annotated[
Optional[dict],
PydanticField(
default=None,
deprecated="Please use skills instead",
description="Elfa integration configuration settings",
),
]
def check_prompt(self):
# Check for markdown headers in text fields
fields_to_check = [
"purpose",
"personality",
"principles",
"prompt",
"prompt_append",
]
for field in fields_to_check:
value = getattr(self, field)
if value and isinstance(value, str):
for line_num, line in enumerate(value.split("\n"), 1):
line = line.strip()
if line.startswith("# ") or line.startswith("## "):
raise HTTPException(
status_code=400,
detail=f"Field '{field}' contains markdown level 1/2 header at line {line_num}. You can use level 3 (### ) instead.",
)
async def update(self, id: str) -> "Agent":
self.check_prompt()
async with get_session() as db:
db_agent = await db.get(AgentTable, id)
if not db_agent:
raise HTTPException(
status_code=404,
detail="Agent not found",
)
# check onwer
if self.owner and db_agent.owner != self.owner:
raise HTTPException(
status_code=403,
detail="You do not have permission to update this agent",
)
# update
for key, value in self.model_dump(exclude_unset=True).items():
setattr(db_agent, key, value)
await db.commit()
await db.refresh(db_agent)
return Agent.model_validate(db_agent)
class AgentCreate(AgentUpdate):
"""Agent create model."""
id: Annotated[
str,
PydanticField(
default_factory=lambda: str(XID()),
description="Unique identifier for the agent. Must be URL-safe, containing only lowercase letters, numbers, and hyphens",
),
constr(pattern=r"^[a-z][a-z0-9-]*$"),
]
async def check_upstream_id(self) -> None:
if not self.upstream_id:
return None
async with get_session() as db:
existing = await db.scalars(
select(AgentTable).where(AgentTable.upstream_id == self.upstream_id)
).one_or_none()
if existing:
raise HTTPException(
status_code=400,
detail="Upstream id already in use",
)
async def create(self) -> "Agent":
self.check_prompt()
await self.check_upstream_id()
async with get_session() as db:
db_agent = AgentTable(**self.model_dump())
db.add(db_agent)
await db.commit()
await db.refresh(db_agent)
return Agent.model_validate(db_agent)
async def create_or_update(self) -> ("Agent", bool):
self.check_prompt()
is_new = False
async with get_session() as db:
db_agent = await db.get(AgentTable, self.id)
if not db_agent:
upstream = await db.scalar(
select(AgentTable).where(AgentTable.upstream_id == self.upstream_id)
)
if upstream:
raise HTTPException(
status_code=400,
detail="Upstream id already in use",
)
db_agent = AgentTable(**self.model_dump())
db.add(db_agent)
is_new = True
else:
# check onwer
if self.owner and db_agent.owner != self.owner:
raise HTTPException(
status_code=403,
detail="You do not have permission to update this agent",
)
for key, value in self.model_dump(exclude_unset=True).items():
setattr(db_agent, key, value)
await db.commit()
await db.refresh(db_agent)
return (Agent.model_validate(db_agent), is_new)
class Agent(AgentCreate):
"""Agent model."""
model_config = ConfigDict(from_attributes=True)
# auto increment number by db
number: Annotated[
int,
PydanticField(
description="Auto-incrementing number assigned by the system for easy reference",
),
]
# auto timestamp
created_at: Annotated[
datetime,
PydanticField(
description="Timestamp when the agent was created, will ignore when importing"
),
]
updated_at: Annotated[
datetime,
PydanticField(
description="Timestamp when the agent was last updated, will ignore when importing"
),
]
def to_yaml(self) -> str:
"""
Dump the agent model to YAML format with field descriptions as comments.
The comments are extracted from the field descriptions in the model.
Fields annotated with SkipJsonSchema will be excluded from the output.
Returns:
str: YAML representation of the agent with field descriptions as comments
"""
data = {}
yaml_lines = []
for field_name, field in self.model_fields.items():
logger.debug(f"Processing field {field_name} with type {field.metadata}")
# Skip fields with SkipJsonSchema annotation
if any(isinstance(item, SkipJsonSchema) for item in field.metadata):
continue
value = getattr(self, field_name)
data[field_name] = value
# Add comment from field description if available
description = field.description
if description:
if len(yaml_lines) > 0: # Add blank line between fields
yaml_lines.append("")
# Split description into multiple lines if too long
desc_lines = [f"# {line}" for line in description.split("\n")]
yaml_lines.extend(desc_lines)
# Check if the field is deprecated and add deprecation notice
if hasattr(field, "deprecated") and field.deprecated:
# Add deprecation message
if (
hasattr(field, "deprecation_message")
and field.deprecation_message
):
yaml_lines.append(f"# Deprecated: {field.deprecation_message}")
else:
yaml_lines.append("# Deprecated")
# Format the value based on its type
if value is None:
yaml_lines.append(f"{field_name}: null")
elif isinstance(value, str):
if "\n" in value or len(value) > 60:
# Use block literal style (|) for multiline strings
# Remove any existing escaped newlines and use actual line breaks
value = value.replace("\\n", "\n")
yaml_value = f"{field_name}: |-\n"
# Indent each line with 2 spaces
yaml_value += "\n".join(f" {line}" for line in value.split("\n"))
yaml_lines.append(yaml_value)
else:
# Use flow style for short strings
yaml_value = yaml.dump(
{field_name: value},
default_flow_style=False,
allow_unicode=True, # This ensures emojis are preserved
)
yaml_lines.append(yaml_value.rstrip())
elif isinstance(value, list) and value and hasattr(value[0], "model_dump"):
# Handle list of Pydantic models (e.g., List[AgentAutonomous])
yaml_lines.append(f"{field_name}:")
# Convert each Pydantic model to dict
model_dicts = [item.model_dump(exclude_none=True) for item in value]
# Dump the list of dicts
yaml_value = yaml.dump(
model_dicts, default_flow_style=False, allow_unicode=True
)
# Indent all lines and append to yaml_lines
indented_yaml = "\n".join(
f" {line}" for line in yaml_value.split("\n")
)
yaml_lines.append(indented_yaml.rstrip())
elif hasattr(value, "model_dump"):
# Handle individual Pydantic model
model_dict = value.model_dump(exclude_none=True)
yaml_value = yaml.dump(
{field_name: model_dict},
default_flow_style=False,
allow_unicode=True,
)
yaml_lines.append(yaml_value.rstrip())
else:
# Handle non-string values
yaml_value = yaml.dump(
{field_name: value},
default_flow_style=False,
allow_unicode=True,
)
yaml_lines.append(yaml_value.rstrip())
return "\n".join(yaml_lines) + "\n"
@staticmethod
async def count() -> int:
async with get_session() as db:
return await db.scalar(select(func.count(AgentTable.id)))
@classmethod
async def get(cls, agent_id: str) -> Optional["Agent"]:
async with get_session() as db:
item = await db.scalar(select(AgentTable).where(AgentTable.id == agent_id))
if item is None:
return None
return cls.model_validate(item)
class AgentResponse(Agent):
"""Response model for Agent API."""
model_config = ConfigDict(
from_attributes=True,
json_encoders={
datetime: lambda dt: dt.isoformat(),
},
)
# data part
cdp_wallet_address: Annotated[
Optional[str], PydanticField(description="CDP wallet address for the agent")
]
has_twitter_linked: Annotated[
bool,
PydanticField(description="Whether the agent has linked their Twitter account"),
]
linked_twitter_username: Annotated[
Optional[str],
PydanticField(description="The username of the linked Twitter account"),
]
linked_twitter_name: Annotated[
Optional[str],
PydanticField(description="The name of the linked Twitter account"),
]
has_twitter_self_key: Annotated[