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
@@ -0,0 +1,392 @@
1
+ import asyncio
2
+ import json
3
+ from collections import deque
4
+ from unittest.mock import patch
5
+
6
+ from django.test import override_settings
7
+
8
+ from graphcore.public.errors import InvalidRequest
9
+
10
+ from agents.entities.conversation import Conversation, ConversationStatus
11
+ from agents.entities.message import MessageRole, ToolCallState
12
+ from agents.providers.fake import FakeProvider, calls, says
13
+ from agents.providers.port import Done, ProviderError, TextDelta, ToolCall, Usage
14
+ from agents.strategies.conversations import UpdateConversation
15
+ from agents.strategies.messages import SendMessage
16
+ from agents.tests.support import AgentsTestCase
17
+
18
+
19
+ class DelegationTests(AgentsTestCase):
20
+ async def conversation(self):
21
+ carl = await self.create_user('carl')
22
+ troy = await self.create_agent(carl, name='Troy')
23
+ planner = await self.create_agent(carl, name='Planner')
24
+ return carl, planner, await self.create_conversation(carl, troy)
25
+
26
+ def delegate(self, planner, **params):
27
+ return calls(ToolCall('d1', 'delegate', {'agent': planner, 'goal': 'Find flights', **params}))
28
+
29
+ async def children(self, principal, conversation_id):
30
+ return await self.listed(principal, Conversation, parent_id=conversation_id)
31
+
32
+ async def tool_call(self, principal, conversation_id):
33
+ return next(m for m in await self.messages(principal, conversation_id) if m.tool_calls).tool_calls[0]
34
+
35
+ async def test_a_waiting_parent_gets_how_the_child_turn_ended_as_the_tool_result(self):
36
+ carl, planner, conversation_id = await self.conversation()
37
+ rules = await self.create_instruction(carl, planner)
38
+ FakeProvider.play(self.delegate(planner, context_ids=[rules]), says('Two flights found.'), says('Here they are.'))
39
+
40
+ await self.send(carl, conversation_id, 'Plan my trip')
41
+
42
+ (child_id,) = await self.children(carl, conversation_id)
43
+ child = await self.get_entity(carl, child_id)
44
+ self.assertEqual(
45
+ (child.agent_id, child.owner, child.context_ids, child.deliver_to_parent),
46
+ (planner, carl.principal_entity_id, [rules], False),
47
+ )
48
+ self.assertEqual(
49
+ [(role, text) for role, text in await self.transcript(carl, child_id) if role != 'system'],
50
+ [('user', 'Find flights'), ('assistant', 'Two flights found.')],
51
+ )
52
+ call = await self.tool_call(carl, conversation_id)
53
+ self.assertEqual(call['state'], ToolCallState.COMPLETED)
54
+ self.assertEqual(
55
+ json.loads(call['result']),
56
+ {'conversation_id': child_id, 'status': 'completed', 'text': 'Two flights found.'},
57
+ )
58
+ self.assertEqual((await self.transcript(carl, conversation_id))[-1], ('assistant', 'Here they are.'))
59
+
60
+ async def test_a_child_turn_that_fails_is_a_result_with_its_error(self):
61
+ carl, planner, conversation_id = await self.conversation()
62
+ FakeProvider.play(
63
+ self.delegate(planner), [ProviderError('invalid_request', 'no such model', retryable=False)], says('Sorry.'),
64
+ )
65
+
66
+ await self.send(carl, conversation_id, 'Plan my trip')
67
+
68
+ result = json.loads((await self.tool_call(carl, conversation_id))['result'])
69
+ self.assertEqual(result['status'], 'error')
70
+ self.assertIn('no such model', result['text'])
71
+
72
+ async def test_a_waiting_parent_is_told_when_the_child_reply_was_cut_off(self):
73
+ carl, planner, conversation_id = await self.conversation()
74
+ FakeProvider.play(self.delegate(planner), says('Two fli', stop='max_tokens'), says('Here.'))
75
+
76
+ await self.send(carl, conversation_id, 'Plan my trip')
77
+
78
+ (child_id,) = await self.children(carl, conversation_id)
79
+ self.assertEqual((await self.get_entity(carl, child_id)).source_call_id, 'd1')
80
+ result = json.loads((await self.tool_call(carl, conversation_id))['result'])
81
+ self.assertEqual((result['text'], result['cut_off']), ('Two fli', True))
82
+
83
+ async def test_a_background_child_tells_the_parent_after_every_turn(self):
84
+ carl, planner, conversation_id = await self.conversation()
85
+ FakeProvider.play(self.delegate(planner, background=True))
86
+
87
+ await self.send(carl, conversation_id, 'Plan my trip')
88
+
89
+ (child_id,) = await self.children(carl, conversation_id)
90
+ self.assertTrue((await self.get_entity(carl, child_id)).deliver_to_parent)
91
+ call = await self.tool_call(carl, conversation_id)
92
+ self.assertEqual(json.loads(call['result']), {'conversation_id': child_id})
93
+ messages = await self.messages(carl, conversation_id)
94
+ (delivered,) = [m for m in messages if m.source_conversation_id]
95
+ self.assertEqual((delivered.role, delivered.source_conversation_id), (MessageRole.SYSTEM, child_id))
96
+ self.assertIn('(completed):\nok', delivered.content)
97
+ answer = messages[-1]
98
+ self.assertEqual((answer.role, answer.read_through), (MessageRole.ASSISTANT, delivered.entity_id))
99
+
100
+ await self.send(carl, child_id, 'Cheaper ones?')
101
+
102
+ delivered = [m for m in await self.messages(carl, conversation_id) if m.source_conversation_id]
103
+ self.assertEqual(len(delivered), 2)
104
+
105
+ async def test_delegating_deeper_than_the_limit_is_an_error_to_the_model(self):
106
+ carl, planner, conversation_id = await self.conversation()
107
+ FakeProvider.play(self.delegate(planner), self.delegate(planner), says('Done alone.'), says('Here.'))
108
+
109
+ await self.send(carl, conversation_id, 'Plan my trip')
110
+
111
+ (child_id,) = await self.children(carl, conversation_id)
112
+ refused = await self.tool_call(carl, child_id)
113
+ self.assertEqual(refused['state'], ToolCallState.ERROR)
114
+ self.assertIn('AGENTS_MAX_DELEGATION_DEPTH is 1', refused['error'])
115
+ self.assertEqual(await self.children(carl, child_id), [])
116
+
117
+ @override_settings(AGENTS_MAX_DELEGATION_DEPTH=2)
118
+ async def test_the_depth_limit_is_a_setting(self):
119
+ carl, planner, conversation_id = await self.conversation()
120
+ FakeProvider.play(self.delegate(planner), self.delegate(planner))
121
+
122
+ await self.send(carl, conversation_id, 'Plan my trip')
123
+
124
+ (child_id,) = await self.children(carl, conversation_id)
125
+ self.assertEqual(len(await self.children(carl, child_id)), 1)
126
+
127
+ async def test_an_agent_the_sender_cannot_read_is_an_error_to_the_model(self):
128
+ carl, _, conversation_id = await self.conversation()
129
+ dana = await self.create_user('dana')
130
+ hers = await self.create_agent(dana, name='Private')
131
+ FakeProvider.play(self.delegate(hers))
132
+
133
+ await self.send(carl, conversation_id, 'Plan my trip')
134
+
135
+ call = await self.tool_call(carl, conversation_id)
136
+ self.assertEqual(call['state'], ToolCallState.ERROR)
137
+ self.assertIn('No agent', call['error'])
138
+ self.assertEqual(await self.children(carl, conversation_id), [])
139
+
140
+ async def test_stopping_the_parent_stops_the_child_it_waits_for(self):
141
+ carl, planner, conversation_id = await self.conversation()
142
+
143
+ def stop():
144
+ return self.run_strategy(carl, UpdateConversation.request_constructor(conversation_id, stop=True))
145
+
146
+ async def parent_stopped():
147
+ # The child also sees the stop; one that ended first would let the parent's call complete.
148
+ async def poll():
149
+ while (await self.tool_call(carl, conversation_id))['state'] != ToolCallState.INTERRUPTED:
150
+ await asyncio.sleep(0.01)
151
+ await asyncio.wait_for(poll(), 5)
152
+
153
+ FakeProvider.play(self.delegate(planner), [
154
+ TextDelta('Searching'), stop, parent_stopped, TextDelta(' airlines'), TextDelta(' one by one'),
155
+ Done('end', Usage(10, 5)),
156
+ ])
157
+
158
+ await self.send(carl, conversation_id, 'Plan my trip')
159
+
160
+ (child_id,) = await self.children(carl, conversation_id)
161
+ self.assertEqual((await self.transcript(carl, child_id))[-1], ('system', 'Stopped.'))
162
+ self.assertEqual((await self.transcript(carl, conversation_id))[-1], ('system', 'Stopped.'))
163
+ self.assertEqual((await self.tool_call(carl, conversation_id))['state'], ToolCallState.INTERRUPTED)
164
+ self.assertEqual(len(FakeProvider.requests), 2)
165
+
166
+ async def test_a_delivered_result_must_come_from_a_contained_conversation(self):
167
+ carl, planner, conversation_id = await self.conversation()
168
+ elsewhere = await self.create_conversation(carl, planner)
169
+
170
+ with self.assertRaises(InvalidRequest):
171
+ await self.run_strategy(carl, SendMessage.request_constructor(
172
+ conversation_id, source_conversation_id=elsewhere, source_ret_val={'status': 'completed', 'text': 'x'},
173
+ ))
174
+ with self.assertRaises(InvalidRequest):
175
+ await self.run_strategy(carl, SendMessage.request_constructor(conversation_id))
176
+
177
+
178
+ class TaskTests(AgentsTestCase):
179
+ """`start_task` and `stop_task`. The fake provider answers a sub-conversation's
180
+ calls with `child` and the parent's from `parent`, since they run at once."""
181
+
182
+ def setUp(self):
183
+ super().setUp()
184
+ self.parent: deque = deque()
185
+ self.child = lambda: says('done')
186
+ self.released = asyncio.Event()
187
+
188
+ async def reply(request):
189
+ if any('This is a sub-conversation of' in turn.text for turn in request.turns):
190
+ return self.child()
191
+ return self.parent.popleft() if self.parent else says('ok')
192
+
193
+ patcher = patch('agents.providers.fake.scripted_reply', reply)
194
+ patcher.start()
195
+ self.addCleanup(patcher.stop)
196
+
197
+ def hang(self):
198
+ async def wait():
199
+ await self.released.wait()
200
+ return [TextDelta('Working'), wait, *says(' Finished.')]
201
+
202
+ async def until(self, check):
203
+ async def poll():
204
+ while not await check():
205
+ await asyncio.sleep(0.01)
206
+ await asyncio.wait_for(poll(), 5)
207
+
208
+ async def setup_conversation(self, **agent_fields):
209
+ carl = await self.create_user('carl')
210
+ troy = await self.create_agent(carl, **agent_fields)
211
+ return carl, troy, await self.create_conversation(carl, troy)
212
+
213
+ async def calls_settled(self, carl, conversation_id, count):
214
+ calls = [call for m in await self.messages(carl, conversation_id) for call in m.tool_calls]
215
+ return len(calls) == count and all(call['state'] != 'running' for call in calls)
216
+
217
+ async def test_a_task_is_this_agent_in_the_background_and_its_reply_starts_a_turn(self):
218
+ carl, troy, conversation_id = await self.setup_conversation()
219
+ self.parent.append(calls(ToolCall('t1', 'start_task', {'goal': 'Research hotels'})))
220
+ self.child = lambda: says('Three hotels.')
221
+
222
+ await self.send(carl, conversation_id, 'Plan my trip')
223
+
224
+ (task_id,) = await self.listed(carl, Conversation, parent_id=conversation_id)
225
+ task = await self.get_entity(carl, task_id)
226
+ self.assertEqual(
227
+ (task.agent_id, task.owner, task.deliver_to_parent, task.source_call_id),
228
+ (troy, carl.principal_entity_id, True, 't1'),
229
+ )
230
+ note, *rest = await self.transcript(carl, task_id)
231
+ self.assertEqual(note[0], 'system')
232
+ self.assertIn(conversation_id, note[1])
233
+ self.assertIn('final reply is all that is sent back', note[1])
234
+ self.assertEqual(rest, [('user', 'Research hotels'), ('assistant', 'Three hotels.')])
235
+ call = next(m for m in await self.messages(carl, conversation_id) if m.tool_calls).tool_calls[0]
236
+ self.assertEqual(json.loads(call['result']), {'conversation_id': task_id})
237
+ messages = await self.messages(carl, conversation_id)
238
+ (delivered,) = [m for m in messages if m.source_conversation_id]
239
+ self.assertIn('Three hotels.', delivered.content)
240
+ self.assertEqual((messages[-1].role, messages[-1].read_through), (MessageRole.ASSISTANT, delivered.entity_id))
241
+
242
+ async def started_past_the_limit(self, carl, conversation_id, count):
243
+ self.parent.append(calls(*[
244
+ ToolCall(f't{n}', 'start_task', {'goal': f'Task {n}'}) for n in range(count)
245
+ ]))
246
+ self.child = self.hang
247
+ await self.send(carl, conversation_id, 'Do it all', settle=False)
248
+ await self.until(lambda: self.calls_settled(carl, conversation_id, count))
249
+ tool_calls = next(m for m in await self.messages(carl, conversation_id) if m.tool_calls).tool_calls
250
+ self.released.set()
251
+ await self.settle()
252
+ return tool_calls
253
+
254
+ async def test_a_conversation_runs_at_most_its_agents_limit_of_tasks_at_once(self):
255
+ carl, _, conversation_id = await self.setup_conversation(max_tasks=2)
256
+
257
+ tool_calls = await self.started_past_the_limit(carl, conversation_id, 3)
258
+
259
+ self.assertEqual(sorted(call['state'] for call in tool_calls), ['completed', 'completed', 'error'])
260
+ refused = next(call for call in tool_calls if call['state'] == 'error')
261
+ self.assertIn("2 tasks are running, this agent's limit", refused['error'])
262
+ self.assertEqual(len(await self.listed(carl, Conversation, parent_id=conversation_id)), 2)
263
+
264
+ @override_settings(AGENTS_MAX_TASKS=1)
265
+ async def test_the_task_limit_defaults_to_the_setting(self):
266
+ carl, _, conversation_id = await self.setup_conversation()
267
+
268
+ tool_calls = await self.started_past_the_limit(carl, conversation_id, 2)
269
+
270
+ self.assertEqual(sorted(call['state'] for call in tool_calls), ['completed', 'error'])
271
+
272
+ async def test_stop_task_stops_a_running_task_which_reports_back(self):
273
+ carl, _, conversation_id = await self.setup_conversation()
274
+ self.parent.append(calls(ToolCall('t1', 'start_task', {'goal': 'Research hotels'})))
275
+ self.child = self.hang
276
+ await self.send(carl, conversation_id, 'Plan my trip', settle=False)
277
+
278
+ async def task_running():
279
+ tasks = await self.listed(carl, Conversation, parent_id=conversation_id)
280
+ parent = await self.get_entity(carl, conversation_id)
281
+ return len(tasks) == 1 and parent.status.value == 'idle'
282
+ await self.until(task_running)
283
+ (task_id,) = await self.listed(carl, Conversation, parent_id=conversation_id)
284
+ self.parent.append(calls(ToolCall('s1', 'stop_task', {'task': task_id})))
285
+ await self.send(carl, conversation_id, 'Never mind', settle=False)
286
+
287
+ async def stop_requested():
288
+ return (await self.get_entity(carl, task_id)).stop_requested
289
+ await self.until(stop_requested)
290
+ self.released.set()
291
+ await self.settle()
292
+
293
+ self.assertEqual((await self.transcript(carl, task_id))[-1], ('system', 'Stopped.'))
294
+ stop = [call for m in await self.messages(carl, conversation_id) for call in m.tool_calls if call['id'] == 's1']
295
+ self.assertEqual(stop[0]['result'], f"Stopping {task_id}. It reports back once it has stopped.")
296
+ delivered = [m for m in await self.messages(carl, conversation_id) if m.source_conversation_id]
297
+ self.assertIn('(stopped)', delivered[-1].content)
298
+
299
+ @override_settings(GRAPHCORE_EXECUTION_MAX_ATTEMPTS=2)
300
+ async def test_a_task_still_failing_on_its_last_attempt_reports_an_error_and_frees_its_place(self):
301
+ carl, _, conversation_id = await self.setup_conversation(max_tasks=1)
302
+ self.parent.append(calls(ToolCall('t1', 'start_task', {'goal': 'Research hotels'})))
303
+ self.child = lambda: [ProviderError('overloaded', 'try later', retryable=True)]
304
+
305
+ async def no_backoff(attempt, outcome='conflict'):
306
+ pass
307
+
308
+ async def delivered():
309
+ return any(m.source_conversation_id for m in await self.messages(carl, conversation_id))
310
+
311
+ with patch.object(self.runtime.executor, 'max_attempts', 2), \
312
+ patch.object(self.runtime.executor, '_backoff', no_backoff):
313
+ await self.send(carl, conversation_id, 'Plan my trip', settle=False)
314
+ await self.until(delivered)
315
+ await self.settle()
316
+
317
+ (task_id,) = await self.listed(carl, Conversation, parent_id=conversation_id)
318
+ self.assertEqual((await self.get_entity(carl, task_id)).status, ConversationStatus.IDLE)
319
+ self.assertIn('still failing after 2 attempts', (await self.transcript(carl, task_id))[-1][1])
320
+ (report,) = [m for m in await self.messages(carl, conversation_id) if m.source_conversation_id]
321
+ self.assertIn('ended its turn (error', report.content)
322
+
323
+ self.parent.append(calls(ToolCall('t2', 'start_task', {'goal': 'Try again'})))
324
+ self.child = lambda: says('done')
325
+ await self.send(carl, conversation_id, 'Once more')
326
+ again = [call for m in await self.messages(carl, conversation_id) for call in m.tool_calls if call['id'] == 't2']
327
+ self.assertEqual(again[0]['state'], ToolCallState.COMPLETED)
328
+
329
+ async def task_saying(self, carl, conversation_id, words):
330
+ async def said():
331
+ tasks = await self.listed(carl, Conversation, parent_id=conversation_id)
332
+ return bool(tasks) and any(words in m.content for m in await self.messages(carl, tasks[0]))
333
+ await self.until(said)
334
+ (task_id,) = await self.listed(carl, Conversation, parent_id=conversation_id)
335
+ return task_id
336
+
337
+ async def test_a_stopped_task_reports_its_text_so_far_and_its_tool_calls(self):
338
+ carl, _, conversation_id = await self.setup_conversation()
339
+ self.parent.append(calls(ToolCall('t1', 'start_task', {'goal': 'Research hotels'})))
340
+ steps = deque([calls(ToolCall('c1', 'open', {'at': '/'})), self.hang()])
341
+ self.child = steps.popleft
342
+ await self.send(carl, conversation_id, 'Plan my trip', settle=False)
343
+ task_id = await self.task_saying(carl, conversation_id, 'Working')
344
+
345
+ await self.run_strategy(carl, UpdateConversation.request_constructor(task_id, stop=True))
346
+ self.released.set()
347
+ await self.settle()
348
+
349
+ (report,) = [m for m in await self.messages(carl, conversation_id) if m.source_conversation_id]
350
+ self.assertIn('ended its turn (stopped):\nWorking', report.content)
351
+ self.assertIn('Tool calls before the stop:\n- open / · completed · ', report.content)
352
+
353
+ async def test_stopping_a_conversation_leaves_its_background_tasks_running(self):
354
+ carl, _, conversation_id = await self.setup_conversation()
355
+ hold = asyncio.Event()
356
+
357
+ async def parent_waits():
358
+ await hold.wait()
359
+
360
+ self.parent.append(calls(ToolCall('t1', 'start_task', {'goal': 'Research hotels'})))
361
+ self.parent.append([TextDelta('Waiting'), parent_waits, *says(' on it.')])
362
+ self.child = self.hang
363
+ await self.send(carl, conversation_id, 'Plan my trip', settle=False)
364
+ task_id = await self.task_saying(carl, conversation_id, 'Working')
365
+
366
+ await self.run_strategy(carl, UpdateConversation.request_constructor(conversation_id, stop=True))
367
+ hold.set()
368
+
369
+ async def parent_stopped():
370
+ return (await self.transcript(carl, conversation_id))[-1] == ('system', 'Stopped.')
371
+ await self.until(parent_stopped)
372
+ task = await self.get_entity(carl, task_id)
373
+ self.assertEqual((task.status, task.stop_requested), (ConversationStatus.RUNNING, False))
374
+ place = (await self.open_place(carl, conversation_id)).text
375
+ self.assertRegex(place, r'## Running tasks\n+- Research hotels · agents\.Conversation')
376
+ self.assertIn('Stopping this conversation does not stop its running tasks.', place)
377
+
378
+ self.released.set()
379
+ await self.settle()
380
+ (report,) = [m for m in await self.messages(carl, conversation_id) if m.source_conversation_id]
381
+ self.assertIn('ended its turn (completed)', report.content)
382
+
383
+ async def test_stop_task_refuses_a_conversation_that_is_not_one_of_its_own(self):
384
+ carl, troy, conversation_id = await self.setup_conversation()
385
+ elsewhere = await self.create_conversation(carl, troy)
386
+ self.parent.append(calls(ToolCall('s1', 'stop_task', {'task': elsewhere})))
387
+
388
+ await self.send(carl, conversation_id, 'Stop that')
389
+
390
+ call = next(m for m in await self.messages(carl, conversation_id) if m.tool_calls).tool_calls[0]
391
+ self.assertEqual(call['state'], ToolCallState.ERROR)
392
+ self.assertIn('is not a sub-conversation of this conversation', call['error'])
@@ -0,0 +1,208 @@
1
+ """The Google adapter against the SDK itself, with the HTTP transport replaced:
2
+ a `ModelRequest` becomes the wire request, a recorded stream becomes the port's
3
+ events, and each vendor error becomes its `code`."""
4
+ import json
5
+
6
+ import httpx
7
+ from django.test import SimpleTestCase
8
+
9
+ from agents.providers.google import GoogleProvider
10
+ from agents.providers.port import (
11
+ Done, ModelRequest, ProviderError, TextDelta, ToolCall, ToolDef, ToolResult, Turn, Usage,
12
+ )
13
+
14
+ OPEN = ToolDef('open', 'Read a place.', {"type": "object", "properties": {"at": {"type": "string"}}})
15
+ SIGNATURE = 'c2lnLTE='
16
+ CALL_PART = {"functionCall": {"name": "open", "args": {"at": "/notes"}}, "thoughtSignature": SIGNATURE}
17
+ USAGE = {"promptTokenCount": 442, "cachedContentTokenCount": 400, "candidatesTokenCount": 20, "thoughtsTokenCount": 5}
18
+
19
+
20
+ def sse(*chunks: dict) -> bytes:
21
+ return b''.join(f"data: {json.dumps(chunk)}\n\n".encode() for chunk in chunks)
22
+
23
+
24
+ def chunk(*parts: dict, finish: str | None = None, **fields) -> dict:
25
+ candidate = {"content": {"role": "model", "parts": list(parts)}, "index": 0}
26
+ if finish:
27
+ candidate["finishReason"] = finish
28
+ return {"candidates": [candidate], **fields}
29
+
30
+
31
+ def recorded_reply(last: dict = CALL_PART, finish: str = 'STOP') -> bytes:
32
+ """A reply that says a sentence and calls `open`, the call carrying a thought signature."""
33
+ return sse(chunk({"text": "Looking"}), chunk({"text": " now."}), chunk(last, finish=finish, usageMetadata=USAGE))
34
+
35
+
36
+ def error_response(status: int, state: str, message: str = 'no') -> httpx.Response:
37
+ return httpx.Response(status, json={"error": {"code": status, "message": message, "status": state}})
38
+
39
+
40
+ class GoogleAdapterTests(SimpleTestCase):
41
+ def provider(self, *responses):
42
+ """A provider whose HTTP calls are answered by `responses`, in order."""
43
+ self.sent: list[dict] = []
44
+ self.urls: list[str] = []
45
+ queue = list(responses)
46
+
47
+ def handler(request: httpx.Request) -> httpx.Response:
48
+ self.sent.append(json.loads(request.content))
49
+ self.urls.append(str(request.url))
50
+ reply = queue.pop(0)
51
+ if isinstance(reply, Exception):
52
+ raise reply
53
+ if isinstance(reply, bytes):
54
+ return httpx.Response(200, content=reply, headers={"content-type": "text/event-stream"})
55
+ return reply
56
+
57
+ return GoogleProvider('test-key', 5, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
58
+
59
+ async def events(self, provider, request):
60
+ return [event async for event in provider.stream(request)]
61
+
62
+ def request(self, **overrides) -> ModelRequest:
63
+ fields = dict(
64
+ model='gemini-3-pro', prefix=('How places work.', 'Be brief.'), tools=(OPEN,),
65
+ turns=(Turn('user', text='What is in notes?'),), max_output_tokens=4096, cache_key='gc://c',
66
+ )
67
+ return ModelRequest(**{**fields, **overrides})
68
+
69
+ async def test_a_request_becomes_the_wire_request(self):
70
+ provider = self.provider(recorded_reply())
71
+ history = (
72
+ Turn('user', text='What is in notes?'),
73
+ Turn('assistant', text='Looking.', calls=(
74
+ ToolCall('call_0', 'open', {'at': '/notes'}),
75
+ ToolCall('call_minted', 'open', {'at': '/tasks'}, provider_state={'vendor_id': False}),
76
+ )),
77
+ Turn('user', results=(ToolResult('call_0', 'open', '# Notes'),
78
+ ToolResult('call_minted', 'open', 'NotFound', is_error=True)), text='And tasks?'),
79
+ )
80
+
81
+ await self.events(provider, self.request(turns=history, tool_choice='none'))
82
+
83
+ (sent,) = self.sent
84
+ self.assertIn('models/gemini-3-pro:streamGenerateContent', self.urls[0])
85
+ self.assertEqual(sent['systemInstruction']['parts'], [{"text": "How places work.\n\nBe brief."}])
86
+ self.assertEqual(sent['tools'], [{"functionDeclarations": [
87
+ {"name": "open", "description": "Read a place.", "parameters_json_schema": OPEN.schema},
88
+ ]}])
89
+ self.assertEqual(sent['toolConfig'], {"functionCallingConfig": {"mode": "NONE"}})
90
+ self.assertEqual(sent['generationConfig'], {"maxOutputTokens": 4096})
91
+ self.assertEqual(sent['contents'], [
92
+ {"role": "user", "parts": [{"text": "What is in notes?"}]},
93
+ {"role": "model", "parts": [
94
+ {"text": "Looking."},
95
+ {"functionCall": {"id": "call_0", "name": "open", "args": {"at": "/notes"}}},
96
+ {"functionCall": {"name": "open", "args": {"at": "/tasks"}}},
97
+ ]},
98
+ {"role": "user", "parts": [
99
+ {"functionResponse": {"id": "call_0", "name": "open", "response": {"result": "# Notes"}}},
100
+ {"functionResponse": {"name": "open", "response": {"error": "NotFound"}}},
101
+ {"text": "And tasks?"},
102
+ ]},
103
+ ])
104
+
105
+ async def test_tool_choice_auto_is_left_to_the_api_default(self):
106
+ provider = self.provider(recorded_reply())
107
+
108
+ await self.events(provider, self.request())
109
+
110
+ self.assertNotIn('toolConfig', self.sent[0])
111
+
112
+ async def test_a_recorded_stream_becomes_text_whole_tool_calls_and_one_done(self):
113
+ events = await self.events(self.provider(recorded_reply()), self.request())
114
+
115
+ self.assertEqual(events[:2], [TextDelta('Looking'), TextDelta(' now.')])
116
+ call, done = events[2:]
117
+ self.assertEqual((call.name, call.params, call.provider_state), ('open', {'at': '/notes'}, {'vendor_id': False}))
118
+ self.assertTrue(call.id.startswith('call_'))
119
+ self.assertIsInstance(done, Done)
120
+ self.assertEqual(done.stop, 'tool_calls')
121
+ self.assertEqual(done.usage, Usage(input_tokens=442, output_tokens=25, cached_input_tokens=400))
122
+ self.assertEqual(done.provider_state, {'parts': [
123
+ {"text": "Looking now."},
124
+ {"function_call": {"name": "open", "args": {"at": "/notes"}}, "thought_signature": SIGNATURE},
125
+ ]})
126
+ json.dumps(done.provider_state)
127
+
128
+ async def test_a_call_the_api_names_keeps_its_id(self):
129
+ named = {"functionCall": {"id": "fc-7", "name": "open", "args": {"at": "/notes"}}}
130
+
131
+ events = await self.events(self.provider(recorded_reply(named)), self.request())
132
+
133
+ self.assertEqual(events[2], ToolCall('fc-7', 'open', {'at': '/notes'}))
134
+ self.assertEqual(events[3].provider_state, {})
135
+
136
+ async def test_stop_reasons_map_to_the_ports(self):
137
+ said = {"text": " Done."}
138
+ for vendor, port in (('STOP', 'end'), ('MAX_TOKENS', 'max_tokens'), ('SAFETY', 'refusal')):
139
+ events = await self.events(self.provider(recorded_reply(said, vendor)), self.request())
140
+ self.assertEqual(events[-1].stop, port)
141
+
142
+ async def test_a_blocked_prompt_is_a_refusal(self):
143
+ blocked = sse({"promptFeedback": {"blockReason": "SAFETY"}, "usageMetadata": {"promptTokenCount": 9}})
144
+
145
+ (done,) = await self.events(self.provider(blocked), self.request())
146
+
147
+ self.assertEqual((done.stop, done.usage.input_tokens), ('refusal', 9))
148
+
149
+ async def test_a_reply_goes_back_as_it_was_sent_signatures_included(self):
150
+ provider = self.provider(recorded_reply(), recorded_reply({"text": " Done."}))
151
+ first = await self.events(provider, self.request())
152
+ call = first[2]
153
+ reply = Turn('assistant', text='Looking now.', calls=(call,), provider_state=first[-1].provider_state)
154
+ results = Turn('user', results=(ToolResult(call.id, 'open', '# Notes'),))
155
+
156
+ await self.events(provider, self.request(turns=(Turn('user', text='Hi'), reply, results)))
157
+
158
+ self.assertEqual(self.sent[1]['contents'][1:], [
159
+ {"role": "model", "parts": [{"text": "Looking now."}, CALL_PART]},
160
+ {"role": "user", "parts": [{"functionResponse": {"name": "open", "response": {"result": "# Notes"}}}]},
161
+ ])
162
+
163
+ async def test_a_signature_the_api_no_longer_accepts_is_dropped_and_the_call_sent_again(self):
164
+ refused = error_response(400, 'INVALID_ARGUMENT', 'Thought signature is not valid.')
165
+ provider = self.provider(refused, recorded_reply({"text": " Done."}))
166
+ reply = Turn('assistant', text='Looking.', provider_state={'parts': [
167
+ {"text": "Looking.", "thought_signature": SIGNATURE},
168
+ ]})
169
+
170
+ events = await self.events(provider, self.request(turns=(
171
+ Turn('user', text='Hi'), reply, Turn('user', text='Go on'),
172
+ )))
173
+
174
+ self.assertEqual(events[-1].stop, 'end')
175
+ self.assertEqual(self.sent[0]['contents'][1]['parts'], [{"text": "Looking.", "thoughtSignature": SIGNATURE}])
176
+ self.assertEqual(self.sent[1]['contents'][1]['parts'], [{"text": "Looking."}])
177
+
178
+ async def test_each_vendor_error_maps_to_its_code(self):
179
+ cases = [
180
+ (error_response(429, 'RESOURCE_EXHAUSTED'), 'rate_limit', True),
181
+ (error_response(503, 'UNAVAILABLE'), 'overloaded', True),
182
+ (error_response(500, 'INTERNAL'), 'server_error', True),
183
+ (error_response(504, 'DEADLINE_EXCEEDED'), 'timeout', True),
184
+ (httpx.ConnectError('refused'), 'connection', True),
185
+ (httpx.ReadTimeout('silent'), 'timeout', True),
186
+ (error_response(403, 'PERMISSION_DENIED'), 'auth', False),
187
+ (error_response(402, 'RESOURCE_EXHAUSTED', 'Your prepayment credits are depleted.'), 'auth', False),
188
+ (error_response(400, 'INVALID_ARGUMENT', 'API key not valid. Please pass a valid API key.'), 'auth', False),
189
+ (error_response(404, 'NOT_FOUND'), 'unknown_model', False),
190
+ (error_response(400, 'INVALID_ARGUMENT',
191
+ 'The input token count (1300000) exceeds the maximum number of tokens allowed (1048576).'),
192
+ 'context_overflow', False),
193
+ (error_response(400, 'INVALID_ARGUMENT', 'tools[0]: bad schema'), 'invalid_request', False),
194
+ ]
195
+ for reply, code, retryable in cases:
196
+ with self.subTest(code=code, reply=reply):
197
+ with self.assertRaises(ProviderError) as raised:
198
+ await self.events(self.provider(reply), self.request())
199
+ self.assertEqual((raised.exception.code, raised.exception.retryable), (code, retryable))
200
+ self.assertEqual(len(self.sent), 1)
201
+
202
+ async def test_a_stream_that_ends_without_a_finish_reason_is_retryable(self):
203
+ cut = sse(chunk({"text": "Looking"}))
204
+
205
+ with self.assertRaises(ProviderError) as raised:
206
+ await self.events(self.provider(cut), self.request())
207
+
208
+ self.assertEqual((raised.exception.code, raised.exception.retryable), ('incomplete_stream', True))
@@ -0,0 +1,59 @@
1
+ from graphcore.public.errors import Forbidden
2
+
3
+ from agents.providers.fake import FakeProvider, says
4
+ from agents.runtime import prompt
5
+ from agents.strategies.agents import UpdateAgent
6
+ from agents.strategies.context import InspectContext
7
+ from agents.tests.support import AgentsTestCase
8
+
9
+
10
+ class InspectContextTests(AgentsTestCase):
11
+ async def inspect(self, principal, conversation_id) -> dict:
12
+ return (await self.run_strategy(principal, InspectContext.request_constructor(conversation_id))).ret_val['context']
13
+
14
+ async def test_the_inspected_request_is_the_one_the_next_call_sends(self):
15
+ carl = await self.create_user('carl')
16
+ agent_id = await self.create_agent(carl, debug_context=True)
17
+ await self.create_instruction(carl, agent_id, text='Answer in one line.', attach=True)
18
+ conversation_id = await self.create_conversation(carl, agent_id)
19
+ FakeProvider.play(says('First answer.'))
20
+ await self.send(carl, conversation_id, 'First')
21
+
22
+ inspected = await self.inspect(carl, conversation_id)
23
+ await self.send(carl, conversation_id, 'Second')
24
+
25
+ sent = prompt.described(FakeProvider.requests[-1])
26
+ self.assertEqual(inspected['model'], 'fake/model')
27
+ self.assertIn('Answer in one line.', inspected['prefix'])
28
+ self.assertEqual((inspected['prefix'], inspected['tools']), (sent['prefix'], sent['tools']))
29
+ self.assertEqual(inspected['turns'], sent['turns'][:-1])
30
+ self.assertEqual([turn['text'] for turn in inspected['turns']], ['First', 'First answer.'])
31
+ self.assertEqual(sent['turns'][-1]['text'], 'Second')
32
+ self.assertGreater(inspected['sizes']['tools'], 0)
33
+ self.assertEqual(len(FakeProvider.requests), 2)
34
+
35
+ async def test_it_is_refused_until_the_agent_turns_it_on(self):
36
+ carl = await self.create_user('carl')
37
+ agent_id = await self.create_agent(carl)
38
+ conversation_id = await self.create_conversation(carl, agent_id)
39
+
40
+ with self.assertRaises(Forbidden):
41
+ await self.inspect(carl, conversation_id)
42
+ await self.run_strategy(carl, UpdateAgent.request_constructor(agent_id, debug_context=True))
43
+
44
+ self.assertEqual((await self.inspect(carl, conversation_id))['turns'], [])
45
+
46
+ async def test_a_reader_of_the_conversation_may_inspect_it_and_only_the_agents_writer_turns_it_on(self):
47
+ carl = await self.create_user('carl')
48
+ dana = await self.create_user('dana')
49
+ agent_id = await self.create_agent(carl, debug_context=True)
50
+ conversation_id = await self.create_conversation(carl, agent_id)
51
+ await self.send(carl, conversation_id, 'Hello')
52
+ await self.grant(carl, agent_id, dana, 'viewer')
53
+ await self.grant(carl, conversation_id, dana, 'viewer')
54
+
55
+ inspected = await self.inspect(dana, conversation_id)
56
+
57
+ self.assertEqual(inspected['turns'][0]['text'], 'Hello')
58
+ with self.assertRaises(Forbidden):
59
+ await self.run_strategy(dana, UpdateAgent.request_constructor(agent_id, debug_context=False))