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,230 @@
1
+ from django.test import override_settings
2
+
3
+ from graphcore.public.errors import Forbidden
4
+ from graphcore.public.strategies import DeleteEntity, StrategyRequest
5
+
6
+ from agents.entities.conversation import ConversationStatus
7
+ from agents.entities.message import MessageRole
8
+ from agents.providers.fake import FakeProvider, calls, says
9
+ from agents.providers.port import ProviderError, TextDelta, ToolCall
10
+ from agents.strategies.agents import UpdateAgent
11
+ from agents.strategies.profiles import CustomizeAgent
12
+ from agents.strategies.turn import RunTurn
13
+ from agents.tests.support import AgentsTestCase
14
+
15
+
16
+ class TurnTests(AgentsTestCase):
17
+ async def conversation(self, **agent_fields):
18
+ carl = await self.create_user('carl')
19
+ agent_id = await self.create_agent(carl, **agent_fields)
20
+ return carl, agent_id, await self.create_conversation(carl, agent_id)
21
+
22
+ async def run_turn(self, principal, conversation_id):
23
+ return (await self.run_strategy(principal, RunTurn.request_constructor(conversation_id))).ret_val
24
+
25
+ async def test_a_message_is_answered_and_the_conversation_ends_idle(self):
26
+ carl, _, conversation_id = await self.conversation()
27
+ FakeProvider.play(says('Hi Carl.', input_tokens=40, output_tokens=7, cached_input_tokens=30))
28
+
29
+ message_id = await self.send(carl, conversation_id, 'Hello')
30
+
31
+ self.assertEqual(
32
+ await self.transcript(carl, conversation_id), [('user', 'Hello'), ('assistant', 'Hi Carl.')],
33
+ )
34
+ reply = (await self.messages(carl, conversation_id))[-1]
35
+ self.assertEqual((reply.read_through, reply.owner), (message_id, carl.principal_entity_id))
36
+ conversation = await self.get_entity(carl, conversation_id)
37
+ self.assertIs(conversation.status, ConversationStatus.IDLE)
38
+ self.assertNotIn('run_lock', conversation.attributes)
39
+ breakdown = conversation.usage['last'].pop('breakdown')
40
+ self.assertEqual(conversation.usage, {
41
+ 'last': {'input_tokens': 40, 'output_tokens': 7, 'cached_input_tokens': 30},
42
+ 'total': {'input_tokens': 40, 'output_tokens': 7, 'cached_input_tokens': 30},
43
+ })
44
+ self.assertEqual(set(breakdown), {'instructions', 'tools', 'context', 'messages', 'tool_calls'})
45
+ self.assertAlmostEqual(sum(breakdown.values()), 40, delta=2)
46
+ self.assertGreater(breakdown['tools'], breakdown['messages'])
47
+
48
+ async def test_the_request_carries_the_instructions_the_skill_index_and_the_fixed_tools(self):
49
+ carl, agent_id, conversation_id = await self.conversation()
50
+ await self.create_instruction(carl, agent_id, text='Answer in one line.', attach=True)
51
+ await self.create_skill(carl, agent_id, attach=True)
52
+
53
+ await self.send(carl, conversation_id, 'Hello')
54
+
55
+ (request,) = FakeProvider.requests
56
+ self.assertEqual(request.model, 'model')
57
+ self.assertIn('open("/")', request.prefix[0])
58
+ self.assertEqual(request.prefix[1], 'Answer in one line.')
59
+ self.assertIn('- research: How to research', request.prefix[2])
60
+ self.assertEqual([tool.name for tool in request.tools], ['open', 'find', 'call', 'delegate', 'start_task', 'stop_task', 'load_skill'])
61
+ self.assertEqual([(turn.role, turn.text) for turn in request.turns], [('user', 'Hello')])
62
+ self.assertEqual((request.tool_choice, request.cache_key), ('auto', conversation_id))
63
+
64
+ async def test_the_profile_adds_instructions_after_the_agents_and_sets_the_model(self):
65
+ carl, agent_id, conversation_id = await self.conversation()
66
+ await self.create_instruction(carl, agent_id, text='Be brief.', attach=True)
67
+ spanish = await self.create_instruction(carl, text='Answer in Spanish.')
68
+ await self.run_strategy(carl, CustomizeAgent.request_constructor(
69
+ agent_id, instruction_ids=[spanish], model='fake/other',
70
+ ))
71
+
72
+ await self.send(carl, conversation_id)
73
+
74
+ (request,) = FakeProvider.requests
75
+ self.assertEqual(request.prefix[1:], ('Be brief.', 'Answer in Spanish.'))
76
+ self.assertEqual(request.model, 'other')
77
+
78
+ async def test_tool_calls_run_as_the_sender_and_their_results_go_back_to_the_model(self):
79
+ carl, agent_id, conversation_id = await self.conversation()
80
+ FakeProvider.play(
81
+ calls(
82
+ ToolCall('c1', 'call', {'at': agent_id, 'tool': 'update_agent', 'params': {'name': 'Renamed'}}),
83
+ ToolCall('c2', 'open', {'at': '/nowhere'}),
84
+ text='Renaming.',
85
+ ),
86
+ says('Done.'),
87
+ )
88
+
89
+ await self.send(carl, conversation_id, 'Rename yourself')
90
+
91
+ self.assertEqual((await self.get_entity(carl, agent_id)).name, 'Renamed')
92
+ step, final = [m for m in await self.messages(carl, conversation_id) if m.role is MessageRole.ASSISTANT]
93
+ renamed, opened = step.tool_calls
94
+ self.assertEqual((renamed['state'], renamed['at'], opened['state'], opened['at']), ('completed', agent_id, 'error', '/nowhere'))
95
+ request = await self.get_entity(carl, renamed['request_id'])
96
+ self.assertIsInstance(request, StrategyRequest)
97
+ self.assertEqual((request.strategy_name, request.owner), ('UpdateAgent', carl.principal_entity_id))
98
+ self.assertIsNone(opened['request_id'])
99
+ self.assertIn('NotFound', opened['error'])
100
+ self.assertEqual(final.content, 'Done.')
101
+
102
+ second = FakeProvider.requests[1]
103
+ self.assertEqual([turn.role for turn in second.turns], ['user', 'assistant', 'user'])
104
+ self.assertEqual([call.id for call in second.turns[1].calls], ['c1', 'c2'])
105
+ results = second.turns[2].results
106
+ self.assertEqual([(r.call_id, r.is_error) for r in results], [('c1', False), ('c2', True)])
107
+ self.assertIn(renamed['request_id'], results[0].content)
108
+
109
+ async def test_a_refused_strategy_is_the_calls_error_and_the_turn_continues(self):
110
+ carl, agent_id, _ = await self.conversation()
111
+ sam = await self.create_user('sam')
112
+ await self.grant(carl, agent_id, sam, 'viewer')
113
+ conversation_id = await self.create_conversation(sam, agent_id)
114
+ FakeProvider.play(
115
+ calls(ToolCall('c1', 'call', {'at': agent_id, 'tool': 'update_agent', 'params': {'name': 'Mine'}})),
116
+ says('I may not rename it.'),
117
+ )
118
+
119
+ await self.send(sam, conversation_id, 'Rename it')
120
+
121
+ self.assertEqual((await self.get_entity(carl, agent_id)).name, 'Troy')
122
+ step, final = [m for m in await self.messages(sam, conversation_id) if m.role is MessageRole.ASSISTANT]
123
+ self.assertEqual(step.tool_calls[0]['state'], 'error')
124
+ self.assertEqual(final.content, 'I may not rename it.')
125
+
126
+ async def test_params_that_did_not_parse_and_an_unknown_tool_are_errors_the_model_sees(self):
127
+ carl, _, conversation_id = await self.conversation()
128
+ FakeProvider.play(
129
+ calls(ToolCall('c1', 'open', {}, error='params are not a JSON object'), ToolCall('c2', 'fly', {})),
130
+ says('Sorry.'),
131
+ )
132
+
133
+ await self.send(carl, conversation_id)
134
+
135
+ results = FakeProvider.requests[1].turns[2].results
136
+ self.assertEqual([r.is_error for r in results], [True, True])
137
+ self.assertEqual(results[0].content, 'params are not a JSON object')
138
+
139
+ async def test_load_skill_returns_the_text_of_one_of_the_agents_skills(self):
140
+ carl, agent_id, conversation_id = await self.conversation()
141
+ await self.create_skill(carl, agent_id, attach=True)
142
+ FakeProvider.play(
143
+ calls(ToolCall('c1', 'load_skill', {'name': 'research'}), ToolCall('c2', 'load_skill', {'name': 'x'})),
144
+ says('Loaded.'),
145
+ )
146
+
147
+ await self.send(carl, conversation_id)
148
+
149
+ loaded, unknown = FakeProvider.requests[1].turns[2].results
150
+ self.assertEqual((loaded.content, loaded.is_error), ('Search first.', False))
151
+ self.assertTrue(unknown.is_error)
152
+
153
+ @override_settings(AGENTS_MAX_STEPS=2)
154
+ async def test_after_the_step_cap_one_closing_call_runs_with_tools_disabled(self):
155
+ carl, _, conversation_id = await self.conversation()
156
+ step = lambda n: calls(ToolCall(f'c{n}', 'open', {'at': '/'})) # noqa: E731
157
+ FakeProvider.play(step(1), step(2), says('That is all I managed.'))
158
+
159
+ await self.send(carl, conversation_id)
160
+
161
+ self.assertEqual([r.tool_choice for r in FakeProvider.requests], ['auto', 'auto', 'none'])
162
+ self.assertEqual(FakeProvider.requests[2].tools, FakeProvider.requests[0].tools)
163
+ self.assertEqual((await self.messages(carl, conversation_id))[-1].content, 'That is all I managed.')
164
+
165
+ async def test_a_reply_cut_off_at_the_output_limit_keeps_its_text_and_says_so(self):
166
+ carl, _, conversation_id = await self.conversation()
167
+ FakeProvider.play(says('Once upon a', stop='max_tokens'))
168
+
169
+ await self.send(carl, conversation_id)
170
+
171
+ transcript = await self.transcript(carl, conversation_id)
172
+ self.assertEqual(transcript[1], ('assistant', 'Once upon a'))
173
+ self.assertEqual(transcript[2][0], 'system')
174
+ self.assertIn('cut off', transcript[2][1])
175
+
176
+ async def test_a_permanent_provider_failure_is_reported_and_the_request_succeeds(self):
177
+ carl, _, conversation_id = await self.conversation()
178
+ await self.send(carl, conversation_id, settle=False)
179
+ FakeProvider.play([TextDelta('Let me'), ProviderError('auth', 'bad key', retryable=False)])
180
+ await self.settle()
181
+ FakeProvider.reset()
182
+ await self.send(carl, conversation_id, 'Again')
183
+
184
+ role, text = (await self.transcript(carl, conversation_id))[2]
185
+ self.assertEqual(role, 'system')
186
+ self.assertIn('auth: bad key', text)
187
+ self.assertIs((await self.get_entity(carl, conversation_id)).status, ConversationStatus.IDLE)
188
+ self.assertEqual((await self.transcript(carl, conversation_id))[-1], ('assistant', 'ok'))
189
+
190
+ async def test_a_turn_returns_how_it_ended(self):
191
+ carl, _, conversation_id = await self.conversation()
192
+ FakeProvider.play([ProviderError('invalid_request', 'no', retryable=False)])
193
+
194
+ await self.send(carl, conversation_id)
195
+ (failed,) = await self.turn_results(carl, conversation_id)
196
+ again = await self.run_turn(carl, conversation_id)
197
+
198
+ self.assertEqual(failed['status'], 'error')
199
+ self.assertIn('invalid_request: no', failed['text'])
200
+ self.assertEqual(again['status'], 'completed')
201
+ self.assertEqual(len(FakeProvider.requests), 1)
202
+
203
+ async def test_a_turn_with_nothing_unread_ends_without_a_model_call(self):
204
+ carl, _, conversation_id = await self.conversation()
205
+ await self.send(carl, conversation_id)
206
+
207
+ result = await self.run_turn(carl, conversation_id)
208
+
209
+ self.assertEqual((result['status'], result['text']), ('completed', 'ok'))
210
+ self.assertEqual(len(FakeProvider.requests), 1)
211
+
212
+ async def test_a_turn_on_a_deleted_agent_ends_with_an_error_message(self):
213
+ carl, agent_id, conversation_id = await self.conversation()
214
+ await self.run_strategy(carl, UpdateAgent.request_constructor(agent_id, name='Doomed'))
215
+ await self.run_strategy(carl, DeleteEntity.request_constructor(agent_id))
216
+
217
+ await self.send(carl, conversation_id)
218
+
219
+ role, text = (await self.transcript(carl, conversation_id))[-1]
220
+ self.assertEqual(role, 'system')
221
+ self.assertIn('agent no longer exists', text)
222
+ self.assertEqual(FakeProvider.requests, [])
223
+
224
+ async def test_a_viewer_of_a_conversation_cannot_send(self):
225
+ alice, _, conversation_id = await self.conversation()
226
+ bob = await self.create_user('bob')
227
+ await self.grant(alice, conversation_id, bob, 'viewer')
228
+
229
+ with self.assertRaises(Forbidden):
230
+ await self.send(bob, conversation_id)
agents/validation.py ADDED
@@ -0,0 +1,48 @@
1
+ """Checks a strategy runs on the ids and model it is about to store, as the caller."""
2
+ from typing import Optional
3
+
4
+ from graphcore.public.agent_frontend import connect
5
+ from graphcore.public.entities import Entity
6
+ from graphcore.public.errors import Forbidden, InvalidRequest, NotFound
7
+ from graphcore.public.strategies import StrategySession
8
+
9
+ from agents import conf
10
+
11
+
12
+ async def readable(session: StrategySession, entity_id: str, entity_cls: type = Entity) -> Entity:
13
+ try:
14
+ entity = await session.get(entity_id)
15
+ except (NotFound, Forbidden):
16
+ raise InvalidRequest(f"No readable entity {entity_id}") from None
17
+ if not isinstance(entity, entity_cls):
18
+ raise InvalidRequest(f"{entity_id} is not an {entity_cls.get_entity_type_id()}")
19
+ return entity
20
+
21
+
22
+ async def readable_ids(session: StrategySession, entity_ids: list[str], entity_cls: type = Entity) -> list[str]:
23
+ for entity_id in entity_ids:
24
+ await readable(session, entity_id, entity_cls)
25
+ return list(entity_ids)
26
+
27
+
28
+ def listed_model(model_id: Optional[str]) -> Optional[str]:
29
+ if model_id is not None and conf.model_entry(model_id) is None:
30
+ raise InvalidRequest(f"{model_id} is not a model in AGENTS_MODELS")
31
+ return model_id
32
+
33
+
34
+ async def openable_address(principal, address: Optional[str]) -> Optional[str]:
35
+ """`address` when it names a place: one `open` finds, as the caller. A place
36
+ that is there but cannot be shown now, such as a connection that does not
37
+ answer, is accepted."""
38
+ if address is None:
39
+ return None
40
+ address = address.strip()
41
+ if not address.startswith(('/', 'gc://')):
42
+ raise InvalidRequest(f"{address!r} is not an address: it starts with / or gc://")
43
+ async with connect(principal) as client:
44
+ result = await client.call_tool('open', {'at': address})
45
+ text = ' '.join(getattr(part, 'text', '') for part in result.content)
46
+ if result.is_error and 'NotFound:' in text:
47
+ raise InvalidRequest(f"{address} names no place: {text.split('NotFound:', 1)[1].strip()}")
48
+ return address
@@ -0,0 +1,3 @@
1
+ # Agent views for the agents app. Every module in this package is
2
+ # imported at startup, and its module-level `@agent_view` functions are
3
+ # registered; `agent_views.py` is the conventional home for them.
@@ -0,0 +1,286 @@
1
+ """The agents app as places (docs/app_design/agents/AGENTS_TDD.md, Agent views and tools)."""
2
+ from graphcore.agent_frontend import agent_view, operation, strategy_tool
3
+
4
+ AGENT, CONVERSATION, MESSAGE = 'agents.Agent', 'agents.Conversation', 'agents.Message'
5
+ INSTRUCTION, SKILL, PROFILE = 'agents.Instruction', 'agents.Skill', 'agents.AgentProfile'
6
+ _SHOWN_MESSAGES = 30
7
+ _SHOWN_CHATS = 50
8
+ _MOST_EARLIER = 50
9
+ _RESULT_CHARS = 120
10
+
11
+
12
+ def _me(ctx) -> str:
13
+ return ctx.principal.principal_entity_id
14
+
15
+
16
+ def _places(ctx, entities) -> list:
17
+ return [ctx.place(entity.entity_id) for entity in entities]
18
+
19
+
20
+ def _guide(*lines) -> list:
21
+ """How an agent works with the place: what each tool does, and who may run it."""
22
+ return ["## Using this place", *(f"- {line}" for line in lines if line)]
23
+
24
+
25
+ _WRITE_ACCESS = "its owner has it, and so does anyone it is shared with as an editor; anyone else is refused"
26
+
27
+
28
+ async def _linked(ctx, entity_ids) -> list:
29
+ """Places for the ids that are readable; a line for each that is not."""
30
+ out = []
31
+ for entity_id in entity_ids:
32
+ out.append(ctx.place(entity_id) if await ctx.get(entity_id) else f"- {entity_id} (not readable to you)")
33
+ return out
34
+
35
+
36
+ async def home_tools(ctx, entity):
37
+ return [
38
+ strategy_tool('CreateAgent', takes_target=False, name='create_agent'),
39
+ strategy_tool('CreateInstruction', takes_target=False, name='create_instruction'),
40
+ strategy_tool('CreateSkill', takes_target=False, name='create_skill'),
41
+ ]
42
+
43
+
44
+ @agent_view('agents.home', tools=home_tools)
45
+ async def home(ctx):
46
+ mine = await ctx.find(AGENT, where={'owner': _me(ctx)})
47
+ shared = await ctx.find(AGENT, granted_to_me=True)
48
+ listed = {agent.entity_id for agent in [*mine, *shared]}
49
+ others = [agent for agent in await ctx.find(AGENT) if agent.entity_id not in listed]
50
+ running = await ctx.find(CONVERSATION, where={'owner': _me(ctx), 'status': 'running'})
51
+ catalog = await ctx.execute('ListModels')
52
+ return [
53
+ "## My agents", *(_places(ctx, mine) or ["None yet. Create one with `create_agent`."]),
54
+ "## Shared with me", *(_places(ctx, shared) or ["None."]),
55
+ "## Other agents I can use", *(_places(ctx, others) or ["None."]),
56
+ "## Running conversations", *(_places(ctx, running) or ["None."]),
57
+ "## Models",
58
+ *[
59
+ f"- {model['id']} · context {model['context_size']}"
60
+ + (" · default" if model['id'] == catalog['default'] else '')
61
+ + ('' if model['available'] else " · no provider key")
62
+ for model in catalog['models']
63
+ ],
64
+ *_guide(
65
+ "Open an agent to see its settings and my conversations with it.",
66
+ "To talk to an agent: `create_conversation` at the agent's address, then `send` at the conversation's "
67
+ "address. The turn runs in the background as me, with my permissions; open the conversation again "
68
+ "once its status is `idle` to read the reply.",
69
+ "`create_agent` makes an agent I own. Give it instructions next with `create_instruction` at its "
70
+ "address and `attach: true`.",
71
+ "`create_instruction` and `create_skill` here make top-level ones I own, for "
72
+ "an agent's `customize` or `update_agent` lists.",
73
+ "A `model` field takes one of the model ids above; one marked \"no provider key\" cannot run.",
74
+ ),
75
+ ]
76
+
77
+
78
+ async def agent_tools(ctx, agent):
79
+ return [
80
+ strategy_tool('CreateConversation', name='create_conversation', bind=agent.entity_id),
81
+ strategy_tool('CustomizeAgent', name='customize', bind=agent.entity_id),
82
+ strategy_tool('UpdateAgent', name='update_agent', bind=agent.entity_id),
83
+ strategy_tool('CreateInstruction', name='create_instruction', bind=agent.entity_id),
84
+ strategy_tool('CreateSkill', name='create_skill', bind=agent.entity_id),
85
+ ]
86
+
87
+
88
+ @agent_view('agents.agent', default_for=[AGENT], tools=agent_tools)
89
+ async def agent(ctx, a):
90
+ fields = a.to_dict()
91
+ profiles = await ctx.find(PROFILE, where={'owner': _me(ctx), 'agent_id': a.entity_id}, limit=1)
92
+ conversations = sorted(
93
+ await ctx.query(CONVERSATION, where={'owner': _me(ctx), 'agent_id': a.entity_id, 'parent_id': None}),
94
+ key=lambda c: (c.last_active_at or 0, c.entity_id), reverse=True,
95
+ )
96
+ parts = [
97
+ fields.get('description') or '_No description._',
98
+ f"Model: {fields.get('model') or 'the default'}",
99
+ f"Compaction threshold: {fields.get('compaction_threshold') or 'the default'}",
100
+ f"Task limit: {fields.get('max_tasks') or 'the default'}",
101
+ f"Starts at: {fields.get('start_address') or 'nowhere in particular'}",
102
+ f"Debug context: {'on' if fields.get('debug_context') else 'off'}",
103
+ "## Instructions", *(await _linked(ctx, fields.get('instruction_ids') or []) or ["None."]),
104
+ "## Skills", *(await _linked(ctx, fields.get('skill_ids') or []) or ["None."]),
105
+ ]
106
+ if profiles:
107
+ profile = profiles[0].to_dict()
108
+ parts += [
109
+ "## My additions",
110
+ f"Model: {profile.get('model') or 'not set'}",
111
+ f"Compaction threshold: {profile.get('compaction_threshold') or 'not set'}",
112
+ *await _linked(ctx, [*(profile.get('instruction_ids') or []), *(profile.get('skill_ids') or [])]),
113
+ ]
114
+ owned = a.owner == _me(ctx)
115
+ return [
116
+ *parts,
117
+ "## My conversations",
118
+ *(_places(ctx, conversations[:_SHOWN_CHATS]) or ["None yet. Start one with `create_conversation`, then `send` there."]),
119
+ *([f"{len(conversations) - _SHOWN_CHATS} older not shown; `find` lists them all."]
120
+ if len(conversations) > _SHOWN_CHATS else []),
121
+ *_guide(
122
+ "Its instructions are placed in its prompt, in order. Its skills are listed there by name and "
123
+ "description, and it loads a skill's text with `load_skill` when the description fits.",
124
+ "`create_conversation(title?, context_ids?, model?)` returns `conversation_id`; `send` at that address "
125
+ "starts a turn, which runs as me. `context_ids` are entities rendered for the agent on every turn. "
126
+ "Anyone who can read the agent can chat with it.",
127
+ "I own this agent, so `update_agent`, `create_instruction` and `create_skill` change it for everyone "
128
+ "who uses it." if owned else
129
+ "I do not own this agent. `update_agent`, `create_instruction` and `create_skill` here need write "
130
+ f"access to it: {_WRITE_ACCESS}. `customize` is how to change it for myself.",
131
+ "`update_agent` sets only the fields passed. `instruction_ids` and `skill_ids` replace the whole list, "
132
+ "so pass every id to keep, in order.",
133
+ "`create_instruction(name, text, attach: true)` and `create_skill(name, description, text, attach: true)` "
134
+ "create one inside this agent and append it to its list. To change an existing one, open it and use "
135
+ "its own update tool.",
136
+ "`customize` changes the agent for my own conversations only, and anyone who can read the agent may "
137
+ "run it: a model, a summarize threshold, and instructions and skills added after the agent's own. It "
138
+ "cannot remove the agent's own. Its lists also replace my whole list of additions. For new text, make "
139
+ "a top-level instruction or skill with `create_instruction` or `create_skill` at `/agents`, then pass "
140
+ "its id to `customize`.",
141
+ "With debug context on, each conversation with it offers `inspect_context`, the exact request its "
142
+ "next model call would send." if fields.get('debug_context') else None,
143
+ ),
144
+ ]
145
+
146
+
147
+ async def _messages(ctx, conversation_id) -> list[dict]:
148
+ return sorted(
149
+ (m.to_dict() for m in await ctx.query(MESSAGE, parent_id=conversation_id)),
150
+ key=lambda message: message.get('sibling_position') or 0,
151
+ )
152
+
153
+
154
+ def _earlier(conversation_id):
155
+ @operation('earlier', "Reads messages older than the ones shown, oldest first", {
156
+ 'type': 'object',
157
+ 'properties': {
158
+ 'skip': {
159
+ 'type': 'integer', 'minimum': 0,
160
+ 'description': f"How many of the latest messages to pass over; {_SHOWN_MESSAGES} when left out",
161
+ },
162
+ 'count': {
163
+ 'type': 'integer', 'minimum': 1, 'maximum': _MOST_EARLIER,
164
+ 'description': f"How many messages to read; {_SHOWN_MESSAGES} when left out",
165
+ },
166
+ },
167
+ 'additionalProperties': False,
168
+ }, read_only=True)
169
+ async def earlier(ctx, skip=_SHOWN_MESSAGES, count=_SHOWN_MESSAGES):
170
+ messages = await _messages(ctx, conversation_id)
171
+ end = max(len(messages) - skip, 0)
172
+ start = max(end - count, 0)
173
+ lines = [line for message in messages[start:end] for line in _message_lines(ctx, message)]
174
+ return {'messages': lines, 'older': start}
175
+ return earlier
176
+
177
+
178
+ async def conversation_tools(ctx, conversation):
179
+ tools = [
180
+ strategy_tool('SendMessage', name='send', bind=conversation.entity_id),
181
+ strategy_tool('UpdateConversation', name='update', bind=conversation.entity_id),
182
+ _earlier(conversation.entity_id),
183
+ ]
184
+ agent = await ctx.get(conversation.agent_id) if conversation.agent_id else None
185
+ if agent is not None and agent.debug_context:
186
+ tools.append(strategy_tool('InspectContext', name='inspect_context', bind=conversation.entity_id))
187
+ return tools
188
+
189
+
190
+ def _one_line(text) -> str:
191
+ line = (str(text or '').strip().splitlines() or [''])[0]
192
+ return line if len(line) <= _RESULT_CHARS else line[:_RESULT_CHARS] + '…'
193
+
194
+
195
+ def _message_lines(ctx, message: dict) -> list[str]:
196
+ if message.get('context_versions'):
197
+ shown = ', '.join(ctx.place(entity_id).address for entity_id in message['context_versions'])
198
+ return [f"**context shown:** {shown}"]
199
+ lines = [f"**{message['role']}:** {message.get('content') or ''}"]
200
+ for call in message.get('tool_calls') or []:
201
+ outcome = _one_line(call.get('error') or call.get('result'))
202
+ lines.append(f" - {call['tool']} {call.get('at') or ''} · {call['state']}" + (f" · {outcome}" if outcome else ''))
203
+ return lines
204
+
205
+
206
+ @agent_view('agents.conversation', default_for=[CONVERSATION], tools=conversation_tools)
207
+ async def conversation(ctx, c):
208
+ fields = c.to_dict()
209
+ messages = await _messages(ctx, c.entity_id)
210
+ usage = (fields.get('usage') or {}).get('last', {}).get('input_tokens', 0)
211
+ parts = [f"{fields.get('status')} · {fields.get('model') or 'default model'} · {usage} tokens in context"]
212
+ if fields.get('agent_id'):
213
+ parts += ["Agent:", *await _linked(ctx, [fields['agent_id']])]
214
+ if fields.get('context_ids'):
215
+ parts += ["Standing context:", *await _linked(ctx, fields['context_ids'])]
216
+ parts.append("## Messages")
217
+ if len(messages) > _SHOWN_MESSAGES:
218
+ parts.append(
219
+ f"_The last {_SHOWN_MESSAGES} of {len(messages)} messages. `earlier` reads the ones before them._"
220
+ )
221
+ for message in messages[-_SHOWN_MESSAGES:]:
222
+ parts.extend(_message_lines(ctx, message))
223
+ if not messages:
224
+ parts.append("None yet. `send` starts a turn.")
225
+ subs = await ctx.children(c, CONVERSATION)
226
+ if subs:
227
+ parts += ["## Sub-conversations", *_places(ctx, subs)]
228
+ tasks = [sub for sub in subs if sub.deliver_to_parent and sub.status == 'running']
229
+ if tasks:
230
+ parts += ["## Running tasks", *_places(ctx, tasks)]
231
+ parent = await ctx.get(c.parent_id) if c.parent_id else None
232
+ return [*parts, *_guide(
233
+ "`send(content, context_ids?)` adds a message and starts a turn that answers it, as me, with my "
234
+ "permissions. It returns once the message is stored; open this place again until the status is `idle` "
235
+ "to read the reply. A message sent while a turn runs is read by that turn. Leave out "
236
+ "`source_conversation_id` and `source_ret_val`: the runtime sets them when a sub-conversation reports back.",
237
+ "`update(stop: true)` stops the running turn. `update` also sets the title, the model, or the standing "
238
+ "context (`context_ids`: entities rendered for the agent on every turn; the list replaces the old one).",
239
+ None if c.owner == _me(ctx) else
240
+ f"This conversation is someone else's. `send` and `update` need write access to it: {_WRITE_ACCESS}.",
241
+ "Each tool call reads `tool address · state · the first line of its result`.",
242
+ (f"This is a sub-conversation of {parent.entity_id}, started by its agent with "
243
+ + ("`start_task` or a background `delegate`. Each turn's final reply is posted to the parent as a "
244
+ "message, which starts a turn there." if c.deliver_to_parent else
245
+ "`delegate`. The parent's turn waited for its final reply."))
246
+ if parent is not None else None,
247
+ "Sub-conversations are work this conversation's agent handed off; open one to see its progress."
248
+ if subs else None,
249
+ "Stopping this conversation does not stop its running tasks. To stop one, call `update` with "
250
+ "`stop: true` at its address; it reports back its text so far and the tool calls it made."
251
+ if tasks else None,
252
+ )]
253
+
254
+
255
+ async def instruction_tools(ctx, instruction):
256
+ return [strategy_tool('UpdateInstruction', name='update_instruction', bind=instruction.entity_id)]
257
+
258
+
259
+ @agent_view('agents.instruction', default_for=[INSTRUCTION], tools=instruction_tools)
260
+ async def instruction(ctx, i):
261
+ return [
262
+ i.to_dict().get('text') or '_This instruction is empty._',
263
+ *_guide(
264
+ "Every agent and profile that lists this instruction places its text in its prompt, in list order.",
265
+ "`update_instruction(name?, text?)` sets what is passed, for everyone whose agent lists it. "
266
+ f"It needs write access: {_WRITE_ACCESS}.",
267
+ ),
268
+ ]
269
+
270
+
271
+ async def skill_tools(ctx, skill):
272
+ return [strategy_tool('UpdateSkill', name='update_skill', bind=skill.entity_id)]
273
+
274
+
275
+ @agent_view('agents.skill', default_for=[SKILL], tools=skill_tools)
276
+ async def skill(ctx, s):
277
+ fields = s.to_dict()
278
+ return [
279
+ fields.get('description') or '_No description._', "## Text", fields.get('text') or '_This skill is empty._',
280
+ *_guide(
281
+ "An agent that lists this skill sees its name and description in its prompt and loads the text with "
282
+ "`load_skill(name)` when the description fits, so the description should say when to use it.",
283
+ "`update_skill(name?, description?, text?)` sets what is passed, for everyone whose agent lists it. "
284
+ f"It needs write access: {_WRITE_ACCESS}.",
285
+ ),
286
+ ]
audio/__init__.py ADDED
File without changes
audio/apps.py ADDED
@@ -0,0 +1,14 @@
1
+ from graphcore.public.apps import GraphCoreAppConfig
2
+
3
+
4
+ class AudioConfig(GraphCoreAppConfig):
5
+ # Django picks this config for the app package.
6
+ default = True
7
+ name = 'audio'
8
+ # Django app label. Must be unique across the deployment.
9
+ label = 'audio'
10
+ # Stable graphcore identity: namespaces this app's entity type ids and keys
11
+ # its per-user mount folder. Safe to move the package; never change this.
12
+ graphcore_app_id = 'audio'
13
+ graphcore_authorization = 'audio.authorization.configure'
14
+ graphcore_persistence = 'audio.persistence.configure'
audio/authorization.py ADDED
@@ -0,0 +1,13 @@
1
+ """Authorization policy for the audio app: a recording is its
2
+ owner's alone, and anyone signed in may open one of their own."""
3
+ from graphcore.public.auth.perms import Create, Write
4
+ from graphcore.public.auth.policy import AccessPolicy
5
+ from graphcore.public.entities import Deployment
6
+
7
+ from audio.entities.recording import Recording
8
+ from audio.strategies.recordings import OpenRecording, Transcribe
9
+
10
+
11
+ def configure(policy: AccessPolicy) -> None:
12
+ policy.define(Recording, shareable=False, can_contain=[], strategies={Transcribe: Write()})
13
+ policy.extend(Deployment, strategies={OpenRecording: Create()})
audio/conf.py ADDED
@@ -0,0 +1,27 @@
1
+ """The app's settings, read at call time so a test may override them."""
2
+ import os
3
+ from typing import Optional
4
+
5
+ from django.conf import settings
6
+
7
+ DEFAULT_MODEL = 'openai/gpt-4o-mini-transcribe'
8
+ # Base64 in a strategy call adds a third; this keeps the message under the
9
+ # web server's 16 MB WebSocket limit.
10
+ DEFAULT_MAX_AUDIO_BYTES = 8 * 1024 * 1024
11
+
12
+
13
+ def model() -> str:
14
+ return getattr(settings, 'AUDIO_TRANSCRIPTION_MODEL', DEFAULT_MODEL)
15
+
16
+
17
+ def max_audio_bytes() -> int:
18
+ return int(getattr(settings, 'AUDIO_MAX_UPLOAD_BYTES', DEFAULT_MAX_AUDIO_BYTES))
19
+
20
+
21
+ def provider_key(provider: str) -> Optional[str]:
22
+ name = f'{provider.upper()}_API_KEY'
23
+ return getattr(settings, name, None) or os.environ.get(name) or None
24
+
25
+
26
+ def provider_read_timeout() -> float:
27
+ return float(getattr(settings, 'AUDIO_PROVIDER_READ_TIMEOUT', 60))
@@ -0,0 +1,11 @@
1
+ # Entity types for the audio app. Every module in this package is
2
+ # imported at startup, so decorated classes register themselves.
3
+ #
4
+ # from graphcore.public.entities import Entity, register_entity
5
+ #
6
+ # @register_entity()
7
+ # class Board(Entity):
8
+ # pass
9
+ #
10
+ # Registers as 'audio.Board' — namespaced by this app's
11
+ # graphcore_app_id, so it cannot collide with another app's Board.
@@ -0,0 +1,10 @@
1
+ from graphcore.public.entities import Entity, register_entity
2
+
3
+
4
+ @register_entity()
5
+ class Recording(Entity):
6
+ """What one person dictated somewhere: the text of the latest take. The
7
+ audio is never kept."""
8
+ purpose: str = ''
9
+ text: str = ''
10
+ take: int = 0