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,21 @@
1
+ from django.db import migrations, models
2
+
3
+
4
+ class Migration(migrations.Migration):
5
+
6
+ dependencies = [
7
+ ('agents', '0005_conversation_last_active_at'),
8
+ ]
9
+
10
+ operations = [
11
+ migrations.AddField(
12
+ model_name='agentmodel',
13
+ name='max_tasks',
14
+ field=models.IntegerField(null=True),
15
+ ),
16
+ migrations.AddField(
17
+ model_name='conversationmodel',
18
+ name='source_call_id',
19
+ field=models.CharField(max_length=255, 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', '0006_tasks'),
8
+ ]
9
+
10
+ operations = [
11
+ migrations.AddField(
12
+ model_name='agentmodel',
13
+ name='start_address',
14
+ field=models.CharField(max_length=1024, null=True),
15
+ ),
16
+ ]
File without changes
agents/models.py ADDED
@@ -0,0 +1,64 @@
1
+ from django.db import models
2
+
3
+ from graphcore.public.persistence.django import EntityModel
4
+
5
+ from agents.entities.conversation import ConversationStatus
6
+ from agents.entities.message import MessageRole
7
+
8
+
9
+ class AgentModel(EntityModel):
10
+ name = models.CharField(max_length=255, default='', blank=True)
11
+ description = models.TextField(default='', blank=True)
12
+ instruction_ids = models.JSONField(default=list)
13
+ skill_ids = models.JSONField(default=list)
14
+ model = models.CharField(max_length=64, null=True)
15
+ compaction_threshold = models.FloatField(null=True)
16
+ debug_context = models.BooleanField(default=False)
17
+ max_tasks = models.IntegerField(null=True)
18
+ start_address = models.CharField(max_length=1024, null=True)
19
+
20
+
21
+ class InstructionModel(EntityModel):
22
+ name = models.CharField(max_length=255, default='', blank=True)
23
+ text = models.TextField(default='', blank=True)
24
+
25
+
26
+ class SkillModel(EntityModel):
27
+ name = models.CharField(max_length=255, default='', blank=True)
28
+ description = models.TextField(default='', blank=True)
29
+ text = models.TextField(default='', blank=True)
30
+
31
+
32
+ class AgentProfileModel(EntityModel):
33
+ agent_id = models.CharField(max_length=96, null=True, db_index=True)
34
+ instruction_ids = models.JSONField(default=list)
35
+ skill_ids = models.JSONField(default=list)
36
+ model = models.CharField(max_length=64, null=True)
37
+ compaction_threshold = models.FloatField(null=True)
38
+
39
+
40
+ class ConversationModel(EntityModel):
41
+ agent_id = models.CharField(max_length=96, null=True, db_index=True)
42
+ title = models.CharField(max_length=255, default='', blank=True)
43
+ status = models.CharField(max_length=16, db_index=True, default=ConversationStatus.IDLE.value,
44
+ choices=[(s.value, s.value) for s in ConversationStatus])
45
+ context_ids = models.JSONField(default=list)
46
+ model = models.CharField(max_length=64, null=True)
47
+ usage = models.JSONField(default=dict)
48
+ stop_requested = models.BooleanField(default=False)
49
+ deliver_to_parent = models.BooleanField(default=False)
50
+ last_active_at = models.FloatField(null=True, db_index=True)
51
+ source_call_id = models.CharField(max_length=255, null=True)
52
+
53
+
54
+ class MessageModel(EntityModel):
55
+ role = models.CharField(max_length=16, db_index=True, default=MessageRole.USER.value,
56
+ choices=[(r.value, r.value) for r in MessageRole])
57
+ content = models.TextField(default='', blank=True)
58
+ context_ids = models.JSONField(default=list)
59
+ tool_calls = models.JSONField(default=list)
60
+ source_conversation_id = models.CharField(max_length=96, null=True)
61
+ summary_through = models.CharField(max_length=96, null=True)
62
+ read_through = models.CharField(max_length=96, null=True)
63
+ context_versions = models.JSONField(default=dict)
64
+ provider_state = models.JSONField(default=dict)
agents/persistence.py ADDED
@@ -0,0 +1,18 @@
1
+ from agents.entities.agent import Agent
2
+ from agents.entities.conversation import Conversation
3
+ from agents.entities.instruction import Instruction
4
+ from agents.entities.message import Message
5
+ from agents.entities.profile import AgentProfile
6
+ from agents.entities.skill import Skill
7
+ from agents.models import (
8
+ AgentModel, AgentProfileModel, ConversationModel, InstructionModel, MessageModel, SkillModel,
9
+ )
10
+
11
+
12
+ def configure(entities) -> None:
13
+ entities.bind_storage(Agent, AgentModel)
14
+ entities.bind_storage(Instruction, InstructionModel)
15
+ entities.bind_storage(Skill, SkillModel)
16
+ entities.bind_storage(AgentProfile, AgentProfileModel)
17
+ entities.bind_storage(Conversation, ConversationModel)
18
+ entities.bind_storage(Message, MessageModel)
File without changes
@@ -0,0 +1,142 @@
1
+ """Anthropic's Messages API behind the provider port."""
2
+ from typing import AsyncIterator, Optional
3
+
4
+ import anthropic
5
+
6
+ from agents.providers.port import Done, Event, ModelRequest, Provider, ProviderError, TextDelta, ToolCall, Turn, Usage
7
+
8
+ _CACHE = {"type": "ephemeral"}
9
+ _STOPS = {'tool_use': 'tool_calls', 'max_tokens': 'max_tokens', 'refusal': 'refusal'}
10
+ _RETRYABLE_TYPES = {'rate_limit_error': 'rate_limit', 'overloaded_error': 'overloaded', 'api_error': 'server_error'}
11
+ _THINKING = ('thinking', 'redacted_thinking')
12
+ # A replayed thinking block is valid only in the conversation that produced it;
13
+ # the API says so with this sentence when an earlier turn is no longer what it was.
14
+ _UNBOUND_THINKING = 'bound to a different conversation'
15
+
16
+
17
+ class AnthropicProvider(Provider):
18
+ name = 'anthropic'
19
+
20
+ def __init__(self, api_key: Optional[str], read_timeout: float, http_client=None):
21
+ super().__init__(api_key, read_timeout)
22
+ # Retries are the executor's: every retry is an attempt that resumes.
23
+ self._client = anthropic.AsyncAnthropic(
24
+ api_key=api_key, max_retries=0, http_client=http_client,
25
+ timeout=anthropic.Timeout(read_timeout, connect=10.0),
26
+ )
27
+
28
+ async def stream(self, request: ModelRequest) -> AsyncIterator[Event]:
29
+ params = wire_request(request)
30
+ try:
31
+ try:
32
+ async for event in self._events(params):
33
+ yield event
34
+ except anthropic.BadRequestError as exc:
35
+ # Refused before any output, so nothing was yielded. The model
36
+ # answers this call without the reasoning those blocks carried.
37
+ if _UNBOUND_THINKING not in str(exc):
38
+ raise
39
+ params['messages'] = _without_thinking(params['messages'])
40
+ async for event in self._events(params):
41
+ yield event
42
+ except anthropic.APIError as exc:
43
+ raise _provider_error(exc) from exc
44
+
45
+ async def _events(self, params: dict) -> AsyncIterator[Event]:
46
+ async with self._client.messages.stream(**params) as stream:
47
+ async for event in stream:
48
+ if event.type == 'text':
49
+ yield TextDelta(event.text)
50
+ elif event.type == 'content_block_stop' and event.content_block.type == 'tool_use':
51
+ block = event.content_block
52
+ if isinstance(block.input, dict):
53
+ yield ToolCall(block.id, block.name, block.input)
54
+ else:
55
+ yield ToolCall(block.id, block.name, {}, error='The params are not a JSON object')
56
+ message = await stream.get_final_message()
57
+ if message.stop_reason is None:
58
+ raise ProviderError('incomplete_stream', 'The stream ended before the reply did', retryable=True)
59
+ usage = message.usage
60
+ cached = usage.cache_read_input_tokens or 0
61
+ yield Done(
62
+ _STOPS.get(message.stop_reason, 'end'),
63
+ Usage(
64
+ input_tokens=usage.input_tokens + cached + (usage.cache_creation_input_tokens or 0),
65
+ output_tokens=usage.output_tokens, cached_input_tokens=cached,
66
+ ),
67
+ # The reply as sent, so its thinking blocks go back where they were.
68
+ provider_state={'content': [block.to_dict() for block in message.content]},
69
+ )
70
+
71
+
72
+ def wire_request(request: ModelRequest) -> dict:
73
+ """The Messages API request for `request`, with a cache breakpoint after
74
+ the tools and system prompt and one after the last turn."""
75
+ system = [{"type": "text", "text": text} for text in request.prefix]
76
+ if system:
77
+ system[-1]["cache_control"] = _CACHE
78
+ messages = [_message(turn) for turn in request.turns]
79
+ if messages:
80
+ messages[-1]["content"][-1]["cache_control"] = _CACHE
81
+ params = {
82
+ "model": request.model,
83
+ "max_tokens": request.max_output_tokens,
84
+ "system": system,
85
+ "tools": [
86
+ {"name": tool.name, "description": tool.description, "input_schema": tool.schema}
87
+ for tool in request.tools
88
+ ],
89
+ "messages": messages,
90
+ }
91
+ if request.tool_choice == 'none':
92
+ params["tool_choice"] = {"type": "none"}
93
+ return params
94
+
95
+
96
+ def _message(turn: Turn) -> dict:
97
+ if turn.role == 'assistant':
98
+ content = turn.provider_state.get('content') or [
99
+ *([{"type": "text", "text": turn.text}] if turn.text else []),
100
+ *({"type": "tool_use", "id": call.id, "name": call.name, "input": call.params} for call in turn.calls),
101
+ ]
102
+ return {"role": "assistant", "content": [dict(block) for block in content]}
103
+ content = [
104
+ {"type": "tool_result", "tool_use_id": result.call_id, "content": result.content,
105
+ **({"is_error": True} if result.is_error else {})}
106
+ for result in turn.results
107
+ ]
108
+ if turn.text or not content:
109
+ content.append({"type": "text", "text": turn.text or '(empty message)'})
110
+ return {"role": "user", "content": content}
111
+
112
+
113
+ def _without_thinking(messages: list[dict]) -> list[dict]:
114
+ return [
115
+ {**message, "content": [block for block in message["content"] if block.get("type") not in _THINKING]}
116
+ if message["role"] == 'assistant' else message
117
+ for message in messages
118
+ ]
119
+
120
+
121
+ def _provider_error(exc: anthropic.APIError) -> ProviderError:
122
+ message = str(exc)
123
+ if isinstance(exc, anthropic.APITimeoutError):
124
+ return ProviderError('timeout', message, retryable=True)
125
+ if isinstance(exc, anthropic.APIConnectionError):
126
+ return ProviderError('connection', message, retryable=True)
127
+ if isinstance(exc, anthropic.APIStatusError):
128
+ # An error event inside a stream carries the type but not the status.
129
+ if exc.type in _RETRYABLE_TYPES:
130
+ return ProviderError(_RETRYABLE_TYPES[exc.type], message, retryable=True)
131
+ if isinstance(exc, anthropic.RateLimitError):
132
+ return ProviderError('rate_limit', message, retryable=True)
133
+ if isinstance(exc, anthropic.InternalServerError):
134
+ return ProviderError('overloaded' if exc.status_code == 529 else 'server_error', message, retryable=True)
135
+ if isinstance(exc, (anthropic.AuthenticationError, anthropic.PermissionDeniedError)):
136
+ return ProviderError('auth', message, retryable=False)
137
+ if isinstance(exc, anthropic.NotFoundError):
138
+ return ProviderError('unknown_model', message, retryable=False)
139
+ if exc.status_code == 413 or 'prompt is too long' in message:
140
+ return ProviderError('context_overflow', message, retryable=False)
141
+ return ProviderError('invalid_request', message, retryable=False)
142
+ return ProviderError('incomplete_stream', message, retryable=True)
@@ -0,0 +1,51 @@
1
+ """A provider that plays scripted replies and records the requests it was sent."""
2
+ import inspect
3
+ from collections import deque
4
+ from typing import AsyncIterator, ClassVar
5
+
6
+ from agents.providers.port import Done, Event, ModelRequest, Provider, TextDelta, ToolCall, Usage
7
+
8
+
9
+ def says(text: str, stop: str = 'end', input_tokens: int = 10, output_tokens: int = 5, cached_input_tokens: int = 0) -> list:
10
+ return [TextDelta(text), Done(stop, Usage(input_tokens, output_tokens, cached_input_tokens))]
11
+
12
+
13
+ def calls(*tool_calls: ToolCall, text: str = '') -> list:
14
+ return [*([TextDelta(text)] if text else []), *tool_calls, Done('tool_calls', Usage(10, 5))]
15
+
16
+
17
+ async def scripted_reply(request: ModelRequest) -> list:
18
+ """The next reply a test queued, else `says('ok')`. Spec tests patch it in the stack's processes."""
19
+ return FakeProvider.replies.popleft() if FakeProvider.replies else says('ok')
20
+
21
+
22
+ class FakeProvider(Provider):
23
+ name = 'fake'
24
+ needs_key = False
25
+
26
+ replies: ClassVar[deque] = deque()
27
+ requests: ClassVar[list[ModelRequest]] = []
28
+
29
+ @classmethod
30
+ def reset(cls) -> None:
31
+ cls.replies.clear()
32
+ cls.requests.clear()
33
+
34
+ @classmethod
35
+ def play(cls, *replies: list) -> None:
36
+ """Queue one reply per provider call. A reply is a list of events; an
37
+ exception in it is raised there, and a function is awaited there."""
38
+ cls.replies.extend(replies)
39
+
40
+ async def stream(self, request: ModelRequest) -> AsyncIterator[Event]:
41
+ self.requests.append(request)
42
+ reply = await scripted_reply(request)
43
+ for item in reply:
44
+ if isinstance(item, Exception):
45
+ raise item
46
+ if callable(item):
47
+ outcome = item()
48
+ if inspect.isawaitable(outcome):
49
+ await outcome
50
+ continue
51
+ yield item
@@ -0,0 +1,186 @@
1
+ """Google's Gemini API through the GenAI SDK, behind the provider port."""
2
+ import uuid
3
+ from typing import AsyncIterator, Optional
4
+
5
+ import httpx
6
+ from google import genai
7
+ from google.genai import errors, types
8
+
9
+ from agents.providers.port import Done, Event, ModelRequest, Provider, ProviderError, TextDelta, ToolCall, Turn, Usage
10
+
11
+ _REFUSALS = frozenset({'SAFETY', 'RECITATION', 'LANGUAGE', 'BLOCKLIST', 'PROHIBITED_CONTENT', 'SPII'})
12
+
13
+
14
+ class GoogleProvider(Provider):
15
+ name = 'google'
16
+
17
+ def __init__(self, api_key: Optional[str], read_timeout: float, http_client=None):
18
+ super().__init__(api_key, read_timeout)
19
+ # One attempt: retries are the executor's, and every retry is an attempt that resumes.
20
+ self._client = genai.Client(api_key=api_key, http_options=types.HttpOptions(
21
+ timeout=int(read_timeout * 1000), retry_options=types.HttpRetryOptions(attempts=1),
22
+ httpx_async_client=http_client,
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 errors.ClientError as exc:
31
+ # Refused before any output. A thought signature is accepted
32
+ # only after the turns it was written after; without them the
33
+ # model answers this call from the text and calls alone.
34
+ if exc.code != 400 or _is_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 ProviderError:
39
+ raise
40
+ except errors.APIError as exc:
41
+ raise _provider_error(exc) from exc
42
+ except (httpx.TimeoutException, TimeoutError) as exc:
43
+ raise ProviderError('timeout', str(exc) or type(exc).__name__, retryable=True) from exc
44
+ except (httpx.TransportError, OSError) as exc:
45
+ raise ProviderError('connection', str(exc) or type(exc).__name__, retryable=True) from exc
46
+
47
+ async def _events(self, params: dict) -> AsyncIterator[Event]:
48
+ parts: list[dict] = []
49
+ finish = usage = None
50
+ called = blocked = False
51
+ stream = await self._client.aio.models.generate_content_stream(**params)
52
+ try:
53
+ async for chunk in stream:
54
+ usage = chunk.usage_metadata or usage
55
+ if chunk.prompt_feedback and chunk.prompt_feedback.block_reason:
56
+ blocked = True
57
+ for candidate in chunk.candidates or []:
58
+ finish = candidate.finish_reason or finish
59
+ for part in (candidate.content.parts if candidate.content else None) or []:
60
+ _keep(parts, part)
61
+ if part.function_call:
62
+ called = True
63
+ yield _tool_call(part.function_call)
64
+ elif part.text and not part.thought:
65
+ yield TextDelta(part.text)
66
+ finally:
67
+ await stream.aclose()
68
+ if finish is None and not blocked:
69
+ raise ProviderError('incomplete_stream', 'The stream ended before the reply did', retryable=True)
70
+
71
+ reason = finish.name if finish is not None else None
72
+ if blocked or reason in _REFUSALS:
73
+ stop = 'refusal'
74
+ elif called:
75
+ stop = 'tool_calls'
76
+ elif reason == 'MAX_TOKENS':
77
+ stop = 'max_tokens'
78
+ else:
79
+ stop = 'end'
80
+ yield Done(
81
+ stop,
82
+ Usage(
83
+ input_tokens=(usage.prompt_token_count or 0) if usage else 0,
84
+ output_tokens=((usage.candidates_token_count or 0) + (usage.thoughts_token_count or 0)) if usage else 0,
85
+ cached_input_tokens=(usage.cached_content_token_count or 0) if usage else 0,
86
+ ),
87
+ # The reply's parts as sent, so each thought signature goes back on its part.
88
+ provider_state={'parts': parts} if any('thought_signature' in part for part in parts) else {},
89
+ )
90
+
91
+
92
+ def wire_request(request: ModelRequest, with_state: bool = True) -> dict:
93
+ """The `generate_content_stream` arguments for `request`. Caching is the vendor's own."""
94
+ vendor_ids = {
95
+ call.id: call.provider_state.get('vendor_id', True)
96
+ for turn in request.turns for call in turn.calls
97
+ }
98
+ config: dict = {
99
+ "max_output_tokens": request.max_output_tokens,
100
+ "automatic_function_calling": {"disable": True},
101
+ }
102
+ if request.prefix:
103
+ config["system_instruction"] = '\n\n'.join(request.prefix)
104
+ if request.tools:
105
+ config["tools"] = [{"function_declarations": [
106
+ {"name": tool.name, "description": tool.description, "parameters_json_schema": tool.schema}
107
+ for tool in request.tools
108
+ ]}]
109
+ if request.tool_choice == 'none':
110
+ config["tool_config"] = {"function_calling_config": {"mode": "NONE"}}
111
+ return {
112
+ "model": request.model,
113
+ "contents": [_content(turn, vendor_ids, with_state) for turn in request.turns],
114
+ "config": config,
115
+ }
116
+
117
+
118
+ def _content(turn: Turn, vendor_ids: dict, with_state: bool) -> dict:
119
+ if turn.role == 'assistant':
120
+ stored = turn.provider_state.get('parts') if with_state else None
121
+ parts = [dict(part) for part in stored] if stored else [
122
+ *([{"text": turn.text}] if turn.text else []),
123
+ *(
124
+ {"function_call": {
125
+ "name": call.name, "args": call.params, **({"id": call.id} if vendor_ids.get(call.id) else {}),
126
+ }}
127
+ for call in turn.calls
128
+ ),
129
+ ]
130
+ return {"role": "model", "parts": parts}
131
+ parts = [
132
+ {"function_response": {
133
+ "name": result.name,
134
+ "response": {"error" if result.is_error else "result": result.content},
135
+ **({"id": result.call_id} if vendor_ids.get(result.call_id) else {}),
136
+ }}
137
+ for result in turn.results
138
+ ]
139
+ if turn.text or not parts:
140
+ parts.append({"text": turn.text or '(empty message)'})
141
+ return {"role": "user", "parts": parts}
142
+
143
+
144
+ def _keep(parts: list[dict], part: types.Part) -> None:
145
+ """Collect a streamed part, joining text that arrived in pieces."""
146
+ kept = part.model_dump(mode='json', exclude_none=True)
147
+ plain = set(kept) == {'text'}
148
+ if plain and parts and set(parts[-1]) == {'text'}:
149
+ parts[-1]['text'] += kept['text']
150
+ else:
151
+ parts.append(kept)
152
+
153
+
154
+ def _tool_call(call: types.FunctionCall) -> ToolCall:
155
+ # The API does not always name a call; the turn needs an id either way.
156
+ call_id = call.id or f"call_{uuid.uuid4().hex[:12]}"
157
+ state = {} if call.id else {'vendor_id': False}
158
+ if not isinstance(call.args, dict):
159
+ return ToolCall(call_id, call.name or '', {}, error='The params are not a JSON object', provider_state=state)
160
+ return ToolCall(call_id, call.name or '', dict(call.args), provider_state=state)
161
+
162
+
163
+ def _is_overflow(exc: errors.APIError) -> bool:
164
+ message = (exc.message or '').lower()
165
+ return 'token count' in message and 'exceeds' in message
166
+
167
+
168
+ def _provider_error(exc: errors.APIError) -> ProviderError:
169
+ message = f"{exc.status}: {exc.message}" if exc.status else str(exc)
170
+ code = exc.code or 0
171
+ if code == 429:
172
+ return ProviderError('rate_limit', message, retryable=True)
173
+ if code == 503:
174
+ return ProviderError('overloaded', message, retryable=True)
175
+ if code == 504:
176
+ return ProviderError('timeout', message, retryable=True)
177
+ if code >= 500:
178
+ return ProviderError('server_error', message, retryable=True)
179
+ # 402: the project's credits are spent, which no wait fixes.
180
+ if code in (401, 402, 403) or 'api key' in (exc.message or '').lower():
181
+ return ProviderError('auth', message, retryable=False)
182
+ if code == 404:
183
+ return ProviderError('unknown_model', message, retryable=False)
184
+ if code == 413 or _is_overflow(exc):
185
+ return ProviderError('context_overflow', message, retryable=False)
186
+ return ProviderError('invalid_request', message, retryable=False)