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/mpp.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Payments that buy AgentJam credits over MPP, for the `payments` option of `connect()`.
|
|
2
|
+
|
|
3
|
+
Requires the `mpp` extra: `pip install "agentjam[mpp]"`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
from mpp import Challenge, Credential
|
|
14
|
+
from mpp.client import PaymentTransport
|
|
15
|
+
from mpp.errors import NoMethodFoundError
|
|
16
|
+
from mpp.methods import Method
|
|
17
|
+
from mpp.methods.stripe import client as stripe
|
|
18
|
+
from mpp.methods.tempo import TempoAccount
|
|
19
|
+
from mpp.methods.tempo import client as tempo
|
|
20
|
+
from mpp.runtime import ChallengeCandidate, ClientMethod, CredentialParams
|
|
21
|
+
|
|
22
|
+
from agentjam._errors import PaymentRequiredError
|
|
23
|
+
from agentjam._models import WireModel
|
|
24
|
+
from agentjam._relay.payments import Pay, Payments
|
|
25
|
+
from agentjam._stripe import CreateToken, issue_token
|
|
26
|
+
from agentjam._types import Period
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"CreateToken",
|
|
30
|
+
"RecurringToken",
|
|
31
|
+
"RecurringTokenRequest",
|
|
32
|
+
"StablecoinWallet",
|
|
33
|
+
"mpp_payments",
|
|
34
|
+
"stablecoin_payments",
|
|
35
|
+
"stripe_payments",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
StablecoinWallet = TempoAccount
|
|
39
|
+
"""A Tempo account that holds USD stablecoin, such as from `TempoAccount.from_key()`."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, kw_only=True)
|
|
43
|
+
class RecurringTokenRequest:
|
|
44
|
+
"""What a recurring token must allow to reload the AgentJam Wallet."""
|
|
45
|
+
|
|
46
|
+
amount_cents: int
|
|
47
|
+
"""The most one period may charge, in cents."""
|
|
48
|
+
currency: str
|
|
49
|
+
"""The currency the token charges in."""
|
|
50
|
+
period: Period
|
|
51
|
+
"""How often the token's allowance resets."""
|
|
52
|
+
expires_at: datetime | None
|
|
53
|
+
"""When the token stops being charged, if it ever does."""
|
|
54
|
+
network_id: str
|
|
55
|
+
"""The Stripe network business profile the token must be granted to."""
|
|
56
|
+
description: str | None
|
|
57
|
+
"""What the token pays for, shown to the payer."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
RecurringToken = Callable[[RecurringTokenRequest], Awaitable[str]]
|
|
61
|
+
"""Issues a recurring Stripe shared payment token, such as through Link, and returns its id."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _SubscriptionDetails(WireModel):
|
|
65
|
+
network_id: str
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _SubscriptionRequest(WireModel):
|
|
69
|
+
amount: str
|
|
70
|
+
currency: str
|
|
71
|
+
period_count: str
|
|
72
|
+
period_unit: Literal["day", "week", "month"]
|
|
73
|
+
subscription_expires: str | None = None
|
|
74
|
+
method_details: _SubscriptionDetails
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class _SubscriptionPayload(WireModel):
|
|
78
|
+
spt: str
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
_subscription: Method[_SubscriptionRequest, _SubscriptionPayload] = Method(
|
|
82
|
+
name="stripe",
|
|
83
|
+
intent="subscription",
|
|
84
|
+
request_model=_SubscriptionRequest,
|
|
85
|
+
payload_model=_SubscriptionPayload,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _construct_subscriber(recurring_token: RecurringToken) -> ClientMethod:
|
|
90
|
+
async def create_credential(params: CredentialParams) -> str:
|
|
91
|
+
challenge = params.challenge
|
|
92
|
+
request = _SubscriptionRequest.model_validate(challenge.request)
|
|
93
|
+
expires = request.subscription_expires
|
|
94
|
+
spt = await recurring_token(
|
|
95
|
+
RecurringTokenRequest(
|
|
96
|
+
amount_cents=int(request.amount),
|
|
97
|
+
currency=request.currency,
|
|
98
|
+
period=Period(
|
|
99
|
+
count=int(request.period_count), unit=request.period_unit
|
|
100
|
+
),
|
|
101
|
+
expires_at=datetime.fromisoformat(expires) if expires else None,
|
|
102
|
+
network_id=request.method_details.network_id,
|
|
103
|
+
description=challenge.description,
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
return Credential(
|
|
108
|
+
challenge=challenge.to_echo(), payload={"spt": spt}
|
|
109
|
+
).to_authorization()
|
|
110
|
+
|
|
111
|
+
return ClientMethod(method=_subscription, create_credential=create_credential)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# Invariant: Tempo amounts are base units of a 6-decimal USD stablecoin, and Stripe amounts are cents.
|
|
115
|
+
def _compute_cents(challenge: Challenge) -> Decimal:
|
|
116
|
+
amount = Decimal(str(challenge.request["amount"]))
|
|
117
|
+
|
|
118
|
+
return amount / 10_000 if challenge.method == "tempo" else amount
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _construct_unpayable_error(offered: Sequence[Challenge]) -> PaymentRequiredError:
|
|
122
|
+
kinds = ", ".join(dict.fromkeys(challenge.method for challenge in offered))
|
|
123
|
+
|
|
124
|
+
return PaymentRequiredError(
|
|
125
|
+
"payment_failed",
|
|
126
|
+
f"The gateway asks for {kinds} payments, which none of your payment methods make",
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _check_price(
|
|
131
|
+
candidates: Sequence[ChallengeCandidate], amount_cents: int
|
|
132
|
+
) -> Sequence[ChallengeCandidate]:
|
|
133
|
+
price = _compute_cents(candidates[0].challenge) if candidates else amount_cents
|
|
134
|
+
if price != amount_cents:
|
|
135
|
+
raise PaymentRequiredError(
|
|
136
|
+
"payment_failed",
|
|
137
|
+
f"The gateway asks for {price:f} cents, not the {amount_cents} you're paying",
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
return candidates
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _construct_pay(methods: Sequence[ClientMethod]) -> Pay:
|
|
144
|
+
async def pay(request: httpx.Request, amount_cents: int) -> httpx.Response:
|
|
145
|
+
transport = PaymentTransport(
|
|
146
|
+
methods,
|
|
147
|
+
max_payment_retries=1,
|
|
148
|
+
order_challenges=lambda candidates: _check_price(candidates, amount_cents),
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
async with httpx.AsyncClient(transport=transport) as client:
|
|
152
|
+
try:
|
|
153
|
+
return await client.send(request)
|
|
154
|
+
except NoMethodFoundError as error:
|
|
155
|
+
if not error.challenges:
|
|
156
|
+
raise
|
|
157
|
+
|
|
158
|
+
raise _construct_unpayable_error(error.challenges) from None
|
|
159
|
+
|
|
160
|
+
return pay
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def mpp_payments(
|
|
164
|
+
methods: ClientMethod | Sequence[ClientMethod],
|
|
165
|
+
*,
|
|
166
|
+
recurring_token: RecurringToken | None = None,
|
|
167
|
+
) -> Payments:
|
|
168
|
+
"""Buys AgentJam credits over MPP, which fill the AgentJam Wallet that pays for tasks.
|
|
169
|
+
|
|
170
|
+
Each payment asks one of `methods` for a new credential, preferring the gateway's order,
|
|
171
|
+
so a Stripe `create_token` must return a new token every time.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
methods: The pympp client methods that pay, such as `charge()` from `mpp.methods.stripe.client` or `mpp.methods.tempo.client`.
|
|
175
|
+
recurring_token: Issues a recurring token that reloads the AgentJam Wallet whenever it runs low.
|
|
176
|
+
Returns:
|
|
177
|
+
The `payments` option for `connect()`.
|
|
178
|
+
"""
|
|
179
|
+
payers = [methods] if isinstance(methods, ClientMethod) else list(methods)
|
|
180
|
+
subscriber = (
|
|
181
|
+
None if recurring_token is None else _construct_subscriber(recurring_token)
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
return Payments(
|
|
185
|
+
buy=_construct_pay(payers),
|
|
186
|
+
subscribe=None if subscriber is None else _construct_pay([subscriber]),
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def stablecoin_payments(*, account: StablecoinWallet) -> Payments:
|
|
191
|
+
"""Buys AgentJam credits over MPP in USD stablecoin on Tempo, which buys any amount from 1 cent.
|
|
192
|
+
|
|
193
|
+
The wallet must hold enough stablecoin to pay each top-up and its network fee.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
account: The wallet that pays for each top-up.
|
|
197
|
+
Returns:
|
|
198
|
+
The `payments` option for `connect()`.
|
|
199
|
+
"""
|
|
200
|
+
return mpp_payments(tempo.charge(account=account))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def stripe_payments(
|
|
204
|
+
*,
|
|
205
|
+
payment_method: str,
|
|
206
|
+
api_key: str | None = None,
|
|
207
|
+
create_token: CreateToken | None = None,
|
|
208
|
+
wallet: StablecoinWallet | None = None,
|
|
209
|
+
recurring_token: RecurringToken | None = None,
|
|
210
|
+
) -> Payments:
|
|
211
|
+
"""Buys AgentJam credits over MPP with a card saved on your own Stripe account.
|
|
212
|
+
|
|
213
|
+
It issues a new shared payment token for each top-up with your secret key. Pass `create_token`
|
|
214
|
+
instead of `api_key` to issue the tokens yourself, such as from a server that keeps the key.
|
|
215
|
+
|
|
216
|
+
Args:
|
|
217
|
+
payment_method: The payment method saved on your Stripe account that pays, such as `pm_…`.
|
|
218
|
+
api_key: Your Stripe secret or restricted key, which issues a new shared payment token for each top-up.
|
|
219
|
+
create_token: Issues a new shared payment token for each top-up instead of the SDK.
|
|
220
|
+
wallet: A stablecoin wallet that pays instead of the card whenever the gateway takes stablecoin, including for top-ups under $5.
|
|
221
|
+
recurring_token: Issues a recurring token that reloads the AgentJam Wallet whenever it runs low.
|
|
222
|
+
Returns:
|
|
223
|
+
The `payments` option for `connect()`.
|
|
224
|
+
Raises:
|
|
225
|
+
AgentJamError: If `create_token` is left out and `api_key` is empty or isn't a Stripe secret or restricted key.
|
|
226
|
+
"""
|
|
227
|
+
if create_token is None:
|
|
228
|
+
create_token = issue_token(api_key=api_key, payment_method=payment_method)
|
|
229
|
+
|
|
230
|
+
card = stripe.charge(create_token=create_token, payment_method=payment_method)
|
|
231
|
+
methods = [card] if wallet is None else [tempo.charge(account=wallet), card]
|
|
232
|
+
|
|
233
|
+
return mpp_payments(methods, recurring_token=recurring_token)
|
agentjam/openai.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Network tools for a hand-written loop over OpenAI's Responses API, through the `openai` package.
|
|
2
|
+
|
|
3
|
+
Requires the `openai` extra: `pip install "agentjam[openai]"`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from typing import assert_never
|
|
9
|
+
|
|
10
|
+
from openai.types.responses import (
|
|
11
|
+
EasyInputMessageParam,
|
|
12
|
+
FunctionToolParam,
|
|
13
|
+
ResponseFunctionCallOutputItemParam,
|
|
14
|
+
ResponseFunctionToolCall,
|
|
15
|
+
)
|
|
16
|
+
from openai.types.responses.response_input_item_param import FunctionCallOutput
|
|
17
|
+
|
|
18
|
+
from agentjam._adapters.responses import to_input_messages
|
|
19
|
+
from agentjam._adapters.shared import (
|
|
20
|
+
ContentPart,
|
|
21
|
+
DocumentPart,
|
|
22
|
+
ImagePart,
|
|
23
|
+
ModelContent,
|
|
24
|
+
TextPart,
|
|
25
|
+
execute_tool,
|
|
26
|
+
get_network_tools,
|
|
27
|
+
to_data_url,
|
|
28
|
+
)
|
|
29
|
+
from agentjam._agent import Agent
|
|
30
|
+
from agentjam._tools import NetworkTool, ToolName
|
|
31
|
+
from agentjam._types import IncomingMessage
|
|
32
|
+
|
|
33
|
+
__all__ = ["OpenAITools", "openai_tools", "to_responses_input"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class OpenAITools:
|
|
37
|
+
"""The network tools as Responses API function definitions, plus a dispatcher for the model's calls to them."""
|
|
38
|
+
|
|
39
|
+
definitions: list[FunctionToolParam]
|
|
40
|
+
"""The function definitions to send alongside your own."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, tools: Sequence[NetworkTool]) -> None:
|
|
43
|
+
self.definitions = [
|
|
44
|
+
{
|
|
45
|
+
"type": "function",
|
|
46
|
+
"name": tool.name,
|
|
47
|
+
"description": tool.description,
|
|
48
|
+
"parameters": tool.input_schema,
|
|
49
|
+
"strict": True,
|
|
50
|
+
}
|
|
51
|
+
for tool in tools
|
|
52
|
+
]
|
|
53
|
+
self._tools = {tool.name: tool for tool in tools}
|
|
54
|
+
|
|
55
|
+
async def execute(
|
|
56
|
+
self, call: ResponseFunctionToolCall
|
|
57
|
+
) -> FunctionCallOutput | None:
|
|
58
|
+
"""Runs a call to a network tool.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
call: The model's function call output item.
|
|
62
|
+
Returns:
|
|
63
|
+
The tool's output item, or None if the call is for one of your tools.
|
|
64
|
+
"""
|
|
65
|
+
tool = self._tools.get(call.name)
|
|
66
|
+
if tool is None:
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
output = await execute_tool(tool, _parse_arguments(call.arguments))
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
"type": "function_call_output",
|
|
73
|
+
"call_id": call.call_id,
|
|
74
|
+
"output": _to_output(output),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _to_output_content(part: ContentPart) -> ResponseFunctionCallOutputItemParam:
|
|
79
|
+
match part:
|
|
80
|
+
case TextPart(text=text):
|
|
81
|
+
return {"type": "input_text", "text": text}
|
|
82
|
+
|
|
83
|
+
case ImagePart():
|
|
84
|
+
return {
|
|
85
|
+
"type": "input_image",
|
|
86
|
+
"detail": "auto",
|
|
87
|
+
"image_url": to_data_url(part),
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
case DocumentPart(name=name):
|
|
91
|
+
return {
|
|
92
|
+
"type": "input_file",
|
|
93
|
+
"filename": name,
|
|
94
|
+
"file_data": to_data_url(part),
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
case _:
|
|
98
|
+
assert_never(part)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _to_output(content: ModelContent) -> list[ResponseFunctionCallOutputItemParam]:
|
|
102
|
+
text: ResponseFunctionCallOutputItemParam = {
|
|
103
|
+
"type": "input_text",
|
|
104
|
+
"text": content.text,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return [text, *map(_to_output_content, content.files)]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _parse_arguments(text: str) -> object:
|
|
111
|
+
try:
|
|
112
|
+
return json.loads(text)
|
|
113
|
+
except json.JSONDecodeError:
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def openai_tools(agent: Agent, pick: Sequence[ToolName] | None = None) -> OpenAITools:
|
|
118
|
+
"""Exposes the agent's network tools to a hand-written Responses API loop.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
agent: The connected agent whose network tools to expose.
|
|
122
|
+
pick: The network tools to expose. Defaults to every tool `connect()` enabled.
|
|
123
|
+
Returns:
|
|
124
|
+
The function definitions to send, and a dispatcher for the model's calls.
|
|
125
|
+
Raises:
|
|
126
|
+
AgentJamError: If `pick` names a tool `connect()` didn't enable.
|
|
127
|
+
"""
|
|
128
|
+
return OpenAITools(get_network_tools(agent, pick))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def to_responses_input(message: IncomingMessage) -> list[EasyInputMessageParam]:
|
|
132
|
+
"""Maps a message and the earlier turns of its conversation to Responses API input messages.
|
|
133
|
+
|
|
134
|
+
The message's own files become image, file and text content, while earlier turns are text only.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
message: A message received by `on_message`.
|
|
138
|
+
Returns:
|
|
139
|
+
The conversation, oldest turn first.
|
|
140
|
+
"""
|
|
141
|
+
return await to_input_messages(message)
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Runs agents built with the OpenAI Agents SDK, through the `openai-agents` package.
|
|
2
|
+
|
|
3
|
+
Requires the `openai-agents` extra: `pip install "agentjam[openai-agents]"`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import AsyncIterator, Callable, Sequence
|
|
8
|
+
from typing import Any, TypeAlias, TypeVar, assert_never
|
|
9
|
+
|
|
10
|
+
from agents import Agent as OpenAIAgent
|
|
11
|
+
from agents import (
|
|
12
|
+
AgentOutputSchemaBase,
|
|
13
|
+
FunctionTool,
|
|
14
|
+
Model,
|
|
15
|
+
RunItemStreamEvent,
|
|
16
|
+
Runner,
|
|
17
|
+
RunResultStreaming,
|
|
18
|
+
ToolCallItem,
|
|
19
|
+
ToolOutputFileContent,
|
|
20
|
+
ToolOutputImage,
|
|
21
|
+
ToolOutputText,
|
|
22
|
+
TResponseInputItem,
|
|
23
|
+
)
|
|
24
|
+
from agents.tool_context import ToolContext
|
|
25
|
+
from openai.types.responses import ResponseTextDeltaEvent
|
|
26
|
+
from pydantic_core import to_json
|
|
27
|
+
|
|
28
|
+
from agentjam._adapters.responses import construct_input_message, to_input_messages
|
|
29
|
+
from agentjam._adapters.shared import (
|
|
30
|
+
AdapterScreen,
|
|
31
|
+
AdapterScreenSettings,
|
|
32
|
+
ContentPart,
|
|
33
|
+
DocumentPart,
|
|
34
|
+
ImagePart,
|
|
35
|
+
ModelContent,
|
|
36
|
+
TextPart,
|
|
37
|
+
construct_adapter_screen,
|
|
38
|
+
construct_task_content,
|
|
39
|
+
execute_tool,
|
|
40
|
+
get_network_tools,
|
|
41
|
+
to_data_url,
|
|
42
|
+
)
|
|
43
|
+
from agentjam._agent import Agent
|
|
44
|
+
from agentjam._agent_options import AdapterHandlers
|
|
45
|
+
from agentjam._artifacts import artifact
|
|
46
|
+
from agentjam._content import LabeledContent
|
|
47
|
+
from agentjam._errors import AgentJamError
|
|
48
|
+
from agentjam._screening import FitSchema, Judge, ScreenRequest
|
|
49
|
+
from agentjam._tasks.incoming import IncomingTask, current_task
|
|
50
|
+
from agentjam._tools import NetworkTool, ToolName
|
|
51
|
+
from agentjam._types import IncomingMessage
|
|
52
|
+
|
|
53
|
+
__all__ = [
|
|
54
|
+
"AdapterScreenSettings",
|
|
55
|
+
"AgentModel",
|
|
56
|
+
"from_openai_agents",
|
|
57
|
+
"openai_agents_tools",
|
|
58
|
+
"to_agent_input",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
TContext = TypeVar("TContext")
|
|
62
|
+
|
|
63
|
+
AgentModel: TypeAlias = str | Model | None
|
|
64
|
+
"""The model an OpenAI agent runs on: a model name, a `Model`, or None for the run's default."""
|
|
65
|
+
|
|
66
|
+
ToolOutput: TypeAlias = ToolOutputText | ToolOutputImage | ToolOutputFileContent
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class _FitOutput(AgentOutputSchemaBase):
|
|
70
|
+
def __init__(self, schema: FitSchema) -> None:
|
|
71
|
+
self._schema = schema
|
|
72
|
+
|
|
73
|
+
def is_plain_text(self) -> bool:
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
def name(self) -> str:
|
|
77
|
+
return "fit"
|
|
78
|
+
|
|
79
|
+
def json_schema(self) -> dict[str, Any]:
|
|
80
|
+
return {**self._schema}
|
|
81
|
+
|
|
82
|
+
def is_strict_json_schema(self) -> bool:
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
def validate_json(self, json_str: str) -> str:
|
|
86
|
+
return json_str
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _to_output_content(part: ContentPart) -> ToolOutput:
|
|
90
|
+
match part:
|
|
91
|
+
case TextPart(text=text):
|
|
92
|
+
return ToolOutputText(text=text)
|
|
93
|
+
|
|
94
|
+
case ImagePart():
|
|
95
|
+
return ToolOutputImage(image_url=to_data_url(part))
|
|
96
|
+
|
|
97
|
+
case DocumentPart(name=name):
|
|
98
|
+
return ToolOutputFileContent(file_data=to_data_url(part), filename=name)
|
|
99
|
+
|
|
100
|
+
case _:
|
|
101
|
+
assert_never(part)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _to_output(content: ModelContent) -> list[ToolOutput]:
|
|
105
|
+
return [ToolOutputText(text=content.text), *map(_to_output_content, content.files)]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _parse_arguments(text: str) -> object:
|
|
109
|
+
try:
|
|
110
|
+
return json.loads(text)
|
|
111
|
+
except json.JSONDecodeError:
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _to_function_tool(tool: NetworkTool) -> FunctionTool:
|
|
116
|
+
async def invoke(context: ToolContext[Any], arguments: str) -> list[ToolOutput]:
|
|
117
|
+
return _to_output(await execute_tool(tool, _parse_arguments(arguments)))
|
|
118
|
+
|
|
119
|
+
return FunctionTool(
|
|
120
|
+
name=tool.name,
|
|
121
|
+
description=tool.description,
|
|
122
|
+
params_json_schema=tool.input_schema,
|
|
123
|
+
on_invoke_tool=invoke,
|
|
124
|
+
strict_json_schema=True,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def openai_agents_tools(
|
|
129
|
+
agent: Agent, pick: Sequence[ToolName] | None = None
|
|
130
|
+
) -> list[FunctionTool]:
|
|
131
|
+
"""Converts the agent's network tools into OpenAI Agents SDK function tools.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
agent: The connected agent whose network tools to convert.
|
|
135
|
+
pick: The network tools to convert. Defaults to every tool `connect()` enabled.
|
|
136
|
+
Returns:
|
|
137
|
+
The network tools, to add next to your own.
|
|
138
|
+
Raises:
|
|
139
|
+
AgentJamError: If `pick` names a tool `connect()` didn't enable.
|
|
140
|
+
"""
|
|
141
|
+
return [_to_function_tool(tool) for tool in get_network_tools(agent, pick)]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
async def to_agent_input(message: IncomingMessage) -> list[TResponseInputItem]:
|
|
145
|
+
"""Maps a message and the earlier turns of its conversation to OpenAI Agents SDK input items.
|
|
146
|
+
|
|
147
|
+
The message's own files become image, file and text content, while earlier turns are text only.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
message: A message received by `on_message`.
|
|
151
|
+
Returns:
|
|
152
|
+
The conversation, oldest turn first.
|
|
153
|
+
"""
|
|
154
|
+
return [*await to_input_messages(message)]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _get_called_tool(event: object) -> str | None:
|
|
158
|
+
if not isinstance(event, RunItemStreamEvent) or not isinstance(
|
|
159
|
+
event.item, ToolCallItem
|
|
160
|
+
):
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
return event.item.tool_name
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _assert_finished(interruptions: Sequence[object]) -> None:
|
|
167
|
+
if interruptions:
|
|
168
|
+
raise AgentJamError(
|
|
169
|
+
"The agent paused for tool approval, which AgentJam doesn't support yet"
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _to_text(output: object) -> str:
|
|
174
|
+
return output if isinstance(output, str) else to_json(output).decode()
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
async def _answer_text(result: RunResultStreaming) -> AsyncIterator[str]:
|
|
178
|
+
async for event in result.stream_events():
|
|
179
|
+
tool_name = _get_called_tool(event)
|
|
180
|
+
|
|
181
|
+
if event.type == "raw_response_event" and isinstance(
|
|
182
|
+
event.data, ResponseTextDeltaEvent
|
|
183
|
+
):
|
|
184
|
+
yield event.data.delta
|
|
185
|
+
elif tool_name is not None and (task := current_task()) is not None:
|
|
186
|
+
await task.update(f"Calling {tool_name}")
|
|
187
|
+
|
|
188
|
+
_assert_finished(result.interruptions)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _construct_judge(name: str) -> Callable[[AgentModel], Judge]:
|
|
192
|
+
def judge_with(model: AgentModel) -> Judge:
|
|
193
|
+
async def judge(request: ScreenRequest) -> str:
|
|
194
|
+
screener = OpenAIAgent[None](
|
|
195
|
+
name=f"{name} screener",
|
|
196
|
+
instructions=request.system,
|
|
197
|
+
model=model,
|
|
198
|
+
output_type=_FitOutput(request.schema),
|
|
199
|
+
)
|
|
200
|
+
result = await Runner.run(screener, request.prompt)
|
|
201
|
+
|
|
202
|
+
return _to_text(result.final_output)
|
|
203
|
+
|
|
204
|
+
return judge
|
|
205
|
+
|
|
206
|
+
return judge_with
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def from_openai_agents(
|
|
210
|
+
base: OpenAIAgent[TContext], *, screen: AdapterScreen[AgentModel] | None = None
|
|
211
|
+
) -> AdapterHandlers:
|
|
212
|
+
"""Runs incoming messages and tasks through a clone of `base` that also has the network tools.
|
|
213
|
+
|
|
214
|
+
Task output streams back as a text artifact. A run can't take input midway, so tasks open no inbox and the
|
|
215
|
+
requester's messages about them go to `on_message`.
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
base: The OpenAI agent to run, including your own tools.
|
|
219
|
+
screen: Screens each proposal with the agent's model, or a cheaper one, before accepting it. Defaults to off.
|
|
220
|
+
Returns:
|
|
221
|
+
Handlers to spread into `connect()`.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
def build_agent(agent: Agent) -> OpenAIAgent[TContext]:
|
|
225
|
+
return base.clone(tools=[*base.tools, *openai_agents_tools(agent)])
|
|
226
|
+
|
|
227
|
+
async def answer_message(message: IncomingMessage, agent: Agent) -> str:
|
|
228
|
+
result = await Runner.run(build_agent(agent), await to_agent_input(message))
|
|
229
|
+
_assert_finished(result.interruptions)
|
|
230
|
+
|
|
231
|
+
return _to_text(result.final_output)
|
|
232
|
+
|
|
233
|
+
async def perform_task(task: IncomingTask, agent: Agent) -> LabeledContent:
|
|
234
|
+
content = await construct_task_content(task)
|
|
235
|
+
result = Runner.run_streamed(
|
|
236
|
+
build_agent(agent), [construct_input_message(content)]
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
return artifact(_answer_text(result))
|
|
240
|
+
|
|
241
|
+
return AdapterHandlers(
|
|
242
|
+
tool_names=[tool.name for tool in base.tools],
|
|
243
|
+
screen=construct_adapter_screen(
|
|
244
|
+
screen,
|
|
245
|
+
model=base.model,
|
|
246
|
+
instructions=base.instructions
|
|
247
|
+
if isinstance(base.instructions, str)
|
|
248
|
+
else None,
|
|
249
|
+
judge_with=_construct_judge(base.name),
|
|
250
|
+
),
|
|
251
|
+
on_message=answer_message,
|
|
252
|
+
on_task=perform_task,
|
|
253
|
+
)
|
agentjam/py.typed
ADDED
|
File without changes
|