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/_utils.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Awaitable, Coroutine
|
|
6
|
+
from dataclasses import fields, is_dataclass
|
|
7
|
+
from typing import Any, TypeVar
|
|
8
|
+
from uuid import uuid4
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
from pydantic.alias_generators import to_camel
|
|
12
|
+
from pydantic_core import to_jsonable_python
|
|
13
|
+
|
|
14
|
+
T = TypeVar("T")
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger("agentjam")
|
|
17
|
+
|
|
18
|
+
background: set[asyncio.Task[Any]] = set()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
async def resolve_value(value: T | Awaitable[T]) -> T:
|
|
22
|
+
if inspect.isawaitable(value):
|
|
23
|
+
return await value
|
|
24
|
+
|
|
25
|
+
return value
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def spawn(work: Coroutine[Any, Any, T]) -> asyncio.Task[T]:
|
|
29
|
+
"""Runs `work` in the background, holding a reference so the task isn't garbage collected mid-flight."""
|
|
30
|
+
task = asyncio.create_task(work)
|
|
31
|
+
background.add(task)
|
|
32
|
+
task.add_done_callback(background.discard)
|
|
33
|
+
|
|
34
|
+
return task
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def create_id() -> str:
|
|
38
|
+
return str(uuid4())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def encode_json(value: Any) -> str:
|
|
42
|
+
return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def omit_none(data: dict[str, Any]) -> dict[str, Any]:
|
|
46
|
+
return {key: value for key, value in data.items() if value is not None}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def to_json_data(value: object) -> Any:
|
|
50
|
+
"""Converts models, dataclasses and dates into JSON-ready data under camelCase names, leaving out unset fields."""
|
|
51
|
+
match value:
|
|
52
|
+
case BaseModel():
|
|
53
|
+
return value.model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
54
|
+
|
|
55
|
+
case list() | tuple():
|
|
56
|
+
return [to_json_data(item) for item in value]
|
|
57
|
+
|
|
58
|
+
case dict():
|
|
59
|
+
return {key: to_json_data(item) for key, item in value.items()}
|
|
60
|
+
|
|
61
|
+
case _ if is_dataclass(value) and not isinstance(value, type):
|
|
62
|
+
return {
|
|
63
|
+
to_camel(member.name): to_json_data(item)
|
|
64
|
+
for member in fields(value)
|
|
65
|
+
if (item := getattr(value, member.name)) is not None
|
|
66
|
+
and not callable(item)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
case _:
|
|
70
|
+
return to_jsonable_python(value)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def encode_data(value: object) -> str:
|
|
74
|
+
"""Encodes `value` as JSON that can't close the prompt section it's embedded in."""
|
|
75
|
+
return encode_json(to_json_data(value)).replace("<", "\\u003c")
|
agentjam/_verdicts.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from agentjam._types import Verdict
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def accept() -> Verdict:
|
|
5
|
+
"""Accepts a proposed task. Return it from `on_proposal`.
|
|
6
|
+
|
|
7
|
+
Returns:
|
|
8
|
+
A verdict accepting the task.
|
|
9
|
+
"""
|
|
10
|
+
return Verdict(accepted=True)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def reject(reason: str) -> Verdict:
|
|
14
|
+
"""Declines a proposed task, telling the requester why. Return it from `on_proposal`.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
reason: Why the task was declined, shown to the requester.
|
|
18
|
+
Returns:
|
|
19
|
+
A verdict rejecting the task.
|
|
20
|
+
"""
|
|
21
|
+
return Verdict(accepted=False, reason=reason)
|
agentjam/_watermarks.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from copy import deepcopy
|
|
2
|
+
from typing import Protocol
|
|
3
|
+
|
|
4
|
+
from agentjam._types import JsonObject
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class WatermarkStore(Protocol):
|
|
8
|
+
"""Where polling triggers keep each schedule's progress, such as the last event they fired.
|
|
9
|
+
|
|
10
|
+
A session that takes a schedule over, or a restarted one, resumes where the last left off.
|
|
11
|
+
Back it with your database in production.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
async def get(self, key: str) -> JsonObject | None:
|
|
15
|
+
"""Reads a schedule's watermark.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
key: Identifies the schedule, as `<requester>/<schedule id>`.
|
|
19
|
+
|
|
20
|
+
Returns:
|
|
21
|
+
The watermark last set for the schedule, or None before the first.
|
|
22
|
+
"""
|
|
23
|
+
...
|
|
24
|
+
|
|
25
|
+
async def set(self, key: str, watermark: JsonObject) -> None:
|
|
26
|
+
"""Replaces a schedule's watermark.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
key: Identifies the schedule, as `<requester>/<schedule id>`.
|
|
30
|
+
watermark: The schedule's progress, a JSON object of a few hundred bytes.
|
|
31
|
+
"""
|
|
32
|
+
...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class MemoryWatermarkStore:
|
|
36
|
+
"""A `WatermarkStore` in this process's memory, for tests. Its watermarks are lost when the process exits."""
|
|
37
|
+
|
|
38
|
+
def __init__(self) -> None:
|
|
39
|
+
self._watermarks: dict[str, JsonObject] = {}
|
|
40
|
+
|
|
41
|
+
async def get(self, key: str) -> JsonObject | None:
|
|
42
|
+
"""Reads a schedule's watermark.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
key: Identifies the schedule, as `<requester>/<schedule id>`.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
The watermark last set for the schedule, or None before the first.
|
|
49
|
+
"""
|
|
50
|
+
return self._watermarks.get(key)
|
|
51
|
+
|
|
52
|
+
async def set(self, key: str, watermark: JsonObject) -> None:
|
|
53
|
+
"""Replaces a schedule's watermark with a copy of `watermark`.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
key: Identifies the schedule, as `<requester>/<schedule id>`.
|
|
57
|
+
watermark: The schedule's progress.
|
|
58
|
+
"""
|
|
59
|
+
self._watermarks[key] = deepcopy(watermark)
|
agentjam/anthropic.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
"""Runs agents on Anthropic's Messages API, through the `anthropic` package.
|
|
2
|
+
|
|
3
|
+
Requires the `anthropic` extra: `pip install "agentjam[anthropic]"`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import AsyncIterator, Callable, Mapping, Sequence
|
|
8
|
+
from typing import Any, Literal, Required, TypeAlias, TypedDict, Unpack, assert_never
|
|
9
|
+
|
|
10
|
+
from anthropic import AsyncAnthropic
|
|
11
|
+
from anthropic.lib.tools import (
|
|
12
|
+
BetaAsyncBuiltinFunctionTool,
|
|
13
|
+
BetaAsyncFunctionTool,
|
|
14
|
+
BetaAsyncRunnableToolset,
|
|
15
|
+
BetaFunctionToolResultType,
|
|
16
|
+
)
|
|
17
|
+
from anthropic.types import ModelParam, ToolParam, ToolResultBlockParam, ToolUseBlock
|
|
18
|
+
from anthropic.types.anthropic_beta_param import AnthropicBetaParam
|
|
19
|
+
from anthropic.types.beta import (
|
|
20
|
+
BetaCacheControlEphemeralParam,
|
|
21
|
+
BetaContentBlockParam,
|
|
22
|
+
BetaContextManagementConfigParam,
|
|
23
|
+
BetaImageBlockParam,
|
|
24
|
+
BetaMessage,
|
|
25
|
+
BetaMessageParam,
|
|
26
|
+
BetaMetadataParam,
|
|
27
|
+
BetaOutputConfigParam,
|
|
28
|
+
BetaRequestDocumentBlockParam,
|
|
29
|
+
BetaRequestMCPServerURLDefinitionParam,
|
|
30
|
+
BetaTextBlockParam,
|
|
31
|
+
BetaThinkingConfigParam,
|
|
32
|
+
BetaToolChoiceParam,
|
|
33
|
+
BetaToolUnionParam,
|
|
34
|
+
BetaToolUseBlock,
|
|
35
|
+
BetaUserMessageParam,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
from agentjam._adapters.shared import (
|
|
39
|
+
AdapterScreen,
|
|
40
|
+
AdapterScreenSettings,
|
|
41
|
+
ContentPart,
|
|
42
|
+
DocumentPart,
|
|
43
|
+
ImagePart,
|
|
44
|
+
ModelContent,
|
|
45
|
+
TextPart,
|
|
46
|
+
Turn,
|
|
47
|
+
construct_adapter_screen,
|
|
48
|
+
construct_model_content,
|
|
49
|
+
construct_task_content,
|
|
50
|
+
execute_tool,
|
|
51
|
+
get_network_tools,
|
|
52
|
+
to_history,
|
|
53
|
+
)
|
|
54
|
+
from agentjam._agent import Agent
|
|
55
|
+
from agentjam._agent_options import AdapterHandlers
|
|
56
|
+
from agentjam._artifacts import artifact
|
|
57
|
+
from agentjam._content import LabeledContent
|
|
58
|
+
from agentjam._errors import AgentJamError
|
|
59
|
+
from agentjam._screening import Judge, ScreenRequest
|
|
60
|
+
from agentjam._tasks.incoming import IncomingTask, current_task
|
|
61
|
+
from agentjam._tools import NetworkTool, ToolName
|
|
62
|
+
from agentjam._types import IncomingMessage, TaskInbox
|
|
63
|
+
|
|
64
|
+
__all__ = [
|
|
65
|
+
"AdapterScreenSettings",
|
|
66
|
+
"AnthropicParams",
|
|
67
|
+
"AnthropicTool",
|
|
68
|
+
"AnthropicTools",
|
|
69
|
+
"anthropic_runnable_tools",
|
|
70
|
+
"anthropic_tools",
|
|
71
|
+
"from_anthropic",
|
|
72
|
+
"to_anthropic_messages",
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
AnthropicTool: TypeAlias = (
|
|
76
|
+
BetaAsyncFunctionTool[Any]
|
|
77
|
+
| BetaAsyncBuiltinFunctionTool
|
|
78
|
+
| BetaAsyncRunnableToolset
|
|
79
|
+
| BetaToolUnionParam
|
|
80
|
+
)
|
|
81
|
+
"""A tool `client.beta.messages.tool_runner()` takes: a runnable tool or toolset, or a tool definition it doesn't run."""
|
|
82
|
+
|
|
83
|
+
ContentBlock: TypeAlias = (
|
|
84
|
+
BetaTextBlockParam | BetaImageBlockParam | BetaRequestDocumentBlockParam
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
FIT_TOOL = "record_fit"
|
|
88
|
+
|
|
89
|
+
SCREEN_TOKENS = 1024
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class AnthropicParams(TypedDict, total=False):
|
|
93
|
+
"""The `client.beta.messages.tool_runner()` params `from_anthropic()` passes on, as the tool runner documents them."""
|
|
94
|
+
|
|
95
|
+
model: Required[ModelParam]
|
|
96
|
+
"""The model to run, which also screens proposals unless the screen names another."""
|
|
97
|
+
max_tokens: Required[int]
|
|
98
|
+
"""The most tokens each of the model's turns may take."""
|
|
99
|
+
system: str | Sequence[BetaTextBlockParam]
|
|
100
|
+
"""The system prompt, which screening also follows."""
|
|
101
|
+
thinking: BetaThinkingConfigParam
|
|
102
|
+
tool_choice: BetaToolChoiceParam
|
|
103
|
+
output_config: BetaOutputConfigParam
|
|
104
|
+
stop_sequences: list[str]
|
|
105
|
+
metadata: BetaMetadataParam
|
|
106
|
+
service_tier: Literal["auto", "standard_only"]
|
|
107
|
+
speed: Literal["standard", "fast"] | None
|
|
108
|
+
cache_control: BetaCacheControlEphemeralParam | None
|
|
109
|
+
context_management: BetaContextManagementConfigParam | None
|
|
110
|
+
mcp_servers: Sequence[BetaRequestMCPServerURLDefinitionParam]
|
|
111
|
+
inference_geo: str | None
|
|
112
|
+
betas: list[AnthropicBetaParam]
|
|
113
|
+
thread: Literal[False] | None
|
|
114
|
+
"""False to send the full history every turn, rather than only new messages over a thread."""
|
|
115
|
+
max_iterations: int
|
|
116
|
+
extra_headers: Mapping[str, str]
|
|
117
|
+
extra_body: object
|
|
118
|
+
timeout: float | None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class AnthropicTools:
|
|
122
|
+
"""The network tools as Messages API tool definitions, plus a dispatcher for the model's calls to them."""
|
|
123
|
+
|
|
124
|
+
definitions: list[ToolParam]
|
|
125
|
+
"""The tool definitions to send alongside your own."""
|
|
126
|
+
|
|
127
|
+
def __init__(self, tools: Sequence[NetworkTool]) -> None:
|
|
128
|
+
self.definitions = [
|
|
129
|
+
{
|
|
130
|
+
"name": tool.name,
|
|
131
|
+
"description": tool.description,
|
|
132
|
+
"input_schema": tool.input_schema,
|
|
133
|
+
}
|
|
134
|
+
for tool in tools
|
|
135
|
+
]
|
|
136
|
+
self._tools = {tool.name: tool for tool in tools}
|
|
137
|
+
|
|
138
|
+
async def execute(
|
|
139
|
+
self, tool_use: ToolUseBlock | BetaToolUseBlock
|
|
140
|
+
) -> ToolResultBlockParam | None:
|
|
141
|
+
"""Runs a call to a network tool.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
tool_use: The model's `tool_use` block.
|
|
145
|
+
Returns:
|
|
146
|
+
The tool's result block, or None if the call is for one of your tools.
|
|
147
|
+
"""
|
|
148
|
+
tool = self._tools.get(tool_use.name)
|
|
149
|
+
if tool is None:
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
output = await execute_tool(tool, tool_use.input)
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
"type": "tool_result",
|
|
156
|
+
"tool_use_id": tool_use.id,
|
|
157
|
+
"content": _to_content(output),
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class _RunnableTool(BetaAsyncBuiltinFunctionTool):
|
|
162
|
+
def __init__(self, tool: NetworkTool) -> None:
|
|
163
|
+
self._tool = tool
|
|
164
|
+
|
|
165
|
+
def to_dict(self) -> BetaToolUnionParam:
|
|
166
|
+
return {
|
|
167
|
+
"name": self._tool.name,
|
|
168
|
+
"description": self._tool.description,
|
|
169
|
+
"input_schema": self._tool.input_schema,
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async def call(self, input: object) -> BetaFunctionToolResultType:
|
|
173
|
+
return _to_content(await execute_tool(self._tool, input))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _to_content_block(part: ContentPart) -> ContentBlock:
|
|
177
|
+
match part:
|
|
178
|
+
case TextPart(text=text):
|
|
179
|
+
return {"type": "text", "text": text}
|
|
180
|
+
|
|
181
|
+
case ImagePart(mime_type=mime_type, data=data):
|
|
182
|
+
return {
|
|
183
|
+
"type": "image",
|
|
184
|
+
"source": {"type": "base64", "media_type": mime_type, "data": data},
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
case DocumentPart(name=name, mime_type=mime_type, data=data):
|
|
188
|
+
return {
|
|
189
|
+
"type": "document",
|
|
190
|
+
"title": name,
|
|
191
|
+
"source": {"type": "base64", "media_type": mime_type, "data": data},
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
case _:
|
|
195
|
+
assert_never(part)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _to_content(content: ModelContent) -> list[ContentBlock]:
|
|
199
|
+
text: ContentBlock = {"type": "text", "text": content.text}
|
|
200
|
+
|
|
201
|
+
return [text, *map(_to_content_block, content.files)]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _to_user_message(content: ModelContent) -> BetaMessageParam:
|
|
205
|
+
return {"role": "user", "content": _to_content(content)}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def anthropic_tools(
|
|
209
|
+
agent: Agent, pick: Sequence[ToolName] | None = None
|
|
210
|
+
) -> AnthropicTools:
|
|
211
|
+
"""Exposes the agent's network tools to a hand-written `messages.create()` loop.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
agent: The connected agent whose network tools to expose.
|
|
215
|
+
pick: The network tools to expose. Defaults to every tool `connect()` enabled.
|
|
216
|
+
Returns:
|
|
217
|
+
The tool definitions to send, and a dispatcher for the model's calls.
|
|
218
|
+
Raises:
|
|
219
|
+
AgentJamError: If `pick` names a tool `connect()` didn't enable.
|
|
220
|
+
"""
|
|
221
|
+
return AnthropicTools(get_network_tools(agent, pick))
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def anthropic_runnable_tools(
|
|
225
|
+
agent: Agent, pick: Sequence[ToolName] | None = None
|
|
226
|
+
) -> list[BetaAsyncBuiltinFunctionTool]:
|
|
227
|
+
"""Converts the agent's network tools into runnable tools for Anthropic's beta tool runner.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
agent: The connected agent whose network tools to convert.
|
|
231
|
+
pick: The network tools to convert. Defaults to every tool `connect()` enabled.
|
|
232
|
+
Returns:
|
|
233
|
+
The network tools, to add next to your own.
|
|
234
|
+
Raises:
|
|
235
|
+
AgentJamError: If `pick` names a tool `connect()` didn't enable.
|
|
236
|
+
"""
|
|
237
|
+
return [_RunnableTool(tool) for tool in get_network_tools(agent, pick)]
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
async def to_anthropic_messages(message: IncomingMessage) -> list[BetaMessageParam]:
|
|
241
|
+
"""Maps a message and the earlier turns of its conversation to Anthropic message params.
|
|
242
|
+
|
|
243
|
+
The message's own files become image, document and text blocks, while earlier turns are text only.
|
|
244
|
+
|
|
245
|
+
Args:
|
|
246
|
+
message: A message received by `on_message`.
|
|
247
|
+
Returns:
|
|
248
|
+
The conversation, oldest turn first.
|
|
249
|
+
"""
|
|
250
|
+
history = [_to_turn_message(turn) for turn in to_history(message)]
|
|
251
|
+
|
|
252
|
+
return [*history, _to_user_message(await construct_model_content(message))]
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _to_turn_message(turn: Turn) -> BetaMessageParam:
|
|
256
|
+
match turn.role:
|
|
257
|
+
case "user":
|
|
258
|
+
return {"role": "user", "content": turn.text}
|
|
259
|
+
|
|
260
|
+
case "assistant":
|
|
261
|
+
return {"role": "assistant", "content": turn.text}
|
|
262
|
+
|
|
263
|
+
case _:
|
|
264
|
+
assert_never(turn.role)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _get_text(message: BetaMessage) -> str:
|
|
268
|
+
return "".join(block.text for block in message.content if block.type == "text")
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _list_blocks(message: BetaUserMessageParam | None) -> list[BetaContentBlockParam]:
|
|
272
|
+
if message is None:
|
|
273
|
+
return []
|
|
274
|
+
|
|
275
|
+
content = message["content"]
|
|
276
|
+
|
|
277
|
+
return (
|
|
278
|
+
[{"type": "text", "text": content}]
|
|
279
|
+
if isinstance(content, str)
|
|
280
|
+
else list(content)
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
async def _take_steering(inbox: TaskInbox) -> list[ContentBlock]:
|
|
285
|
+
contents = [await construct_model_content(message) for message in inbox.take()]
|
|
286
|
+
|
|
287
|
+
return [block for content in contents for block in _to_content(content)]
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
async def _answer_text(
|
|
291
|
+
client: AsyncAnthropic,
|
|
292
|
+
params: AnthropicParams,
|
|
293
|
+
tools: list[AnthropicTool],
|
|
294
|
+
messages: list[BetaMessageParam],
|
|
295
|
+
inbox: TaskInbox,
|
|
296
|
+
) -> AsyncIterator[str]:
|
|
297
|
+
while True:
|
|
298
|
+
runner = client.beta.messages.tool_runner(
|
|
299
|
+
**params, tools=tools, messages=messages, stream=True
|
|
300
|
+
)
|
|
301
|
+
steering: list[ContentBlock] = []
|
|
302
|
+
|
|
303
|
+
try:
|
|
304
|
+
async for turn in runner:
|
|
305
|
+
async for event in turn:
|
|
306
|
+
if (
|
|
307
|
+
event.type == "content_block_delta"
|
|
308
|
+
and event.delta.type == "text_delta"
|
|
309
|
+
):
|
|
310
|
+
yield event.delta.text
|
|
311
|
+
elif (
|
|
312
|
+
event.type == "content_block_start"
|
|
313
|
+
and event.content_block.type == "tool_use"
|
|
314
|
+
and (task := current_task()) is not None
|
|
315
|
+
):
|
|
316
|
+
await task.update(f"Calling {event.content_block.name}")
|
|
317
|
+
|
|
318
|
+
reply = await turn.get_final_message()
|
|
319
|
+
results = (
|
|
320
|
+
await runner.generate_tool_call_response()
|
|
321
|
+
if reply.stop_reason == "tool_use"
|
|
322
|
+
else None
|
|
323
|
+
)
|
|
324
|
+
steering = await _take_steering(inbox)
|
|
325
|
+
blocks = [*_list_blocks(results), *steering]
|
|
326
|
+
messages = [*messages, reply.to_param()]
|
|
327
|
+
if blocks:
|
|
328
|
+
messages.append({"role": "user", "content": blocks})
|
|
329
|
+
|
|
330
|
+
if steering:
|
|
331
|
+
break
|
|
332
|
+
finally:
|
|
333
|
+
await runner.close()
|
|
334
|
+
|
|
335
|
+
if not steering:
|
|
336
|
+
return
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _get_system_text(system: str | Sequence[BetaTextBlockParam] | None) -> str | None:
|
|
340
|
+
if system is None or isinstance(system, str):
|
|
341
|
+
return system
|
|
342
|
+
|
|
343
|
+
return "\n\n".join(block["text"] for block in system)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _get_tool_name(tool: AnthropicTool) -> str | None:
|
|
347
|
+
if isinstance(tool, BetaAsyncRunnableToolset):
|
|
348
|
+
return None
|
|
349
|
+
|
|
350
|
+
if isinstance(tool, BetaAsyncFunctionTool | BetaAsyncBuiltinFunctionTool):
|
|
351
|
+
return tool.name
|
|
352
|
+
|
|
353
|
+
name = tool.get("name")
|
|
354
|
+
|
|
355
|
+
return name if isinstance(name, str) else None
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _construct_judge(client: AsyncAnthropic) -> Callable[[ModelParam], Judge]:
|
|
359
|
+
def judge_with(model: ModelParam) -> Judge:
|
|
360
|
+
async def judge(request: ScreenRequest) -> str:
|
|
361
|
+
reply = await client.messages.create(
|
|
362
|
+
model=model,
|
|
363
|
+
max_tokens=SCREEN_TOKENS,
|
|
364
|
+
system=request.system,
|
|
365
|
+
messages=[{"role": "user", "content": request.prompt}],
|
|
366
|
+
tools=[
|
|
367
|
+
{
|
|
368
|
+
"name": FIT_TOOL,
|
|
369
|
+
"description": "Records how fully the agent can do the proposal",
|
|
370
|
+
"input_schema": {**request.schema},
|
|
371
|
+
}
|
|
372
|
+
],
|
|
373
|
+
tool_choice={"type": "tool", "name": FIT_TOOL},
|
|
374
|
+
)
|
|
375
|
+
recorded = next(
|
|
376
|
+
(block for block in reply.content if block.type == "tool_use"), None
|
|
377
|
+
)
|
|
378
|
+
if recorded is None:
|
|
379
|
+
raise AgentJamError("The model recorded no fit")
|
|
380
|
+
|
|
381
|
+
return json.dumps(recorded.input)
|
|
382
|
+
|
|
383
|
+
return judge
|
|
384
|
+
|
|
385
|
+
return judge_with
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def from_anthropic(
|
|
389
|
+
client: AsyncAnthropic,
|
|
390
|
+
*,
|
|
391
|
+
tools: Sequence[AnthropicTool] = (),
|
|
392
|
+
screen: AdapterScreen[ModelParam] | None = None,
|
|
393
|
+
**params: Unpack[AnthropicParams],
|
|
394
|
+
) -> AdapterHandlers:
|
|
395
|
+
"""Runs incoming messages and tasks through Anthropic's tool runner, adding the network tools to your own.
|
|
396
|
+
|
|
397
|
+
Task output streams back as a text artifact, and the requester's steering messages reach Claude once its
|
|
398
|
+
current turn ends, after the turn's tool results.
|
|
399
|
+
|
|
400
|
+
Args:
|
|
401
|
+
client: The Anthropic client to run the model with.
|
|
402
|
+
tools: Your own tools, which run alongside the network tools.
|
|
403
|
+
screen: Screens each proposal with the model, or a cheaper one, before accepting it. Defaults to off.
|
|
404
|
+
**params: The tool runner params, such as `model`, `max_tokens` and `system`.
|
|
405
|
+
Returns:
|
|
406
|
+
Handlers to spread into `connect()`.
|
|
407
|
+
"""
|
|
408
|
+
|
|
409
|
+
def construct_tools(agent: Agent) -> list[AnthropicTool]:
|
|
410
|
+
return [*tools, *anthropic_runnable_tools(agent)]
|
|
411
|
+
|
|
412
|
+
async def answer_message(message: IncomingMessage, agent: Agent) -> str:
|
|
413
|
+
runner = client.beta.messages.tool_runner(
|
|
414
|
+
**params,
|
|
415
|
+
tools=construct_tools(agent),
|
|
416
|
+
messages=await to_anthropic_messages(message),
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
return _get_text(await runner.until_done())
|
|
420
|
+
|
|
421
|
+
async def perform_task(task: IncomingTask, agent: Agent) -> LabeledContent:
|
|
422
|
+
inbox = task.open_inbox()
|
|
423
|
+
content = await construct_task_content(task)
|
|
424
|
+
messages = [_to_user_message(content)]
|
|
425
|
+
|
|
426
|
+
return artifact(
|
|
427
|
+
_answer_text(client, params, construct_tools(agent), messages, inbox)
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
return AdapterHandlers(
|
|
431
|
+
tool_names=[
|
|
432
|
+
name for tool in tools if (name := _get_tool_name(tool)) is not None
|
|
433
|
+
],
|
|
434
|
+
screen=construct_adapter_screen(
|
|
435
|
+
screen,
|
|
436
|
+
model=params["model"],
|
|
437
|
+
instructions=_get_system_text(params.get("system")),
|
|
438
|
+
judge_with=_construct_judge(client),
|
|
439
|
+
),
|
|
440
|
+
on_message=answer_message,
|
|
441
|
+
on_task=perform_task,
|
|
442
|
+
)
|