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,69 @@
1
+ """One real call per provider, through a tool call and its result. Runs only
2
+ for a provider whose key is in the environment, never in CI:
3
+
4
+ ANTHROPIC_API_KEY=... OPENAI_API_KEY=... GOOGLE_API_KEY=... scripts/test agents.tests.test_live_providers
5
+ """
6
+ import os
7
+ from unittest import skipUnless
8
+
9
+ from django.test import SimpleTestCase
10
+
11
+ from agents.providers.port import Done, ModelRequest, TextDelta, ToolCall, ToolDef, ToolResult, Turn
12
+
13
+ OPEN = ToolDef('open', 'Read a place by its address.', {
14
+ "type": "object", "properties": {"at": {"type": "string", "description": "The address, such as /notes"}},
15
+ "required": ["at"],
16
+ })
17
+ ASK = Turn('user', text='Open the place at /notes with the open tool, then tell me in one sentence what it holds.')
18
+ MODELS = {
19
+ 'anthropic': ('agents.providers.anthropic.AnthropicProvider', 'claude-sonnet-5-5'),
20
+ 'openai': ('agents.providers.openai.OpenAIProvider', 'gpt-5.5'),
21
+ 'google': ('agents.providers.google.GoogleProvider', 'gemini-3.5-flash'),
22
+ }
23
+
24
+
25
+ def live(name: str):
26
+ return skipUnless(os.environ.get(f'{name.upper()}_API_KEY'), f"{name.upper()}_API_KEY is not set")
27
+
28
+
29
+ class LiveProviderTests(SimpleTestCase):
30
+ async def round_trip(self, name: str):
31
+ from django.utils.module_loading import import_string
32
+
33
+ path, default_model = MODELS[name]
34
+ provider = import_string(path)(os.environ[f'{name.upper()}_API_KEY'], 60)
35
+ model = os.environ.get(f'AGENTS_LIVE_{name.upper()}_MODEL', default_model)
36
+
37
+ def request(*turns: Turn) -> ModelRequest:
38
+ return ModelRequest(
39
+ model=model, prefix=('You read places for the person. Be brief.',), tools=(OPEN,), turns=turns,
40
+ max_output_tokens=2048, cache_key='live-test',
41
+ )
42
+
43
+ first = [event async for event in provider.stream(request(ASK))]
44
+ (call,) = [event for event in first if isinstance(event, ToolCall)]
45
+ done = first[-1]
46
+ self.assertIsInstance(done, Done)
47
+ self.assertEqual((call.name, call.params, done.stop), ('open', {'at': '/notes'}, 'tool_calls'))
48
+ self.assertGreater(done.usage.input_tokens, 0)
49
+
50
+ said = ''.join(event.text for event in first if isinstance(event, TextDelta))
51
+ reply = Turn('assistant', text=said, calls=(call,), provider_state=done.provider_state)
52
+ result = Turn('user', results=(ToolResult(call.id, 'open', '# Notes\n\nA shopping list: eggs, flour, butter.'),))
53
+ second = [event async for event in provider.stream(request(ASK, reply, result))]
54
+
55
+ answer = ''.join(event.text for event in second if isinstance(event, TextDelta))
56
+ self.assertEqual(second[-1].stop, 'end')
57
+ self.assertIn('shopping', answer.lower())
58
+
59
+ @live('anthropic')
60
+ async def test_anthropic(self):
61
+ await self.round_trip('anthropic')
62
+
63
+ @live('openai')
64
+ async def test_openai(self):
65
+ await self.round_trip('openai')
66
+
67
+ @live('google')
68
+ async def test_google(self):
69
+ await self.round_trip('google')
@@ -0,0 +1,259 @@
1
+ """The OpenAI 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
+ from openai import DefaultAsyncHttpxClient
9
+
10
+ from agents.providers.openai import OpenAIProvider
11
+ from agents.providers.port import (
12
+ Done, ModelRequest, ProviderError, TextDelta, ToolCall, ToolDef, ToolResult, Turn, Usage,
13
+ )
14
+
15
+ OPEN = ToolDef('open', 'Read a place.', {"type": "object", "properties": {"at": {"type": "string"}}})
16
+ REASONING = {"type": "reasoning", "id": "rs_1", "summary": [], "encrypted_content": "enc-1"}
17
+ MESSAGE = {
18
+ "type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
19
+ "content": [{"type": "output_text", "text": "Looking now.", "annotations": []}],
20
+ }
21
+ CALL = {
22
+ "type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "open",
23
+ "arguments": '{"at": "/notes"}', "status": "completed",
24
+ }
25
+
26
+
27
+ def sse(*events: dict) -> bytes:
28
+ return b''.join(
29
+ f"event: {e['type']}\ndata: {json.dumps({**e, 'sequence_number': n})}\n\n".encode()
30
+ for n, e in enumerate(events)
31
+ )
32
+
33
+
34
+ def response(output: list, status: str = 'completed', **fields) -> dict:
35
+ return {
36
+ "id": "resp_1", "object": "response", "created_at": 0, "model": "gpt-5.5", "status": status,
37
+ "output": output, "parallel_tool_calls": True, "tool_choice": "auto", "tools": [],
38
+ "usage": {
39
+ "input_tokens": 442, "input_tokens_details": {"cached_tokens": 400},
40
+ "output_tokens": 25, "output_tokens_details": {"reasoning_tokens": 5}, "total_tokens": 467,
41
+ },
42
+ **fields,
43
+ }
44
+
45
+
46
+ def text_delta(text: str) -> dict:
47
+ return {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 1, "content_index": 0,
48
+ "delta": text, "logprobs": []}
49
+
50
+
51
+ def recorded_reply(output=(REASONING, MESSAGE, CALL), end: str = 'response.completed', **fields) -> bytes:
52
+ """A reply that reasons, says a sentence, and calls `open`."""
53
+ return sse(
54
+ {"type": "response.created", "response": response([], status='in_progress')},
55
+ {"type": "response.output_item.done", "output_index": 0, "item": REASONING},
56
+ text_delta('Looking'), text_delta(' now.'),
57
+ {"type": "response.output_item.done", "output_index": 1, "item": MESSAGE},
58
+ *([{"type": "response.output_item.done", "output_index": 2, "item": CALL}] if CALL in output else []),
59
+ {"type": end, "response": response(list(output), **fields)},
60
+ )
61
+
62
+
63
+ def error_response(status: int, code: str = 'x', message: str = 'no') -> httpx.Response:
64
+ return httpx.Response(status, json={"error": {"type": "invalid_request_error", "code": code, "message": message}})
65
+
66
+
67
+ class OpenAIAdapterTests(SimpleTestCase):
68
+ def provider(self, *responses):
69
+ """A provider whose HTTP calls are answered by `responses`, in order."""
70
+ self.sent: list[dict] = []
71
+ queue = list(responses)
72
+
73
+ def handler(request: httpx.Request) -> httpx.Response:
74
+ self.sent.append(json.loads(request.content))
75
+ reply = queue.pop(0)
76
+ if isinstance(reply, Exception):
77
+ raise reply
78
+ if isinstance(reply, bytes):
79
+ return httpx.Response(200, content=reply, headers={"content-type": "text/event-stream"})
80
+ return reply
81
+
82
+ return OpenAIProvider('test-key', 5, http_client=DefaultAsyncHttpxClient(
83
+ transport=httpx.MockTransport(handler),
84
+ ))
85
+
86
+ async def events(self, provider, request):
87
+ return [event async for event in provider.stream(request)]
88
+
89
+ def request(self, **overrides) -> ModelRequest:
90
+ fields = dict(
91
+ model='gpt-5.5', prefix=('How places work.', 'Be brief.'), tools=(OPEN,),
92
+ turns=(Turn('user', text='What is in notes?'),), max_output_tokens=4096, cache_key='gc://c',
93
+ )
94
+ return ModelRequest(**{**fields, **overrides})
95
+
96
+ async def test_a_request_becomes_the_wire_request_with_nothing_stored_at_the_vendor(self):
97
+ provider = self.provider(recorded_reply())
98
+ history = (
99
+ Turn('user', text='What is in notes?'),
100
+ Turn('assistant', text='Looking.', calls=(ToolCall('call_0', 'open', {'at': '/notes'}),)),
101
+ Turn('user', results=(ToolResult('call_0', 'open', '# Notes'),
102
+ ToolResult('call_9', 'open', 'NotFound', is_error=True)), text='And tasks?'),
103
+ )
104
+
105
+ await self.events(provider, self.request(turns=history, tool_choice='none'))
106
+
107
+ (sent,) = self.sent
108
+ self.assertEqual(
109
+ (sent['model'], sent['max_output_tokens'], sent['stream'], sent['store'], sent['prompt_cache_key']),
110
+ ('gpt-5.5', 4096, True, False, 'gc://c'),
111
+ )
112
+ self.assertEqual(sent['instructions'], 'How places work.\n\nBe brief.')
113
+ self.assertEqual(sent['include'], ['reasoning.encrypted_content'])
114
+ self.assertEqual(sent['tools'], [
115
+ {"type": "function", "name": "open", "description": "Read a place.", "parameters": OPEN.schema,
116
+ "strict": False},
117
+ ])
118
+ self.assertEqual(sent['tool_choice'], 'none')
119
+ self.assertEqual(sent['input'], [
120
+ {"role": "user", "content": "What is in notes?"},
121
+ {"role": "assistant", "content": "Looking."},
122
+ {"type": "function_call", "call_id": "call_0", "name": "open", "arguments": '{"at": "/notes"}'},
123
+ {"type": "function_call_output", "call_id": "call_0", "output": "# Notes"},
124
+ {"type": "function_call_output", "call_id": "call_9", "output": "Error: NotFound"},
125
+ {"role": "user", "content": "And tasks?"},
126
+ ])
127
+ for unset in ('reasoning', 'temperature', 'previous_response_id'):
128
+ self.assertNotIn(unset, sent)
129
+
130
+ async def test_tool_choice_auto_is_left_to_the_api_default(self):
131
+ provider = self.provider(recorded_reply())
132
+
133
+ await self.events(provider, self.request())
134
+
135
+ self.assertNotIn('tool_choice', self.sent[0])
136
+
137
+ async def test_a_recorded_stream_becomes_text_whole_tool_calls_and_one_done(self):
138
+ events = await self.events(self.provider(recorded_reply()), self.request())
139
+
140
+ self.assertEqual(events[:3], [
141
+ TextDelta('Looking'), TextDelta(' now.'), ToolCall('call_1', 'open', {'at': '/notes'}),
142
+ ])
143
+ (done,) = events[3:]
144
+ self.assertIsInstance(done, Done)
145
+ self.assertEqual(done.stop, 'tool_calls')
146
+ self.assertEqual(done.usage, Usage(input_tokens=442, output_tokens=25, cached_input_tokens=400))
147
+ self.assertEqual(
148
+ [item['type'] for item in done.provider_state['output']], ['reasoning', 'message', 'function_call'],
149
+ )
150
+ self.assertEqual(done.provider_state['output'][0]['encrypted_content'], 'enc-1')
151
+ json.dumps(done.provider_state)
152
+
153
+ async def test_params_that_are_not_an_object_come_back_on_the_call_as_its_error(self):
154
+ broken = {**CALL, "arguments": '["/notes"]'}
155
+ reply = sse(
156
+ {"type": "response.output_item.done", "output_index": 0, "item": broken},
157
+ {"type": "response.completed", "response": response([broken])},
158
+ )
159
+
160
+ call, done = await self.events(self.provider(reply), self.request())
161
+
162
+ self.assertEqual((call.id, call.params, call.error), ('call_1', {}, 'The params are not a JSON object'))
163
+ self.assertEqual(done.stop, 'tool_calls')
164
+
165
+ async def test_stop_reasons_map_to_the_ports(self):
166
+ said = (REASONING, MESSAGE)
167
+ cases = [
168
+ (recorded_reply(said), 'end'),
169
+ (recorded_reply(said, 'response.incomplete', status='incomplete',
170
+ incomplete_details={"reason": "max_output_tokens"}), 'max_tokens'),
171
+ (recorded_reply(said, 'response.incomplete', status='incomplete',
172
+ incomplete_details={"reason": "content_filter"}), 'refusal'),
173
+ ]
174
+ for reply, port in cases:
175
+ events = await self.events(self.provider(reply), self.request())
176
+ self.assertEqual(events[-1].stop, port)
177
+
178
+ async def test_a_refusal_is_text_and_a_stop_not_an_error(self):
179
+ refusal = {**MESSAGE, "content": [{"type": "refusal", "refusal": "I can't help with that."}]}
180
+ reply = sse(
181
+ {"type": "response.refusal.delta", "item_id": "msg_1", "output_index": 0, "content_index": 0,
182
+ "delta": "I can't help with that."},
183
+ {"type": "response.completed", "response": response([refusal])},
184
+ )
185
+
186
+ text, done = await self.events(self.provider(reply), self.request())
187
+
188
+ self.assertEqual((text, done.stop), (TextDelta("I can't help with that."), 'refusal'))
189
+
190
+ async def test_a_reply_goes_back_as_it_was_sent_reasoning_included(self):
191
+ provider = self.provider(recorded_reply(), recorded_reply((REASONING, MESSAGE)))
192
+ first = await self.events(provider, self.request())
193
+ reply = Turn('assistant', text='Looking now.', calls=(first[2],), provider_state=first[-1].provider_state)
194
+ results = Turn('user', results=(ToolResult('call_1', 'open', '# Notes'),))
195
+
196
+ await self.events(provider, self.request(turns=(Turn('user', text='Hi'), reply, results)))
197
+
198
+ replayed = self.sent[1]['input'][1:4]
199
+ self.assertEqual([item['type'] for item in replayed], ['reasoning', 'message', 'function_call'])
200
+ self.assertEqual(replayed[0]['encrypted_content'], 'enc-1')
201
+ self.assertEqual(self.sent[1]['input'][4], {"type": "function_call_output", "call_id": "call_1", "output": "# Notes"})
202
+
203
+ async def test_reasoning_the_api_no_longer_accepts_is_dropped_and_the_call_sent_again(self):
204
+ refused = error_response(400, 'invalid_encrypted_content', 'The encrypted content could not be verified.')
205
+ provider = self.provider(refused, recorded_reply((REASONING, MESSAGE)))
206
+ reply = Turn('assistant', text='Looking.', provider_state={'output': [REASONING, MESSAGE]})
207
+
208
+ events = await self.events(provider, self.request(turns=(
209
+ Turn('user', text='Hi'), reply, Turn('user', text='Go on'),
210
+ )))
211
+
212
+ self.assertEqual(events[-1].stop, 'end')
213
+ self.assertEqual(self.sent[0]['input'][1]['type'], 'reasoning')
214
+ self.assertEqual(self.sent[1]['input'], [
215
+ {"role": "user", "content": "Hi"}, {"role": "assistant", "content": "Looking."},
216
+ {"role": "user", "content": "Go on"},
217
+ ])
218
+
219
+ async def test_each_vendor_error_maps_to_its_code(self):
220
+ cases = [
221
+ (error_response(429, 'rate_limit_exceeded'), 'rate_limit', True),
222
+ (error_response(429, 'insufficient_quota'), 'auth', False),
223
+ (error_response(500, 'server_error'), 'server_error', True),
224
+ (error_response(503, 'server_error'), 'overloaded', True),
225
+ (httpx.ConnectError('refused'), 'connection', True),
226
+ (httpx.ReadTimeout('silent'), 'timeout', True),
227
+ (error_response(401, 'invalid_api_key'), 'auth', False),
228
+ (error_response(403, 'forbidden'), 'auth', False),
229
+ (error_response(404, 'model_not_found'), 'unknown_model', False),
230
+ (error_response(400, 'model_not_found'), 'unknown_model', False),
231
+ (error_response(400, 'context_length_exceeded', 'Your input exceeds the context window of this model.'),
232
+ 'context_overflow', False),
233
+ (error_response(400, 'invalid_function_parameters', 'bad schema'), 'invalid_request', False),
234
+ ]
235
+ for reply, code, retryable in cases:
236
+ with self.subTest(code=code, reply=reply):
237
+ with self.assertRaises(ProviderError) as raised:
238
+ await self.events(self.provider(reply), self.request())
239
+ self.assertEqual((raised.exception.code, raised.exception.retryable), (code, retryable))
240
+ self.assertEqual(len(self.sent), 1)
241
+
242
+ async def test_a_failure_inside_a_stream_maps_to_its_code(self):
243
+ failed = sse({"type": "response.failed", "response": response(
244
+ [], status='failed', error={"code": "server_error", "message": "The model failed."},
245
+ )})
246
+ errored = sse({"type": "error", "code": "rate_limit_exceeded", "message": "Slow down.", "param": None})
247
+
248
+ for reply, code in ((failed, 'server_error'), (errored, 'rate_limit')):
249
+ with self.assertRaises(ProviderError) as raised:
250
+ await self.events(self.provider(reply), self.request())
251
+ self.assertEqual((raised.exception.code, raised.exception.retryable), (code, True))
252
+
253
+ async def test_a_stream_that_ends_without_its_reply_is_retryable(self):
254
+ cut = recorded_reply().split(b'event: response.completed')[0]
255
+
256
+ with self.assertRaises(ProviderError) as raised:
257
+ await self.events(self.provider(cut), self.request())
258
+
259
+ self.assertEqual((raised.exception.code, raised.exception.retryable), ('incomplete_stream', True))
@@ -0,0 +1,92 @@
1
+ from graphcore.public.errors import Forbidden, InvalidRequest
2
+ from graphcore.public.strategies import DeleteEntity, SetAttributes
3
+
4
+ from agents.entities.instruction import Instruction
5
+ from agents.entities.profile import AgentProfile
6
+ from agents.strategies.profiles import CustomizeAgent
7
+ from agents.tests.support import AgentsTestCase
8
+
9
+
10
+ class ProfileTests(AgentsTestCase):
11
+ async def customize(self, principal, agent_id, **fields):
12
+ completed = await self.run_strategy(principal, CustomizeAgent.request_constructor(agent_id, **fields))
13
+ return completed.ret_val['profile_id']
14
+
15
+ async def shared_agent(self):
16
+ carl = await self.create_user('carl')
17
+ riley = await self.create_user('riley')
18
+ agent_id = await self.create_agent(carl)
19
+ await self.grant(carl, agent_id, riley, 'viewer')
20
+ return carl, riley, agent_id
21
+
22
+ async def test_a_viewer_gets_their_own_profile_and_the_agent_is_untouched(self):
23
+ carl, riley, agent_id = await self.shared_agent()
24
+ spanish = await self.create_instruction(riley, name='Spanish')
25
+ before = (await self.get_entity(carl, agent_id)).version
26
+
27
+ profile_id = await self.customize(riley, agent_id, instruction_ids=[spanish])
28
+
29
+ profile = await self.get_entity(riley, profile_id)
30
+ self.assertIsInstance(profile, AgentProfile)
31
+ self.assertEqual((profile.agent_id, profile.instruction_ids), (agent_id, [spanish]))
32
+ self.assertEqual((profile.owner, profile.parent_id), (riley.principal_entity_id, None))
33
+ agent = await self.get_entity(carl, agent_id)
34
+ self.assertEqual((agent.version, agent.instruction_ids), (before, []))
35
+
36
+ async def test_a_second_customize_writes_the_same_profile(self):
37
+ _, riley, agent_id = await self.shared_agent()
38
+ skill_id = await self.create_skill(riley)
39
+
40
+ first = await self.customize(riley, agent_id, skill_ids=[skill_id])
41
+ second = await self.customize(riley, agent_id, instruction_ids=[])
42
+
43
+ self.assertEqual(first, second)
44
+ self.assertEqual(await self.listed(riley, AgentProfile), [first])
45
+ self.assertEqual((await self.get_entity(riley, first)).skill_ids, [skill_id])
46
+
47
+ async def test_each_person_has_their_own_profile_and_nobody_else_reads_it(self):
48
+ carl, riley, agent_id = await self.shared_agent()
49
+
50
+ carls = await self.customize(carl, agent_id)
51
+ rileys = await self.customize(riley, agent_id)
52
+
53
+ self.assertNotEqual(carls, rileys)
54
+ self.assertEqual(await self.listed(carl, AgentProfile), [carls])
55
+ self.assertTrue((await self.get_entity(carl, rileys)).to_client().get('forbidden'))
56
+
57
+ async def test_customizing_needs_read_on_the_agent(self):
58
+ carl = await self.create_user('carl')
59
+ stranger = await self.create_user('stranger')
60
+ agent_id = await self.create_agent(carl)
61
+
62
+ with self.assertRaises(Forbidden):
63
+ await self.customize(stranger, agent_id)
64
+
65
+ async def test_a_profile_cannot_be_shared_or_written_by_a_generic_strategy(self):
66
+ carl, riley, agent_id = await self.shared_agent()
67
+ profile_id = await self.customize(riley, agent_id)
68
+
69
+ with self.assertRaises((Forbidden, InvalidRequest)):
70
+ await self.grant(riley, profile_id, carl, 'viewer')
71
+ with self.assertRaises(Forbidden):
72
+ await self.run_strategy(riley, SetAttributes.request_constructor(profile_id, {'x': 1}))
73
+
74
+ async def test_instructions_live_inside_a_profile_and_die_with_it(self):
75
+ _, riley, agent_id = await self.shared_agent()
76
+ profile_id = await self.customize(riley, agent_id)
77
+
78
+ instruction_id = await self.create_instruction(riley, profile_id, attach=True)
79
+ self.assertEqual((await self.get_entity(riley, profile_id)).instruction_ids, [instruction_id])
80
+
81
+ await self.run_strategy(riley, DeleteEntity.request_constructor(profile_id))
82
+
83
+ self.assertEqual(await self.listed(riley, AgentProfile), [])
84
+ self.assertEqual(await self.listed(riley, Instruction), [])
85
+
86
+ async def test_deleting_the_agent_deletes_every_profile_on_it(self):
87
+ carl, riley, agent_id = await self.shared_agent()
88
+ await self.customize(riley, agent_id)
89
+
90
+ await self.run_strategy(carl, DeleteEntity.request_constructor(agent_id))
91
+
92
+ self.assertEqual(await self.listed(riley, AgentProfile), [])
@@ -0,0 +1,150 @@
1
+ import asyncio
2
+ import time
3
+ from unittest.mock import patch
4
+
5
+ from graphcore.public.persistence.django import StrategyRequestModel
6
+ from graphcore.public.strategies import Workload
7
+
8
+ from agents.entities.conversation import ConversationStatus
9
+ from agents.models import ConversationModel, MessageModel
10
+ from agents.providers.fake import FakeProvider, calls, says
11
+ from agents.providers.port import ProviderError, TextDelta, ToolCall
12
+ from agents.runtime.resume import RESUMED
13
+ from agents.strategies.turn import RunTurn
14
+ from agents.tests.support import AgentsTestCase
15
+
16
+ OVERLOADED = ProviderError('overloaded', 'try later', retryable=True)
17
+
18
+
19
+ class ResumptionTests(AgentsTestCase):
20
+ """A retryable provider failure ends the attempt; the executor's next
21
+ attempt resumes from the graph, as an attempt after a dead process does."""
22
+
23
+ def setUp(self):
24
+ super().setUp()
25
+
26
+ async def no_backoff(attempt, outcome='conflict'):
27
+ pass
28
+
29
+ patcher = patch.object(self.runtime.executor, '_backoff', no_backoff)
30
+ patcher.start()
31
+ self.addCleanup(patcher.stop)
32
+
33
+ async def settle(self) -> None:
34
+ # A retried attempt is dispatched after the first one's task ends.
35
+ for _ in range(5):
36
+ await self.runtime.executor.dispatchers[Workload.IO].drain()
37
+
38
+ async def conversation(self):
39
+ alice = await self.create_user('alice')
40
+ return alice, await self.create_conversation(alice, await self.create_agent(alice))
41
+
42
+ async def test_a_reply_cut_short_is_continued_by_the_next_attempt(self):
43
+ alice, conversation_id = await self.conversation()
44
+ FakeProvider.play([TextDelta('Let me look'), OVERLOADED], says(' at that. Here it is.'))
45
+
46
+ await self.send(alice, conversation_id)
47
+
48
+ self.assertEqual(await self.transcript(alice, conversation_id), [
49
+ ('user', 'Hello'), ('assistant', 'Let me look'), ('system', RESUMED),
50
+ ('assistant', ' at that. Here it is.'),
51
+ ])
52
+ second = FakeProvider.requests[1]
53
+ self.assertEqual([turn.role for turn in second.turns], ['user', 'assistant', 'user'])
54
+ self.assertIn(RESUMED, second.turns[-1].text)
55
+ (result,) = await self.turn_results(alice, conversation_id)
56
+ self.assertEqual(result['status'], 'completed')
57
+ conversation = await self.get_entity(alice, conversation_id)
58
+ self.assertIs(conversation.status, ConversationStatus.IDLE)
59
+
60
+ async def test_a_call_the_dead_attempt_left_running_is_interrupted_and_the_model_sees_it(self):
61
+ alice, conversation_id = await self.conversation()
62
+ FakeProvider.play([ToolCall('c1', 'open', {'at': '/'}), OVERLOADED], says('Trying again.'))
63
+
64
+ await self.send(alice, conversation_id)
65
+
66
+ step = (await self.messages(alice, conversation_id))[1]
67
+ self.assertEqual(step.tool_calls[0]['state'], 'interrupted')
68
+ (result,) = FakeProvider.requests[1].turns[-1].results
69
+ self.assertEqual((result.call_id, result.is_error), ('c1', True))
70
+ self.assertEqual(
71
+ [role for role, _ in await self.transcript(alice, conversation_id)], ['user', 'assistant', 'assistant'],
72
+ )
73
+
74
+ async def test_a_failure_before_any_reply_leaves_nothing_in_the_conversation(self):
75
+ alice, conversation_id = await self.conversation()
76
+ FakeProvider.play([OVERLOADED], says('Hi.'))
77
+
78
+ await self.send(alice, conversation_id)
79
+
80
+ self.assertEqual(await self.transcript(alice, conversation_id), [('user', 'Hello'), ('assistant', 'Hi.')])
81
+
82
+ async def test_an_attempt_that_still_holds_the_lock_keeps_a_stop_the_dead_one_never_saw(self):
83
+ alice, conversation_id = await self.conversation()
84
+
85
+ async def stop_unseen():
86
+ await ConversationModel.objects.filter(entity_id=conversation_id).aupdate(stop_requested=True)
87
+
88
+ async def process_died(strategy):
89
+ """A dead process releases nothing."""
90
+
91
+ FakeProvider.play([TextDelta('Working'), stop_unseen, OVERLOADED])
92
+ with patch.object(RunTurn, 'cleanup', process_died):
93
+ await self.send(alice, conversation_id)
94
+
95
+ self.assertEqual((await self.transcript(alice, conversation_id))[-1], ('system', 'Stopped.'))
96
+ self.assertEqual(len(FakeProvider.requests), 1)
97
+
98
+ async def test_the_next_turn_repairs_what_a_turn_that_never_ended_left(self):
99
+ alice, conversation_id = await self.conversation()
100
+ FakeProvider.play(calls(ToolCall('c1', 'open', {'at': '/'})), says('Done.'))
101
+ await self.send(alice, conversation_id)
102
+ step = (await self.messages(alice, conversation_id))[1]
103
+ await MessageModel.objects.filter(entity_id=step.entity_id).aupdate(
104
+ tool_calls=[{**step.tool_calls[0], 'state': 'running', 'result': None}],
105
+ )
106
+ await ConversationModel.objects.filter(entity_id=conversation_id).aupdate(status='running')
107
+
108
+ await self.run_strategy(alice, RunTurn.request_constructor(conversation_id))
109
+
110
+ self.assertEqual((await self.messages(alice, conversation_id))[1].tool_calls[0]['state'], 'interrupted')
111
+ self.assertIs((await self.get_entity(alice, conversation_id)).status, ConversationStatus.IDLE)
112
+
113
+
114
+ class ReconcileTests(AgentsTestCase):
115
+ """An attempt that stops reporting is found by the kernel's reconciler,
116
+ whose next attempt resumes the turn; the silent one is fenced out."""
117
+
118
+ async def test_the_reconciler_resumes_a_turn_whose_attempt_went_silent(self):
119
+ alice = await self.create_user('alice')
120
+ conversation_id = await self.create_conversation(alice, await self.create_agent(alice))
121
+ reached, released = asyncio.Event(), asyncio.Event()
122
+
123
+ async def go_silent():
124
+ reached.set()
125
+ await released.wait()
126
+
127
+ FakeProvider.play([TextDelta('Let me look'), go_silent, TextDelta(' (late)')], says(' at that.'))
128
+ await self.send(alice, conversation_id, settle=False)
129
+ await asyncio.wait_for(reached.wait(), 5)
130
+
131
+ turn = StrategyRequestModel.objects.filter(strategy_name='RunTurn', target_entity_id=conversation_id)
132
+ await turn.aupdate(attempt_deadline=time.time() - 1)
133
+ self.assertEqual(await self.runtime.executor.reconcile_runs(), 1)
134
+ # settle() would wait on the silent attempt too.
135
+ async def finished():
136
+ while (await turn.aget()).status != 'succeeded':
137
+ await asyncio.sleep(0.01)
138
+ await asyncio.wait_for(finished(), 5)
139
+
140
+ released.set()
141
+ await self.settle()
142
+
143
+ self.assertEqual(await self.transcript(alice, conversation_id), [
144
+ ('user', 'Hello'), ('assistant', 'Let me look'), ('system', RESUMED), ('assistant', ' at that.'),
145
+ ])
146
+ request = await turn.aget()
147
+ self.assertEqual((request.status, request.attempt), ('succeeded', 2))
148
+ conversation = await self.get_entity(alice, conversation_id)
149
+ self.assertIs(conversation.status, ConversationStatus.IDLE)
150
+ self.assertNotIn('run_lock', conversation.attributes)