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,65 @@
1
+ import time
2
+
3
+ from graphcore.public.strategies import Strategy, StrategyRequestPayload, register_strategy
4
+
5
+ from agents.entities.agent import Agent
6
+ from agents.delegation import stop_waited_children
7
+ from agents.entities.conversation import Conversation, ConversationStatus
8
+ from agents.strategies._schema import IDS, MODEL, STRING, params
9
+ from agents.validation import listed_model, readable_ids
10
+
11
+ _CONTEXT = {**IDS, "description": "Entities rendered for the agent on every turn"}
12
+
13
+
14
+ @register_strategy(Agent)
15
+ class CreateConversation(Strategy):
16
+ strategy_description = "Creates the caller's own conversation with an agent; a message sent to it starts a turn"
17
+ param_schema = params({"title": STRING, "context_ids": _CONTEXT, "model": MODEL})
18
+
19
+ async def apply(self) -> tuple:
20
+ given = self.strategy_request.param_config
21
+ conversation = self.session.create(
22
+ Conversation, agent_id=self.entity.entity_id, title=given.get('title', ''),
23
+ context_ids=await readable_ids(self.session, given.get('context_ids', [])),
24
+ model=listed_model(given.get('model')), last_active_at=time.time(),
25
+ )
26
+ conversation = await self.save_entity(conversation)
27
+ self.strategy_request.ret_val['conversation_id'] = conversation.entity_id
28
+ return self.strategy_request, self.entity
29
+
30
+ @classmethod
31
+ def request_constructor(cls, target_entity_id: str, **fields) -> StrategyRequestPayload:
32
+ return cls._build_request(target_entity_id=target_entity_id, param_config=fields)
33
+
34
+
35
+ @register_strategy(Conversation)
36
+ class UpdateConversation(Strategy):
37
+ strategy_description = "Sets a conversation's title, model or standing context, or stops its running turn"
38
+ param_schema = params({
39
+ "title": STRING,
40
+ "model": MODEL,
41
+ "context_ids": _CONTEXT,
42
+ "stop": {
43
+ "type": "boolean",
44
+ "description": "true stops the turn in progress, if one is running, and any sub-conversation it waits "
45
+ "on. Background tasks keep running; stop each on its own",
46
+ },
47
+ })
48
+
49
+ async def apply(self) -> tuple:
50
+ given = self.strategy_request.param_config
51
+ if 'title' in given:
52
+ self.entity.title = given['title']
53
+ if 'model' in given:
54
+ self.entity.model = listed_model(given['model'])
55
+ if 'context_ids' in given:
56
+ self.entity.context_ids = await readable_ids(self.session, given['context_ids'])
57
+ if given.get('stop') and self.entity.status is ConversationStatus.RUNNING:
58
+ self.entity.stop_requested = True
59
+ await stop_waited_children(self.session, self.entity.entity_id)
60
+ self.entity = await self.save_entity(self.entity)
61
+ return self.strategy_request, self.entity
62
+
63
+ @classmethod
64
+ def request_constructor(cls, target_entity_id: str, **fields) -> StrategyRequestPayload:
65
+ return cls._build_request(target_entity_id=target_entity_id, param_config=fields)
@@ -0,0 +1,62 @@
1
+ from typing import Optional
2
+
3
+ from graphcore.public.entities import Entity
4
+ from graphcore.public.errors import InvalidRequest
5
+ from graphcore.public.strategies import Strategy, StrategyRequestPayload, register_strategy
6
+
7
+ from agents.entities.agent import Agent
8
+ from agents.entities.instruction import Instruction
9
+ from agents.entities.profile import AgentProfile
10
+ from agents.strategies._schema import STRING, params
11
+
12
+ ATTACH = {"type": "boolean", "description": "Also append it to the target agent's or profile's list"}
13
+
14
+
15
+ async def create_attached(strategy: Strategy, entity_cls: type, list_field: str, fields: dict) -> str:
16
+ """Creates an instruction or skill inside the strategy's target and, with
17
+ `attach`, appends it to the target's list."""
18
+ target = strategy.entity
19
+ attach = strategy.strategy_request.param_config.get('attach', False)
20
+ if attach and not isinstance(target, (Agent, AgentProfile)):
21
+ raise InvalidRequest("attach needs an agent or a profile as the target")
22
+ created = strategy.session.create(
23
+ entity_cls, parent_id=target.entity_id if target is not None else None, **fields,
24
+ )
25
+ created = await strategy.save_entity(created)
26
+ if attach:
27
+ setattr(target, list_field, [*getattr(target, list_field), created.entity_id])
28
+ strategy.entity = await strategy.save_entity(target)
29
+ return created.entity_id
30
+
31
+
32
+ @register_strategy(Entity)
33
+ class CreateInstruction(Strategy):
34
+ strategy_description = "Creates an instruction inside the target, or a top-level one owned by the caller"
35
+ param_schema = params({"name": STRING, "text": STRING, "attach": ATTACH}, required=('name', 'text'))
36
+
37
+ async def apply(self) -> tuple:
38
+ given = self.strategy_request.param_config
39
+ self.strategy_request.ret_val['instruction_id'] = await create_attached(
40
+ self, Instruction, 'instruction_ids', {'name': given['name'], 'text': given['text']},
41
+ )
42
+ return self.strategy_request, self.entity
43
+
44
+ @classmethod
45
+ def request_constructor(cls, target_entity_id: Optional[str] = None, **fields) -> StrategyRequestPayload:
46
+ return cls._build_request(target_entity_id=target_entity_id, param_config=fields)
47
+
48
+
49
+ @register_strategy(Instruction)
50
+ class UpdateInstruction(Strategy):
51
+ strategy_description = "Sets the given fields of an instruction"
52
+ param_schema = params({"name": STRING, "text": STRING})
53
+
54
+ async def apply(self) -> tuple:
55
+ for name, value in self.strategy_request.param_config.items():
56
+ setattr(self.entity, name, value)
57
+ self.entity = await self.save_entity(self.entity)
58
+ return self.strategy_request, self.entity
59
+
60
+ @classmethod
61
+ def request_constructor(cls, target_entity_id: str, **fields) -> StrategyRequestPayload:
62
+ return cls._build_request(target_entity_id=target_entity_id, param_config=fields)
@@ -0,0 +1,56 @@
1
+ from graphcore.public.errors import InvalidRequest
2
+ from graphcore.public.strategies import Strategy, StrategyRequestPayload, register_strategy
3
+
4
+ from agents.delegation import run_turn
5
+ from agents.entities.conversation import Conversation
6
+ from agents.entities.message import Message, MessageRole
7
+ from agents.strategies._schema import IDS, params
8
+ from agents.validation import readable, readable_ids
9
+
10
+
11
+ @register_strategy(Conversation)
12
+ class SendMessage(Strategy):
13
+ strategy_description = "Appends a message to a conversation and starts a turn that answers it"
14
+ param_schema = params({
15
+ "content": {"type": "string", "description": "The message text"},
16
+ "context_ids": {**IDS, "description": "Entities rendered for the agent for this message"},
17
+ "source_conversation_id": {
18
+ "type": "string", "description": "Set by a sub-conversation's callback: the sub-conversation",
19
+ },
20
+ "source_ret_val": {"type": "object", "description": "Set by the executor: what the sub-conversation's turn returned"},
21
+ })
22
+
23
+ async def apply(self) -> tuple:
24
+ given = self.strategy_request.param_config
25
+ if 'source_ret_val' in given:
26
+ message = await self._delivered(given)
27
+ elif 'content' in given and 'source_conversation_id' not in given:
28
+ message = self.session.create(
29
+ Message, parent_id=self.entity.entity_id, role=MessageRole.USER, content=given['content'],
30
+ context_ids=await readable_ids(self.session, given.get('context_ids', [])),
31
+ )
32
+ else:
33
+ raise InvalidRequest("content is required")
34
+ message = await self.save_entity(message)
35
+ await self.session.execute(run_turn(self.entity), wait=False)
36
+ self.strategy_request.ret_val['message_id'] = message.entity_id
37
+ return self.strategy_request, self.entity
38
+
39
+ async def _delivered(self, given: dict) -> Message:
40
+ source = await readable(self.session, given.get('source_conversation_id') or '', Conversation)
41
+ if source.parent_id != self.entity.entity_id:
42
+ raise InvalidRequest(f"{source.entity_id} is not a sub-conversation of {self.entity.entity_id}")
43
+ result = given['source_ret_val']
44
+ return self.session.create(
45
+ Message, parent_id=self.entity.entity_id, role=MessageRole.SYSTEM,
46
+ content=(
47
+ f"The sub-conversation {source.entity_id} ended its turn ({result.get('status')}"
48
+ f"{', cut off at the output limit' if result.get('cut_off') else ''}):\n"
49
+ f"{result.get('text') or ''}"
50
+ ),
51
+ source_conversation_id=source.entity_id,
52
+ )
53
+
54
+ @classmethod
55
+ def request_constructor(cls, target_entity_id: str, **fields) -> StrategyRequestPayload:
56
+ return cls._build_request(target_entity_id=target_entity_id, param_config=fields)
@@ -0,0 +1,27 @@
1
+ from typing import Optional
2
+
3
+ from graphcore.public.entities import Entity
4
+ from graphcore.public.strategies import Strategy, StrategyRequestPayload, register_strategy
5
+
6
+ from agents import conf
7
+ from agents.providers.registry import available
8
+
9
+
10
+ @register_strategy(Entity)
11
+ class ListModels(Strategy):
12
+ strategy_description = "Returns the models an agent, profile or conversation may name, the default, and the default compaction threshold and task limit"
13
+ read_only_strategy = True
14
+
15
+ async def apply(self) -> tuple:
16
+ self.strategy_request.ret_val['models'] = [
17
+ {**entry, 'available': available(entry['id'])}
18
+ for entry in conf.models()
19
+ ]
20
+ self.strategy_request.ret_val['default'] = conf.default_model()
21
+ self.strategy_request.ret_val['compaction_threshold'] = conf.compaction_threshold()
22
+ self.strategy_request.ret_val['max_tasks'] = conf.max_tasks()
23
+ return self.strategy_request, self.entity
24
+
25
+ @classmethod
26
+ def request_constructor(cls, target_entity_id: Optional[str] = None) -> StrategyRequestPayload:
27
+ return cls._build_request(target_entity_id=target_entity_id)
@@ -0,0 +1,43 @@
1
+ from typing import Optional
2
+
3
+ from graphcore.public.persistence import AllOf, EntityFilter, Equal
4
+ from graphcore.public.strategies import Strategy, StrategyRequestPayload, StrategySession, register_strategy
5
+
6
+ from agents.entities.agent import Agent
7
+ from agents.entities.profile import AgentProfile
8
+ from agents.strategies._schema import IDS, MODEL, THRESHOLD, params
9
+ from agents.strategies.agents import set_agent_fields
10
+
11
+
12
+ async def find_profile(session: StrategySession, agent_id: str) -> Optional[AgentProfile]:
13
+ """The session principal's profile on the agent: the first in listing
14
+ order, so a duplicate left by a lost race never takes over."""
15
+ page = await session.list(EntityFilter(
16
+ type_ids=frozenset({AgentProfile.get_entity_type_id()}),
17
+ where=AllOf((Equal('owner', session.principal.principal_entity_id), Equal('agent_id', agent_id))),
18
+ ), limit=1)
19
+ return page.entities[0] if page.entities else None
20
+
21
+
22
+ @register_strategy(Agent)
23
+ class CustomizeAgent(Strategy):
24
+ strategy_description = "Sets the caller's own added instructions, added skills, model and compaction threshold for an agent"
25
+ param_schema = params({
26
+ "instruction_ids": {**IDS, "description": "Instructions added after the agent's own"},
27
+ "skill_ids": {**IDS, "description": "Skills added to the agent's own"},
28
+ "model": MODEL,
29
+ "compaction_threshold": THRESHOLD,
30
+ })
31
+
32
+ async def apply(self) -> tuple:
33
+ profile = await find_profile(self.session, self.entity.entity_id)
34
+ if profile is None:
35
+ profile = self.session.create(AgentProfile, agent_id=self.entity.entity_id)
36
+ await set_agent_fields(self.session, profile, self.strategy_request.param_config)
37
+ profile = await self.save_entity(profile)
38
+ self.strategy_request.ret_val['profile_id'] = profile.entity_id
39
+ return self.strategy_request, self.entity
40
+
41
+ @classmethod
42
+ def request_constructor(cls, target_entity_id: str, **fields) -> StrategyRequestPayload:
43
+ return cls._build_request(target_entity_id=target_entity_id, param_config=fields)
@@ -0,0 +1,47 @@
1
+ from typing import Optional
2
+
3
+ from graphcore.public.entities import Entity
4
+ from graphcore.public.strategies import Strategy, StrategyRequestPayload, register_strategy
5
+
6
+ from agents.entities.skill import Skill
7
+ from agents.strategies._schema import STRING, params
8
+ from agents.strategies.instructions import ATTACH, create_attached
9
+
10
+ _DESCRIPTION = {"type": "string", "description": "One line, always in the prompt, saying when to load the skill"}
11
+
12
+
13
+ @register_strategy(Entity)
14
+ class CreateSkill(Strategy):
15
+ strategy_description = "Creates a skill inside the target, or a top-level one owned by the caller"
16
+ param_schema = params(
17
+ {"name": STRING, "description": _DESCRIPTION, "text": STRING, "attach": ATTACH},
18
+ required=('name', 'description', 'text'),
19
+ )
20
+
21
+ async def apply(self) -> tuple:
22
+ given = self.strategy_request.param_config
23
+ self.strategy_request.ret_val['skill_id'] = await create_attached(
24
+ self, Skill, 'skill_ids',
25
+ {'name': given['name'], 'description': given['description'], 'text': given['text']},
26
+ )
27
+ return self.strategy_request, self.entity
28
+
29
+ @classmethod
30
+ def request_constructor(cls, target_entity_id: Optional[str] = None, **fields) -> StrategyRequestPayload:
31
+ return cls._build_request(target_entity_id=target_entity_id, param_config=fields)
32
+
33
+
34
+ @register_strategy(Skill)
35
+ class UpdateSkill(Strategy):
36
+ strategy_description = "Sets the given fields of a skill"
37
+ param_schema = params({"name": STRING, "description": _DESCRIPTION, "text": STRING})
38
+
39
+ async def apply(self) -> tuple:
40
+ for name, value in self.strategy_request.param_config.items():
41
+ setattr(self.entity, name, value)
42
+ self.entity = await self.save_entity(self.entity)
43
+ return self.strategy_request, self.entity
44
+
45
+ @classmethod
46
+ def request_constructor(cls, target_entity_id: str, **fields) -> StrategyRequestPayload:
47
+ return cls._build_request(target_entity_id=target_entity_id, param_config=fields)
@@ -0,0 +1,47 @@
1
+ import asyncio
2
+
3
+ from graphcore.public.agent_frontend import connect
4
+ from graphcore.public.strategies import RetryMode, Strategy, StrategyRequestPayload, Workload, register_strategy
5
+
6
+ from agents import conf
7
+ from agents.entities.conversation import Conversation
8
+ from agents.runtime.loop import TurnRun
9
+
10
+ RUN_LOCK = 'run_lock'
11
+
12
+
13
+ @register_strategy(Conversation)
14
+ class RunTurn(Strategy):
15
+ """Submitted by `SendMessage`; no client calls it."""
16
+
17
+ strategy_description = "Runs one turn of a conversation: the model loop until it ends"
18
+ workload = Workload.IO
19
+ retry = RetryMode.CONTINUE
20
+ timeout = 120
21
+ param_schema = {"type": "object", "properties": {}, "additionalProperties": False}
22
+
23
+ async def apply(self) -> tuple:
24
+ # A lock that already names this request was left by an attempt that died holding it.
25
+ resumed = self.entity.attributes.get(RUN_LOCK) == self.strategy_request.entity_id
26
+ while not await self.try_acquire_lock(RUN_LOCK):
27
+ await asyncio.sleep(conf.lock_poll_seconds())
28
+ failure = None
29
+ async with connect(self.principal) as client:
30
+ try:
31
+ result = await TurnRun(self, client, resumed).run()
32
+ except Exception as exc:
33
+ # Raised through the client, it would arrive wrapped in an
34
+ # exception group, and the executor would not see a transient error.
35
+ failure = exc
36
+ if failure is not None:
37
+ raise failure
38
+ self.strategy_request.ret_val.update(result)
39
+ self.entity = await self.get_entity(self.entity.entity_id)
40
+ return self.strategy_request, self.entity
41
+
42
+ async def cleanup(self) -> None:
43
+ await self.release_lock(RUN_LOCK)
44
+
45
+ @classmethod
46
+ def request_constructor(cls, target_entity_id: str) -> StrategyRequestPayload:
47
+ return cls._build_request(target_entity_id=target_entity_id)
@@ -0,0 +1,6 @@
1
+ # Runs this app's tests without a project:
2
+ # python -m django test agents --settings=agents.test_settings
3
+ # Inside a project, `graphcore test` runs them with the project's settings.
4
+ from graphcore.public.test_settings import app_test_settings
5
+
6
+ globals().update(app_test_settings('agents'))
File without changes
@@ -0,0 +1,94 @@
1
+ from unittest.mock import patch
2
+
3
+ from django.test import override_settings
4
+
5
+ from graphcore.public.persistence import AllOf, EntityFilter, Equal
6
+ from graphcore.public.strategies import StrategyRequest, Workload
7
+ from graphcore.public.testing import GraphCoreTestCase
8
+
9
+ from agents.entities.message import Message
10
+ from agents.providers import registry
11
+ from agents.providers.fake import FakeProvider
12
+
13
+ from agents.strategies.agents import CreateAgent
14
+ from agents.strategies.conversations import CreateConversation
15
+ from agents.strategies.instructions import CreateInstruction
16
+ from agents.strategies.messages import SendMessage
17
+ from agents.strategies.skills import CreateSkill
18
+
19
+
20
+ FAKE_MODEL = 'fake/model'
21
+
22
+
23
+ @override_settings(
24
+ AGENTS_MODELS=[{'id': FAKE_MODEL, 'context_size': 1000}, {'id': 'fake/other', 'context_size': 1000}],
25
+ AGENTS_DEFAULT_MODEL=FAKE_MODEL, AGENTS_STREAM_INTERVAL_MS=0, AGENTS_LOCK_POLL_SECONDS=0.01,
26
+ )
27
+ class TurnTestCase(GraphCoreTestCase):
28
+ """Turns on the `FakeProvider`, with the in-process agent frontend on the test's runtime."""
29
+
30
+ def setUp(self):
31
+ super().setUp()
32
+ FakeProvider.reset()
33
+ registry.reset()
34
+ patcher = patch('graphcore.transport.agent_client.get_runtime', return_value=self.runtime)
35
+ patcher.start()
36
+ self.addCleanup(patcher.stop)
37
+
38
+ async def settle(self) -> None:
39
+ """Wait for every turn in flight to end."""
40
+ await self.runtime.executor.dispatchers[Workload.IO].drain()
41
+
42
+ async def send(self, principal, conversation_id, content='Hello', settle=True, **fields):
43
+ completed = await self.run_strategy(
44
+ principal, SendMessage.request_constructor(conversation_id, content=content, **fields),
45
+ )
46
+ if settle:
47
+ await self.settle()
48
+ return completed.ret_val['message_id']
49
+
50
+ async def messages(self, principal, conversation_id):
51
+ page = await self.api.list_entities(principal, EntityFilter(
52
+ type_ids=frozenset({Message.get_entity_type_id()}), parent_id=conversation_id,
53
+ ), limit=100)
54
+ return sorted(page.entities, key=lambda message: message.sibling_position)
55
+
56
+ async def turn_results(self, principal, conversation_id):
57
+ """What each finished `RunTurn` on the conversation returned."""
58
+ page = await self.api.list_entities(principal, EntityFilter(
59
+ type_ids=frozenset({StrategyRequest.get_entity_type_id()}),
60
+ where=AllOf((Equal('strategy_name', 'RunTurn'), Equal('target_entity_id', conversation_id))),
61
+ ), limit=100)
62
+ return [request.ret_val for request in page.entities]
63
+
64
+ async def transcript(self, principal, conversation_id):
65
+ return [(m.role.value, m.content) for m in await self.messages(principal, conversation_id)]
66
+
67
+
68
+ class AgentsTestCase(TurnTestCase):
69
+ async def create_agent(self, principal, target_id=None, name='Troy', **fields):
70
+ completed = await self.run_strategy(principal, CreateAgent.request_constructor(target_id, name=name, **fields))
71
+ return completed.ret_val['agent_id']
72
+
73
+ async def create_instruction(self, principal, target_id=None, name='Brief', text='Be brief.', **fields):
74
+ completed = await self.run_strategy(
75
+ principal, CreateInstruction.request_constructor(target_id, name=name, text=text, **fields),
76
+ )
77
+ return completed.ret_val['instruction_id']
78
+
79
+ async def create_skill(self, principal, target_id=None, name='research', description='How to research',
80
+ text='Search first.', **fields):
81
+ completed = await self.run_strategy(principal, CreateSkill.request_constructor(
82
+ target_id, name=name, description=description, text=text, **fields,
83
+ ))
84
+ return completed.ret_val['skill_id']
85
+
86
+ async def create_conversation(self, principal, agent_id, **fields):
87
+ completed = await self.run_strategy(principal, CreateConversation.request_constructor(agent_id, **fields))
88
+ return completed.ret_val['conversation_id']
89
+
90
+ async def listed(self, principal, *entity_classes, **criteria):
91
+ page = await self.api.list_entities(principal, EntityFilter(
92
+ type_ids=frozenset(cls.get_entity_type_id() for cls in entity_classes), **criteria,
93
+ ))
94
+ return sorted(entity.entity_id for entity in page.entities)
@@ -0,0 +1,181 @@
1
+ """The app's agent views, rendered and called as an agent does over `/mcp`."""
2
+ from unittest.mock import patch
3
+
4
+ from graphcore.agent_frontend import AgentError
5
+
6
+ import agents_agent_frontend.agent_views as agent_views
7
+
8
+ from agents.entities.conversation import Conversation
9
+ from agents.providers.fake import FakeProvider, calls, says
10
+ from agents.providers.port import ToolCall
11
+ from agents.strategies.profiles import CustomizeAgent
12
+ from agents.tests.support import AgentsTestCase
13
+
14
+
15
+ class AgentViewTests(AgentsTestCase):
16
+ async def test_the_app_is_listed_in_the_catalog_at_its_home(self):
17
+ carl = await self.create_user('carl')
18
+
19
+ entries = (await self.api.catalog(carl))['entries']
20
+
21
+ self.assertIn(('/agents', 'agents', 'Agents'), [(e['route'], e['app_id'], e['label']) for e in entries])
22
+
23
+ async def test_home_lists_my_agents_shared_ones_and_the_models(self):
24
+ carl = await self.create_user('carl')
25
+ dana = await self.create_user('dana')
26
+ await self.create_agent(carl, name='Troy')
27
+ shared = await self.create_agent(dana, name='Helper')
28
+ await self.create_agent(dana, name='Private')
29
+ await self.grant(dana, shared, carl, 'viewer')
30
+
31
+ place = await self.open_place(carl, '/agents')
32
+
33
+ mine, rest = place.text.split('## Shared with me')
34
+ theirs, rest = rest.split('## Other agents I can use')
35
+ self.assertRegex(mine, r'- Troy · agents\.Agent · gc://')
36
+ self.assertRegex(theirs, r'- Helper · agents\.Agent · gc://')
37
+ self.assertNotIn('Private', place.text)
38
+ self.assertIn('- fake/model · context 1000 · default', place.text)
39
+ self.assertTrue({'create_agent', 'create_instruction', 'create_skill'} <= set(place.tools))
40
+ self.assertIn('## Using this place', place.text)
41
+
42
+ async def test_an_agent_is_created_and_talked_to_through_place_tools(self):
43
+ carl = await self.create_user('carl')
44
+ FakeProvider.play(says('Hi Carl.'))
45
+
46
+ created = await self.call_tool(carl, '/agents', 'create_agent', {'name': 'Troy'})
47
+ agent_id = created['result']['agent_id']
48
+ started = await self.call_tool(carl, agent_id, 'create_conversation', {'title': 'Trip'})
49
+ conversation_id = started['result']['conversation_id']
50
+ await self.call_tool(carl, conversation_id, 'send', {'content': 'Hello'})
51
+ await self.settle()
52
+
53
+ self.assertRegex((await self.open_place(carl, agent_id)).text, r'- Trip · agents\.Conversation · gc://')
54
+ text = (await self.open_place(carl, conversation_id)).text
55
+ self.assertIn('idle · default model · 10 tokens in context', text)
56
+ self.assertIn('**user:** Hello\n', text)
57
+ self.assertIn('**assistant:** Hi Carl.', text)
58
+
59
+ async def test_an_agent_shows_its_pieces_and_my_additions(self):
60
+ carl = await self.create_user('carl')
61
+ dana = await self.create_user('dana')
62
+ agent_id = await self.create_agent(dana, name='Helper', description='Helps.', start_address='/agents')
63
+ await self.create_instruction(dana, agent_id, name='House rules', attach=True)
64
+ await self.grant(dana, agent_id, carl, 'viewer')
65
+ mine = await self.create_skill(carl, name='my-way')
66
+ await self.run_strategy(carl, CustomizeAgent.request_constructor(agent_id, skill_ids=[mine], model='fake/other'))
67
+
68
+ place = await self.open_place(carl, agent_id)
69
+
70
+ self.assertIn('Helps.', place.text)
71
+ self.assertIn('Starts at: /agents', place.text)
72
+ self.assertRegex(place.text, r'## Instructions\n+- House rules · agents\.Instruction')
73
+ self.assertRegex(place.text, r'## My additions\n+Model: fake/other\n+Compaction threshold: not set\n+- my-way')
74
+ self.assertEqual(
75
+ set(place.tools), {'create_conversation', 'customize', 'update_agent', 'create_instruction', 'create_skill'},
76
+ )
77
+ self.assertIn('I do not own this agent.', place.text)
78
+ self.assertIn('I own this agent', (await self.open_place(dana, agent_id)).text)
79
+ with self.assertRaises(AgentError) as raised:
80
+ await self.call_tool(carl, agent_id, 'update_agent', {'name': 'Mine now'})
81
+ self.assertEqual(raised.exception.code, 'Refused')
82
+
83
+ async def test_my_own_instruction_goes_on_a_shared_agent_the_way_its_place_says(self):
84
+ carl = await self.create_user('carl')
85
+ dana = await self.create_user('dana')
86
+ agent_id = await self.create_agent(dana, name='Helper')
87
+ await self.grant(dana, agent_id, carl, 'viewer')
88
+
89
+ made = await self.call_tool(carl, '/agents', 'create_instruction', {'name': 'Mine', 'text': 'Use metric.'})
90
+ await self.call_tool(carl, agent_id, 'customize', {'instruction_ids': [made['result']['instruction_id']]})
91
+
92
+ self.assertRegex((await self.open_place(carl, agent_id)).text, r'## My additions\n(.*\n)*- Mine · agents\.Instruction')
93
+ self.assertNotIn('Mine', (await self.open_place(dana, agent_id)).text)
94
+
95
+ async def test_an_agent_lists_my_conversations_most_recently_active_first(self):
96
+ dana = await self.create_user('dana')
97
+ agent_id = await self.create_agent(dana)
98
+ older = await self.create_conversation(dana, agent_id, title='Older')
99
+ newer = await self.create_conversation(dana, agent_id, title='Newer')
100
+ await self.send(dana, older)
101
+
102
+ listed = (await self.open_place(dana, agent_id)).text.split('## My conversations', 1)[1]
103
+
104
+ self.assertLess(listed.index('Older'), listed.index('Newer'))
105
+ await self.send(dana, newer)
106
+ listed = (await self.open_place(dana, agent_id)).text.split('## My conversations', 1)[1]
107
+ self.assertLess(listed.index('Newer'), listed.index('Older'))
108
+
109
+ async def test_a_conversation_shows_tool_calls_context_and_sub_conversations(self):
110
+ carl = await self.create_user('carl')
111
+ agent_id = await self.create_agent(carl)
112
+ rules = await self.create_instruction(carl, agent_id, name='House rules')
113
+ conversation_id = await self.create_conversation(carl, agent_id, context_ids=[rules])
114
+ FakeProvider.play(
115
+ calls(ToolCall('c1', 'open', {'at': '/nowhere'})),
116
+ calls(ToolCall('c2', 'delegate', {'agent': agent_id, 'goal': 'Look around'})),
117
+ )
118
+
119
+ await self.send(carl, conversation_id, 'Hello')
120
+
121
+ place = await self.open_place(carl, conversation_id)
122
+ self.assertIn(f"**context shown:** {rules}", place.text)
123
+ self.assertRegex(place.text, r' - open /nowhere · error · .*no route matches')
124
+ self.assertRegex(place.text, r' - delegate · completed · \{"conversation_id"')
125
+ (child_id,) = await self.listed(carl, Conversation, parent_id=conversation_id)
126
+ self.assertRegex(place.text, r'## Sub-conversations\n+- Look around · agents\.Conversation · gc://')
127
+ child = await self.open_place(carl, child_id)
128
+ self.assertIn('**user:** Look around', child.text)
129
+ self.assertIn(f'This is a sub-conversation of {conversation_id}, started by its agent with `delegate`.', child.text)
130
+ self.assertEqual(set(place.tools), {'send', 'update', 'earlier'})
131
+ self.assertIn('`send(content, context_ids?)` adds a message', place.text)
132
+ self.assertNotIn("someone else's", place.text)
133
+
134
+ async def test_a_conversation_with_a_debug_agent_offers_inspect_context(self):
135
+ carl = await self.create_user('carl')
136
+ conversation_id = await self.create_conversation(carl, await self.create_agent(carl, debug_context=True))
137
+
138
+ place = await self.open_place(carl, conversation_id)
139
+ inspected = await self.call_tool(carl, conversation_id, 'inspect_context', {})
140
+
141
+ self.assertIn('inspect_context', place.tools)
142
+ self.assertIn('turns', str(inspected['result']))
143
+
144
+ async def test_a_long_conversation_shows_its_last_messages_and_pages_back(self):
145
+ carl = await self.create_user('carl')
146
+ conversation_id = await self.create_conversation(carl, await self.create_agent(carl))
147
+ for content in ('One', 'Two', 'Three'):
148
+ FakeProvider.play(says(f'Heard {content}.'))
149
+ await self.send(carl, conversation_id, content)
150
+
151
+ with patch.object(agent_views, '_SHOWN_MESSAGES', 2):
152
+ place = await self.open_place(carl, conversation_id)
153
+ before = await self.call_tool(carl, conversation_id, 'earlier', {})
154
+ first = await self.call_tool(carl, conversation_id, 'earlier', {'skip': 4, 'count': 5})
155
+
156
+ self.assertIn('The last 2 of 6 messages. `earlier` reads the ones before them.', place.text)
157
+ self.assertNotIn('Heard Two.', place.text)
158
+ self.assertEqual(before['result'], {'messages': ['**user:** Two', '**assistant:** Heard Two.'], 'older': 2})
159
+ self.assertEqual(first['result'], {'messages': ['**user:** One', '**assistant:** Heard One.'], 'older': 0})
160
+
161
+ async def test_instructions_and_skills_render_and_update(self):
162
+ carl = await self.create_user('carl')
163
+ instruction_id = await self.create_instruction(carl, text='Be brief.')
164
+ skill_id = await self.create_skill(carl)
165
+
166
+ await self.call_tool(carl, instruction_id, 'update_instruction', {'text': 'Be thorough.'})
167
+ await self.call_tool(carl, skill_id, 'update_skill', {'description': 'How to dig'})
168
+
169
+ self.assertIn('Be thorough.', (await self.open_place(carl, instruction_id)).text)
170
+ skill = (await self.open_place(carl, skill_id)).text
171
+ self.assertIn('How to dig', skill)
172
+ self.assertIn('Search first.', skill)
173
+
174
+ async def test_a_stranger_cannot_open_a_conversation(self):
175
+ carl = await self.create_user('carl')
176
+ dana = await self.create_user('dana')
177
+ conversation_id = await self.create_conversation(carl, await self.create_agent(carl))
178
+
179
+ with self.assertRaises(AgentError) as raised:
180
+ await self.open_place(dana, conversation_id)
181
+ self.assertEqual(raised.exception.code, 'NotFound')