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.
- agents/__init__.py +0 -0
- agents/apps.py +15 -0
- agents/authorization.py +62 -0
- agents/conf.py +78 -0
- agents/delegation.py +218 -0
- agents/entities/__init__.py +0 -0
- agents/entities/agent.py +16 -0
- agents/entities/conversation.py +23 -0
- agents/entities/instruction.py +7 -0
- agents/entities/message.py +30 -0
- agents/entities/profile.py +14 -0
- agents/entities/skill.py +8 -0
- agents/migrations/0001_initial.py +88 -0
- agents/migrations/0002_message_context_versions.py +16 -0
- agents/migrations/0003_compaction_threshold.py +21 -0
- agents/migrations/0004_agent_debug_context.py +16 -0
- agents/migrations/0005_conversation_last_active_at.py +34 -0
- agents/migrations/0006_tasks.py +21 -0
- agents/migrations/0007_agent_start_address.py +16 -0
- agents/migrations/__init__.py +0 -0
- agents/models.py +64 -0
- agents/persistence.py +18 -0
- agents/providers/__init__.py +0 -0
- agents/providers/anthropic.py +142 -0
- agents/providers/fake.py +51 -0
- agents/providers/google.py +186 -0
- agents/providers/openai.py +177 -0
- agents/providers/port.py +101 -0
- agents/providers/registry.py +40 -0
- agents/routes.py +5 -0
- agents/runtime/__init__.py +0 -0
- agents/runtime/compaction.py +29 -0
- agents/runtime/context.py +78 -0
- agents/runtime/dispatch.py +76 -0
- agents/runtime/effective_agent.py +70 -0
- agents/runtime/loop.py +454 -0
- agents/runtime/prompt.py +183 -0
- agents/runtime/resume.py +30 -0
- agents/runtime/tools.py +35 -0
- agents/specs/__init__.py +3 -0
- agents/specs/dsl.py +310 -0
- agents/specs/test_r01_agents.py +74 -0
- agents/specs/test_r02_conversations.py +146 -0
- agents/specs/test_r03_acts_as_the_sender.py +60 -0
- agents/specs/test_r04_context.py +63 -0
- agents/specs/test_r05_personal_configuration.py +86 -0
- agents/specs/test_r06_delegation.py +70 -0
- agents/specs/test_r07_sharing.py +103 -0
- agents/specs/test_r08_embedding.py +40 -0
- agents/specs/test_r09_finding.py +41 -0
- agents/specs/test_r10_clients.py +41 -0
- agents/strategies/__init__.py +0 -0
- agents/strategies/_schema.py +16 -0
- agents/strategies/agents.py +93 -0
- agents/strategies/context.py +45 -0
- agents/strategies/conversations.py +65 -0
- agents/strategies/instructions.py +62 -0
- agents/strategies/messages.py +56 -0
- agents/strategies/models.py +27 -0
- agents/strategies/profiles.py +43 -0
- agents/strategies/skills.py +47 -0
- agents/strategies/turn.py +47 -0
- agents/test_settings.py +6 -0
- agents/tests/__init__.py +0 -0
- agents/tests/support.py +94 -0
- agents/tests/test_agent_views.py +181 -0
- agents/tests/test_agents.py +166 -0
- agents/tests/test_anthropic_adapter.py +221 -0
- agents/tests/test_context.py +231 -0
- agents/tests/test_control.py +162 -0
- agents/tests/test_conversations.py +158 -0
- agents/tests/test_delegation.py +392 -0
- agents/tests/test_google_adapter.py +208 -0
- agents/tests/test_inspect.py +59 -0
- agents/tests/test_live_providers.py +69 -0
- agents/tests/test_openai_adapter.py +259 -0
- agents/tests/test_profiles.py +92 -0
- agents/tests/test_resumption.py +150 -0
- agents/tests/test_turns.py +230 -0
- agents/validation.py +48 -0
- agents_agent_frontend/__init__.py +3 -0
- agents_agent_frontend/agent_views.py +286 -0
- audio/__init__.py +0 -0
- audio/apps.py +14 -0
- audio/authorization.py +13 -0
- audio/conf.py +27 -0
- audio/entities/__init__.py +11 -0
- audio/entities/recording.py +10 -0
- audio/migrations/0001_initial.py +26 -0
- audio/migrations/__init__.py +0 -0
- audio/models.py +9 -0
- audio/persistence.py +6 -0
- audio/providers/__init__.py +0 -0
- audio/providers/fake.py +35 -0
- audio/providers/openai.py +50 -0
- audio/providers/port.py +31 -0
- audio/providers/registry.py +31 -0
- audio/specs/__init__.py +3 -0
- audio/specs/dsl.py +120 -0
- audio/specs/test_clients.py +20 -0
- audio/specs/test_dictation.py +87 -0
- audio/specs/test_privacy.py +45 -0
- audio/specs/test_vendor.py +59 -0
- audio/strategies/__init__.py +11 -0
- audio/strategies/recordings.py +88 -0
- audio/test_settings.py +6 -0
- audio/tests/__init__.py +0 -0
- audio/tests/test_openai_adapter.py +65 -0
- audio/tests/test_recordings.py +139 -0
- audio_agent_frontend/__init__.py +3 -0
- audio_agent_frontend/agent_views.py +11 -0
- graphcore_apps-0.5.0.dist-info/METADATA +14 -0
- graphcore_apps-0.5.0.dist-info/RECORD +118 -0
- graphcore_apps-0.5.0.dist-info/WHEEL +5 -0
- graphcore_apps-0.5.0.dist-info/entry_points.txt +7 -0
- graphcore_apps-0.5.0.dist-info/licenses/LICENSE +202 -0
- graphcore_apps-0.5.0.dist-info/licenses/NOTICE +2 -0
- graphcore_apps-0.5.0.dist-info/top_level.txt +4 -0
agents/__init__.py
ADDED
|
File without changes
|
agents/apps.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from graphcore.public.apps import GraphCoreAppConfig
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AgentsConfig(GraphCoreAppConfig):
|
|
5
|
+
# Django picks this config for the app package.
|
|
6
|
+
default = True
|
|
7
|
+
name = 'agents'
|
|
8
|
+
# Django app label. Must be unique across the deployment.
|
|
9
|
+
label = 'agents'
|
|
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 = 'agents'
|
|
13
|
+
graphcore_routes = 'agents.routes.configure'
|
|
14
|
+
graphcore_authorization = 'agents.authorization.configure'
|
|
15
|
+
graphcore_persistence = 'agents.persistence.configure'
|
agents/authorization.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Authorization policy for the agents app: the kernel's default roles and
|
|
2
|
+
permissions, with the strategies that need less or more than `Write` listed."""
|
|
3
|
+
from graphcore.public.auth.perms import Create, Delete, Read, Write
|
|
4
|
+
from graphcore.public.auth.policy import AccessPolicy
|
|
5
|
+
from graphcore.public.entities import Deployment
|
|
6
|
+
from graphcore.public.strategies import DeleteEntity
|
|
7
|
+
|
|
8
|
+
from agents.entities.agent import Agent
|
|
9
|
+
from agents.entities.conversation import Conversation
|
|
10
|
+
from agents.entities.instruction import Instruction
|
|
11
|
+
from agents.entities.message import Message
|
|
12
|
+
from agents.entities.profile import AgentProfile
|
|
13
|
+
from agents.entities.skill import Skill
|
|
14
|
+
from agents.strategies.agents import CreateAgent
|
|
15
|
+
from agents.strategies.context import InspectContext
|
|
16
|
+
from agents.strategies.conversations import CreateConversation, UpdateConversation
|
|
17
|
+
from agents.strategies.instructions import CreateInstruction
|
|
18
|
+
from agents.strategies.messages import SendMessage
|
|
19
|
+
from agents.strategies.models import ListModels
|
|
20
|
+
from agents.strategies.profiles import CustomizeAgent
|
|
21
|
+
from agents.strategies.skills import CreateSkill
|
|
22
|
+
from agents.strategies.turn import RunTurn
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def configure(policy: AccessPolicy) -> None:
|
|
26
|
+
policy.define(
|
|
27
|
+
Agent, shareable=True, can_contain=[Instruction, Skill],
|
|
28
|
+
strategies={
|
|
29
|
+
CustomizeAgent: Read(),
|
|
30
|
+
CreateConversation: Read(),
|
|
31
|
+
CreateInstruction: Create(),
|
|
32
|
+
CreateSkill: Create(),
|
|
33
|
+
},
|
|
34
|
+
)
|
|
35
|
+
policy.define(Instruction, shareable=True)
|
|
36
|
+
policy.define(Skill, shareable=True)
|
|
37
|
+
policy.define(
|
|
38
|
+
AgentProfile, shareable=False, can_contain=[Instruction, Skill], other_strategies=False,
|
|
39
|
+
strategies={
|
|
40
|
+
CustomizeAgent: Write(),
|
|
41
|
+
CreateInstruction: Create(),
|
|
42
|
+
CreateSkill: Create(),
|
|
43
|
+
DeleteEntity: Delete(),
|
|
44
|
+
},
|
|
45
|
+
)
|
|
46
|
+
policy.define(
|
|
47
|
+
Conversation, shareable=True, can_contain=[Message, Conversation],
|
|
48
|
+
strategies={SendMessage: Write(), RunTurn: Write(), UpdateConversation: Write(), InspectContext: Read()},
|
|
49
|
+
)
|
|
50
|
+
policy.define(
|
|
51
|
+
Message, contained_by=[Conversation], can_contain=[], other_strategies=False,
|
|
52
|
+
strategies={SendMessage: Write(), RunTurn: Write()},
|
|
53
|
+
)
|
|
54
|
+
policy.extend(
|
|
55
|
+
Deployment,
|
|
56
|
+
strategies={
|
|
57
|
+
CreateAgent: Create(),
|
|
58
|
+
CreateInstruction: Create(),
|
|
59
|
+
CreateSkill: Create(),
|
|
60
|
+
ListModels: Read(),
|
|
61
|
+
},
|
|
62
|
+
)
|
agents/conf.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
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 = 'anthropic/claude-sonnet-5-5'
|
|
8
|
+
DEFAULT_CONTEXT_SIZE = 200_000
|
|
9
|
+
# The context window each provider's API documents; an entry of AGENTS_MODELS may give its own.
|
|
10
|
+
CONTEXT_SIZES = {
|
|
11
|
+
'anthropic/claude-sonnet-5-5': 1_000_000,
|
|
12
|
+
'openai/gpt-5.5': 1_050_000,
|
|
13
|
+
'google/gemini-3.5-flash': 1_048_576,
|
|
14
|
+
}
|
|
15
|
+
DEFAULT_MAX_OUTPUT_TOKENS = 8192
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def default_model() -> str:
|
|
19
|
+
return getattr(settings, 'AGENTS_DEFAULT_MODEL', DEFAULT_MODEL)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def models() -> list[dict]:
|
|
23
|
+
"""The catalog, every entry with its `id`, `context_size` and `max_output_tokens`."""
|
|
24
|
+
configured = getattr(settings, 'AGENTS_MODELS', None)
|
|
25
|
+
if configured is None:
|
|
26
|
+
configured = [{'id': default_model()}]
|
|
27
|
+
return [
|
|
28
|
+
{
|
|
29
|
+
'id': entry['id'],
|
|
30
|
+
'context_size': entry.get('context_size', CONTEXT_SIZES.get(entry['id'], DEFAULT_CONTEXT_SIZE)),
|
|
31
|
+
'max_output_tokens': entry.get('max_output_tokens', DEFAULT_MAX_OUTPUT_TOKENS),
|
|
32
|
+
}
|
|
33
|
+
for entry in configured
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def model_entry(model_id: str) -> Optional[dict]:
|
|
38
|
+
return next((entry for entry in models() if entry['id'] == model_id), None)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def provider_key(provider: str) -> Optional[str]:
|
|
42
|
+
name = f'{provider.upper()}_API_KEY'
|
|
43
|
+
return getattr(settings, name, None) or os.environ.get(name) or None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def provider_read_timeout() -> float:
|
|
47
|
+
return float(getattr(settings, 'AGENTS_PROVIDER_READ_TIMEOUT', 60))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def max_steps() -> int:
|
|
51
|
+
return int(getattr(settings, 'AGENTS_MAX_STEPS', 50))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def stream_interval() -> float:
|
|
55
|
+
"""Seconds between saves of a streaming assistant message."""
|
|
56
|
+
return float(getattr(settings, 'AGENTS_STREAM_INTERVAL_MS', 500)) / 1000
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def lock_poll_seconds() -> float:
|
|
60
|
+
return float(getattr(settings, 'AGENTS_LOCK_POLL_SECONDS', 2))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def compaction_threshold() -> float:
|
|
64
|
+
return float(getattr(settings, 'AGENTS_COMPACTION_THRESHOLD', 0.7))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def max_delegation_depth() -> int:
|
|
68
|
+
return int(getattr(settings, 'AGENTS_MAX_DELEGATION_DEPTH', 1))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def max_attempts() -> int:
|
|
72
|
+
"""The kernel's attempt limit for a request (`GRAPHCORE_EXECUTION_MAX_ATTEMPTS`)."""
|
|
73
|
+
return int(getattr(settings, 'GRAPHCORE_EXECUTION_MAX_ATTEMPTS', 6))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def max_tasks() -> int:
|
|
77
|
+
"""Background sub-conversations one conversation may have running at once, unless its agent sets its own."""
|
|
78
|
+
return int(getattr(settings, 'AGENTS_MAX_TASKS', 10))
|
agents/delegation.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Sub-conversations: a goal handed to an agent in a conversation inside
|
|
2
|
+
the parent's (docs/app_design/agents/AGENTS_TDD.md, Delegation)."""
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
from graphcore.public.entities import Entity
|
|
8
|
+
from graphcore.public.errors import Forbidden, InvalidRequest, NotFound
|
|
9
|
+
from graphcore.public.persistence import AllOf, EntityFilter, Equal
|
|
10
|
+
from graphcore.public.strategies import StrategyRequestPayload, StrategySession
|
|
11
|
+
|
|
12
|
+
from agents import conf
|
|
13
|
+
from agents.entities.agent import Agent
|
|
14
|
+
from agents.entities.conversation import Conversation, ConversationStatus
|
|
15
|
+
from agents.entities.message import Message, MessageRole
|
|
16
|
+
from agents.providers.port import ToolDef
|
|
17
|
+
from agents.runtime.effective_agent import EffectiveAgent
|
|
18
|
+
from agents.runtime.tools import RuntimeTool, ToolFailure
|
|
19
|
+
|
|
20
|
+
_CONVERSATIONS = frozenset({Conversation.get_entity_type_id()})
|
|
21
|
+
|
|
22
|
+
NOTE = (
|
|
23
|
+
"This is a sub-conversation of {parent}. Open it if you need more; its `earlier` tool pages back through "
|
|
24
|
+
"older messages. Your final reply is all that is sent back, so make it a complete report."
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def run_turn(conversation: Conversation) -> StrategyRequestPayload:
|
|
29
|
+
"""A turn's request. One on a background sub-conversation tells the parent how it ended."""
|
|
30
|
+
callbacks = None
|
|
31
|
+
if conversation.deliver_to_parent and conversation.parent_id:
|
|
32
|
+
callbacks = [StrategyRequestPayload(
|
|
33
|
+
'SendMessage', {'source_conversation_id': conversation.entity_id}, conversation.parent_id,
|
|
34
|
+
).to_dict()]
|
|
35
|
+
return StrategyRequestPayload('RunTurn', {}, conversation.entity_id, callbacks=callbacks)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def stop_waited_children(session: StrategySession, conversation_id: str) -> None:
|
|
39
|
+
"""Stops the running sub-conversations a stopped turn waits on. Background
|
|
40
|
+
tasks keep running: each is stopped on its own."""
|
|
41
|
+
cursor = None
|
|
42
|
+
while True:
|
|
43
|
+
page = await session.list(EntityFilter(
|
|
44
|
+
type_ids=_CONVERSATIONS, parent_id=conversation_id,
|
|
45
|
+
where=AllOf((Equal('status', ConversationStatus.RUNNING.value), Equal('deliver_to_parent', False))),
|
|
46
|
+
), cursor=cursor)
|
|
47
|
+
for child in page.entities:
|
|
48
|
+
child.stop_requested = True
|
|
49
|
+
await session.save(child)
|
|
50
|
+
await stop_waited_children(session, child.entity_id)
|
|
51
|
+
cursor = page.next_cursor
|
|
52
|
+
if cursor is None:
|
|
53
|
+
return
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def _depth(session: StrategySession, conversation: Entity) -> int:
|
|
57
|
+
depth = 0
|
|
58
|
+
while conversation.parent_id:
|
|
59
|
+
conversation = await session.get(conversation.parent_id)
|
|
60
|
+
if not isinstance(conversation, Conversation):
|
|
61
|
+
break
|
|
62
|
+
depth += 1
|
|
63
|
+
return depth
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def _agent(session: StrategySession, named: str) -> Agent:
|
|
67
|
+
try:
|
|
68
|
+
found = await session.get(named)
|
|
69
|
+
except (NotFound, Forbidden, InvalidRequest):
|
|
70
|
+
page = await session.list(EntityFilter(
|
|
71
|
+
type_ids=frozenset({Agent.get_entity_type_id()}), where=AllOf((Equal('key', named),)),
|
|
72
|
+
), limit=1)
|
|
73
|
+
found = page.entities[0] if page.entities else None
|
|
74
|
+
if not isinstance(found, Agent):
|
|
75
|
+
raise ToolFailure(f"No agent {named!r} that you can read")
|
|
76
|
+
return found
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def sub_conversation_tools(session: StrategySession, conversation_id: str) -> list[RuntimeTool]:
|
|
80
|
+
"""`delegate`, `start_task` and `stop_task` for one turn. The lock keeps
|
|
81
|
+
the calls of one step from starting more tasks than the limit between
|
|
82
|
+
them; only one turn runs on a conversation at a time."""
|
|
83
|
+
starting = asyncio.Lock()
|
|
84
|
+
|
|
85
|
+
async def start(agent_now: EffectiveAgent, params: dict, call_id: str, agent_id, background: bool):
|
|
86
|
+
goal = params.get('goal')
|
|
87
|
+
if not isinstance(goal, str) or not goal.strip():
|
|
88
|
+
raise ToolFailure("`goal` is required")
|
|
89
|
+
parent = await session.get(conversation_id)
|
|
90
|
+
if await _depth(session, parent) >= conf.max_delegation_depth():
|
|
91
|
+
raise ToolFailure(
|
|
92
|
+
"This conversation is as deep as sub-conversations nest "
|
|
93
|
+
f"(AGENTS_MAX_DELEGATION_DEPTH is {conf.max_delegation_depth()}); do the work here."
|
|
94
|
+
)
|
|
95
|
+
agent_id = agent_id or parent.agent_id
|
|
96
|
+
context_ids = list(params.get('context_ids') or [])
|
|
97
|
+
readable = await session.get_many(context_ids)
|
|
98
|
+
missing = [entity_id for entity_id in context_ids if entity_id not in readable]
|
|
99
|
+
if missing:
|
|
100
|
+
raise ToolFailure(f"Not readable to you: {', '.join(missing)}")
|
|
101
|
+
async with starting:
|
|
102
|
+
if background:
|
|
103
|
+
running = await running_tasks(session, conversation_id)
|
|
104
|
+
if len(running) >= agent_now.max_tasks:
|
|
105
|
+
listed = '\n'.join(f"- {task.entity_id}: {task.title}" for task in running)
|
|
106
|
+
raise ToolFailure(
|
|
107
|
+
f"{len(running)} tasks are running, this agent's limit. Wait for one to report back, "
|
|
108
|
+
f"or stop one with `stop_task`:\n{listed}"
|
|
109
|
+
)
|
|
110
|
+
child = await session.save(session.create(
|
|
111
|
+
Conversation, parent_id=conversation_id, agent_id=agent_id, title=goal[:80],
|
|
112
|
+
context_ids=context_ids, deliver_to_parent=background, source_call_id=call_id,
|
|
113
|
+
status=ConversationStatus.RUNNING, last_active_at=time.time(),
|
|
114
|
+
))
|
|
115
|
+
await session.save(session.create(
|
|
116
|
+
Message, parent_id=child.entity_id, role=MessageRole.SYSTEM, content=NOTE.format(parent=conversation_id),
|
|
117
|
+
))
|
|
118
|
+
await session.save(session.create(
|
|
119
|
+
Message, parent_id=child.entity_id, role=MessageRole.USER, content=goal,
|
|
120
|
+
))
|
|
121
|
+
request, _ = await session.execute(run_turn(child), wait=not background)
|
|
122
|
+
return child, request
|
|
123
|
+
|
|
124
|
+
async def delegate(agent_now: EffectiveAgent, params: dict, call_id: str) -> str:
|
|
125
|
+
agent = await _agent(session, str(params.get('agent')))
|
|
126
|
+
background = bool(params.get('background'))
|
|
127
|
+
child, request = await start(agent_now, params, call_id, agent.entity_id, background)
|
|
128
|
+
if background:
|
|
129
|
+
return json.dumps({'conversation_id': child.entity_id})
|
|
130
|
+
if request.status != 'succeeded':
|
|
131
|
+
raise ToolFailure(
|
|
132
|
+
f"The sub-conversation {child.entity_id} did not finish: {request.error or request.status}"
|
|
133
|
+
)
|
|
134
|
+
return json.dumps({
|
|
135
|
+
'conversation_id': child.entity_id,
|
|
136
|
+
'status': request.ret_val.get('status'), 'text': request.ret_val.get('text'),
|
|
137
|
+
**({'cut_off': True} if request.ret_val.get('cut_off') else {}),
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
async def start_task(agent_now: EffectiveAgent, params: dict, call_id: str) -> str:
|
|
141
|
+
child, _ = await start(agent_now, params, call_id, None, background=True)
|
|
142
|
+
return json.dumps({'conversation_id': child.entity_id})
|
|
143
|
+
|
|
144
|
+
async def stop_task(_agent_now: EffectiveAgent, params: dict, _call_id: str) -> str:
|
|
145
|
+
task_id = str(params.get('task'))
|
|
146
|
+
try:
|
|
147
|
+
task = await session.get(task_id)
|
|
148
|
+
except (NotFound, Forbidden, InvalidRequest):
|
|
149
|
+
task = None
|
|
150
|
+
if not isinstance(task, Conversation) or task.parent_id != conversation_id:
|
|
151
|
+
raise ToolFailure(f"{task_id} is not a sub-conversation of this conversation")
|
|
152
|
+
if task.status is not ConversationStatus.RUNNING:
|
|
153
|
+
return f"{task_id} is not running."
|
|
154
|
+
await session.execute(StrategyRequestPayload('UpdateConversation', {'stop': True}, task_id))
|
|
155
|
+
return f"Stopping {task_id}." + (" It reports back once it has stopped." if task.deliver_to_parent else "")
|
|
156
|
+
|
|
157
|
+
ids = {"type": "array", "items": {"type": "string"}, "description": "Entities rendered for it on its first turn"}
|
|
158
|
+
goal = {"type": "string", "description": "Its first message. It does not see this conversation's messages, so say everything it needs"}
|
|
159
|
+
return [
|
|
160
|
+
RuntimeTool(
|
|
161
|
+
ToolDef(
|
|
162
|
+
'delegate',
|
|
163
|
+
"Hand a goal to another agent in a sub-conversation of this one. By default you wait, and get how its "
|
|
164
|
+
"turn ended and its final reply as `text`. To do several things at once, call `delegate` several "
|
|
165
|
+
"times in the same step: they run in parallel and you get every result together. Use `background` "
|
|
166
|
+
"for long work the person is not waiting on, or when they want to keep talking meanwhile: you get the "
|
|
167
|
+
"sub-conversation's id now and its final reply later as a message. To work on something yourself in "
|
|
168
|
+
"the background, use `start_task`.",
|
|
169
|
+
{
|
|
170
|
+
"type": "object",
|
|
171
|
+
"properties": {
|
|
172
|
+
"agent": {"type": "string", "description": "The agent's key or id"},
|
|
173
|
+
"goal": goal,
|
|
174
|
+
"context_ids": ids,
|
|
175
|
+
"background": {"type": "boolean"},
|
|
176
|
+
},
|
|
177
|
+
"required": ["agent", "goal"],
|
|
178
|
+
},
|
|
179
|
+
),
|
|
180
|
+
delegate,
|
|
181
|
+
),
|
|
182
|
+
RuntimeTool(
|
|
183
|
+
ToolDef(
|
|
184
|
+
'start_task',
|
|
185
|
+
"Work on a goal yourself in the background, in a task (a sub-conversation of this one), so you and "
|
|
186
|
+
"the person can keep talking meanwhile. You get the task's id now. Its final reply arrives later as a "
|
|
187
|
+
"message, and you take a turn to act on it. Start several to do several things at once. A task keeps "
|
|
188
|
+
"running if this conversation is stopped; `stop_task` stops it.",
|
|
189
|
+
{
|
|
190
|
+
"type": "object",
|
|
191
|
+
"properties": {"goal": goal, "context_ids": ids},
|
|
192
|
+
"required": ["goal"],
|
|
193
|
+
},
|
|
194
|
+
),
|
|
195
|
+
start_task,
|
|
196
|
+
),
|
|
197
|
+
RuntimeTool(
|
|
198
|
+
ToolDef(
|
|
199
|
+
'stop_task',
|
|
200
|
+
"Stop a running task, or a sub-conversation of this one. It reports back its text so far and the tool "
|
|
201
|
+
"calls it made. Tasks it started itself keep running.",
|
|
202
|
+
{
|
|
203
|
+
"type": "object",
|
|
204
|
+
"properties": {"task": {"type": "string", "description": "The id `start_task` or `delegate` returned"}},
|
|
205
|
+
"required": ["task"],
|
|
206
|
+
},
|
|
207
|
+
),
|
|
208
|
+
stop_task,
|
|
209
|
+
),
|
|
210
|
+
]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
async def running_tasks(session: StrategySession, conversation_id: str) -> list[Conversation]:
|
|
214
|
+
"""The background sub-conversations of a conversation that are running."""
|
|
215
|
+
return await session.list_all(EntityFilter(
|
|
216
|
+
type_ids=_CONVERSATIONS, parent_id=conversation_id,
|
|
217
|
+
where=AllOf((Equal('status', ConversationStatus.RUNNING.value), Equal('deliver_to_parent', True))),
|
|
218
|
+
))
|
|
File without changes
|
agents/entities/agent.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
from graphcore.public.entities import Entity, register_entity
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@register_entity()
|
|
7
|
+
class Agent(Entity):
|
|
8
|
+
name: str = ''
|
|
9
|
+
description: str = ''
|
|
10
|
+
instruction_ids: list[str] = []
|
|
11
|
+
skill_ids: list[str] = []
|
|
12
|
+
model: Optional[str] = None
|
|
13
|
+
compaction_threshold: Optional[float] = None
|
|
14
|
+
debug_context: bool = False
|
|
15
|
+
max_tasks: Optional[int] = None
|
|
16
|
+
start_address: Optional[str] = None
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from enum import StrEnum
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
from graphcore.public.entities import Entity, register_entity
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ConversationStatus(StrEnum):
|
|
8
|
+
IDLE = 'idle'
|
|
9
|
+
RUNNING = 'running'
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@register_entity()
|
|
13
|
+
class Conversation(Entity):
|
|
14
|
+
agent_id: Optional[str] = None
|
|
15
|
+
title: str = ''
|
|
16
|
+
status: ConversationStatus = ConversationStatus.IDLE
|
|
17
|
+
context_ids: list[str] = []
|
|
18
|
+
model: Optional[str] = None
|
|
19
|
+
usage: dict = {}
|
|
20
|
+
stop_requested: bool = False
|
|
21
|
+
deliver_to_parent: bool = False
|
|
22
|
+
last_active_at: Optional[float] = None
|
|
23
|
+
source_call_id: Optional[str] = None
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from enum import StrEnum
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
from graphcore.public.entities import Entity, register_entity
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MessageRole(StrEnum):
|
|
8
|
+
USER = 'user'
|
|
9
|
+
ASSISTANT = 'assistant'
|
|
10
|
+
SYSTEM = 'system'
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ToolCallState(StrEnum):
|
|
14
|
+
RUNNING = 'running'
|
|
15
|
+
COMPLETED = 'completed'
|
|
16
|
+
ERROR = 'error'
|
|
17
|
+
INTERRUPTED = 'interrupted'
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@register_entity()
|
|
21
|
+
class Message(Entity):
|
|
22
|
+
role: MessageRole = MessageRole.USER
|
|
23
|
+
content: str = ''
|
|
24
|
+
context_ids: list[str] = []
|
|
25
|
+
tool_calls: list[dict] = []
|
|
26
|
+
source_conversation_id: Optional[str] = None
|
|
27
|
+
summary_through: Optional[str] = None
|
|
28
|
+
read_through: Optional[str] = None
|
|
29
|
+
context_versions: dict = {}
|
|
30
|
+
provider_state: dict = {}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from typing import ClassVar, Optional
|
|
2
|
+
|
|
3
|
+
from graphcore.public.entities import Entity, register_entity
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@register_entity()
|
|
7
|
+
class AgentProfile(Entity):
|
|
8
|
+
dependent_on: ClassVar[tuple[str, ...]] = ('agent_id',)
|
|
9
|
+
|
|
10
|
+
agent_id: Optional[str] = None
|
|
11
|
+
instruction_ids: list[str] = []
|
|
12
|
+
skill_ids: list[str] = []
|
|
13
|
+
model: Optional[str] = None
|
|
14
|
+
compaction_threshold: Optional[float] = None
|
agents/entities/skill.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Generated by Django 5.2.19 on 2026-11-10 18:41
|
|
2
|
+
|
|
3
|
+
import django.db.models.deletion
|
|
4
|
+
from django.db import migrations, models
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Migration(migrations.Migration):
|
|
8
|
+
|
|
9
|
+
initial = True
|
|
10
|
+
|
|
11
|
+
dependencies = [
|
|
12
|
+
('graphcore', '0003_entity_key'),
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
operations = [
|
|
16
|
+
migrations.CreateModel(
|
|
17
|
+
name='AgentModel',
|
|
18
|
+
fields=[
|
|
19
|
+
('entitymodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='graphcore.entitymodel')),
|
|
20
|
+
('name', models.CharField(blank=True, default='', max_length=255)),
|
|
21
|
+
('description', models.TextField(blank=True, default='')),
|
|
22
|
+
('instruction_ids', models.JSONField(default=list)),
|
|
23
|
+
('skill_ids', models.JSONField(default=list)),
|
|
24
|
+
('model', models.CharField(max_length=64, null=True)),
|
|
25
|
+
],
|
|
26
|
+
bases=('graphcore.entitymodel',),
|
|
27
|
+
),
|
|
28
|
+
migrations.CreateModel(
|
|
29
|
+
name='AgentProfileModel',
|
|
30
|
+
fields=[
|
|
31
|
+
('entitymodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='graphcore.entitymodel')),
|
|
32
|
+
('agent_id', models.CharField(db_index=True, max_length=96, null=True)),
|
|
33
|
+
('instruction_ids', models.JSONField(default=list)),
|
|
34
|
+
('skill_ids', models.JSONField(default=list)),
|
|
35
|
+
('model', models.CharField(max_length=64, null=True)),
|
|
36
|
+
],
|
|
37
|
+
bases=('graphcore.entitymodel',),
|
|
38
|
+
),
|
|
39
|
+
migrations.CreateModel(
|
|
40
|
+
name='ConversationModel',
|
|
41
|
+
fields=[
|
|
42
|
+
('entitymodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='graphcore.entitymodel')),
|
|
43
|
+
('agent_id', models.CharField(db_index=True, max_length=96, null=True)),
|
|
44
|
+
('title', models.CharField(blank=True, default='', max_length=255)),
|
|
45
|
+
('status', models.CharField(choices=[('idle', 'idle'), ('running', 'running')], db_index=True, default='idle', max_length=16)),
|
|
46
|
+
('context_ids', models.JSONField(default=list)),
|
|
47
|
+
('model', models.CharField(max_length=64, null=True)),
|
|
48
|
+
('usage', models.JSONField(default=dict)),
|
|
49
|
+
('stop_requested', models.BooleanField(default=False)),
|
|
50
|
+
('deliver_to_parent', models.BooleanField(default=False)),
|
|
51
|
+
],
|
|
52
|
+
bases=('graphcore.entitymodel',),
|
|
53
|
+
),
|
|
54
|
+
migrations.CreateModel(
|
|
55
|
+
name='InstructionModel',
|
|
56
|
+
fields=[
|
|
57
|
+
('entitymodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='graphcore.entitymodel')),
|
|
58
|
+
('name', models.CharField(blank=True, default='', max_length=255)),
|
|
59
|
+
('text', models.TextField(blank=True, default='')),
|
|
60
|
+
],
|
|
61
|
+
bases=('graphcore.entitymodel',),
|
|
62
|
+
),
|
|
63
|
+
migrations.CreateModel(
|
|
64
|
+
name='MessageModel',
|
|
65
|
+
fields=[
|
|
66
|
+
('entitymodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='graphcore.entitymodel')),
|
|
67
|
+
('role', models.CharField(choices=[('user', 'user'), ('assistant', 'assistant'), ('system', 'system')], db_index=True, default='user', max_length=16)),
|
|
68
|
+
('content', models.TextField(blank=True, default='')),
|
|
69
|
+
('context_ids', models.JSONField(default=list)),
|
|
70
|
+
('tool_calls', models.JSONField(default=list)),
|
|
71
|
+
('source_conversation_id', models.CharField(max_length=96, null=True)),
|
|
72
|
+
('summary_through', models.CharField(max_length=96, null=True)),
|
|
73
|
+
('read_through', models.CharField(max_length=96, null=True)),
|
|
74
|
+
('provider_state', models.JSONField(default=dict)),
|
|
75
|
+
],
|
|
76
|
+
bases=('graphcore.entitymodel',),
|
|
77
|
+
),
|
|
78
|
+
migrations.CreateModel(
|
|
79
|
+
name='SkillModel',
|
|
80
|
+
fields=[
|
|
81
|
+
('entitymodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='graphcore.entitymodel')),
|
|
82
|
+
('name', models.CharField(blank=True, default='', max_length=255)),
|
|
83
|
+
('description', models.TextField(blank=True, default='')),
|
|
84
|
+
('text', models.TextField(blank=True, default='')),
|
|
85
|
+
],
|
|
86
|
+
bases=('graphcore.entitymodel',),
|
|
87
|
+
),
|
|
88
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from django.db import migrations, models
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Migration(migrations.Migration):
|
|
5
|
+
|
|
6
|
+
dependencies = [
|
|
7
|
+
('agents', '0001_initial'),
|
|
8
|
+
]
|
|
9
|
+
|
|
10
|
+
operations = [
|
|
11
|
+
migrations.AddField(
|
|
12
|
+
model_name='messagemodel',
|
|
13
|
+
name='context_versions',
|
|
14
|
+
field=models.JSONField(default=dict),
|
|
15
|
+
),
|
|
16
|
+
]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from django.db import migrations, models
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Migration(migrations.Migration):
|
|
5
|
+
|
|
6
|
+
dependencies = [
|
|
7
|
+
('agents', '0002_message_context_versions'),
|
|
8
|
+
]
|
|
9
|
+
|
|
10
|
+
operations = [
|
|
11
|
+
migrations.AddField(
|
|
12
|
+
model_name='agentmodel',
|
|
13
|
+
name='compaction_threshold',
|
|
14
|
+
field=models.FloatField(null=True),
|
|
15
|
+
),
|
|
16
|
+
migrations.AddField(
|
|
17
|
+
model_name='agentprofilemodel',
|
|
18
|
+
name='compaction_threshold',
|
|
19
|
+
field=models.FloatField(null=True),
|
|
20
|
+
),
|
|
21
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from django.db import migrations, models
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Migration(migrations.Migration):
|
|
5
|
+
|
|
6
|
+
dependencies = [
|
|
7
|
+
('agents', '0003_compaction_threshold'),
|
|
8
|
+
]
|
|
9
|
+
|
|
10
|
+
operations = [
|
|
11
|
+
migrations.AddField(
|
|
12
|
+
model_name='agentmodel',
|
|
13
|
+
name='debug_context',
|
|
14
|
+
field=models.BooleanField(default=False),
|
|
15
|
+
),
|
|
16
|
+
]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from django.db import migrations, models
|
|
2
|
+
from django.db.models import Max
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def backfill(apps, schema_editor):
|
|
6
|
+
"""A conversation was last active when its latest message was created, or
|
|
7
|
+
when it was created if it has none."""
|
|
8
|
+
conversations = apps.get_model('agents', 'ConversationModel')
|
|
9
|
+
messages = apps.get_model('agents', 'MessageModel')
|
|
10
|
+
latest = dict(
|
|
11
|
+
messages.objects.values('parent_id').annotate(at=Max('created_at')).values_list('parent_id', 'at')
|
|
12
|
+
)
|
|
13
|
+
changed = []
|
|
14
|
+
for conversation in conversations.objects.filter(last_active_at__isnull=True).only('entity_id', 'created_at'):
|
|
15
|
+
at = latest.get(conversation.entity_id) or conversation.created_at
|
|
16
|
+
conversation.last_active_at = at.timestamp()
|
|
17
|
+
changed.append(conversation)
|
|
18
|
+
conversations.objects.bulk_update(changed, ['last_active_at'], batch_size=500)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Migration(migrations.Migration):
|
|
22
|
+
|
|
23
|
+
dependencies = [
|
|
24
|
+
('agents', '0004_agent_debug_context'),
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
operations = [
|
|
28
|
+
migrations.AddField(
|
|
29
|
+
model_name='conversationmodel',
|
|
30
|
+
name='last_active_at',
|
|
31
|
+
field=models.FloatField(db_index=True, null=True),
|
|
32
|
+
),
|
|
33
|
+
migrations.RunPython(backfill, migrations.RunPython.noop),
|
|
34
|
+
]
|