-
Notifications
You must be signed in to change notification settings - Fork 575
/
Copy pathagent.py
1080 lines (994 loc) · 39.2 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
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
import yaml
from epyxid import XID
from fastapi import HTTPException
from pydantic import BaseModel
from pydantic.json_schema import SkipJsonSchema
from sqlalchemy import BigInteger, Column, DateTime, Identity, String, func
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
from sqlmodel import Field, SQLModel, select
from models.db import get_session
from models.skill import SkillConfig
logger = logging.getLogger(__name__)
class Agent(SQLModel, table=True):
"""Agent model."""
__tablename__ = "agents"
id: str = Field(
primary_key=True,
description="Unique identifier for the agent. Must be URL-safe, containing only lowercase letters, numbers, and hyphens",
)
number: SkipJsonSchema[int] = Field(
sa_column=Column(BigInteger, Identity(start=1, increment=1), nullable=False),
description="Auto-incrementing number assigned by the system for easy reference",
)
name: Optional[str] = Field(default=None, description="Display name of the agent")
slug: Optional[str] = Field(
default=None,
description="Slug of the agent, used for URL generation",
)
ticker: Optional[str] = Field(
default=None,
description="Ticker symbol of the agent",
)
token_address: Optional[str] = Field(
default=None,
description="Token address of the agent",
)
purpose: Optional[str] = Field(
default=None,
description="Purpose or role of the agent",
)
personality: Optional[str] = Field(
default=None,
description="Personality traits of the agent",
)
principles: Optional[str] = Field(
default=None,
description="Principles or values of the agent",
)
owner: Optional[str] = Field(
default=None,
description="Owner identifier of the agent, used for access control",
)
upstream_id: Optional[str] = Field(
default=None, description="External reference ID for idempotent operations"
)
# AI part
model: Optional[str] = Field(
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: Optional[str] = Field(
default=None,
description="Base system prompt that defines the agent's behavior and capabilities",
)
prompt_append: Optional[str] = Field(
default=None,
description="Additional system prompt that has higher priority than the base prompt",
)
temperature: Optional[float] = Field(
default=0.7,
description="AI model temperature parameter controlling response randomness (0.0~1.0)",
)
frequency_penalty: Optional[float] = Field(
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: Optional[float] = Field(
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_enabled: Optional[bool] = Field(
default=False,
description="Whether the agent can operate autonomously without user input",
)
autonomous_minutes: Optional[int] = Field(
default=240,
description="Interval in minutes between autonomous operations when enabled",
)
autonomous_prompt: Optional[str] = Field(
default=None, description="Special prompt used during autonomous operation mode"
)
# if cdp_enabled, agent will have a cdp wallet
cdp_enabled: Optional[bool] = Field(
default=False,
description="Whether CDP (Crestal Development Platform) integration is enabled",
)
cdp_skills: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
description="List of CDP skills available to this agent",
)
cdp_network_id: Optional[str] = Field(
default="base-mainnet", description="Network identifier for CDP integration"
)
# if goat_enabled, will load goat skills
crossmint_config: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Dict of Crossmint wallet configurations",
)
goat_enabled: Optional[bool] = Field(
default=False,
description="Whether GOAT integration is enabled",
)
goat_skills: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
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: Optional[bool] = Field(
default=False, description="Whether the agent can receive events from Twitter"
)
twitter_config: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Twitter integration configuration settings",
)
# 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: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
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: Optional[bool] = Field(
default=False, description="Whether the agent can receive events from Telegram"
)
telegram_config: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Telegram integration configuration settings",
)
# telegram skills not used for now
telegram_skills: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
description="List of Telegram-specific skills available to this agent",
)
# skills
skills: Optional[Dict[str, SkillConfig]] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Dict of skills and their corresponding configurations",
)
# skills have no category
common_skills: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
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: Optional[bool] = Field(
default=False, description="Whether Enso integration is enabled"
)
# enso skills
enso_skills: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
description="List of Enso-specific skills available to this agent",
)
enso_config: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Enso integration configuration settings",
)
# Acolyt skills
acolyt_skills: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
description="List of Acolyt-specific skills available to this agent",
)
acolyt_config: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Acolyt integration configuration settings",
)
# Allora skills
allora_skills: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
description="List of Allora-specific skills available to this agent",
)
allora_config: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Allora integration configuration settings",
)
# ELFA skills
elfa_skills: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
description="List of Elfa-specific skills available to this agent",
)
elfa_config: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Elfa integration configuration settings",
)
# auto timestamp
created_at: SkipJsonSchema[datetime] = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_type=DateTime(timezone=True),
sa_column_kwargs={"server_default": func.now()},
nullable=False,
)
updated_at: SkipJsonSchema[datetime] = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_type=DateTime(timezone=True),
sa_column_kwargs={
"onupdate": lambda: datetime.now(timezone.utc),
},
nullable=False,
)
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)
# 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())
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"
@classmethod
async def count(cls) -> int:
async with get_session() as db:
return (await db.exec(select(func.count(Agent.id)))).one()
@classmethod
async def get(cls, agent_id: str) -> "Agent | None":
async with get_session() as db:
return (await db.exec(select(Agent).where(Agent.id == agent_id))).first()
async def create_or_update(self) -> ("Agent", bool):
"""Create the agent if not exists, otherwise update it.
Returns:
Agent: The created or updated agent
Raises:
HTTPException: If there are permission or validation errors
SQLAlchemyError: If there are database errors
"""
try:
# Generate ID if not provided
if not self.id:
self.id = str(XID())
# input check
self.number = None
self.created_at = None
self.updated_at = None
# 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.",
)
if not all(c.islower() or c.isdigit() or c == "-" for c in self.id):
raise HTTPException(
status_code=400,
detail="Agent ID must contain only lowercase letters, numbers, and hyphens.",
)
# Check if agent exists
existing_agent = await self.__class__.get(self.id)
if existing_agent:
# Check owner
if (
existing_agent.owner
and self.owner # if no owner, the request is coming from internal call, so skip the check
and existing_agent.owner != self.owner
):
raise HTTPException(
status_code=403,
detail="Your JWT token does not match the agent owner",
)
# Check upstream_id
if (
existing_agent.upstream_id
and self.upstream_id
and existing_agent.upstream_id != self.upstream_id
):
raise HTTPException(
status_code=400,
detail="upstream_id cannot be changed after creation",
)
# Update existing agent
for field in self.model_fields:
if field != "id": # Skip the primary key
if getattr(self, field) is not None:
setattr(existing_agent, field, getattr(self, field))
async with get_session() as db:
db.add(existing_agent)
await db.commit()
await db.refresh(existing_agent)
return existing_agent, False
else:
# Check upstream_id for idempotent
async with get_session() as db:
if self.upstream_id:
upstream_match = (
await db.exec(
select(Agent).where(
Agent.upstream_id == self.upstream_id
)
)
).first()
if upstream_match:
raise HTTPException(
status_code=400,
detail="upstream_id already exists",
)
# Create new agent
db.add(self)
await db.commit()
await db.refresh(self)
return self, True
except HTTPException:
await db.rollback()
raise
except Exception as e:
await db.rollback()
raise HTTPException(
status_code=500,
detail=f"Database error: {str(e)}",
) from e
class AgentResponse(BaseModel):
"""Response model for Agent API."""
# config part
id: str = Field(
description="Unique identifier for the agent. Must be URL-safe, containing only lowercase letters, numbers, and hyphens"
)
number: int = Field(
description="Auto-incrementing number assigned by the system for easy reference"
)
name: Optional[str] = Field(default=None, description="Display name of the agent")
slug: Optional[str] = Field(
default=None,
description="Slug of the agent, used for URL generation",
)
ticker: Optional[str] = Field(
default=None,
description="Ticker symbol of the agent",
)
token_address: Optional[str] = Field(
default=None,
description="Token address of the agent",
)
purpose: Optional[str] = Field(
default=None,
description="Purpose or role of the agent",
)
personality: Optional[str] = Field(
default=None,
description="Personality traits of the agent",
)
principles: Optional[str] = Field(
default=None,
description="Principles or values of the agent",
)
owner: Optional[str] = Field(
default=None,
description="Owner identifier of the agent, used for access control",
)
upstream_id: Optional[str] = Field(
default=None, description="External reference ID for idempotent operations"
)
model: str = Field(
description="AI model identifier to be used by this agent for processing requests"
)
prompt: Optional[str] = Field(
default=None,
description="Base system prompt that defines the agent's behavior and capabilities",
)
prompt_append: Optional[str] = Field(
default=None,
description="Additional system prompt that overrides or extends the base prompt",
)
temperature: float = Field(
description="AI model temperature parameter controlling response randomness (0.0-1.0)"
)
frequency_penalty: Optional[float] = Field(
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: Optional[float] = Field(
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_enabled: bool = Field(
description="Whether the agent can operate autonomously without user input"
)
autonomous_minutes: Optional[int] = Field(
description="Interval in minutes between autonomous operations when enabled"
)
autonomous_prompt: Optional[str] = Field(
description="Special prompt used during autonomous operation mode"
)
cdp_enabled: bool = Field(
description="Whether CDP (Crestal Development Platform) integration is enabled"
)
cdp_skills: Optional[List[str]] = Field(
description="List of CDP skills available to this agent"
)
cdp_network_id: Optional[str] = Field(
description="Network identifier for CDP integration"
)
crossmint_config: Optional[dict] = Field(
description="Dict of Crossmint wallet configurations",
)
goat_enabled: Optional[bool] = Field(
default=False,
description="Whether GOAT integration is enabled",
)
goat_skills: Optional[dict] = Field(
description="Dict of GOAT skills and their corresponding configurations",
)
twitter_entrypoint_enabled: bool = Field(
description="Whether the agent can receive events from Twitter"
)
twitter_config: Optional[dict] = Field(
description="Twitter integration configuration settings",
)
twitter_skills: Optional[List[str]] = Field(
description="List of Twitter-specific skills available to this agent"
)
telegram_entrypoint_enabled: bool = Field(
description="Whether the agent can receive events from Telegram"
)
telegram_config: Optional[dict] = Field(
description="Telegram integration configuration settings",
)
telegram_skills: Optional[List[str]] = Field(
description="List of Telegram-specific skills available to this agent"
)
common_skills: Optional[List[str]] = Field(
description="List of general-purpose skills available to this agent"
)
enso_enabled: bool = Field(description="Whether Enso integration is enabled")
enso_skills: Optional[List[str]] = Field(
description="List of Enso-specific skills available to this agent",
)
enso_config: Optional[dict] = Field(
description="Enso integration configuration settings",
)
acolyt_skills: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
description="List of Acolyt-specific skills available to this agent",
)
acolyt_config: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Acolyt integration configuration settings",
)
allora_skills: Optional[List[str]] = Field(
default=None,
sa_column=Column(ARRAY(String)),
description="List of Allora-specific skills available to this agent",
)
allora_config: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Allora integration configuration settings",
)
elfa_skills: Optional[List[str]] = Field(
default=None,
description="List of Elfa-specific skills available to this agent",
)
elfa_config: Optional[dict] = Field(
default=None,
description="Elfa integration configuration settings",
)
skills: Optional[Dict[str, SkillConfig]] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Dict of skills and their corresponding configurations",
)
created_at: datetime | None = Field(
description="Timestamp when this agent was created"
)
updated_at: datetime | None = Field(
description="Timestamp when this agent was last updated"
)
# data part
cdp_wallet_address: Optional[str] = Field(
description="CDP wallet address for the agent"
)
has_twitter_linked: bool = Field(
description="Whether the agent has linked their Twitter account"
)
linked_twitter_username: Optional[str] = Field(
description="The username of the linked Twitter account"
)
linked_twitter_name: Optional[str] = Field(
description="The name of the linked Twitter account"
)
has_twitter_self_key: bool = Field(
description="Whether the agent has self-keyed their Twitter account"
)
has_telegram_self_key: bool = Field(
description="Whether the agent has self-keyed their Telegram account"
)
linked_telegram_username: Optional[str] = Field(
description="The username of the linked Telegram account"
)
linked_telegram_name: Optional[str] = Field(
description="The name of the linked Telegram account"
)
@classmethod
def from_agent(
cls, agent: Agent, agent_data: Optional["AgentData"] = None
) -> "AgentResponse":
"""Create an AgentResponse from an Agent instance.
Args:
agent: Agent instance
agent_data: Optional AgentData instance
Returns:
AgentResponse: Response model with additional processed data
"""
# Get base data from agent
data = agent.model_dump()
# Process CDP wallet address
cdp_wallet_address = None
if agent_data and agent_data.cdp_wallet_data:
try:
wallet_data = json.loads(agent_data.cdp_wallet_data)
cdp_wallet_address = wallet_data.get("default_address_id")
except (json.JSONDecodeError, AttributeError):
pass
# Process Twitter linked status
has_twitter_linked = False
linked_twitter_username = None
linked_twitter_name = None
if agent_data and agent_data.twitter_access_token:
linked_twitter_username = agent_data.twitter_username
linked_twitter_name = agent_data.twitter_name
if agent_data.twitter_access_token_expires_at:
has_twitter_linked = (
agent_data.twitter_access_token_expires_at
> datetime.now(timezone.utc)
)
else:
has_twitter_linked = True
# Process Twitter self-key status and remove sensitive fields
has_twitter_self_key = False
twitter_config = data.get("twitter_config", {})
if twitter_config:
required_keys = {
"access_token",
"bearer_token",
"consumer_key",
"consumer_secret",
"access_token_secret",
}
has_twitter_self_key = all(
key in twitter_config and twitter_config[key] for key in required_keys
)
# Process Telegram self-key status and remove token
linked_telegram_username = None
linked_telegram_name = None
telegram_config = data.get("telegram_config", {})
has_telegram_self_key = bool(
telegram_config and "token" in telegram_config and telegram_config["token"]
)
if telegram_config and "token" in telegram_config:
if agent_data:
linked_telegram_username = agent_data.telegram_username
linked_telegram_name = agent_data.telegram_name
# Add processed fields to response
data.update(
{
"cdp_wallet_address": cdp_wallet_address,
"has_twitter_linked": has_twitter_linked,
"linked_twitter_username": linked_twitter_username,
"linked_twitter_name": linked_twitter_name,
"has_twitter_self_key": has_twitter_self_key,
"has_telegram_self_key": has_telegram_self_key,
"linked_telegram_username": linked_telegram_username,
"linked_telegram_name": linked_telegram_name,
}
)
return cls(**data)
class AgentData(SQLModel, table=True):
"""Agent data model for storing additional data related to the agent."""
__tablename__ = "agent_data"
id: str = Field(primary_key=True) # Same as Agent.id
cdp_wallet_data: Optional[str]
crossmint_wallet_data: Optional[dict] = Field(
default=None,
sa_column=Column(JSONB, nullable=True),
description="Crossmint wallet information",
)
twitter_id: Optional[str]
twitter_username: Optional[str]
twitter_name: Optional[str]
twitter_access_token: Optional[str]
twitter_access_token_expires_at: Optional[datetime] = Field(
sa_type=DateTime(timezone=True)
)
twitter_refresh_token: Optional[str]
telegram_id: Optional[str]
telegram_username: Optional[str]
telegram_name: Optional[str]
error_message: Optional[str]
created_at: datetime | None = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_type=DateTime(timezone=True),
sa_column_kwargs={"server_default": func.now()},
nullable=False,
)
updated_at: datetime | None = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_type=DateTime(timezone=True),
sa_column_kwargs={
"onupdate": lambda: datetime.now(timezone.utc),
},
nullable=False,
)
@classmethod
async def get(cls, agent_id: str) -> Optional["AgentData"]:
"""Get agent data by ID.
Args:
id: Agent ID
db: Database session
Returns:
AgentData if found, None otherwise
Raises:
HTTPException: If there are database errors
"""
try:
async with get_session() as db:
return (await db.exec(select(cls).where(cls.id == agent_id))).first()
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Failed to get agent data: {str(e)}",
) from e
async def save(self) -> None:
"""Save or update agent data.
Args:
db: Database session
Raises:
HTTPException: If there are database errors
"""
try:
async with get_session() as db:
existing = (
await db.exec(
select(self.__class__).where(self.__class__.id == self.id)
)
).first()
if existing:
# Update existing record
for field in self.model_fields:
if getattr(self, field) is not None:
setattr(existing, field, getattr(self, field))
db.add(existing)
else:
# Create new record
db.add(self)
await db.commit()
await db.refresh(self if not existing else existing)
except Exception as e:
await db.rollback()
raise HTTPException(
status_code=500,
detail=f"Failed to save agent data: {str(e)}",
) from e
class AgentQuota(SQLModel, table=True):
"""AgentQuota model."""
__tablename__ = "agent_quotas"
id: str = Field(primary_key=True)
plan: str = Field(default="self-hosted")
message_count_total: int = Field(default=0)
message_limit_total: int = Field(default=99999999)
message_count_monthly: int = Field(default=0)
message_limit_monthly: int = Field(default=99999999)
message_count_daily: int = Field(default=0)
message_limit_daily: int = Field(default=99999999)
last_message_time: Optional[datetime] = Field(default=None)
autonomous_count_total: int = Field(default=0)
autonomous_limit_total: int = Field(default=99999999)
autonomous_count_monthly: int = Field(default=0)
autonomous_limit_monthly: int = Field(default=99999999)
last_autonomous_time: Optional[datetime] = Field(default=None)
twitter_count_total: int = Field(default=0)
twitter_limit_total: int = Field(default=99999999)
twitter_count_daily: int = Field(default=0)
twitter_limit_daily: int = Field(default=99999999)
last_twitter_time: Optional[datetime] = Field(default=None)
created_at: datetime | None = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_type=DateTime(timezone=True),
sa_column_kwargs={"server_default": func.now()},
nullable=False,
)
updated_at: datetime | None = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_type=DateTime(timezone=True),
sa_column_kwargs={
"onupdate": lambda: datetime.now(timezone.utc),
},
nullable=False,
)
@classmethod
async def get(cls, agent_id: str) -> "AgentQuota":
"""Get agent quota by id, if not exists, create a new one.
Args:
agent_id: Agent ID
db: Database session
Returns:
AgentQuota: The agent's quota object
Raises:
HTTPException: If there are database errors
"""
try:
async with get_session() as db:
quota = (await db.exec(select(cls).where(cls.id == agent_id))).first()
if not quota:
quota = cls(id=agent_id)
db.add(quota)
await db.commit()
await db.refresh(quota)
return quota
except Exception as e:
await db.rollback()
raise HTTPException(
status_code=500,
detail=f"Failed to get agent quota: {str(e)}",
) from e
def has_message_quota(self) -> bool:
"""Check if the agent has message quota.
Returns:
bool: True if the agent has quota, False otherwise
"""
# Check total limit
if self.message_count_total >= self.message_limit_total:
return False
# Check monthly limit
if self.message_count_monthly >= self.message_limit_monthly:
return False
# Check daily limit
if self.message_count_daily >= self.message_limit_daily:
return False
return True
def has_autonomous_quota(self) -> bool:
"""Check if the agent has autonomous quota.
Returns:
bool: True if the agent has quota, False otherwise
"""
# Check total limit
if self.autonomous_count_total >= self.autonomous_limit_total:
return False
# Check monthly limit
if self.autonomous_count_monthly >= self.autonomous_limit_monthly:
return False
return True
def has_twitter_quota(self) -> bool:
"""Check if the agent has twitter quota.
Returns:
bool: True if the agent has quota, False otherwise
"""
# Check total limit
if self.twitter_count_total >= self.twitter_limit_total:
return False
# Check daily limit
if self.twitter_count_daily >= self.twitter_limit_daily:
return False
return True
async def add_message(self) -> None:
"""Add a message to the agent's message count.
Args:
db: Database session
Raises:
HTTPException: If there are database errors
"""
try:
async with get_session() as db:
self.message_count_total += 1
self.message_count_monthly += 1
self.message_count_daily += 1
self.last_message_time = datetime.now()
db.add(self)
await db.commit()
await db.refresh(self)
except Exception as e:
await db.rollback()
raise HTTPException(
status_code=500,
detail=f"Failed to add message: {str(e)}",
) from e
async def add_autonomous(self) -> None:
"""Add an autonomous message to the agent's autonomous count.
Args:
db: Database session
Raises:
HTTPException: If there are database errors
"""
try:
async with get_session() as db:
self.autonomous_count_total += 1
self.autonomous_count_monthly += 1
self.last_autonomous_time = datetime.now()
db.add(self)
await db.commit()
await db.refresh(self)
except Exception as e:
await db.rollback()
raise HTTPException(
status_code=500,
detail=f"Failed to add autonomous message: {str(e)}",
) from e
async def add_twitter(self) -> None:
"""Add a twitter message to the agent's twitter count.
Args:
db: Database session
Raises:
HTTPException: If there are database errors
"""
try:
async with get_session() as db:
self.twitter_count_total += 1
self.twitter_count_daily += 1
self.last_twitter_time = datetime.now()
db.add(self)
await db.commit()
await db.refresh(self)
except Exception as e:
await db.rollback()
raise HTTPException(
status_code=500,
detail=f"Failed to add twitter message: {str(e)}",
) from e
class AgentPluginData(SQLModel, table=True):
"""Model for storing plugin-specific data for agents.
This model uses a composite primary key of (agent_id, plugin, key) to store
plugin-specific data for agents in a flexible way.
Attributes:
agent_id: ID of the agent this data belongs to
plugin: Name of the plugin this data is for
key: Key for this specific piece of data
data: JSON data stored for this key
"""
__tablename__ = "agent_plugin_data"
agent_id: str = Field(primary_key=True)
plugin: str = Field(primary_key=True)
key: str = Field(primary_key=True)
data: Dict[str, Any] = Field(sa_column=Column(JSONB, nullable=True))
created_at: datetime | None = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_type=DateTime(timezone=True),
sa_column_kwargs={"server_default": func.now()},
nullable=False,
)
updated_at: datetime | None = Field(