graphcore-apps 0.5.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 (118) hide show
  1. agents/__init__.py +0 -0
  2. agents/apps.py +15 -0
  3. agents/authorization.py +62 -0
  4. agents/conf.py +78 -0
  5. agents/delegation.py +218 -0
  6. agents/entities/__init__.py +0 -0
  7. agents/entities/agent.py +16 -0
  8. agents/entities/conversation.py +23 -0
  9. agents/entities/instruction.py +7 -0
  10. agents/entities/message.py +30 -0
  11. agents/entities/profile.py +14 -0
  12. agents/entities/skill.py +8 -0
  13. agents/migrations/0001_initial.py +88 -0
  14. agents/migrations/0002_message_context_versions.py +16 -0
  15. agents/migrations/0003_compaction_threshold.py +21 -0
  16. agents/migrations/0004_agent_debug_context.py +16 -0
  17. agents/migrations/0005_conversation_last_active_at.py +34 -0
  18. agents/migrations/0006_tasks.py +21 -0
  19. agents/migrations/0007_agent_start_address.py +16 -0
  20. agents/migrations/__init__.py +0 -0
  21. agents/models.py +64 -0
  22. agents/persistence.py +18 -0
  23. agents/providers/__init__.py +0 -0
  24. agents/providers/anthropic.py +142 -0
  25. agents/providers/fake.py +51 -0
  26. agents/providers/google.py +186 -0
  27. agents/providers/openai.py +177 -0
  28. agents/providers/port.py +101 -0
  29. agents/providers/registry.py +40 -0
  30. agents/routes.py +5 -0
  31. agents/runtime/__init__.py +0 -0
  32. agents/runtime/compaction.py +29 -0
  33. agents/runtime/context.py +78 -0
  34. agents/runtime/dispatch.py +76 -0
  35. agents/runtime/effective_agent.py +70 -0
  36. agents/runtime/loop.py +454 -0
  37. agents/runtime/prompt.py +183 -0
  38. agents/runtime/resume.py +30 -0
  39. agents/runtime/tools.py +35 -0
  40. agents/specs/__init__.py +3 -0
  41. agents/specs/dsl.py +310 -0
  42. agents/specs/test_r01_agents.py +74 -0
  43. agents/specs/test_r02_conversations.py +146 -0
  44. agents/specs/test_r03_acts_as_the_sender.py +60 -0
  45. agents/specs/test_r04_context.py +63 -0
  46. agents/specs/test_r05_personal_configuration.py +86 -0
  47. agents/specs/test_r06_delegation.py +70 -0
  48. agents/specs/test_r07_sharing.py +103 -0
  49. agents/specs/test_r08_embedding.py +40 -0
  50. agents/specs/test_r09_finding.py +41 -0
  51. agents/specs/test_r10_clients.py +41 -0
  52. agents/strategies/__init__.py +0 -0
  53. agents/strategies/_schema.py +16 -0
  54. agents/strategies/agents.py +93 -0
  55. agents/strategies/context.py +45 -0
  56. agents/strategies/conversations.py +65 -0
  57. agents/strategies/instructions.py +62 -0
  58. agents/strategies/messages.py +56 -0
  59. agents/strategies/models.py +27 -0
  60. agents/strategies/profiles.py +43 -0
  61. agents/strategies/skills.py +47 -0
  62. agents/strategies/turn.py +47 -0
  63. agents/test_settings.py +6 -0
  64. agents/tests/__init__.py +0 -0
  65. agents/tests/support.py +94 -0
  66. agents/tests/test_agent_views.py +181 -0
  67. agents/tests/test_agents.py +166 -0
  68. agents/tests/test_anthropic_adapter.py +221 -0
  69. agents/tests/test_context.py +231 -0
  70. agents/tests/test_control.py +162 -0
  71. agents/tests/test_conversations.py +158 -0
  72. agents/tests/test_delegation.py +392 -0
  73. agents/tests/test_google_adapter.py +208 -0
  74. agents/tests/test_inspect.py +59 -0
  75. agents/tests/test_live_providers.py +69 -0
  76. agents/tests/test_openai_adapter.py +259 -0
  77. agents/tests/test_profiles.py +92 -0
  78. agents/tests/test_resumption.py +150 -0
  79. agents/tests/test_turns.py +230 -0
  80. agents/validation.py +48 -0
  81. agents_agent_frontend/__init__.py +3 -0
  82. agents_agent_frontend/agent_views.py +286 -0
  83. audio/__init__.py +0 -0
  84. audio/apps.py +14 -0
  85. audio/authorization.py +13 -0
  86. audio/conf.py +27 -0
  87. audio/entities/__init__.py +11 -0
  88. audio/entities/recording.py +10 -0
  89. audio/migrations/0001_initial.py +26 -0
  90. audio/migrations/__init__.py +0 -0
  91. audio/models.py +9 -0
  92. audio/persistence.py +6 -0
  93. audio/providers/__init__.py +0 -0
  94. audio/providers/fake.py +35 -0
  95. audio/providers/openai.py +50 -0
  96. audio/providers/port.py +31 -0
  97. audio/providers/registry.py +31 -0
  98. audio/specs/__init__.py +3 -0
  99. audio/specs/dsl.py +120 -0
  100. audio/specs/test_clients.py +20 -0
  101. audio/specs/test_dictation.py +87 -0
  102. audio/specs/test_privacy.py +45 -0
  103. audio/specs/test_vendor.py +59 -0
  104. audio/strategies/__init__.py +11 -0
  105. audio/strategies/recordings.py +88 -0
  106. audio/test_settings.py +6 -0
  107. audio/tests/__init__.py +0 -0
  108. audio/tests/test_openai_adapter.py +65 -0
  109. audio/tests/test_recordings.py +139 -0
  110. audio_agent_frontend/__init__.py +3 -0
  111. audio_agent_frontend/agent_views.py +11 -0
  112. graphcore_apps-0.5.0.dist-info/METADATA +14 -0
  113. graphcore_apps-0.5.0.dist-info/RECORD +118 -0
  114. graphcore_apps-0.5.0.dist-info/WHEEL +5 -0
  115. graphcore_apps-0.5.0.dist-info/entry_points.txt +7 -0
  116. graphcore_apps-0.5.0.dist-info/licenses/LICENSE +202 -0
  117. graphcore_apps-0.5.0.dist-info/licenses/NOTICE +2 -0
  118. graphcore_apps-0.5.0.dist-info/top_level.txt +4 -0
agents/runtime/loop.py ADDED
@@ -0,0 +1,454 @@
1
+ """One turn: the model loop over a conversation, run as its sender
2
+ (docs/app_design/agents/AGENTS_TDD.md, Turns)."""
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ import time
7
+ from dataclasses import dataclass
8
+ from typing import Optional
9
+
10
+ from mcp import Client
11
+
12
+ from graphcore.public.errors import ConcurrentModificationError, StaleAttempt, TransientError
13
+ from graphcore.public.persistence import EntityFilter
14
+ from graphcore.public.strategies import Strategy
15
+
16
+ from agents import conf
17
+ from agents.entities.conversation import Conversation, ConversationStatus
18
+ from agents.entities.message import Message, MessageRole, ToolCallState
19
+ from agents.providers.port import Done, ModelRequest, Provider, ProviderError, TextDelta, Usage
20
+ from agents.delegation import sub_conversation_tools
21
+ from agents.providers.registry import provider_for
22
+ from agents.runtime import compaction, prompt, resume
23
+ from agents.runtime.context import ContextTracker, shown_versions
24
+ from agents.runtime.dispatch import Dispatcher
25
+ from agents.runtime.effective_agent import EffectiveAgent, TurnFailure, resolve
26
+ from agents.runtime.tools import LOAD_SKILL
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ COMPLETED, STOPPED, ERROR = 'completed', 'stopped', 'error'
31
+ _PAGE = 100
32
+ _SAVE_TRIES = 4
33
+ _STOP_POLL = 0.05
34
+ _DONE_LINE = 120
35
+
36
+
37
+ def dispatcher_for(session, client: Client, conversation_id: str) -> Dispatcher:
38
+ """The tools a conversation's model is offered: the agent frontend's and the runtime's own."""
39
+ return Dispatcher(client, [*sub_conversation_tools(session, conversation_id), LOAD_SKILL])
40
+
41
+
42
+ async def messages_of(session, conversation_id: str) -> list[Message]:
43
+ found: list[Message] = []
44
+ cursor = None
45
+ while True:
46
+ page = await session.list(EntityFilter(
47
+ type_ids=frozenset({Message.get_entity_type_id()}), parent_id=conversation_id,
48
+ ), cursor=cursor, limit=_PAGE)
49
+ found.extend(page.entities)
50
+ cursor = page.next_cursor
51
+ if cursor is None:
52
+ return sorted(found, key=lambda message: message.sibling_position)
53
+
54
+
55
+ class _Stop(Exception):
56
+ """The conversation's `stop_requested` was seen."""
57
+
58
+ def __init__(self, message: Optional[Message] = None):
59
+ self.message = message
60
+
61
+
62
+ @dataclass
63
+ class _Step:
64
+ stop: str
65
+ usage: Usage
66
+ made_calls: bool
67
+
68
+
69
+ class TurnRun:
70
+ def __init__(self, strategy: Strategy, client: Client, resumed: bool):
71
+ self.strategy = strategy
72
+ self.session = strategy.session
73
+ self.conversation_id = strategy.entity.entity_id
74
+ self.sender = strategy.principal_entity_id
75
+ self.request_id = strategy.strategy_request.entity_id
76
+ self.attempt = strategy.strategy_request.attempt
77
+ self.resumed = resumed
78
+ self.client = client
79
+ self.dispatcher = dispatcher_for(self.session, client, self.conversation_id)
80
+ self.context = ContextTracker(client)
81
+ self.context_ids: list[str] = []
82
+ self.noticed: set[str] = set()
83
+ # Messages that existed when the turn took the lock. Another person's
84
+ # later message stays out of the prompt: acting on it would use the
85
+ # sender's permissions.
86
+ self.history: frozenset[str] = frozenset()
87
+ self.answered_from: Optional[str] = None
88
+ self.cut_off = False
89
+
90
+ async def run(self) -> dict:
91
+ """Ends the turn with a status on every path its code reaches: the
92
+ request's callbacks, which report a background turn to its parent, fire
93
+ only when the request succeeds."""
94
+ try:
95
+ return await self._run()
96
+ except StaleAttempt:
97
+ raise
98
+ except (TransientError, ConcurrentModificationError) as exc:
99
+ if self.attempt < conf.max_attempts():
100
+ raise
101
+ error = f"still failing after {self.attempt} attempts: {exc}"
102
+ except Exception as exc:
103
+ logger.exception("Turn %s on %s failed", self.request_id, self.conversation_id)
104
+ error = f"{type(exc).__name__}: {exc}"
105
+ await resume.interrupt_running_calls(self.session, await self._messages())
106
+ await self._say(f"The turn failed: {error} (request {self.request_id})", answers=True)
107
+ await self._set_conversation(status=ConversationStatus.IDLE, last_active_at=time.time(), stop_requested=False)
108
+ return self._result(ERROR, self._visible(await self._messages()), error)
109
+
110
+ async def _run(self) -> dict:
111
+ messages = await resume.interrupt_running_calls(self.session, await self._messages())
112
+ self.history = frozenset(message.entity_id for message in messages)
113
+ continuing = self.attempt > 1 and resume.cut_short(messages, self.sender)
114
+ if not continuing and not self._unread(messages):
115
+ # A turn whose attempts ran out leaves `running` behind it.
116
+ if (await self.session.get(self.conversation_id)).status is not ConversationStatus.IDLE:
117
+ await self._set_conversation(status=ConversationStatus.IDLE)
118
+ return self._result(COMPLETED, messages)
119
+ answering = self._unread(messages) or [m for m in messages if m.entity_id == self._last_from_sender(messages)]
120
+ self.context_ids = [entity_id for message in answering for entity_id in message.context_ids]
121
+ self.answered_from = answering[0].entity_id if answering else None
122
+ if continuing and not messages[-1].tool_calls:
123
+ await self._say(resume.RESUMED)
124
+
125
+ # A stop on a conversation already running is for this turn (a task is
126
+ # marked running before its turn starts); one on an idle one is stale.
127
+ stale_stop = not self.resumed and (
128
+ (await self.session.get(self.conversation_id)).status is ConversationStatus.IDLE
129
+ )
130
+ await self._set_conversation(
131
+ status=ConversationStatus.RUNNING, last_active_at=time.time(),
132
+ **({'stop_requested': False} if stale_stop else {}),
133
+ )
134
+ error = None
135
+ try:
136
+ status = await self._steps()
137
+ except (TransientError, ConcurrentModificationError, StaleAttempt):
138
+ raise
139
+ except _Stop as stop:
140
+ status = STOPPED
141
+ await self._interrupt(stop.message)
142
+ await self._say("Stopped.", answers=True)
143
+ except ProviderError as exc:
144
+ if exc.retryable:
145
+ raise TransientError(str(exc)) from exc
146
+ status, error = ERROR, str(exc)
147
+ except TurnFailure as exc:
148
+ status, error = ERROR, str(exc)
149
+ except Exception as exc:
150
+ logger.exception("Turn %s on %s failed", self.request_id, self.conversation_id)
151
+ status, error = ERROR, f"{type(exc).__name__}: {exc}"
152
+ if error is not None:
153
+ await self._say(f"The turn failed: {error} (request {self.request_id})", answers=True)
154
+ await self._set_conversation(status=ConversationStatus.IDLE, last_active_at=time.time(), stop_requested=False)
155
+ return self._result(status, self._visible(await self._messages()), error)
156
+
157
+ # --- the loop -----------------------------------------------------------
158
+
159
+ async def _steps(self) -> str:
160
+ tool_defs = await self.dispatcher.tool_defs()
161
+ taken = 0
162
+ show_context = True
163
+ overflowed = False
164
+ while True:
165
+ conversation = await self.session.get(self.conversation_id)
166
+ if conversation.stop_requested:
167
+ raise _Stop()
168
+ agent = await resolve(self.session, conversation)
169
+ provider, model = provider_for(agent.model)
170
+
171
+ asking = (model, agent, self.client.instructions, tool_defs)
172
+ if overflowed or compaction.due(conversation, agent):
173
+ compacted = await self._compact(provider, asking, half=overflowed)
174
+ if overflowed and not compacted:
175
+ raise ProviderError('context_overflow', 'The prompt exceeds the model\'s context', retryable=False)
176
+ show_context = show_context or compacted
177
+ await self._say_notices(agent)
178
+ await self._show_context(conversation, show_context, agent.start_address)
179
+ show_context = False
180
+
181
+ messages = self._visible(await self._messages())
182
+ closing = taken >= conf.max_steps()
183
+ asked, summary, rest = prompt.next_request(
184
+ *asking, messages, provider.name, self.conversation_id, closing=closing,
185
+ )
186
+ try:
187
+ step = await self._step(provider, asked, agent, self._last_from_sender(messages))
188
+ except ProviderError as exc:
189
+ if exc.code != 'context_overflow' or overflowed:
190
+ raise
191
+ overflowed = True
192
+ continue
193
+ overflowed = False
194
+ taken += 1
195
+ await self._record_usage(step.usage, prompt.sizes(asked.prefix, asked.tools, summary, rest))
196
+ if step.stop == 'max_tokens':
197
+ self.cut_off = True
198
+ await self._say("The reply was cut off at the model's output limit.")
199
+ return COMPLETED
200
+ if closing or step.stop == 'refusal':
201
+ return COMPLETED
202
+ if not step.made_calls and not self._unread(self._visible(await self._messages())):
203
+ return COMPLETED
204
+
205
+ async def _step(self, provider: Provider, request: ModelRequest, agent: EffectiveAgent,
206
+ read_through: Optional[str]) -> _Step:
207
+ """One provider call: its text and tool calls saved on one assistant
208
+ message as they arrive, each call dispatched at once."""
209
+ message: Optional[Message] = None
210
+ tasks: list[Optional[asyncio.Task]] = []
211
+ call_state: dict = {}
212
+ done: Optional[Done] = None
213
+ saved_at = 0.0
214
+ stream = provider.stream(request)
215
+ try:
216
+ async for event in stream:
217
+ if isinstance(event, Done):
218
+ done = event
219
+ continue
220
+ if message is None:
221
+ message = self.session.create(
222
+ Message, parent_id=self.conversation_id, role=MessageRole.ASSISTANT,
223
+ read_through=read_through,
224
+ )
225
+ if isinstance(event, TextDelta):
226
+ message.content += event.text
227
+ if time.monotonic() - saved_at < conf.stream_interval():
228
+ continue
229
+ else:
230
+ record = {
231
+ 'id': event.id, 'tool': event.name, 'at': event.params.get('at'), 'params': event.params,
232
+ 'state': ToolCallState.RUNNING.value, 'result': None, 'error': None, 'request_id': None,
233
+ }
234
+ if event.error is not None:
235
+ record.update(state=ToolCallState.ERROR.value, error=event.error)
236
+ if event.provider_state:
237
+ call_state[event.id] = event.provider_state
238
+ message.tool_calls.append(record)
239
+ message = await self.session.save(message)
240
+ saved_at = time.monotonic()
241
+ if await self._stop_requested():
242
+ raise _Stop(message)
243
+ if not isinstance(event, TextDelta):
244
+ # Recorded as running before it runs.
245
+ tasks.append(
246
+ None if event.error is not None
247
+ else asyncio.create_task(self.dispatcher.run(dict(record), agent))
248
+ )
249
+ if done is None:
250
+ raise ProviderError('incomplete_stream', 'The stream ended before the reply did', retryable=True)
251
+ except BaseException:
252
+ for task in tasks:
253
+ if task is not None:
254
+ task.cancel()
255
+ raise
256
+ finally:
257
+ await stream.aclose()
258
+
259
+ if message is None:
260
+ # An empty reply still records what the turn has read.
261
+ message = self.session.create(
262
+ Message, parent_id=self.conversation_id, role=MessageRole.ASSISTANT, read_through=read_through,
263
+ )
264
+ if done.provider_state or call_state:
265
+ message.provider_state = {'provider': provider.name, 'turn': done.provider_state, 'calls': call_state}
266
+ message = await self.session.save(message)
267
+ for index, task in enumerate(tasks):
268
+ if task is None:
269
+ continue
270
+ while not task.done():
271
+ await asyncio.wait({task}, timeout=max(conf.stream_interval(), _STOP_POLL))
272
+ if not task.done() and await self._stop_requested():
273
+ for running in tasks:
274
+ if running is not None:
275
+ running.cancel()
276
+ raise _Stop(message)
277
+ message.tool_calls[index].update(task.result())
278
+ message = await self.session.save(message)
279
+ return _Step(done.stop, done.usage, bool(tasks))
280
+
281
+ async def _compact(self, provider: Provider, asking: tuple, half: bool) -> bool:
282
+ """Summarize the messages after the last summary, or their older half."""
283
+ summary, rest = prompt.window(self._visible(await self._messages()))
284
+ covered = compaction.to_cover(rest, half)
285
+ if covered is None:
286
+ return False
287
+ text, done = '', None
288
+ stream = provider.stream(prompt.request(
289
+ *asking, summary, covered, provider.name, self.conversation_id,
290
+ closing=True, note=compaction.SUMMARY_REQUEST,
291
+ ))
292
+ try:
293
+ async for event in stream:
294
+ if isinstance(event, TextDelta):
295
+ text += event.text
296
+ elif isinstance(event, Done):
297
+ done = event
298
+ finally:
299
+ await stream.aclose()
300
+ if done is None or not text:
301
+ raise ProviderError('incomplete_stream', 'The summary did not arrive', retryable=True)
302
+ await self._record_usage(done.usage)
303
+ await self.session.save(self.session.create(
304
+ Message, parent_id=self.conversation_id, role=MessageRole.SYSTEM, content=text,
305
+ summary_through=covered[-1].entity_id,
306
+ ))
307
+ return True
308
+
309
+ async def _say_notices(self, agent: EffectiveAgent) -> None:
310
+ new = [notice for notice in agent.notices if notice not in self.noticed]
311
+ if new:
312
+ self.noticed.update(new)
313
+ await self._say('\n'.join(new))
314
+
315
+ async def _show_context(self, conversation: Conversation, show: bool, start_address: Optional[str]) -> None:
316
+ messages = self._visible(await self._messages())
317
+ self.context_ids.extend(
318
+ entity_id for message in self._unread(messages) for entity_id in message.context_ids
319
+ if entity_id not in self.context_ids
320
+ )
321
+ # Shown once, when the conversation begins, and not followed after.
322
+ starting = [start_address] if start_address and start_address not in shown_versions(messages) else []
323
+ _, rest = prompt.window(messages)
324
+ update = await self.context.update(
325
+ [*starting, *conversation.context_ids, *self.context_ids], shown_versions(rest), show,
326
+ )
327
+ if update.renders:
328
+ await self.session.save(self.session.create(
329
+ Message, parent_id=self.conversation_id, role=MessageRole.SYSTEM, content=update.content,
330
+ context_versions=update.versions,
331
+ ))
332
+ if update.changed:
333
+ await self._say(update.notice)
334
+
335
+ # --- the conversation ------------------------------------------------------
336
+
337
+ async def _messages(self) -> list[Message]:
338
+ return await messages_of(self.session, self.conversation_id)
339
+
340
+ def _visible(self, messages: list[Message]) -> list[Message]:
341
+ return [m for m in messages if m.entity_id in self.history or m.owner == self.sender]
342
+
343
+ def _from_sender(self, message: Message) -> bool:
344
+ """A message this turn must answer: the sender's own, or a result delivered to them."""
345
+ if message.owner != self.sender:
346
+ return False
347
+ return message.role is MessageRole.USER or (
348
+ message.role is MessageRole.SYSTEM and message.source_conversation_id is not None
349
+ )
350
+
351
+ def _last_from_sender(self, messages: list[Message]) -> Optional[str]:
352
+ return next((m.entity_id for m in reversed(messages) if self._from_sender(m)), None)
353
+
354
+ def _unread(self, messages: list[Message]) -> list[Message]:
355
+ """The sender's messages after the last one a turn of theirs has read."""
356
+ read = next((
357
+ m.read_through for m in reversed(messages)
358
+ if m.role is not MessageRole.USER and m.owner == self.sender and m.read_through
359
+ ), None)
360
+ ids = [m.entity_id for m in messages]
361
+ after = ids.index(read) + 1 if read in ids else 0
362
+ return [m for m in messages[after:] if self._from_sender(m)]
363
+
364
+ async def _stop_requested(self) -> bool:
365
+ return (await self.session.get(self.conversation_id)).stop_requested
366
+
367
+ async def _interrupt(self, message: Optional[Message]) -> None:
368
+ """Mark the calls a stopped step left running. A strategy one of them
369
+ already submitted runs to completion; its outcome is not recorded."""
370
+ if message is None:
371
+ return
372
+ running = [call for call in message.tool_calls if call['state'] == ToolCallState.RUNNING]
373
+ for call in running:
374
+ call.update(state=ToolCallState.INTERRUPTED.value, result="Stopped before the call finished.")
375
+ if running:
376
+ await self.session.save(message)
377
+
378
+ def _progress(self, messages: list[Message]) -> str:
379
+ """What a stopped turn had done: its text so far and each tool call it made."""
380
+ ids = [m.entity_id for m in messages]
381
+ start = ids.index(self.answered_from) + 1 if self.answered_from in ids else 0
382
+ replies = [m for m in messages[start:] if m.role is MessageRole.ASSISTANT]
383
+ text = '\n\n'.join(m.content.strip() for m in replies if m.content.strip())
384
+ calls = [_call_line(call) for m in replies for call in m.tool_calls]
385
+ if not text and not calls:
386
+ return "Stopped before doing anything."
387
+ return '\n\n'.join(part for part in (
388
+ text, "Tool calls before the stop:\n" + '\n'.join(calls) if calls else '',
389
+ ) if part)
390
+
391
+ async def _say(self, text: str, answers: bool = False) -> Message:
392
+ """A `system` message. One that `answers` stands where the reply would
393
+ have been, so no later turn answers the same messages again."""
394
+ read_through = self._last_from_sender(self._visible(await self._messages())) if answers else None
395
+ return await self.session.save(self.session.create(
396
+ Message, parent_id=self.conversation_id, role=MessageRole.SYSTEM, content=text,
397
+ read_through=read_through,
398
+ ))
399
+
400
+ async def _set_conversation(self, **fields) -> Conversation:
401
+ """Reloads before writing, so a write made meanwhile is kept."""
402
+ for attempt in range(_SAVE_TRIES):
403
+ conversation = await self.session.get(self.conversation_id)
404
+ for name, value in fields.items():
405
+ setattr(conversation, name, value)
406
+ try:
407
+ return await self.session.save(conversation)
408
+ except ConcurrentModificationError:
409
+ if attempt == _SAVE_TRIES - 1:
410
+ raise
411
+
412
+ async def _record_usage(self, usage: Usage, sizes: Optional[dict[str, int]] = None) -> None:
413
+ """`sizes` splits the call's input tokens by what the prompt held, in proportion."""
414
+ conversation = await self.session.get(self.conversation_id)
415
+ total = conversation.usage.get('total', {})
416
+ last = {
417
+ 'input_tokens': usage.input_tokens, 'output_tokens': usage.output_tokens,
418
+ 'cached_input_tokens': usage.cached_input_tokens,
419
+ }
420
+ if sizes and sum(sizes.values()):
421
+ whole = sum(sizes.values())
422
+ last['breakdown'] = {part: round(usage.input_tokens * size / whole) for part, size in sizes.items()}
423
+ await self._set_conversation(usage={
424
+ 'last': last,
425
+ 'total': {
426
+ 'input_tokens': total.get('input_tokens', 0) + usage.input_tokens,
427
+ 'output_tokens': total.get('output_tokens', 0) + usage.output_tokens,
428
+ 'cached_input_tokens': total.get('cached_input_tokens', 0) + usage.cached_input_tokens,
429
+ },
430
+ })
431
+
432
+ def _result(self, status: str, messages: list[Message], error: Optional[str] = None) -> dict:
433
+ if error is not None:
434
+ text = error
435
+ elif status == STOPPED:
436
+ text = self._progress(messages)
437
+ else:
438
+ text = next((m.content for m in reversed(messages) if m.role is MessageRole.ASSISTANT), '')
439
+ return {
440
+ 'status': status,
441
+ 'last_message_id': messages[-1].entity_id if messages else None,
442
+ 'text': text,
443
+ **({'cut_off': True} if self.cut_off else {}),
444
+ }
445
+
446
+
447
+ def _call_line(call: dict) -> str:
448
+ """`tool target · state · the first line of its result`."""
449
+ target = call.get('at') or json.dumps(call.get('params') or {}, separators=(',', ':'))[:80]
450
+ outcome = str(call.get('error') or call.get('result') or '').strip()
451
+ first = next((line for line in outcome.splitlines() if line.strip()), '')
452
+ if len(first) > _DONE_LINE:
453
+ first = first[:_DONE_LINE] + '…'
454
+ return f"- {call['tool']} {target} · {call['state']}" + (f" · {first}" if first else '')
@@ -0,0 +1,183 @@
1
+ """A provider request built from the graph, the same for every provider."""
2
+ import json
3
+ from typing import Optional
4
+
5
+ from agents import conf
6
+ from agents.entities.message import Message, MessageRole, ToolCallState
7
+ from agents.providers.port import ModelRequest, ToolCall, ToolDef, ToolResult, Turn
8
+ from agents.runtime.effective_agent import EffectiveAgent
9
+
10
+ RUNTIME_NOTE = "[From the runtime, not from the person]"
11
+
12
+
13
+ def prefix(server_instructions: Optional[str], agent: EffectiveAgent) -> tuple[str, ...]:
14
+ parts = [server_instructions] if server_instructions else []
15
+ parts.extend(instruction.text for instruction in agent.instructions if instruction.text)
16
+ if agent.skills:
17
+ index = '\n'.join(f"- {skill.name}: {skill.description}" for skill in agent.skills)
18
+ parts.append(f"Skills you can load with load_skill(name) when one applies:\n{index}")
19
+ return tuple(parts)
20
+
21
+
22
+ def window(messages: list[Message]) -> tuple[Optional[Message], list[Message]]:
23
+ """The latest compaction summary, and the messages a prompt sends after
24
+ it: those the summary does not cover, and the latest `user` message verbatim."""
25
+ summary = next((m for m in reversed(messages) if m.summary_through), None)
26
+ if summary is None:
27
+ return None, messages
28
+ ids = [m.entity_id for m in messages]
29
+ cut = ids.index(summary.summary_through) + 1 if summary.summary_through in ids else 0
30
+ rest = [m for m in messages[cut:] if not m.summary_through]
31
+ if not any(m.role is MessageRole.USER for m in rest):
32
+ asked = next((m for m in reversed(messages[:cut]) if m.role is MessageRole.USER), None)
33
+ rest = [*([asked] if asked else []), *rest]
34
+ return summary, rest
35
+
36
+
37
+ def reading_order(messages: list[Message]) -> list[Message]:
38
+ """`messages` with each one that arrived while a reply was being written
39
+ moved after that reply. A reply is stored when its first token streams, so
40
+ a message sent while the model was still thinking is stored before a reply
41
+ that never read it."""
42
+ at = {message.entity_id: index for index, message in enumerate(messages)}
43
+ moved: dict[int, list[Message]] = {}
44
+ held: set[int] = set()
45
+ for index, message in enumerate(messages):
46
+ if not _arrives(message):
47
+ continue
48
+ last_unread_by = None
49
+ for later in range(index + 1, len(messages)):
50
+ reply = messages[later]
51
+ if reply.role is MessageRole.USER or not reply.read_through or reply.read_through not in at:
52
+ continue
53
+ if at[reply.read_through] >= index:
54
+ break
55
+ last_unread_by = later
56
+ if last_unread_by is not None:
57
+ moved.setdefault(last_unread_by, []).append(message)
58
+ held.add(index)
59
+ out: list[Message] = []
60
+ for index, message in enumerate(messages):
61
+ if index not in held:
62
+ out.append(message)
63
+ out.extend(moved.get(index, ()))
64
+ return out
65
+
66
+
67
+ def _arrives(message: Message) -> bool:
68
+ """A message a turn answers rather than one it wrote."""
69
+ return message.role is MessageRole.USER or (
70
+ message.role is MessageRole.SYSTEM and message.source_conversation_id is not None
71
+ )
72
+
73
+
74
+ def turns(summary: Optional[Message], messages: list[Message], provider_name: str,
75
+ request: Optional[str] = None) -> tuple[Turn, ...]:
76
+ """Alternating turns, the first and last `user`. `request` is a runtime
77
+ instruction for this call only, after everything else."""
78
+ out: list[Turn] = []
79
+ if summary is not None:
80
+ _add(out, Turn('user', text=f"{RUNTIME_NOTE}\nSummary of the earlier conversation:\n{summary.content}"))
81
+ for message in reading_order(messages):
82
+ if message.role is MessageRole.USER:
83
+ _add(out, Turn('user', text=message.content))
84
+ elif message.role is MessageRole.SYSTEM:
85
+ _add(out, Turn('user', text=f"{RUNTIME_NOTE}\n{message.content}"))
86
+ elif message.content or message.tool_calls:
87
+ state = message.provider_state if message.provider_state.get('provider') == provider_name else {}
88
+ calls = tuple(
89
+ ToolCall(call['id'], call['tool'], call['params'],
90
+ provider_state=state.get('calls', {}).get(call['id'], {}))
91
+ for call in message.tool_calls
92
+ )
93
+ _add(out, Turn('assistant', text=message.content, calls=calls, provider_state=state.get('turn', {})))
94
+ if calls:
95
+ _add(out, Turn('user', results=tuple(_result(call) for call in message.tool_calls)))
96
+ if request is not None:
97
+ _add(out, Turn('user', text=f"{RUNTIME_NOTE}\n{request}"))
98
+ if out and out[0].role == 'assistant':
99
+ out.insert(0, Turn('user', text=f"{RUNTIME_NOTE}\nThe conversation starts with your own message."))
100
+ return tuple(out)
101
+
102
+
103
+ def request(model: str, agent: EffectiveAgent, server_instructions: Optional[str], tools: tuple[ToolDef, ...],
104
+ summary: Optional[Message], messages: list[Message], provider_name: str, cache_key: str,
105
+ closing: bool = False, note: Optional[str] = None) -> ModelRequest:
106
+ """A provider request over `summary` and `messages`. Every request the app
107
+ sends or shows is assembled here, so what a person inspects is what a call sends."""
108
+ return ModelRequest(
109
+ model=model,
110
+ prefix=prefix(server_instructions, agent),
111
+ tools=tools,
112
+ turns=turns(summary, messages, provider_name, request=note),
113
+ tool_choice='none' if closing else 'auto',
114
+ max_output_tokens=conf.model_entry(agent.model)['max_output_tokens'],
115
+ cache_key=cache_key,
116
+ )
117
+
118
+
119
+ def next_request(model: str, agent: EffectiveAgent, server_instructions: Optional[str], tools: tuple[ToolDef, ...],
120
+ messages: list[Message], provider_name: str, cache_key: str,
121
+ closing: bool = False) -> tuple[ModelRequest, Optional[Message], list[Message]]:
122
+ """The request a conversation's next call sends, with the summary and the messages it covers."""
123
+ summary, rest = window(messages)
124
+ asked = request(model, agent, server_instructions, tools, summary, rest, provider_name, cache_key, closing)
125
+ return asked, summary, rest
126
+
127
+
128
+ def described(asked: ModelRequest) -> dict:
129
+ """A request as JSON for a person to read. Provider state is left out: it is opaque outside its adapter."""
130
+ return {
131
+ 'tool_choice': asked.tool_choice,
132
+ 'max_output_tokens': asked.max_output_tokens,
133
+ 'prefix': list(asked.prefix),
134
+ 'tools': [{'name': tool.name, 'description': tool.description, 'schema': tool.schema} for tool in asked.tools],
135
+ 'turns': [
136
+ {
137
+ 'role': turn.role,
138
+ 'text': turn.text,
139
+ 'calls': [{'id': call.id, 'name': call.name, 'params': call.params} for call in turn.calls],
140
+ 'results': [
141
+ {'call_id': result.call_id, 'name': result.name, 'content': result.content, 'is_error': result.is_error}
142
+ for result in turn.results
143
+ ],
144
+ }
145
+ for turn in asked.turns
146
+ ],
147
+ }
148
+
149
+
150
+ def sizes(prefix_parts: tuple[str, ...], tools: tuple[ToolDef, ...], summary: Optional[Message],
151
+ messages: list[Message]) -> dict[str, int]:
152
+ """Characters of a prompt by what they are, for splitting its token count."""
153
+ out = {
154
+ 'instructions': sum(len(part) for part in prefix_parts),
155
+ 'tools': sum(len(tool.name) + len(tool.description) + len(json.dumps(tool.schema)) for tool in tools),
156
+ 'context': 0,
157
+ 'messages': len(summary.content) if summary is not None else 0,
158
+ 'tool_calls': 0,
159
+ }
160
+ for message in messages:
161
+ out['context' if message.context_versions else 'messages'] += len(message.content)
162
+ for call in message.tool_calls:
163
+ out['tool_calls'] += len(json.dumps(call['params'])) + len(call.get('result') or call.get('error') or '')
164
+ return out
165
+
166
+
167
+ def _result(call: dict) -> ToolResult:
168
+ if call['state'] == ToolCallState.COMPLETED:
169
+ return ToolResult(call['id'], call['tool'], call.get('result') or '')
170
+ content = call.get('error') or call.get('result') or f"The call is {call['state']}; it has no result."
171
+ return ToolResult(call['id'], call['tool'], content, is_error=True)
172
+
173
+
174
+ def _add(out: list[Turn], turn: Turn) -> None:
175
+ if not out or out[-1].role != turn.role:
176
+ out.append(turn)
177
+ return
178
+ last = out[-1]
179
+ out[-1] = Turn(
180
+ last.role, text='\n\n'.join(text for text in (last.text, turn.text) if text),
181
+ calls=last.calls + turn.calls, results=last.results + turn.results,
182
+ # State describes one reply as the provider sent it, so a merged turn has none.
183
+ )
@@ -0,0 +1,30 @@
1
+ """Repairing the record an earlier attempt or a dead turn left behind
2
+ (docs/app_design/agents/AGENTS_TDD.md, Resumption)."""
3
+ from graphcore.public.strategies import StrategySession
4
+
5
+ from agents.entities.message import Message, MessageRole, ToolCallState
6
+
7
+ RESUMED = "Resumed after an interruption. The reply above may stop short; continue from it."
8
+
9
+
10
+ async def interrupt_running_calls(session: StrategySession, messages: list[Message]) -> list[Message]:
11
+ """Every call still `running` becomes `interrupted`. The caller holds the
12
+ conversation's lock, so no live turn owns one."""
13
+ repaired = []
14
+ for message in messages:
15
+ running = [call for call in message.tool_calls if call['state'] == ToolCallState.RUNNING]
16
+ for call in running:
17
+ call.update(
18
+ state=ToolCallState.INTERRUPTED.value,
19
+ result="Interrupted: the turn that made this call ended before the call returned, so whether "
20
+ "it ran is unknown. Check the place it acted on before repeating it.",
21
+ )
22
+ repaired.append(await session.save(message) if running else message)
23
+ return repaired
24
+
25
+
26
+ def cut_short(messages: list[Message], sender: str) -> bool:
27
+ """Whether the conversation ends on a reply an earlier attempt of this
28
+ turn was still writing."""
29
+ last = messages[-1] if messages else None
30
+ return last is not None and last.role is MessageRole.ASSISTANT and last.owner == sender