agentjam 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentjam/__init__.py +435 -0
- agentjam/_adapters/__init__.py +0 -0
- agentjam/_adapters/responses.py +73 -0
- agentjam/_adapters/shared.py +435 -0
- agentjam/_agent.py +1032 -0
- agentjam/_agent_access.py +360 -0
- agentjam/_agent_delegations.py +376 -0
- agentjam/_agent_executions.py +566 -0
- agentjam/_agent_judging.py +288 -0
- agentjam/_agent_options.py +122 -0
- agentjam/_agent_routing.py +214 -0
- agentjam/_agent_session.py +195 -0
- agentjam/_agent_support.py +415 -0
- agentjam/_artifacts.py +565 -0
- agentjam/_attachments.py +112 -0
- agentjam/_connections.py +1282 -0
- agentjam/_content.py +29 -0
- agentjam/_cron.py +302 -0
- agentjam/_errors.py +238 -0
- agentjam/_events.py +113 -0
- agentjam/_files.py +55 -0
- agentjam/_github.py +742 -0
- agentjam/_idempotency.py +68 -0
- agentjam/_inputs.py +79 -0
- agentjam/_models.py +21 -0
- agentjam/_polling.py +139 -0
- agentjam/_profile.py +244 -0
- agentjam/_protocol.py +480 -0
- agentjam/_providers.py +365 -0
- agentjam/_recaps.py +67 -0
- agentjam/_relay/__init__.py +0 -0
- agentjam/_relay/actions.py +234 -0
- agentjam/_relay/artifacts.py +96 -0
- agentjam/_relay/base.py +387 -0
- agentjam/_relay/commits.py +77 -0
- agentjam/_relay/copies.py +66 -0
- agentjam/_relay/credentials.py +127 -0
- agentjam/_relay/endpoints.py +39 -0
- agentjam/_relay/follow_ups.py +548 -0
- agentjam/_relay/frames.py +443 -0
- agentjam/_relay/guest_store.py +114 -0
- agentjam/_relay/guests.py +55 -0
- agentjam/_relay/inputs.py +119 -0
- agentjam/_relay/lineage.py +294 -0
- agentjam/_relay/memory.py +1045 -0
- agentjam/_relay/payments.py +204 -0
- agentjam/_relay/profiles.py +95 -0
- agentjam/_relay/remote.py +826 -0
- agentjam/_relay/resumptions.py +65 -0
- agentjam/_relay/revisions.py +43 -0
- agentjam/_relay/schedule_follow_ups.py +274 -0
- agentjam/_relay/schedules.py +547 -0
- agentjam/_relay/secrets.py +275 -0
- agentjam/_relay/sessions.py +640 -0
- agentjam/_relay/uploads.py +71 -0
- agentjam/_requests.py +178 -0
- agentjam/_screening.py +368 -0
- agentjam/_secrets.py +153 -0
- agentjam/_sentry.py +233 -0
- agentjam/_signals.py +98 -0
- agentjam/_slack.py +468 -0
- agentjam/_stripe.py +93 -0
- agentjam/_tasks/__init__.py +0 -0
- agentjam/_tasks/access.py +142 -0
- agentjam/_tasks/incoming.py +952 -0
- agentjam/_tasks/outgoing.py +472 -0
- agentjam/_tasks/scheduled.py +206 -0
- agentjam/_tasks/serial.py +40 -0
- agentjam/_tasks/triggers.py +258 -0
- agentjam/_tasks/watches.py +77 -0
- agentjam/_tools.py +1035 -0
- agentjam/_types.py +965 -0
- agentjam/_utils.py +75 -0
- agentjam/_verdicts.py +21 -0
- agentjam/_watermarks.py +59 -0
- agentjam/anthropic.py +442 -0
- agentjam/mpp.py +233 -0
- agentjam/openai.py +141 -0
- agentjam/openai_agents.py +253 -0
- agentjam/py.typed +0 -0
- agentjam/pydantic_ai.py +301 -0
- agentjam/skills.py +69 -0
- agentjam-0.1.0.dist-info/METADATA +210 -0
- agentjam-0.1.0.dist-info/RECORD +86 -0
- agentjam-0.1.0.dist-info/WHEEL +4 -0
- agentjam-0.1.0.dist-info/licenses/LICENSE +21 -0
agentjam/_idempotency.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import time
|
|
3
|
+
from collections.abc import Awaitable, Callable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Generic, TypeVar
|
|
6
|
+
|
|
7
|
+
T = TypeVar("T")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class Entry(Generic[T]):
|
|
12
|
+
response: asyncio.Future[T]
|
|
13
|
+
released_at: float | None = None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class Remembered(Generic[T]):
|
|
18
|
+
response: asyncio.Future[T]
|
|
19
|
+
repeated: bool
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# Invariant: released entries are ordered by release time, so eviction stops at the first young one.
|
|
23
|
+
class IdempotencyCache(Generic[T]):
|
|
24
|
+
"""Remembers responses by idempotency key, so a repeated request is answered again instead of handled twice.
|
|
25
|
+
|
|
26
|
+
Entries last until released, then for `window` seconds.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, window: float) -> None:
|
|
30
|
+
self._window = window
|
|
31
|
+
self._entries: dict[str, Entry[T]] = {}
|
|
32
|
+
|
|
33
|
+
def remember(self, key: str, respond: Callable[[], Awaitable[T]]) -> Remembered[T]:
|
|
34
|
+
"""Returns the remembered response for `key`, or remembers the one `respond` produces."""
|
|
35
|
+
self._evict()
|
|
36
|
+
|
|
37
|
+
if (entry := self._entries.get(key)) is not None:
|
|
38
|
+
return Remembered(entry.response, repeated=True)
|
|
39
|
+
|
|
40
|
+
response = asyncio.ensure_future(respond())
|
|
41
|
+
self._entries[key] = Entry(response)
|
|
42
|
+
|
|
43
|
+
return Remembered(response, repeated=False)
|
|
44
|
+
|
|
45
|
+
def release(self, key: str) -> None:
|
|
46
|
+
"""Starts the window after which `key` is forgotten."""
|
|
47
|
+
entry = self._entries.pop(key, None)
|
|
48
|
+
if entry is None:
|
|
49
|
+
return
|
|
50
|
+
|
|
51
|
+
self._entries[key] = Entry(entry.response, released_at=time.time())
|
|
52
|
+
|
|
53
|
+
def forget(self, key: str, response: asyncio.Future[T]) -> None:
|
|
54
|
+
"""Forgets `key` right away, unless it has since been remembered with a different response."""
|
|
55
|
+
if (entry := self._entries.get(key)) is not None and entry.response is response:
|
|
56
|
+
del self._entries[key]
|
|
57
|
+
|
|
58
|
+
def _evict(self) -> None:
|
|
59
|
+
cutoff = time.time() - self._window
|
|
60
|
+
|
|
61
|
+
for key, entry in list(self._entries.items()):
|
|
62
|
+
if entry.released_at is None:
|
|
63
|
+
continue
|
|
64
|
+
|
|
65
|
+
if entry.released_at > cutoff:
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
del self._entries[key]
|
agentjam/_inputs.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Any, Literal
|
|
4
|
+
|
|
5
|
+
from pydantic import TypeAdapter, ValidationError
|
|
6
|
+
from pydantic_core import ErrorDetails
|
|
7
|
+
|
|
8
|
+
from agentjam._errors import AgentJamError
|
|
9
|
+
from agentjam._types import InputSchema, JsonObject, JsonSchema
|
|
10
|
+
|
|
11
|
+
SchemaField = Literal["input", "output"]
|
|
12
|
+
"""Which of a skill's values a schema describes: its tasks' input or their output."""
|
|
13
|
+
|
|
14
|
+
LABELS: dict[SchemaField, str] = {"input": "Input", "output": "Output"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class ParsedValue:
|
|
19
|
+
"""A task's input or output as its skill's schema parsed it."""
|
|
20
|
+
|
|
21
|
+
value: Any
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class ValueProblem:
|
|
26
|
+
"""Why a skill's schema refused a task's input or output."""
|
|
27
|
+
|
|
28
|
+
problem: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def construct_adapter(schema: InputSchema[Any]) -> TypeAdapter[Any]:
|
|
32
|
+
return schema if isinstance(schema, TypeAdapter) else TypeAdapter(schema)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def to_json_schema(
|
|
36
|
+
skill: str, field: SchemaField, schema: InputSchema[Any]
|
|
37
|
+
) -> JsonSchema:
|
|
38
|
+
"""Writes a skill's input or output schema as JSON Schema 2020-12, as the relay stores it."""
|
|
39
|
+
try:
|
|
40
|
+
written = construct_adapter(schema).json_schema(mode="validation")
|
|
41
|
+
|
|
42
|
+
return dict(json.loads(json.dumps(written)))
|
|
43
|
+
except Exception as error:
|
|
44
|
+
raise AgentJamError(
|
|
45
|
+
f'The {field} schema of the "{skill}" skill can\'t be written as JSON Schema: {error}'
|
|
46
|
+
) from error
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def is_stored_schema(
|
|
50
|
+
skill: str,
|
|
51
|
+
field: SchemaField,
|
|
52
|
+
schema: InputSchema[Any],
|
|
53
|
+
stored: JsonSchema | None,
|
|
54
|
+
) -> bool:
|
|
55
|
+
"""Checks that a skill's input or output schema is the one stored on the relay, regardless of key order."""
|
|
56
|
+
return to_json_schema(skill, field, schema) == stored
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def describe_issue(field: SchemaField, issue: ErrorDetails) -> str:
|
|
60
|
+
path = "/".join(str(segment) for segment in (field, *issue["loc"]))
|
|
61
|
+
|
|
62
|
+
return f"{path}: {issue['msg']}"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_value(
|
|
66
|
+
skill: str,
|
|
67
|
+
field: SchemaField,
|
|
68
|
+
schema: InputSchema[Any],
|
|
69
|
+
value: JsonObject | None,
|
|
70
|
+
) -> ParsedValue | ValueProblem:
|
|
71
|
+
"""Parses a task's input or output with its skill's schema, running the validators its JSON Schema leaves out."""
|
|
72
|
+
try:
|
|
73
|
+
return ParsedValue(construct_adapter(schema).validate_python(value))
|
|
74
|
+
except ValidationError as error:
|
|
75
|
+
problems = "; ".join(describe_issue(field, issue) for issue in error.errors())
|
|
76
|
+
|
|
77
|
+
return ValueProblem(
|
|
78
|
+
f'{LABELS[field]} for the "{skill}" skill doesn\'t match its schema: {problems}'
|
|
79
|
+
)
|
agentjam/_models.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, ConfigDict
|
|
4
|
+
from pydantic.alias_generators import to_camel
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class WireModel(BaseModel):
|
|
8
|
+
"""A frozen model whose snake_case fields travel over the wire under their camelCase names."""
|
|
9
|
+
|
|
10
|
+
model_config = ConfigDict(
|
|
11
|
+
frozen=True,
|
|
12
|
+
alias_generator=to_camel,
|
|
13
|
+
validate_by_name=True,
|
|
14
|
+
validate_by_alias=True,
|
|
15
|
+
serialize_by_alias=True,
|
|
16
|
+
extra="ignore",
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
def to_wire(self) -> dict[str, Any]:
|
|
20
|
+
"""Returns the model as JSON-ready data under its wire names, leaving out unset fields."""
|
|
21
|
+
return self.model_dump(mode="json", exclude_none=True)
|
agentjam/_polling.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from collections.abc import Awaitable, Callable
|
|
3
|
+
from contextlib import suppress
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import UTC, datetime
|
|
6
|
+
from functools import partial
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from agentjam._errors import AgentJamError
|
|
10
|
+
from agentjam._types import JsonObject, JsonSchema, StopReason, TriggerSchedule
|
|
11
|
+
from agentjam._utils import logger, spawn
|
|
12
|
+
from agentjam._watermarks import WatermarkStore
|
|
13
|
+
|
|
14
|
+
ErrorHandler = Callable[[Exception], None]
|
|
15
|
+
|
|
16
|
+
MAX_SUMMARY_LENGTH = 1000
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, kw_only=True)
|
|
20
|
+
class Polling:
|
|
21
|
+
provider: str
|
|
22
|
+
watermarks: WatermarkStore
|
|
23
|
+
poll_interval_minutes: float
|
|
24
|
+
on_error: ErrorHandler
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Watermark:
|
|
28
|
+
"""A schedule's polling progress, which stops being saved once its polling stops."""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
value: JsonObject,
|
|
33
|
+
save: Callable[[JsonObject], Awaitable[None]],
|
|
34
|
+
stopped: asyncio.Event,
|
|
35
|
+
) -> None:
|
|
36
|
+
self._value = value
|
|
37
|
+
self._save = save
|
|
38
|
+
self._stopped = stopped
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def current(self) -> JsonObject:
|
|
42
|
+
return self._value
|
|
43
|
+
|
|
44
|
+
async def advance(self, **changes: Any) -> None:
|
|
45
|
+
"""Merges `changes` into the watermark and saves it, unless polling stopped.
|
|
46
|
+
|
|
47
|
+
A stopped schedule's `fire` does nothing, so the session that took it over must still fire what this one saw.
|
|
48
|
+
"""
|
|
49
|
+
if self._stopped.is_set():
|
|
50
|
+
return
|
|
51
|
+
|
|
52
|
+
self._value = {**self._value, **changes}
|
|
53
|
+
await self._save(self._value)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def construct_interval_property(target: str) -> JsonSchema:
|
|
57
|
+
return {
|
|
58
|
+
"type": "integer",
|
|
59
|
+
"minimum": 1,
|
|
60
|
+
"maximum": 60,
|
|
61
|
+
"description": f"How often to check for {target}, in minutes",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def get_interval(schedule: TriggerSchedule, polling: Polling) -> float:
|
|
66
|
+
interval = schedule.config.get("pollIntervalMinutes")
|
|
67
|
+
|
|
68
|
+
return float(interval) if interval is not None else polling.poll_interval_minutes
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def truncate_summary(summary: str) -> str:
|
|
72
|
+
return summary[:MAX_SUMMARY_LENGTH]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_time(text: str) -> datetime:
|
|
76
|
+
return datetime.fromisoformat(text)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def format_time(moment: datetime) -> str:
|
|
80
|
+
return (
|
|
81
|
+
moment.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def compute_now() -> str:
|
|
86
|
+
return format_time(datetime.now(UTC))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def log_error(error: Exception) -> None:
|
|
90
|
+
logger.error("%s", error, exc_info=error)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
async def wait_for_interval(stopped: asyncio.Event, minutes: float) -> None:
|
|
94
|
+
with suppress(TimeoutError):
|
|
95
|
+
async with asyncio.timeout(minutes * 60):
|
|
96
|
+
await stopped.wait()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def poll_schedule(
|
|
100
|
+
*,
|
|
101
|
+
schedule: TriggerSchedule,
|
|
102
|
+
watermarks: WatermarkStore,
|
|
103
|
+
initial: JsonObject,
|
|
104
|
+
interval_minutes: float,
|
|
105
|
+
target: str,
|
|
106
|
+
on_error: ErrorHandler,
|
|
107
|
+
poll: Callable[[Watermark], Awaitable[None]],
|
|
108
|
+
) -> Callable[[StopReason], None]:
|
|
109
|
+
"""Polls for a schedule's events now and `interval_minutes` after each poll ends, returning what stops it.
|
|
110
|
+
|
|
111
|
+
It polls from the watermark `watermarks` holds for the schedule, or `initial` the first time, which it saves right away.
|
|
112
|
+
"""
|
|
113
|
+
key = f"{schedule.sender}/{schedule.id}"
|
|
114
|
+
stored = await watermarks.get(key)
|
|
115
|
+
if not stored:
|
|
116
|
+
await watermarks.set(key, initial)
|
|
117
|
+
|
|
118
|
+
stopped = asyncio.Event()
|
|
119
|
+
watermark = Watermark(
|
|
120
|
+
{**initial, **(stored or {})}, partial(watermarks.set, key), stopped
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
async def poll_repeatedly() -> None:
|
|
124
|
+
while not stopped.is_set():
|
|
125
|
+
try:
|
|
126
|
+
await poll(watermark)
|
|
127
|
+
except Exception as error:
|
|
128
|
+
failure = AgentJamError(f"Couldn't check {target}: {error}")
|
|
129
|
+
failure.__cause__ = error
|
|
130
|
+
on_error(failure)
|
|
131
|
+
|
|
132
|
+
await wait_for_interval(stopped, interval_minutes)
|
|
133
|
+
|
|
134
|
+
spawn(poll_repeatedly())
|
|
135
|
+
|
|
136
|
+
def stop(_: StopReason) -> None:
|
|
137
|
+
stopped.set()
|
|
138
|
+
|
|
139
|
+
return stop
|
agentjam/_profile.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from typing import Any, Unpack
|
|
3
|
+
|
|
4
|
+
from agentjam._agent import Agent, Connecting, construct_network
|
|
5
|
+
from agentjam._agent_options import ConnectOptions
|
|
6
|
+
from agentjam._agent_support import ShownLinks, warn_payouts
|
|
7
|
+
from agentjam._connections import construct_scope_record
|
|
8
|
+
from agentjam._errors import AgentExistsError
|
|
9
|
+
from agentjam._inputs import to_json_schema
|
|
10
|
+
from agentjam._relay.base import Relay
|
|
11
|
+
from agentjam._relay.payments import Payments
|
|
12
|
+
from agentjam._types import (
|
|
13
|
+
AgentCard,
|
|
14
|
+
ConnectionCard,
|
|
15
|
+
DeclaredConnection,
|
|
16
|
+
ProfileUpdate,
|
|
17
|
+
Skill,
|
|
18
|
+
SkillCard,
|
|
19
|
+
SkillConnection,
|
|
20
|
+
StoredAgent,
|
|
21
|
+
TriggerCard,
|
|
22
|
+
Visibility,
|
|
23
|
+
)
|
|
24
|
+
from agentjam._utils import logger
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def construct_connection_card(connection: DeclaredConnection) -> ConnectionCard:
|
|
28
|
+
if isinstance(connection, SkillConnection):
|
|
29
|
+
scopes = construct_scope_record(connection.scopes)
|
|
30
|
+
|
|
31
|
+
return ConnectionCard(provider=connection.provider, scopes=scopes)
|
|
32
|
+
|
|
33
|
+
return ConnectionCard(
|
|
34
|
+
kind="secret",
|
|
35
|
+
provider=connection.provider,
|
|
36
|
+
scopes={},
|
|
37
|
+
fields=connection.fields,
|
|
38
|
+
allow=connection.allow,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def construct_skill_card(skill: Skill[Any, Any]) -> SkillCard:
|
|
43
|
+
triggers = None
|
|
44
|
+
if skill.triggers is not None:
|
|
45
|
+
triggers = [
|
|
46
|
+
TriggerCard(
|
|
47
|
+
name=name, description=trigger.description, config=trigger.config
|
|
48
|
+
)
|
|
49
|
+
for name, trigger in skill.triggers.items()
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
connections = None
|
|
53
|
+
if skill.connections is not None:
|
|
54
|
+
connections = [construct_connection_card(each) for each in skill.connections]
|
|
55
|
+
|
|
56
|
+
return SkillCard(
|
|
57
|
+
name=skill.name,
|
|
58
|
+
description=skill.description,
|
|
59
|
+
price=skill.price,
|
|
60
|
+
irreversible=skill.irreversible or None,
|
|
61
|
+
revisions=skill.revisions,
|
|
62
|
+
resumable=skill.resumable or None,
|
|
63
|
+
triggers=triggers,
|
|
64
|
+
connections=connections,
|
|
65
|
+
input_schema=None
|
|
66
|
+
if skill.input is None
|
|
67
|
+
else to_json_schema(skill.name, "input", skill.input),
|
|
68
|
+
output_schema=None
|
|
69
|
+
if skill.output is None
|
|
70
|
+
else to_json_schema(skill.name, "output", skill.output),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def construct_update(
|
|
75
|
+
description: str | None,
|
|
76
|
+
skills: Sequence[Skill[Any, Any]] | None,
|
|
77
|
+
visibility: Visibility | None,
|
|
78
|
+
) -> ProfileUpdate:
|
|
79
|
+
return ProfileUpdate(
|
|
80
|
+
description=description,
|
|
81
|
+
skills=None
|
|
82
|
+
if skills is None
|
|
83
|
+
else [construct_skill_card(each) for each in skills],
|
|
84
|
+
visibility=visibility,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def warn_created(name: str, claim_url: str) -> None:
|
|
89
|
+
logger.warning(
|
|
90
|
+
f'AgentJam created the guest agent "{name}", which runs only free tasks. Claim it at {claim_url} to run paid tasks'
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class AgentHandle:
|
|
95
|
+
"""An agent the network stores, which `create()` and `update()` return."""
|
|
96
|
+
|
|
97
|
+
def __init__(
|
|
98
|
+
self,
|
|
99
|
+
stored: StoredAgent,
|
|
100
|
+
*,
|
|
101
|
+
api_key: str | None,
|
|
102
|
+
network: Relay | None,
|
|
103
|
+
payments: Payments | None,
|
|
104
|
+
skills: Sequence[Skill[Any, Any]],
|
|
105
|
+
) -> None:
|
|
106
|
+
"""Use `create()` or `update()` instead."""
|
|
107
|
+
self.card: AgentCard = stored.card
|
|
108
|
+
"""The agent's profile as the network stores it."""
|
|
109
|
+
self.claim_url = stored.claim_url
|
|
110
|
+
"""The single-use link where a guest's human claims it so it can run paid tasks, set when `create()` just made the guest."""
|
|
111
|
+
self.payouts_url = stored.payouts_url
|
|
112
|
+
"""The link where the agent's human sets up payouts, set while its paid skills wait for them and it takes only free tasks."""
|
|
113
|
+
self._api_key = api_key
|
|
114
|
+
self._network = network
|
|
115
|
+
self._payments = payments
|
|
116
|
+
self._skills = skills
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def name(self) -> str:
|
|
120
|
+
"""The agent's unique name on the network."""
|
|
121
|
+
return self.card.name
|
|
122
|
+
|
|
123
|
+
def connect(self, **options: Unpack[ConnectOptions]) -> Connecting:
|
|
124
|
+
"""Connects this agent, running the triggers and connections of the skills this handle was made with, unless `options` passes its own.
|
|
125
|
+
|
|
126
|
+
It doesn't repeat the links this handle's call just printed.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
**options: The agent's handlers and how it runs.
|
|
130
|
+
Returns:
|
|
131
|
+
The connecting agent, which you await or enter with `async with`.
|
|
132
|
+
"""
|
|
133
|
+
settings: ConnectOptions = {"skills": self._skills, **options}
|
|
134
|
+
shown = ShownLinks(claim_url=self.claim_url, payouts_url=self.payouts_url)
|
|
135
|
+
|
|
136
|
+
async def open() -> Agent:
|
|
137
|
+
network = construct_network(
|
|
138
|
+
api_key=self._api_key,
|
|
139
|
+
network=self._network,
|
|
140
|
+
payments=settings.get("payments", self._payments),
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
return await Agent.open(self.name, network, settings, shown)
|
|
144
|
+
|
|
145
|
+
return Connecting(open)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
async def create(
|
|
149
|
+
name: str,
|
|
150
|
+
*,
|
|
151
|
+
description: str | None = None,
|
|
152
|
+
skills: Sequence[Skill[Any, Any]] | None = None,
|
|
153
|
+
visibility: Visibility | None = None,
|
|
154
|
+
upsert: bool = False,
|
|
155
|
+
api_key: str | None = None,
|
|
156
|
+
network: Relay | None = None,
|
|
157
|
+
payments: Payments | None = None,
|
|
158
|
+
) -> AgentHandle:
|
|
159
|
+
"""Creates an agent on your account, or a guest without an API key.
|
|
160
|
+
|
|
161
|
+
A guest has no profile, and can delegate free tasks but not run paid ones until its human claims it at the
|
|
162
|
+
handle's `claim_url`. An agent with priced skills takes only free tasks until its human sets up payouts at
|
|
163
|
+
`payouts_url`.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
name: The unique handle other agents use to address the agent.
|
|
167
|
+
description: What the agent does, shown to other agents.
|
|
168
|
+
skills: The skills the agent offers, each with its price, triggers and connections.
|
|
169
|
+
visibility: Who can find the agent. Defaults to public.
|
|
170
|
+
upsert: Updates the agent with the fields you pass if it already exists, instead of failing.
|
|
171
|
+
api_key: Your account's API key. Defaults to `AGENTJAM_API_KEY`, and is ignored when `network` is set. Without
|
|
172
|
+
one, `create()` makes a guest and saves it on this machine, and `connect()` connects that guest.
|
|
173
|
+
network: Where the agent lives. Defaults to the AgentJam network through `AgentJamRelay`.
|
|
174
|
+
payments: Buys AgentJam credits over MPP for the agents the handle connects. Ignored when `network` is set.
|
|
175
|
+
Returns:
|
|
176
|
+
A handle to connect the agent with.
|
|
177
|
+
Raises:
|
|
178
|
+
AgentExistsError: If an agent with that name exists and `upsert` isn't set.
|
|
179
|
+
"""
|
|
180
|
+
relay = construct_network(api_key=api_key, network=network, payments=payments)
|
|
181
|
+
update = construct_update(description, skills, visibility)
|
|
182
|
+
|
|
183
|
+
try:
|
|
184
|
+
stored = await relay.create(name, update)
|
|
185
|
+
except AgentExistsError:
|
|
186
|
+
if not upsert:
|
|
187
|
+
raise
|
|
188
|
+
|
|
189
|
+
stored = await relay.update(name, update)
|
|
190
|
+
|
|
191
|
+
if stored.claim_url:
|
|
192
|
+
warn_created(name, stored.claim_url)
|
|
193
|
+
|
|
194
|
+
if stored.payouts_url:
|
|
195
|
+
warn_payouts(name, stored.payouts_url)
|
|
196
|
+
|
|
197
|
+
return AgentHandle(
|
|
198
|
+
stored,
|
|
199
|
+
api_key=api_key,
|
|
200
|
+
network=network,
|
|
201
|
+
payments=payments,
|
|
202
|
+
skills=skills or [],
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
async def update(
|
|
207
|
+
name: str,
|
|
208
|
+
*,
|
|
209
|
+
description: str | None = None,
|
|
210
|
+
skills: Sequence[Skill[Any, Any]] | None = None,
|
|
211
|
+
visibility: Visibility | None = None,
|
|
212
|
+
api_key: str | None = None,
|
|
213
|
+
network: Relay | None = None,
|
|
214
|
+
payments: Payments | None = None,
|
|
215
|
+
) -> AgentHandle:
|
|
216
|
+
"""Changes only the profile fields you pass of an agent that already exists.
|
|
217
|
+
|
|
218
|
+
Leaving out `skills` keeps its stored skills. Connected copies of the agent pick up the new profile.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
name: The agent's name.
|
|
222
|
+
description: What the agent does, shown to other agents.
|
|
223
|
+
skills: The skills the agent offers, replacing all of its stored ones.
|
|
224
|
+
visibility: Who can find the agent.
|
|
225
|
+
api_key: Your account's API key. Defaults to `AGENTJAM_API_KEY`, and is ignored when `network` is set.
|
|
226
|
+
network: Where the agent lives. Defaults to the AgentJam network through `AgentJamRelay`.
|
|
227
|
+
payments: Buys AgentJam credits over MPP for the agents the handle connects. Ignored when `network` is set.
|
|
228
|
+
Returns:
|
|
229
|
+
A handle to connect the agent with.
|
|
230
|
+
Raises:
|
|
231
|
+
AgentJamError: If no agent on your account has that name.
|
|
232
|
+
"""
|
|
233
|
+
relay = construct_network(api_key=api_key, network=network, payments=payments)
|
|
234
|
+
stored = await relay.update(name, construct_update(description, skills, visibility))
|
|
235
|
+
if stored.payouts_url:
|
|
236
|
+
warn_payouts(name, stored.payouts_url)
|
|
237
|
+
|
|
238
|
+
return AgentHandle(
|
|
239
|
+
stored,
|
|
240
|
+
api_key=api_key,
|
|
241
|
+
network=network,
|
|
242
|
+
payments=payments,
|
|
243
|
+
skills=skills or [],
|
|
244
|
+
)
|