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.
Files changed (86) hide show
  1. agentjam/__init__.py +435 -0
  2. agentjam/_adapters/__init__.py +0 -0
  3. agentjam/_adapters/responses.py +73 -0
  4. agentjam/_adapters/shared.py +435 -0
  5. agentjam/_agent.py +1032 -0
  6. agentjam/_agent_access.py +360 -0
  7. agentjam/_agent_delegations.py +376 -0
  8. agentjam/_agent_executions.py +566 -0
  9. agentjam/_agent_judging.py +288 -0
  10. agentjam/_agent_options.py +122 -0
  11. agentjam/_agent_routing.py +214 -0
  12. agentjam/_agent_session.py +195 -0
  13. agentjam/_agent_support.py +415 -0
  14. agentjam/_artifacts.py +565 -0
  15. agentjam/_attachments.py +112 -0
  16. agentjam/_connections.py +1282 -0
  17. agentjam/_content.py +29 -0
  18. agentjam/_cron.py +302 -0
  19. agentjam/_errors.py +238 -0
  20. agentjam/_events.py +113 -0
  21. agentjam/_files.py +55 -0
  22. agentjam/_github.py +742 -0
  23. agentjam/_idempotency.py +68 -0
  24. agentjam/_inputs.py +79 -0
  25. agentjam/_models.py +21 -0
  26. agentjam/_polling.py +139 -0
  27. agentjam/_profile.py +244 -0
  28. agentjam/_protocol.py +480 -0
  29. agentjam/_providers.py +365 -0
  30. agentjam/_recaps.py +67 -0
  31. agentjam/_relay/__init__.py +0 -0
  32. agentjam/_relay/actions.py +234 -0
  33. agentjam/_relay/artifacts.py +96 -0
  34. agentjam/_relay/base.py +387 -0
  35. agentjam/_relay/commits.py +77 -0
  36. agentjam/_relay/copies.py +66 -0
  37. agentjam/_relay/credentials.py +127 -0
  38. agentjam/_relay/endpoints.py +39 -0
  39. agentjam/_relay/follow_ups.py +548 -0
  40. agentjam/_relay/frames.py +443 -0
  41. agentjam/_relay/guest_store.py +114 -0
  42. agentjam/_relay/guests.py +55 -0
  43. agentjam/_relay/inputs.py +119 -0
  44. agentjam/_relay/lineage.py +294 -0
  45. agentjam/_relay/memory.py +1045 -0
  46. agentjam/_relay/payments.py +204 -0
  47. agentjam/_relay/profiles.py +95 -0
  48. agentjam/_relay/remote.py +826 -0
  49. agentjam/_relay/resumptions.py +65 -0
  50. agentjam/_relay/revisions.py +43 -0
  51. agentjam/_relay/schedule_follow_ups.py +274 -0
  52. agentjam/_relay/schedules.py +547 -0
  53. agentjam/_relay/secrets.py +275 -0
  54. agentjam/_relay/sessions.py +640 -0
  55. agentjam/_relay/uploads.py +71 -0
  56. agentjam/_requests.py +178 -0
  57. agentjam/_screening.py +368 -0
  58. agentjam/_secrets.py +153 -0
  59. agentjam/_sentry.py +233 -0
  60. agentjam/_signals.py +98 -0
  61. agentjam/_slack.py +468 -0
  62. agentjam/_stripe.py +93 -0
  63. agentjam/_tasks/__init__.py +0 -0
  64. agentjam/_tasks/access.py +142 -0
  65. agentjam/_tasks/incoming.py +952 -0
  66. agentjam/_tasks/outgoing.py +472 -0
  67. agentjam/_tasks/scheduled.py +206 -0
  68. agentjam/_tasks/serial.py +40 -0
  69. agentjam/_tasks/triggers.py +258 -0
  70. agentjam/_tasks/watches.py +77 -0
  71. agentjam/_tools.py +1035 -0
  72. agentjam/_types.py +965 -0
  73. agentjam/_utils.py +75 -0
  74. agentjam/_verdicts.py +21 -0
  75. agentjam/_watermarks.py +59 -0
  76. agentjam/anthropic.py +442 -0
  77. agentjam/mpp.py +233 -0
  78. agentjam/openai.py +141 -0
  79. agentjam/openai_agents.py +253 -0
  80. agentjam/py.typed +0 -0
  81. agentjam/pydantic_ai.py +301 -0
  82. agentjam/skills.py +69 -0
  83. agentjam-0.1.0.dist-info/METADATA +210 -0
  84. agentjam-0.1.0.dist-info/RECORD +86 -0
  85. agentjam-0.1.0.dist-info/WHEEL +4 -0
  86. agentjam-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,435 @@
1
+ import base64
2
+ from collections.abc import Callable, Sequence
3
+ from dataclasses import dataclass
4
+ from typing import (
5
+ TYPE_CHECKING,
6
+ Generic,
7
+ Literal,
8
+ Protocol,
9
+ TypeAlias,
10
+ TypeVar,
11
+ assert_never,
12
+ )
13
+
14
+ from strompt import MarkdownPromptRenderer
15
+
16
+ from agentjam._files import File
17
+ from agentjam._screening import (
18
+ Judge,
19
+ ProposalScreen,
20
+ ScreenSettings,
21
+ add_section,
22
+ )
23
+ from agentjam._tools import NetworkTool, ToolName, pick_tools
24
+ from agentjam._types import Attachment, IncomingMessage, JsonObject, TaskRecap
25
+ from agentjam._utils import encode_data
26
+
27
+ if TYPE_CHECKING:
28
+ from agentjam._agent import Agent
29
+
30
+ ModelT = TypeVar("ModelT")
31
+
32
+ ImageType = Literal["image/png", "image/jpeg", "image/gif", "image/webp"]
33
+
34
+ MEBIBYTE = 1024 * 1024
35
+
36
+ MAX_SHOWN_FILES = 20
37
+
38
+ MAX_SHOWN_BYTES = 20 * MEBIBYTE
39
+
40
+ # WARNING: Anthropic refuses images over 5 MiB once base64-encoded, which grows them by a third.
41
+ MAX_IMAGE_BYTES = int(3.75 * MEBIBYTE)
42
+
43
+ MAX_DOCUMENT_BYTES = 10 * MEBIBYTE
44
+
45
+ MAX_TEXT_BYTES = 100 * 1024
46
+
47
+ IMAGE_TYPES: tuple[ImageType, ...] = (
48
+ "image/png",
49
+ "image/jpeg",
50
+ "image/gif",
51
+ "image/webp",
52
+ )
53
+
54
+ TEXT_TYPES = frozenset(
55
+ {
56
+ "application/json",
57
+ "application/xml",
58
+ "application/yaml",
59
+ "application/x-yaml",
60
+ "application/csv",
61
+ }
62
+ )
63
+
64
+ TEXT_SUFFIXES = ("+json", "+xml", "+yaml")
65
+
66
+
67
+ @dataclass(frozen=True, kw_only=True)
68
+ class TextPart:
69
+ """Text the model sees."""
70
+
71
+ text: str
72
+ type: Literal["text"] = "text"
73
+
74
+
75
+ @dataclass(frozen=True, kw_only=True)
76
+ class ImagePart:
77
+ """An image the model sees."""
78
+
79
+ name: str
80
+ mime_type: ImageType
81
+ data: str
82
+ """The image's bytes, base64-encoded."""
83
+ type: Literal["image"] = "image"
84
+
85
+
86
+ @dataclass(frozen=True, kw_only=True)
87
+ class DocumentPart:
88
+ """A PDF the model sees."""
89
+
90
+ name: str
91
+ data: str
92
+ """The PDF's bytes, base64-encoded."""
93
+ mime_type: Literal["application/pdf"] = "application/pdf"
94
+ type: Literal["document"] = "document"
95
+
96
+
97
+ ContentPart: TypeAlias = TextPart | ImagePart | DocumentPart
98
+ """A provider-neutral piece of what the model sees, which each adapter maps to its SDK's content format."""
99
+
100
+
101
+ @dataclass(frozen=True, kw_only=True)
102
+ class ModelContent:
103
+ """What the model sees of a task, message or tool result: its text, then the parts its files convert to."""
104
+
105
+ text: str
106
+ files: list[ContentPart]
107
+
108
+
109
+ @dataclass(frozen=True, kw_only=True)
110
+ class Turn:
111
+ """A conversation turn from the receiving agent's point of view, where the sender is the user."""
112
+
113
+ role: Literal["user", "assistant"]
114
+ text: str
115
+
116
+
117
+ class AttachedText(Protocol):
118
+ @property
119
+ def text(self) -> str: ...
120
+
121
+ @property
122
+ def attachments(self) -> Sequence[Attachment]: ...
123
+
124
+
125
+ class TaskDetails(AttachedText, Protocol):
126
+ @property
127
+ def input(self) -> JsonObject | None: ...
128
+
129
+ @property
130
+ def previous(self) -> TaskRecap | None: ...
131
+
132
+
133
+ @dataclass(frozen=True, kw_only=True)
134
+ class AdapterScreenSettings(ScreenSettings, Generic[ModelT]):
135
+ """Screen settings for an adapter, which can name a cheaper `model` to screen with."""
136
+
137
+ model: ModelT | None = None
138
+ """The model to screen with. Defaults to the adapter's own."""
139
+
140
+
141
+ AdapterScreen: TypeAlias = bool | AdapterScreenSettings[ModelT]
142
+ """An adapter's `screen` option: True to screen proposals with the adapter's own model, or settings that can name a cheaper `model`."""
143
+
144
+
145
+ @dataclass(frozen=True)
146
+ class ImageKind:
147
+ mime_type: ImageType
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class DocumentKind:
152
+ pass
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class TextKind:
157
+ pass
158
+
159
+
160
+ FileKind: TypeAlias = ImageKind | DocumentKind | TextKind
161
+
162
+
163
+ def is_text_type(mime_type: str) -> bool:
164
+ return (
165
+ mime_type.startswith("text/")
166
+ or mime_type in TEXT_TYPES
167
+ or mime_type.endswith(TEXT_SUFFIXES)
168
+ )
169
+
170
+
171
+ def classify_file(file: File) -> FileKind | None:
172
+ mime_type = file.mime_type.split(";")[0].strip().lower()
173
+ image_type = next((each for each in IMAGE_TYPES if each == mime_type), None)
174
+
175
+ if image_type is not None:
176
+ return ImageKind(image_type)
177
+ if mime_type == "application/pdf":
178
+ return DocumentKind()
179
+ if is_text_type(mime_type):
180
+ return TextKind()
181
+
182
+ return None
183
+
184
+
185
+ def measure_file(file: File, kind: FileKind) -> int | None:
186
+ """Returns how many of the call's bytes showing the file takes, or None if it's over its type's cap."""
187
+ match kind:
188
+ case ImageKind():
189
+ return file.size if file.size <= MAX_IMAGE_BYTES else None
190
+
191
+ case DocumentKind():
192
+ return file.size if file.size <= MAX_DOCUMENT_BYTES else None
193
+
194
+ case TextKind():
195
+ return min(file.size, MAX_TEXT_BYTES)
196
+
197
+ case _:
198
+ assert_never(kind)
199
+
200
+
201
+ def describe_file(file: File) -> str:
202
+ return f'File "{file.name}" ({file.mime_type or "unknown type"}, {file.size} bytes)'
203
+
204
+
205
+ def encode_file(file: File) -> str:
206
+ return base64.b64encode(file.data).decode("ascii")
207
+
208
+
209
+ def read_text(file: File) -> str:
210
+ text = file.data[:MAX_TEXT_BYTES].decode(errors="replace")
211
+
212
+ if file.size <= MAX_TEXT_BYTES:
213
+ return text
214
+
215
+ return f"{text}\n[Truncated to the first {MAX_TEXT_BYTES} of {file.size} bytes]"
216
+
217
+
218
+ def show_file(file: File, kind: FileKind) -> list[ContentPart]:
219
+ heading = f"{describe_file(file)}:"
220
+
221
+ match kind:
222
+ case ImageKind(mime_type=mime_type):
223
+ image = ImagePart(
224
+ name=file.name, mime_type=mime_type, data=encode_file(file)
225
+ )
226
+
227
+ return [TextPart(text=heading), image]
228
+
229
+ case DocumentKind():
230
+ document = DocumentPart(name=file.name, data=encode_file(file))
231
+
232
+ return [TextPart(text=heading), document]
233
+
234
+ case TextKind():
235
+ return [TextPart(text=f"{heading}\n{read_text(file)}")]
236
+
237
+ case _:
238
+ assert_never(kind)
239
+
240
+
241
+ async def convert_files(files: Sequence[File]) -> list[ContentPart]:
242
+ """Converts the files of one model call into content parts, in order.
243
+
244
+ Images and PDFs become image and document parts, text files are inlined, and the rest, or any past the caps, are only described.
245
+
246
+ Args:
247
+ files: The files to show the model.
248
+ Returns:
249
+ The content parts.
250
+ """
251
+ parts: list[ContentPart] = []
252
+ shown_files = 0
253
+ shown_bytes = 0
254
+
255
+ for file in files:
256
+ kind = classify_file(file)
257
+ size = None if kind is None else measure_file(file, kind)
258
+ if (
259
+ kind is None
260
+ or size is None
261
+ or shown_files >= MAX_SHOWN_FILES
262
+ or shown_bytes + size > MAX_SHOWN_BYTES
263
+ ):
264
+ parts.append(
265
+ TextPart(text=f"{describe_file(file)} is attached but can't be shown.")
266
+ )
267
+
268
+ continue
269
+
270
+ parts.extend(show_file(file, kind))
271
+ shown_files += 1
272
+ shown_bytes += size
273
+
274
+ return parts
275
+
276
+
277
+ async def construct_model_content(source: AttachedText) -> ModelContent:
278
+ """Builds what the model sees of a message: its text, then the parts its attachments convert to.
279
+
280
+ Args:
281
+ source: The message, or anything else with text and attachments.
282
+ Returns:
283
+ The text and the converted files.
284
+ """
285
+ files = [attachment.file for attachment in source.attachments]
286
+
287
+ return ModelContent(text=source.text, files=await convert_files(files))
288
+
289
+
290
+ def describe_recap(sentence: str, recap: TaskRecap) -> tuple[str, str]:
291
+ return f"{sentence} Its recap:", encode_data(recap)
292
+
293
+
294
+ async def construct_task_content(task: TaskDetails) -> ModelContent:
295
+ """Builds what the model sees of a task: its text, structured input and a recap of the task it follows up on.
296
+
297
+ Args:
298
+ task: The task, or anything else with its text, input, previous task and attachments.
299
+ Returns:
300
+ The text and the converted files.
301
+ """
302
+ context = MarkdownPromptRenderer()
303
+ if task.input is not None:
304
+ add_section(context, "input", "Input", encode_data(task.input))
305
+
306
+ if (previous := task.previous) is not None:
307
+ sentence = f"This task follows up on task {previous.id}, which you ran for {previous.requester}."
308
+ add_section(
309
+ context,
310
+ "previous_task",
311
+ "Previous Task",
312
+ *describe_recap(sentence, previous),
313
+ )
314
+
315
+ rendered = context.render()
316
+ files = await convert_files([attachment.file for attachment in task.attachments])
317
+
318
+ return ModelContent(
319
+ text=f"{task.text}\n\n{rendered}" if rendered else task.text, files=files
320
+ )
321
+
322
+
323
+ def render_note(tag: str, header: str, *texts: str) -> str:
324
+ note = MarkdownPromptRenderer()
325
+ add_section(note, tag, header, *texts)
326
+
327
+ return note.render()
328
+
329
+
330
+ def to_history(message: IncomingMessage) -> list[Turn]:
331
+ """Maps the earlier turns of a message's conversation, which keep no files, from the receiver's point of view.
332
+
333
+ The turns follow a recap of the task the message is about, and end with a note when the message steers a task that can't take it.
334
+
335
+ Args:
336
+ message: The message whose conversation to map.
337
+ Returns:
338
+ The turns, oldest first.
339
+ """
340
+ turns = [
341
+ Turn(
342
+ role="user" if turn.sender == message.sender else "assistant",
343
+ text=turn.text,
344
+ )
345
+ for turn in message.history
346
+ ]
347
+
348
+ if (task := message.task) is not None:
349
+ sentence = f"This conversation is about task {task.id}, which you ran for {task.requester}."
350
+ recap = render_note("task_recap", "Task Recap", *describe_recap(sentence, task))
351
+ turns.insert(0, Turn(role="user", text=recap))
352
+
353
+ if message.steer:
354
+ steer = f"The next message asks to change task {message.task_id} while it runs, which the work in progress can't take, so answer it and say the change may need a follow-up once the task ends."
355
+ turns.append(
356
+ Turn(role="user", text=render_note("steer_note", "Steering", steer))
357
+ )
358
+
359
+ return turns
360
+
361
+
362
+ def to_data_url(part: ImagePart | DocumentPart) -> str:
363
+ """Encodes an image or document part as a base64 data URL.
364
+
365
+ Args:
366
+ part: The part to encode.
367
+ Returns:
368
+ The data URL.
369
+ """
370
+ return f"data:{part.mime_type};base64,{part.data}"
371
+
372
+
373
+ async def execute_tool(tool: NetworkTool, input: object) -> ModelContent:
374
+ """Runs a network tool, converting the files it received into content parts.
375
+
376
+ Args:
377
+ tool: The tool to run.
378
+ input: The model's arguments.
379
+ Returns:
380
+ The tool's text and the converted files.
381
+ """
382
+ result = await tool.execute(input)
383
+
384
+ return ModelContent(text=result.text, files=await convert_files(result.files))
385
+
386
+
387
+ def get_network_tools(
388
+ agent: "Agent", pick: Sequence[ToolName] | None = None
389
+ ) -> list[NetworkTool]:
390
+ """Returns the agent's network tools, or only those `pick` names.
391
+
392
+ Args:
393
+ agent: The agent whose tools to return.
394
+ pick: The names of the tools to keep, in any order.
395
+ Returns:
396
+ The tools, in the agent's order.
397
+ Raises:
398
+ AgentJamError: If a name in `pick` isn't among the agent's tools.
399
+ """
400
+ return list(agent.tools) if pick is None else pick_tools(agent.tools, pick)
401
+
402
+
403
+ def construct_adapter_screen(
404
+ option: "AdapterScreen[ModelT] | None",
405
+ *,
406
+ model: ModelT,
407
+ instructions: str | None,
408
+ judge_with: Callable[[ModelT], Judge],
409
+ ) -> ProposalScreen | None:
410
+ """Builds the screen an adapter passes to `connect()`, adding the adapter's instructions to the screen's own.
411
+
412
+ Args:
413
+ option: The adapter's `screen` option.
414
+ model: The adapter's own model, which screens unless `option` names another.
415
+ instructions: The adapter's instructions, such as its system prompt.
416
+ judge_with: Builds a judge that calls the given model.
417
+ Returns:
418
+ The screen, or None when `option` turns screening off.
419
+ """
420
+ if not option:
421
+ return None
422
+
423
+ settings = AdapterScreenSettings[ModelT]() if isinstance(option, bool) else option
424
+ chosen = model if settings.model is None else settings.model
425
+ joined = "\n\n".join(
426
+ rules for rules in (instructions, settings.instructions) if rules
427
+ )
428
+
429
+ return ProposalScreen(
430
+ instructions=joined or None,
431
+ partial=settings.partial,
432
+ timeout=settings.timeout,
433
+ on_failure=settings.on_failure,
434
+ judge=judge_with(chosen),
435
+ )