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
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""OpenAI's Responses API behind the provider port. Nothing is stored at the
|
|
2
|
+
vendor: every call sends the full input."""
|
|
3
|
+
import json
|
|
4
|
+
from typing import AsyncIterator, Optional
|
|
5
|
+
|
|
6
|
+
import openai
|
|
7
|
+
|
|
8
|
+
from agents.providers.port import Done, Event, ModelRequest, Provider, ProviderError, TextDelta, ToolCall, Turn, Usage
|
|
9
|
+
|
|
10
|
+
_RETRYABLE_CODES = {'server_error': 'server_error', 'rate_limit_exceeded': 'rate_limit'}
|
|
11
|
+
_OVERFLOW = ('context_length_exceeded', 'context window')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OpenAIProvider(Provider):
|
|
15
|
+
name = 'openai'
|
|
16
|
+
|
|
17
|
+
def __init__(self, api_key: Optional[str], read_timeout: float, http_client=None):
|
|
18
|
+
super().__init__(api_key, read_timeout)
|
|
19
|
+
# Retries are the executor's: every retry is an attempt that resumes.
|
|
20
|
+
self._client = openai.AsyncOpenAI(
|
|
21
|
+
api_key=api_key, max_retries=0, http_client=http_client,
|
|
22
|
+
timeout=openai.Timeout(read_timeout, connect=10.0),
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
async def stream(self, request: ModelRequest) -> AsyncIterator[Event]:
|
|
26
|
+
try:
|
|
27
|
+
try:
|
|
28
|
+
async for event in self._events(wire_request(request)):
|
|
29
|
+
yield event
|
|
30
|
+
except openai.BadRequestError as exc:
|
|
31
|
+
# Refused before any output. Reasoning items are accepted only
|
|
32
|
+
# after the turns they were written after; without them the
|
|
33
|
+
# model answers this call from the text and calls alone.
|
|
34
|
+
if _overflow(exc) or not any(turn.provider_state for turn in request.turns):
|
|
35
|
+
raise
|
|
36
|
+
async for event in self._events(wire_request(request, with_state=False)):
|
|
37
|
+
yield event
|
|
38
|
+
except openai.APIError as exc:
|
|
39
|
+
raise _provider_error(exc) from exc
|
|
40
|
+
|
|
41
|
+
async def _events(self, params: dict) -> AsyncIterator[Event]:
|
|
42
|
+
final = None
|
|
43
|
+
refused = False
|
|
44
|
+
stream = await self._client.responses.create(**params)
|
|
45
|
+
try:
|
|
46
|
+
async for event in stream:
|
|
47
|
+
if event.type == 'response.output_text.delta':
|
|
48
|
+
yield TextDelta(event.delta)
|
|
49
|
+
elif event.type == 'response.refusal.delta':
|
|
50
|
+
refused = True
|
|
51
|
+
yield TextDelta(event.delta)
|
|
52
|
+
elif event.type == 'response.output_item.done' and event.item.type == 'function_call':
|
|
53
|
+
yield _tool_call(event.item)
|
|
54
|
+
elif event.type in ('response.completed', 'response.incomplete'):
|
|
55
|
+
final = event.response
|
|
56
|
+
elif event.type == 'response.failed':
|
|
57
|
+
error = event.response.error
|
|
58
|
+
raise _stream_error(error.code if error else None, error.message if error else 'The response failed')
|
|
59
|
+
elif event.type == 'error':
|
|
60
|
+
raise _stream_error(event.code, event.message)
|
|
61
|
+
finally:
|
|
62
|
+
await stream.close()
|
|
63
|
+
if final is None:
|
|
64
|
+
raise ProviderError('incomplete_stream', 'The stream ended before the reply did', retryable=True)
|
|
65
|
+
|
|
66
|
+
reason = final.incomplete_details.reason if final.incomplete_details else None
|
|
67
|
+
if refused or reason == 'content_filter':
|
|
68
|
+
stop = 'refusal'
|
|
69
|
+
elif reason == 'max_output_tokens':
|
|
70
|
+
stop = 'max_tokens'
|
|
71
|
+
elif any(item.type == 'function_call' for item in final.output):
|
|
72
|
+
stop = 'tool_calls'
|
|
73
|
+
else:
|
|
74
|
+
stop = 'end'
|
|
75
|
+
usage = final.usage
|
|
76
|
+
cached = usage.input_tokens_details.cached_tokens if usage and usage.input_tokens_details else 0
|
|
77
|
+
yield Done(
|
|
78
|
+
stop,
|
|
79
|
+
Usage(
|
|
80
|
+
input_tokens=usage.input_tokens if usage else 0, output_tokens=usage.output_tokens if usage else 0,
|
|
81
|
+
cached_input_tokens=cached or 0,
|
|
82
|
+
),
|
|
83
|
+
# The reply's items as sent, so its encrypted reasoning goes back where it was.
|
|
84
|
+
provider_state={'output': [item.model_dump(mode='json', exclude_none=True) for item in final.output]},
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def wire_request(request: ModelRequest, with_state: bool = True) -> dict:
|
|
89
|
+
"""The Responses API request for `request`. Caching is the vendor's own,
|
|
90
|
+
keyed by the conversation."""
|
|
91
|
+
params = {
|
|
92
|
+
"model": request.model,
|
|
93
|
+
"input": [item for turn in request.turns for item in _items(turn, with_state)],
|
|
94
|
+
"tools": [
|
|
95
|
+
{"type": "function", "name": tool.name, "description": tool.description,
|
|
96
|
+
"parameters": tool.schema, "strict": False}
|
|
97
|
+
for tool in request.tools
|
|
98
|
+
],
|
|
99
|
+
"max_output_tokens": request.max_output_tokens,
|
|
100
|
+
"store": False,
|
|
101
|
+
"include": ["reasoning.encrypted_content"],
|
|
102
|
+
"prompt_cache_key": request.cache_key,
|
|
103
|
+
"stream": True,
|
|
104
|
+
}
|
|
105
|
+
if request.prefix:
|
|
106
|
+
params["instructions"] = '\n\n'.join(request.prefix)
|
|
107
|
+
if request.tool_choice == 'none':
|
|
108
|
+
params["tool_choice"] = 'none'
|
|
109
|
+
return params
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _items(turn: Turn, with_state: bool) -> list[dict]:
|
|
113
|
+
if turn.role == 'assistant':
|
|
114
|
+
stored = turn.provider_state.get('output') if with_state else None
|
|
115
|
+
if stored:
|
|
116
|
+
return [dict(item) for item in stored]
|
|
117
|
+
return [
|
|
118
|
+
*([{"role": "assistant", "content": turn.text}] if turn.text else []),
|
|
119
|
+
*(
|
|
120
|
+
{"type": "function_call", "call_id": call.id, "name": call.name, "arguments": json.dumps(call.params)}
|
|
121
|
+
for call in turn.calls
|
|
122
|
+
),
|
|
123
|
+
]
|
|
124
|
+
items = [
|
|
125
|
+
{"type": "function_call_output", "call_id": result.call_id,
|
|
126
|
+
"output": f"Error: {result.content}" if result.is_error else result.content}
|
|
127
|
+
for result in turn.results
|
|
128
|
+
]
|
|
129
|
+
if turn.text or not items:
|
|
130
|
+
items.append({"role": "user", "content": turn.text or '(empty message)'})
|
|
131
|
+
return items
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _tool_call(item) -> ToolCall:
|
|
135
|
+
try:
|
|
136
|
+
params = json.loads(item.arguments or '{}')
|
|
137
|
+
except ValueError:
|
|
138
|
+
params = None
|
|
139
|
+
if not isinstance(params, dict):
|
|
140
|
+
return ToolCall(item.call_id, item.name, {}, error='The params are not a JSON object')
|
|
141
|
+
return ToolCall(item.call_id, item.name, params)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _overflow(exc: openai.APIError) -> bool:
|
|
145
|
+
return any(marker in f"{getattr(exc, 'code', '')} {exc}" for marker in _OVERFLOW)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _stream_error(code: Optional[str], message: str) -> ProviderError:
|
|
149
|
+
if code in _RETRYABLE_CODES:
|
|
150
|
+
return ProviderError(_RETRYABLE_CODES[code], message, retryable=True)
|
|
151
|
+
if any(marker in f"{code} {message}" for marker in _OVERFLOW):
|
|
152
|
+
return ProviderError('context_overflow', message, retryable=False)
|
|
153
|
+
return ProviderError('invalid_request', message, retryable=False)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _provider_error(exc: openai.APIError) -> ProviderError:
|
|
157
|
+
message = str(exc)
|
|
158
|
+
if isinstance(exc, openai.APITimeoutError):
|
|
159
|
+
return ProviderError('timeout', message, retryable=True)
|
|
160
|
+
if isinstance(exc, openai.APIConnectionError):
|
|
161
|
+
return ProviderError('connection', message, retryable=True)
|
|
162
|
+
if isinstance(exc, openai.APIStatusError):
|
|
163
|
+
if isinstance(exc, openai.RateLimitError):
|
|
164
|
+
# A spent quota is a 429 that no wait fixes.
|
|
165
|
+
if exc.code == 'insufficient_quota':
|
|
166
|
+
return ProviderError('auth', message, retryable=False)
|
|
167
|
+
return ProviderError('rate_limit', message, retryable=True)
|
|
168
|
+
if isinstance(exc, openai.InternalServerError):
|
|
169
|
+
return ProviderError('overloaded' if exc.status_code == 503 else 'server_error', message, retryable=True)
|
|
170
|
+
if isinstance(exc, (openai.AuthenticationError, openai.PermissionDeniedError)):
|
|
171
|
+
return ProviderError('auth', message, retryable=False)
|
|
172
|
+
if isinstance(exc, openai.NotFoundError) or exc.code == 'model_not_found':
|
|
173
|
+
return ProviderError('unknown_model', message, retryable=False)
|
|
174
|
+
if exc.status_code == 413 or _overflow(exc):
|
|
175
|
+
return ProviderError('context_overflow', message, retryable=False)
|
|
176
|
+
return ProviderError('invalid_request', message, retryable=False)
|
|
177
|
+
return ProviderError('incomplete_stream', message, retryable=True)
|
agents/providers/port.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""The provider port: what a turn sends a model and what it reads back
|
|
2
|
+
(docs/app_design/agents/AGENTS_TDD.md, Providers)."""
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import AsyncIterator, ClassVar, Literal, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class ToolDef:
|
|
10
|
+
name: str
|
|
11
|
+
description: str
|
|
12
|
+
schema: dict
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class ToolCall:
|
|
17
|
+
id: str
|
|
18
|
+
name: str
|
|
19
|
+
params: dict
|
|
20
|
+
# Params that did not parse; the call is recorded with this as its result and not dispatched.
|
|
21
|
+
error: Optional[str] = None
|
|
22
|
+
provider_state: dict = field(default_factory=dict)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class ToolResult:
|
|
27
|
+
call_id: str
|
|
28
|
+
name: str
|
|
29
|
+
content: str
|
|
30
|
+
is_error: bool = False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Turn:
|
|
35
|
+
role: Literal['user', 'assistant']
|
|
36
|
+
text: str = ''
|
|
37
|
+
calls: tuple[ToolCall, ...] = ()
|
|
38
|
+
results: tuple[ToolResult, ...] = ()
|
|
39
|
+
provider_state: dict = field(default_factory=dict)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class ModelRequest:
|
|
44
|
+
model: str
|
|
45
|
+
prefix: tuple[str, ...]
|
|
46
|
+
tools: tuple[ToolDef, ...]
|
|
47
|
+
turns: tuple[Turn, ...]
|
|
48
|
+
tool_choice: Literal['auto', 'none'] = 'auto'
|
|
49
|
+
max_output_tokens: int = 8192
|
|
50
|
+
cache_key: str = ''
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class TextDelta:
|
|
55
|
+
text: str
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class Usage:
|
|
60
|
+
input_tokens: int
|
|
61
|
+
output_tokens: int
|
|
62
|
+
cached_input_tokens: int = 0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Done:
|
|
67
|
+
stop: Literal['end', 'tool_calls', 'max_tokens', 'refusal']
|
|
68
|
+
usage: Usage
|
|
69
|
+
provider_state: dict = field(default_factory=dict)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
Event = TextDelta | ToolCall | Done
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ProviderError(Exception):
|
|
76
|
+
def __init__(self, code: str, message: str, *, retryable: bool):
|
|
77
|
+
super().__init__(f"{code}: {message}")
|
|
78
|
+
self.code = code
|
|
79
|
+
self.message = message
|
|
80
|
+
self.retryable = retryable
|
|
81
|
+
|
|
82
|
+
def __reduce__(self):
|
|
83
|
+
return _provider_error, (type(self), self.code, self.message, self.retryable)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _provider_error(cls, code: str, message: str, retryable: bool) -> 'ProviderError':
|
|
87
|
+
return cls(code, message, retryable=retryable)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Provider(ABC):
|
|
91
|
+
name: ClassVar[str]
|
|
92
|
+
needs_key: ClassVar[bool] = True
|
|
93
|
+
|
|
94
|
+
def __init__(self, api_key: Optional[str], read_timeout: float):
|
|
95
|
+
self.api_key = api_key
|
|
96
|
+
self.read_timeout = read_timeout
|
|
97
|
+
|
|
98
|
+
@abstractmethod
|
|
99
|
+
def stream(self, request: ModelRequest) -> AsyncIterator[Event]:
|
|
100
|
+
"""Yields text as it arrives, each tool call once its params are
|
|
101
|
+
complete, and exactly one `Done`, last. Raises only `ProviderError`."""
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from importlib import import_module
|
|
2
|
+
|
|
3
|
+
from agents import conf
|
|
4
|
+
from agents.providers.port import Provider, ProviderError
|
|
5
|
+
|
|
6
|
+
_ADAPTERS = {
|
|
7
|
+
'fake': 'agents.providers.fake.FakeProvider',
|
|
8
|
+
'anthropic': 'agents.providers.anthropic.AnthropicProvider',
|
|
9
|
+
'openai': 'agents.providers.openai.OpenAIProvider',
|
|
10
|
+
'google': 'agents.providers.google.GoogleProvider',
|
|
11
|
+
}
|
|
12
|
+
_KEYLESS = frozenset({'fake'})
|
|
13
|
+
_built: dict[str, Provider] = {}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def available(model_id: str) -> bool:
|
|
17
|
+
"""Whether a turn on `model_id` can reach its provider."""
|
|
18
|
+
name = model_id.partition('/')[0]
|
|
19
|
+
return name in _ADAPTERS and (name in _KEYLESS or conf.provider_key(name) is not None)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def provider_for(model_id: str) -> tuple[Provider, str]:
|
|
23
|
+
"""The provider serving `model_id`, built once per process, and the model
|
|
24
|
+
name to send it."""
|
|
25
|
+
name, _, model = model_id.partition('/')
|
|
26
|
+
if name not in _built:
|
|
27
|
+
path = _ADAPTERS.get(name)
|
|
28
|
+
if path is None:
|
|
29
|
+
raise ProviderError('unknown_model', f"No provider named {name!r}", retryable=False)
|
|
30
|
+
module, _, cls_name = path.rpartition('.')
|
|
31
|
+
provider_cls = getattr(import_module(module), cls_name)
|
|
32
|
+
key = conf.provider_key(name)
|
|
33
|
+
if provider_cls.needs_key and not key:
|
|
34
|
+
raise ProviderError('no_key', f"{name.upper()}_API_KEY is not set", retryable=False)
|
|
35
|
+
_built[name] = provider_cls(key, conf.provider_read_timeout())
|
|
36
|
+
return _built[name], model
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def reset() -> None:
|
|
40
|
+
_built.clear()
|
agents/routes.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Replacing the oldest messages of a long conversation with a summary in the
|
|
2
|
+
prompt (docs/app_design/agents/AGENTS_TDD.md, Turns: Compaction)."""
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from agents import conf
|
|
6
|
+
from agents.entities.conversation import Conversation
|
|
7
|
+
from agents.entities.message import Message, MessageRole
|
|
8
|
+
from agents.runtime.effective_agent import EffectiveAgent
|
|
9
|
+
|
|
10
|
+
SUMMARY_REQUEST = (
|
|
11
|
+
"Summarize the conversation so far for your own later use: what the person wants, what was decided, "
|
|
12
|
+
"what you did and what it returned (keep ids and addresses), and what is still open. Reply with the "
|
|
13
|
+
"summary only."
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def due(conversation: Conversation, agent: EffectiveAgent) -> bool:
|
|
18
|
+
last_input = conversation.usage.get('last', {}).get('input_tokens', 0)
|
|
19
|
+
return last_input > agent.compaction_threshold * conf.model_entry(agent.model)['context_size']
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def to_cover(rest: list[Message], half: bool) -> Optional[list[Message]]:
|
|
23
|
+
"""The messages a summary would replace: all of those after the last
|
|
24
|
+
summary, or their older half when even the summary request would not fit.
|
|
25
|
+
None when they hold no reply, so there is nothing worth summarizing."""
|
|
26
|
+
covered = rest[:(len(rest) + 1) // 2] if half else rest
|
|
27
|
+
if not any(message.role is MessageRole.ASSISTANT for message in covered):
|
|
28
|
+
return None
|
|
29
|
+
return covered
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Context entities shown to the model as stored messages
|
|
2
|
+
(docs/app_design/agents/AGENTS_TDD.md, Turns: Context)."""
|
|
3
|
+
import hashlib
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from mcp import Client
|
|
9
|
+
|
|
10
|
+
from agents.entities.message import Message
|
|
11
|
+
|
|
12
|
+
_VERSION = re.compile(r"version: (\S+)")
|
|
13
|
+
_ADDRESS = re.compile(r"address: (\S+)")
|
|
14
|
+
_NEVER = object()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class ContextUpdate:
|
|
19
|
+
"""What a turn saves before a provider call: a context message with the
|
|
20
|
+
renders of entities the conversation has not shown at their current
|
|
21
|
+
version, and a notice naming the ones that changed since the turn last said so."""
|
|
22
|
+
renders: list[str] = field(default_factory=list)
|
|
23
|
+
versions: dict = field(default_factory=dict)
|
|
24
|
+
changed: list[str] = field(default_factory=list)
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def content(self) -> str:
|
|
28
|
+
return '\n\n---\n\n'.join([
|
|
29
|
+
"Context for this conversation, as it is now. Open an address to read its current state.",
|
|
30
|
+
*self.renders,
|
|
31
|
+
])
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def notice(self) -> str:
|
|
35
|
+
return '\n'.join(f"{address} changed since it was shown to you; open it to read it." for address in self.changed)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def shown_versions(messages: list[Message]) -> dict:
|
|
39
|
+
"""The version each entity was last shown at, by the context messages in `messages`."""
|
|
40
|
+
versions: dict = {}
|
|
41
|
+
for message in messages:
|
|
42
|
+
versions.update(message.context_versions)
|
|
43
|
+
return versions
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ContextTracker:
|
|
47
|
+
def __init__(self, client: Client):
|
|
48
|
+
self.client = client
|
|
49
|
+
# The version of each entity this turn last told the model about.
|
|
50
|
+
self._told: dict = {}
|
|
51
|
+
|
|
52
|
+
async def update(self, entity_ids: list[str], shown: dict, show: bool) -> ContextUpdate:
|
|
53
|
+
"""`shown` is what the prompt's context messages hold. With `show`,
|
|
54
|
+
every entity is compared with it; otherwise only one this turn has not seen yet."""
|
|
55
|
+
update = ContextUpdate()
|
|
56
|
+
for entity_id in dict.fromkeys(entity_ids):
|
|
57
|
+
text, version, address = await self._open(entity_id)
|
|
58
|
+
if show or entity_id not in self._told:
|
|
59
|
+
if shown.get(entity_id, _NEVER) != version:
|
|
60
|
+
update.renders.append(
|
|
61
|
+
text if text is not None else f"{entity_id} is not readable to you and was left out."
|
|
62
|
+
)
|
|
63
|
+
update.versions[entity_id] = version
|
|
64
|
+
elif self._told[entity_id] != version:
|
|
65
|
+
update.changed.append(address or entity_id)
|
|
66
|
+
self._told[entity_id] = version
|
|
67
|
+
return update
|
|
68
|
+
|
|
69
|
+
async def _open(self, entity_id: str) -> tuple[Optional[str], Optional[str], Optional[str]]:
|
|
70
|
+
result = await self.client.call_tool('open', {'at': entity_id})
|
|
71
|
+
if result.is_error:
|
|
72
|
+
return None, None, None
|
|
73
|
+
text = '\n'.join(part.text for part in result.content if getattr(part, 'text', None))
|
|
74
|
+
version, address = _VERSION.search(text), _ADDRESS.search(text)
|
|
75
|
+
return (
|
|
76
|
+
text, version.group(1) if version else hashlib.sha256(text.encode()).hexdigest(),
|
|
77
|
+
address.group(1) if address else None,
|
|
78
|
+
)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Runs a model's tool calls: the agent frontend's through an MCP client
|
|
2
|
+
connected as the sender, the runtime's own in process."""
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
from mcp import Client
|
|
8
|
+
|
|
9
|
+
from agents.entities.message import ToolCallState
|
|
10
|
+
from agents.providers.port import ToolDef
|
|
11
|
+
from agents.runtime.effective_agent import EffectiveAgent
|
|
12
|
+
from agents.runtime.tools import RuntimeTool, ToolFailure
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
# The frontend tools whose result names the strategy request they caused.
|
|
17
|
+
_STRATEGY_TOOLS = frozenset({'call'})
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Dispatcher:
|
|
21
|
+
def __init__(self, client: Client, runtime_tools: list[RuntimeTool]):
|
|
22
|
+
self.client = client
|
|
23
|
+
self.runtime_tools = {tool.definition.name: tool for tool in runtime_tools}
|
|
24
|
+
self.frontend_tools: frozenset[str] = frozenset()
|
|
25
|
+
|
|
26
|
+
async def tool_defs(self) -> tuple[ToolDef, ...]:
|
|
27
|
+
"""Read once per turn, so the list a model sees stays fixed for the turn."""
|
|
28
|
+
listed = (await self.client.list_tools()).tools
|
|
29
|
+
self.frontend_tools = frozenset(tool.name for tool in listed)
|
|
30
|
+
return (
|
|
31
|
+
*(ToolDef(tool.name, tool.description or '', tool.input_schema) for tool in listed),
|
|
32
|
+
*(tool.definition for tool in self.runtime_tools.values()),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
def refusal(self, call: dict) -> Optional[str]:
|
|
36
|
+
"""The one enforcement point before a call runs. The kernel enforces
|
|
37
|
+
the sender's permissions; a cap narrower than those is checked here."""
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
async def run(self, call: dict, agent: EffectiveAgent) -> dict:
|
|
41
|
+
"""The outcome of `call`, as the fields to set on its record."""
|
|
42
|
+
refusal = self.refusal(call)
|
|
43
|
+
if refusal is not None:
|
|
44
|
+
return _failed(refusal)
|
|
45
|
+
name, params = call['tool'], call['params']
|
|
46
|
+
try:
|
|
47
|
+
if name in self.runtime_tools:
|
|
48
|
+
return _completed(await self.runtime_tools[name].run(agent, params, call['id']))
|
|
49
|
+
if name not in self.frontend_tools:
|
|
50
|
+
return _failed(f"{name!r} is not a tool")
|
|
51
|
+
result = await self.client.call_tool(name, params)
|
|
52
|
+
except ToolFailure as exc:
|
|
53
|
+
return _failed(str(exc))
|
|
54
|
+
except Exception as exc:
|
|
55
|
+
logger.exception("Tool call %s failed", name)
|
|
56
|
+
return _failed(f"{type(exc).__name__}: {exc}")
|
|
57
|
+
text = '\n'.join(part.text for part in result.content if getattr(part, 'text', None))
|
|
58
|
+
if result.is_error:
|
|
59
|
+
return _failed(text)
|
|
60
|
+
return _completed(text, _request_id(text) if name in _STRATEGY_TOOLS else None)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _completed(result: str, request_id: Optional[str] = None) -> dict:
|
|
64
|
+
return {'state': ToolCallState.COMPLETED.value, 'result': result, 'request_id': request_id}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _failed(error: str) -> dict:
|
|
68
|
+
return {'state': ToolCallState.ERROR.value, 'error': error}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _request_id(text: str) -> Optional[str]:
|
|
72
|
+
try:
|
|
73
|
+
parsed = json.loads(text)
|
|
74
|
+
except ValueError:
|
|
75
|
+
return None
|
|
76
|
+
return parsed.get('request_id') if isinstance(parsed, dict) else None
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""What a turn runs with, assembled as its sender before every provider call."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from graphcore.public.errors import Forbidden, NotFound
|
|
6
|
+
from graphcore.public.strategies import StrategySession
|
|
7
|
+
|
|
8
|
+
from agents import conf
|
|
9
|
+
from agents.entities.agent import Agent
|
|
10
|
+
from agents.entities.conversation import Conversation
|
|
11
|
+
from agents.entities.instruction import Instruction
|
|
12
|
+
from agents.entities.skill import Skill
|
|
13
|
+
from agents.strategies.profiles import find_profile
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TurnFailure(Exception):
|
|
17
|
+
"""A failure the turn reports in the conversation and ends on."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class EffectiveAgent:
|
|
22
|
+
instructions: tuple[Instruction, ...]
|
|
23
|
+
skills: tuple[Skill, ...]
|
|
24
|
+
model: str
|
|
25
|
+
compaction_threshold: float
|
|
26
|
+
debug_context: bool
|
|
27
|
+
notices: tuple[str, ...]
|
|
28
|
+
max_tasks: int
|
|
29
|
+
start_address: Optional[str] = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def resolve(session: StrategySession, conversation: Conversation) -> EffectiveAgent:
|
|
33
|
+
try:
|
|
34
|
+
agent = await session.get(conversation.agent_id) if conversation.agent_id else None
|
|
35
|
+
except (NotFound, Forbidden):
|
|
36
|
+
agent = None
|
|
37
|
+
if not isinstance(agent, Agent):
|
|
38
|
+
raise TurnFailure("This conversation's agent no longer exists, or you can no longer read it")
|
|
39
|
+
profile = await find_profile(session, agent.entity_id)
|
|
40
|
+
|
|
41
|
+
notices: list[str] = []
|
|
42
|
+
instructions = await _readable(
|
|
43
|
+
session, [*agent.instruction_ids, *(profile.instruction_ids if profile else [])], Instruction, notices,
|
|
44
|
+
)
|
|
45
|
+
skills = await _readable(session, [*agent.skill_ids, *(profile.skill_ids if profile else [])], Skill, notices)
|
|
46
|
+
|
|
47
|
+
model = conversation.model or (profile.model if profile else None) or agent.model or conf.default_model()
|
|
48
|
+
if conf.model_entry(model) is None:
|
|
49
|
+
raise TurnFailure(f"{model} is not a model in AGENTS_MODELS")
|
|
50
|
+
threshold = next(
|
|
51
|
+
(layer.compaction_threshold for layer in (profile, agent) if layer and layer.compaction_threshold is not None),
|
|
52
|
+
conf.compaction_threshold(),
|
|
53
|
+
)
|
|
54
|
+
return EffectiveAgent(
|
|
55
|
+
tuple(instructions), tuple(skills), model, threshold, agent.debug_context, tuple(notices),
|
|
56
|
+
agent.max_tasks or conf.max_tasks(), agent.start_address,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def _readable(session: StrategySession, entity_ids: list[str], entity_cls: type, notices: list[str]) -> list:
|
|
61
|
+
ordered = list(dict.fromkeys(entity_ids))
|
|
62
|
+
found = await session.get_many(ordered)
|
|
63
|
+
kind = entity_cls.__name__.lower()
|
|
64
|
+
kept = []
|
|
65
|
+
for entity_id in ordered:
|
|
66
|
+
if isinstance(found.get(entity_id), entity_cls):
|
|
67
|
+
kept.append(found[entity_id])
|
|
68
|
+
else:
|
|
69
|
+
notices.append(f"One {kind} of this agent ({entity_id}) is not readable to you and was left out.")
|
|
70
|
+
return kept
|