glaip-sdk 0.6.15b2__py3-none-any.whl → 0.6.16__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 (154) hide show
  1. glaip_sdk/agents/__init__.py +27 -0
  2. glaip_sdk/agents/base.py +1196 -0
  3. glaip_sdk/cli/__init__.py +9 -0
  4. glaip_sdk/cli/account_store.py +540 -0
  5. glaip_sdk/cli/agent_config.py +78 -0
  6. glaip_sdk/cli/auth.py +699 -0
  7. glaip_sdk/cli/commands/__init__.py +5 -0
  8. glaip_sdk/cli/commands/accounts.py +746 -0
  9. glaip_sdk/cli/commands/agents.py +1509 -0
  10. glaip_sdk/cli/commands/common_config.py +104 -0
  11. glaip_sdk/cli/commands/configure.py +896 -0
  12. glaip_sdk/cli/commands/mcps.py +1356 -0
  13. glaip_sdk/cli/commands/models.py +69 -0
  14. glaip_sdk/cli/commands/tools.py +576 -0
  15. glaip_sdk/cli/commands/transcripts.py +755 -0
  16. glaip_sdk/cli/commands/update.py +61 -0
  17. glaip_sdk/cli/config.py +95 -0
  18. glaip_sdk/cli/constants.py +38 -0
  19. glaip_sdk/cli/context.py +150 -0
  20. glaip_sdk/cli/core/__init__.py +79 -0
  21. glaip_sdk/cli/core/context.py +124 -0
  22. glaip_sdk/cli/core/output.py +851 -0
  23. glaip_sdk/cli/core/prompting.py +649 -0
  24. glaip_sdk/cli/core/rendering.py +187 -0
  25. glaip_sdk/cli/display.py +355 -0
  26. glaip_sdk/cli/hints.py +57 -0
  27. glaip_sdk/cli/io.py +112 -0
  28. glaip_sdk/cli/main.py +615 -0
  29. glaip_sdk/cli/masking.py +136 -0
  30. glaip_sdk/cli/mcp_validators.py +287 -0
  31. glaip_sdk/cli/pager.py +266 -0
  32. glaip_sdk/cli/parsers/__init__.py +7 -0
  33. glaip_sdk/cli/parsers/json_input.py +177 -0
  34. glaip_sdk/cli/resolution.py +67 -0
  35. glaip_sdk/cli/rich_helpers.py +27 -0
  36. glaip_sdk/cli/slash/__init__.py +15 -0
  37. glaip_sdk/cli/slash/accounts_controller.py +578 -0
  38. glaip_sdk/cli/slash/accounts_shared.py +75 -0
  39. glaip_sdk/cli/slash/agent_session.py +285 -0
  40. glaip_sdk/cli/slash/prompt.py +256 -0
  41. glaip_sdk/cli/slash/remote_runs_controller.py +566 -0
  42. glaip_sdk/cli/slash/session.py +1708 -0
  43. glaip_sdk/cli/slash/tui/__init__.py +9 -0
  44. glaip_sdk/cli/slash/tui/accounts_app.py +876 -0
  45. glaip_sdk/cli/slash/tui/background_tasks.py +72 -0
  46. glaip_sdk/cli/slash/tui/loading.py +58 -0
  47. glaip_sdk/cli/slash/tui/remote_runs_app.py +628 -0
  48. glaip_sdk/cli/transcript/__init__.py +31 -0
  49. glaip_sdk/cli/transcript/cache.py +536 -0
  50. glaip_sdk/cli/transcript/capture.py +329 -0
  51. glaip_sdk/cli/transcript/export.py +38 -0
  52. glaip_sdk/cli/transcript/history.py +815 -0
  53. glaip_sdk/cli/transcript/launcher.py +77 -0
  54. glaip_sdk/cli/transcript/viewer.py +374 -0
  55. glaip_sdk/cli/update_notifier.py +290 -0
  56. glaip_sdk/cli/utils.py +263 -0
  57. glaip_sdk/cli/validators.py +238 -0
  58. glaip_sdk/client/__init__.py +11 -0
  59. glaip_sdk/client/_agent_payloads.py +520 -0
  60. glaip_sdk/client/agent_runs.py +147 -0
  61. glaip_sdk/client/agents.py +1335 -0
  62. glaip_sdk/client/base.py +502 -0
  63. glaip_sdk/client/main.py +249 -0
  64. glaip_sdk/client/mcps.py +370 -0
  65. glaip_sdk/client/run_rendering.py +700 -0
  66. glaip_sdk/client/shared.py +21 -0
  67. glaip_sdk/client/tools.py +661 -0
  68. glaip_sdk/client/validators.py +198 -0
  69. glaip_sdk/config/constants.py +52 -0
  70. glaip_sdk/mcps/__init__.py +21 -0
  71. glaip_sdk/mcps/base.py +345 -0
  72. glaip_sdk/models/__init__.py +90 -0
  73. glaip_sdk/models/agent.py +47 -0
  74. glaip_sdk/models/agent_runs.py +116 -0
  75. glaip_sdk/models/common.py +42 -0
  76. glaip_sdk/models/mcp.py +33 -0
  77. glaip_sdk/models/tool.py +33 -0
  78. glaip_sdk/payload_schemas/__init__.py +7 -0
  79. glaip_sdk/payload_schemas/agent.py +85 -0
  80. glaip_sdk/registry/__init__.py +55 -0
  81. glaip_sdk/registry/agent.py +164 -0
  82. glaip_sdk/registry/base.py +139 -0
  83. glaip_sdk/registry/mcp.py +253 -0
  84. glaip_sdk/registry/tool.py +232 -0
  85. glaip_sdk/runner/__init__.py +59 -0
  86. glaip_sdk/runner/base.py +84 -0
  87. glaip_sdk/runner/deps.py +112 -0
  88. glaip_sdk/runner/langgraph.py +782 -0
  89. glaip_sdk/runner/mcp_adapter/__init__.py +13 -0
  90. glaip_sdk/runner/mcp_adapter/base_mcp_adapter.py +43 -0
  91. glaip_sdk/runner/mcp_adapter/langchain_mcp_adapter.py +257 -0
  92. glaip_sdk/runner/mcp_adapter/mcp_config_builder.py +95 -0
  93. glaip_sdk/runner/tool_adapter/__init__.py +18 -0
  94. glaip_sdk/runner/tool_adapter/base_tool_adapter.py +44 -0
  95. glaip_sdk/runner/tool_adapter/langchain_tool_adapter.py +219 -0
  96. glaip_sdk/tools/__init__.py +22 -0
  97. glaip_sdk/tools/base.py +435 -0
  98. glaip_sdk/utils/__init__.py +86 -0
  99. glaip_sdk/utils/a2a/__init__.py +34 -0
  100. glaip_sdk/utils/a2a/event_processor.py +188 -0
  101. glaip_sdk/utils/agent_config.py +194 -0
  102. glaip_sdk/utils/bundler.py +267 -0
  103. glaip_sdk/utils/client.py +111 -0
  104. glaip_sdk/utils/client_utils.py +486 -0
  105. glaip_sdk/utils/datetime_helpers.py +58 -0
  106. glaip_sdk/utils/discovery.py +78 -0
  107. glaip_sdk/utils/display.py +135 -0
  108. glaip_sdk/utils/export.py +143 -0
  109. glaip_sdk/utils/general.py +61 -0
  110. glaip_sdk/utils/import_export.py +168 -0
  111. glaip_sdk/utils/import_resolver.py +492 -0
  112. glaip_sdk/utils/instructions.py +101 -0
  113. glaip_sdk/utils/rendering/__init__.py +115 -0
  114. glaip_sdk/utils/rendering/formatting.py +264 -0
  115. glaip_sdk/utils/rendering/layout/__init__.py +64 -0
  116. glaip_sdk/utils/rendering/layout/panels.py +156 -0
  117. glaip_sdk/utils/rendering/layout/progress.py +202 -0
  118. glaip_sdk/utils/rendering/layout/summary.py +74 -0
  119. glaip_sdk/utils/rendering/layout/transcript.py +606 -0
  120. glaip_sdk/utils/rendering/models.py +85 -0
  121. glaip_sdk/utils/rendering/renderer/__init__.py +55 -0
  122. glaip_sdk/utils/rendering/renderer/base.py +1024 -0
  123. glaip_sdk/utils/rendering/renderer/config.py +27 -0
  124. glaip_sdk/utils/rendering/renderer/console.py +55 -0
  125. glaip_sdk/utils/rendering/renderer/debug.py +178 -0
  126. glaip_sdk/utils/rendering/renderer/factory.py +138 -0
  127. glaip_sdk/utils/rendering/renderer/stream.py +202 -0
  128. glaip_sdk/utils/rendering/renderer/summary_window.py +79 -0
  129. glaip_sdk/utils/rendering/renderer/thinking.py +273 -0
  130. glaip_sdk/utils/rendering/renderer/toggle.py +182 -0
  131. glaip_sdk/utils/rendering/renderer/tool_panels.py +442 -0
  132. glaip_sdk/utils/rendering/renderer/transcript_mode.py +162 -0
  133. glaip_sdk/utils/rendering/state.py +204 -0
  134. glaip_sdk/utils/rendering/step_tree_state.py +100 -0
  135. glaip_sdk/utils/rendering/steps/__init__.py +34 -0
  136. glaip_sdk/utils/rendering/steps/event_processor.py +778 -0
  137. glaip_sdk/utils/rendering/steps/format.py +176 -0
  138. glaip_sdk/utils/rendering/steps/manager.py +387 -0
  139. glaip_sdk/utils/rendering/timing.py +36 -0
  140. glaip_sdk/utils/rendering/viewer/__init__.py +21 -0
  141. glaip_sdk/utils/rendering/viewer/presenter.py +184 -0
  142. glaip_sdk/utils/resource_refs.py +195 -0
  143. glaip_sdk/utils/run_renderer.py +41 -0
  144. glaip_sdk/utils/runtime_config.py +425 -0
  145. glaip_sdk/utils/serialization.py +424 -0
  146. glaip_sdk/utils/sync.py +142 -0
  147. glaip_sdk/utils/tool_detection.py +33 -0
  148. glaip_sdk/utils/validation.py +264 -0
  149. {glaip_sdk-0.6.15b2.dist-info → glaip_sdk-0.6.16.dist-info}/METADATA +4 -5
  150. glaip_sdk-0.6.16.dist-info/RECORD +160 -0
  151. glaip_sdk-0.6.15b2.dist-info/RECORD +0 -12
  152. {glaip_sdk-0.6.15b2.dist-info → glaip_sdk-0.6.16.dist-info}/WHEEL +0 -0
  153. {glaip_sdk-0.6.15b2.dist-info → glaip_sdk-0.6.16.dist-info}/entry_points.txt +0 -0
  154. {glaip_sdk-0.6.15b2.dist-info → glaip_sdk-0.6.16.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1196 @@
1
+ """Agent class for GL AIP platform.
2
+
3
+ This module provides the Agent class that serves as the foundation
4
+ for defining agents in glaip-sdk. The Agent class supports both:
5
+ - Direct instantiation for simple agents
6
+ - Subclassing for complex, reusable agent definitions
7
+
8
+ Authors:
9
+ Christian Trisno Sen Long Chen (christian.t.s.l.chen@gdplabs.id)
10
+
11
+ Example - Direct Instantiation:
12
+ >>> from glaip_sdk.agents import Agent
13
+ >>>
14
+ >>> agent = Agent(
15
+ ... name="hello_agent",
16
+ ... instruction="You are a helpful assistant.",
17
+ ... )
18
+ >>> agent.deploy()
19
+ >>> result = agent.run("Hello!")
20
+
21
+ Example - Subclassing:
22
+ >>> from glaip_sdk.agents import Agent
23
+ >>>
24
+ >>> class WeatherAgent(Agent):
25
+ ... @property
26
+ ... def name(self) -> str:
27
+ ... return "weather_agent"
28
+ ...
29
+ ... @property
30
+ ... def instruction(self) -> str:
31
+ ... return "You are a helpful weather assistant."
32
+ ...
33
+ ... @property
34
+ ... def tools(self) -> list:
35
+ ... return [WeatherAPITool, "web_search"]
36
+ >>>
37
+ >>> # Deploy and run the agent
38
+ >>> agent = WeatherAgent()
39
+ >>> agent.deploy()
40
+ >>> result = agent.run("What's the weather?")
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import inspect
46
+ import logging
47
+ import warnings
48
+ from collections.abc import AsyncGenerator
49
+
50
+
51
+ from pathlib import Path
52
+ from typing import TYPE_CHECKING, Any
53
+
54
+ from glaip_sdk.registry import get_agent_registry, get_mcp_registry, get_tool_registry
55
+ from glaip_sdk.utils.resource_refs import is_uuid
56
+
57
+ if TYPE_CHECKING:
58
+ from glaip_sdk.models import AgentResponse
59
+ from glaip_sdk.registry import AgentRegistry, MCPRegistry, ToolRegistry
60
+
61
+ logger = logging.getLogger(__name__)
62
+
63
+ _AGENT_NOT_DEPLOYED_MSG = "Agent must be deployed before running. Call deploy() first."
64
+ _CLIENT_NOT_AVAILABLE_MSG = "Client not available. Agent may not have been deployed properly."
65
+
66
+
67
+ class Agent:
68
+ """Agent class for GL AIP platform.
69
+
70
+ Supports both direct instantiation and subclassing.
71
+ The deploy() method updates the agent in-place, so you can use the
72
+ same instance for deployment and running.
73
+
74
+ Direct instantiation (simple):
75
+ >>> agent = Agent(
76
+ ... name="my_agent",
77
+ ... instruction="You are helpful.",
78
+ ... tools=["web_search"],
79
+ ... )
80
+ >>> agent.deploy()
81
+ >>> result = agent.run("Hello!")
82
+
83
+ Subclassing (complex):
84
+ >>> class MyAgent(Agent):
85
+ ... @property
86
+ ... def name(self) -> str:
87
+ ... return "my_agent"
88
+ ...
89
+ ... @property
90
+ ... def instruction(self) -> str:
91
+ ... return self.load_instruction_from_file("instructions.md")
92
+ ...
93
+ >>> agent = MyAgent()
94
+ >>> agent.deploy()
95
+ >>> result = agent.run("Hello!")
96
+
97
+ Properties (override in subclass OR pass to __init__):
98
+ - name: Agent name on the AIP platform (required)
99
+ - instruction: Agent instruction text (required)
100
+ - description: Agent description (default: "")
101
+ - tools: List of tools (default: [])
102
+ - agents: List of sub-agents (default: [])
103
+ - mcps: List of MCPs (default: [])
104
+ - timeout: Timeout in seconds (default: 300)
105
+ - metadata: Optional metadata dict (default: None)
106
+ - model: Optional model override (default: None)
107
+ - framework: Agent framework (default: "langchain")
108
+ - version: Agent version (default: "1.0.0")
109
+ - agent_type: Agent type (default: "config")
110
+ - agent_config: Agent execution config (default: None)
111
+ - tool_configs: Per-tool config overrides (default: None)
112
+ - mcp_configs: Per-MCP config overrides (default: None)
113
+ - a2a_profile: A2A profile config (default: None)
114
+
115
+ Instance attributes (set after deployment or from_response):
116
+ - id: The agent's unique ID on the platform
117
+ - _client: Client reference for run/update/delete operations
118
+ """
119
+
120
+ # Sentinel value to detect unset optional params
121
+ _UNSET = object()
122
+
123
+ def __init__(
124
+ self,
125
+ name: str | None = None,
126
+ instruction: str | None = None,
127
+ *,
128
+ id: str | None = None, # noqa: A002 - Allow shadowing builtin for API compat
129
+ description: str | None = _UNSET, # type: ignore[assignment]
130
+ tools: list | None = None,
131
+ agents: list | None = None,
132
+ mcps: list | None = None,
133
+ model: str | None = _UNSET, # type: ignore[assignment]
134
+ _client: Any = None,
135
+ **kwargs: Any,
136
+ ) -> None:
137
+ """Initialize an Agent.
138
+
139
+ For direct instantiation, name and instruction are required.
140
+ For subclassing, override the properties instead.
141
+
142
+ Args:
143
+ name: Agent name (required for direct instantiation).
144
+ instruction: Agent instruction (required for direct instantiation).
145
+ id: Agent ID (set after deployment or when created from API response).
146
+ description: Agent description.
147
+ tools: List of tools (Tool classes, SDK Tool objects, or strings).
148
+ agents: List of sub-agents (Agent classes, instances, or strings).
149
+ mcps: List of MCPs.
150
+ model: Model identifier.
151
+ _client: Internal client reference (set automatically).
152
+ **kwargs: Additional configuration parameters:
153
+ - timeout: Execution timeout in seconds.
154
+ - metadata: Optional metadata dictionary.
155
+ - framework: Agent framework identifier.
156
+ - version: Agent version string.
157
+ - agent_type: Agent type identifier.
158
+ - agent_config: Agent execution configuration.
159
+ - tool_configs: Per-tool configuration overrides.
160
+ - mcp_configs: Per-MCP configuration overrides.
161
+ - a2a_profile: A2A profile configuration.
162
+ """
163
+ # Instance attributes for deployed agents
164
+ self._id = id
165
+ self._client = _client
166
+ self._created_at: str | None = None
167
+ self._updated_at: str | None = None
168
+
169
+ # Store values (None/UNSET means "use property default or override")
170
+ self._name = name
171
+ self._instruction = instruction
172
+ self._description = description
173
+ self._tools = tools
174
+ self._agents = agents
175
+ self._mcps = mcps
176
+ self._model = model
177
+ self._language_model_id: str | None = None
178
+ # Extract parameters from kwargs with _UNSET defaults
179
+ self._timeout = kwargs.pop("timeout", Agent._UNSET) # type: ignore[assignment]
180
+ self._metadata = kwargs.pop("metadata", Agent._UNSET) # type: ignore[assignment]
181
+ self._framework = kwargs.pop("framework", Agent._UNSET) # type: ignore[assignment]
182
+ self._version = kwargs.pop("version", Agent._UNSET) # type: ignore[assignment]
183
+ self._agent_type = kwargs.pop("agent_type", Agent._UNSET) # type: ignore[assignment]
184
+ self._agent_config = kwargs.pop("agent_config", Agent._UNSET) # type: ignore[assignment]
185
+ self._tool_configs = kwargs.pop("tool_configs", Agent._UNSET) # type: ignore[assignment]
186
+ self._mcp_configs = kwargs.pop("mcp_configs", Agent._UNSET) # type: ignore[assignment]
187
+ self._a2a_profile = kwargs.pop("a2a_profile", Agent._UNSET) # type: ignore[assignment]
188
+
189
+ # Warn about unexpected kwargs
190
+ if kwargs:
191
+ warnings.warn(
192
+ f"Unexpected keyword arguments: {list(kwargs.keys())}. These will be ignored.",
193
+ UserWarning,
194
+ stacklevel=2,
195
+ )
196
+
197
+ # ─────────────────────────────────────────────────────────────────
198
+ # Properties (override in subclasses OR pass to __init__)
199
+ # ─────────────────────────────────────────────────────────────────
200
+
201
+ @property
202
+ def id(self) -> str | None: # noqa: A003 - Allow shadowing builtin for API compat
203
+ """Agent ID on the platform.
204
+
205
+ This is set after deployment or when created from an API response.
206
+
207
+ Returns:
208
+ The unique ID or None if not deployed yet.
209
+ """
210
+ return self._id
211
+
212
+ @id.setter
213
+ def id(self, value: str | None) -> None: # noqa: A003
214
+ """Set the agent ID."""
215
+ self._id = value
216
+
217
+ @property
218
+ def created_at(self) -> str | None:
219
+ """Timestamp when the agent was created.
220
+
221
+ Returns:
222
+ ISO format timestamp string or None if not deployed.
223
+ """
224
+ return self._created_at
225
+
226
+ @created_at.setter
227
+ def created_at(self, value: str | None) -> None:
228
+ """Set the created_at timestamp."""
229
+ self._created_at = value
230
+
231
+ @property
232
+ def updated_at(self) -> str | None:
233
+ """Timestamp when the agent was last updated.
234
+
235
+ Returns:
236
+ ISO format timestamp string or None if not deployed.
237
+ """
238
+ return self._updated_at
239
+
240
+ @updated_at.setter
241
+ def updated_at(self, value: str | None) -> None:
242
+ """Set the updated_at timestamp."""
243
+ self._updated_at = value
244
+
245
+ @property
246
+ def name(self) -> str:
247
+ """Agent name on the AIP platform.
248
+
249
+ Returns:
250
+ The unique identifier name for this agent.
251
+
252
+ Raises:
253
+ ValueError: If name is not provided via __init__ or property override.
254
+ """
255
+ if self._name is None:
256
+ raise ValueError(
257
+ "Agent name is required. Either pass name to __init__() or override the name property in a subclass."
258
+ )
259
+ return self._name
260
+
261
+ @property
262
+ def instruction(self) -> str:
263
+ """Agent instruction text.
264
+
265
+ Returns:
266
+ The instruction/prompt for the agent.
267
+
268
+ Raises:
269
+ ValueError: If instruction is not provided via __init__ or property
270
+ override.
271
+ """
272
+ if self._instruction is None:
273
+ raise ValueError(
274
+ "Agent instruction is required. Either pass instruction to __init__() "
275
+ "or override the instruction property in a subclass."
276
+ )
277
+ return self._instruction
278
+
279
+ @property
280
+ def description(self) -> str:
281
+ """Agent description.
282
+
283
+ Returns:
284
+ A description of what this agent does. Defaults to empty string.
285
+ """
286
+ if self._description is not self._UNSET:
287
+ return self._description or ""
288
+ return ""
289
+
290
+ @property
291
+ def tools(self) -> list:
292
+ """Tools available to this agent.
293
+
294
+ Tools can be:
295
+ - Tool class: Custom tool that will be auto-uploaded
296
+ - glaip_sdk.models.Tool: SDK Tool object (uses tool.id)
297
+ - str: Native tool name or ID (resolved by platform)
298
+
299
+ Returns:
300
+ List of tool references. Defaults to empty list.
301
+ """
302
+ return self._tools or []
303
+
304
+ @property
305
+ def agents(self) -> list:
306
+ """Sub-agents available to this agent.
307
+
308
+ Sub-agents can be:
309
+ - Agent class: Will be deployed recursively
310
+ - glaip_sdk.models.Agent: SDK Agent object (uses agent.id)
311
+ - str: Agent name or ID (resolved by platform)
312
+
313
+ Returns:
314
+ List of sub-agent references. Defaults to empty list.
315
+ """
316
+ return self._agents or []
317
+
318
+ @property
319
+ def timeout(self) -> int:
320
+ """Agent timeout in seconds.
321
+
322
+ Returns:
323
+ Timeout value in seconds. Defaults to 300.
324
+ """
325
+ if self._timeout is not self._UNSET and self._timeout is not None:
326
+ return self._timeout
327
+ return 300
328
+
329
+ @property
330
+ def metadata(self) -> dict[str, Any] | None:
331
+ """Optional metadata dictionary.
332
+
333
+ Returns:
334
+ Metadata dict or None.
335
+ """
336
+ if self._metadata is not self._UNSET:
337
+ return self._metadata
338
+ return None
339
+
340
+ @property
341
+ def model(self) -> str | None:
342
+ """Optional model override.
343
+
344
+ Returns:
345
+ Model identifier string or None to use default.
346
+ """
347
+ if self._model is not self._UNSET:
348
+ return self._model
349
+ return None
350
+
351
+ @property
352
+ def language_model_id(self) -> str | None:
353
+ """Language model ID from the API.
354
+
355
+ Returns:
356
+ The language model UUID or None.
357
+ """
358
+ return self._language_model_id
359
+
360
+ @property
361
+ def framework(self) -> str:
362
+ """Agent framework identifier.
363
+
364
+ Returns:
365
+ The framework name. Defaults to "langchain".
366
+ """
367
+ if self._framework is not self._UNSET and self._framework is not None:
368
+ return self._framework
369
+ return "langchain"
370
+
371
+ @property
372
+ def version(self) -> str:
373
+ """Agent version string.
374
+
375
+ Returns:
376
+ The version identifier. Defaults to "1.0.0".
377
+ """
378
+ if self._version is not self._UNSET and self._version is not None:
379
+ return self._version
380
+ return "1.0.0"
381
+
382
+ @property
383
+ def agent_type(self) -> str:
384
+ """Agent type identifier.
385
+
386
+ Returns:
387
+ The agent type. Defaults to "config".
388
+ """
389
+ if self._agent_type is not self._UNSET and self._agent_type is not None:
390
+ return self._agent_type
391
+ return "config"
392
+
393
+ @property
394
+ def agent_config(self) -> dict[str, Any] | None:
395
+ """Agent configuration for execution settings.
396
+
397
+ This is used for agent-level settings like execution_timeout.
398
+ Note: The `timeout` property is a convenience shortcut that
399
+ maps to agent_config.execution_timeout.
400
+
401
+ Returns:
402
+ Agent configuration dict or None.
403
+ """
404
+ if self._agent_config is not self._UNSET:
405
+ return self._agent_config
406
+ return None
407
+
408
+ @property
409
+ def tool_configs(self) -> dict[Any, dict[str, Any]] | None:
410
+ """Per-tool configuration overrides.
411
+
412
+ A mapping of tool references (classes, names, or IDs) to their
413
+ configuration overrides. Supports both class keys and string keys.
414
+
415
+ Example:
416
+ >>> @property
417
+ ... def tool_configs(self):
418
+ ... return {
419
+ ... MyToolClass: {"api_key": "xxx"}, # Class key
420
+ ... "other_tool": {"setting": "value"}, # String key
421
+ ... }
422
+
423
+ Returns:
424
+ Tool configurations dict or None.
425
+ """
426
+ if self._tool_configs is not self._UNSET:
427
+ return self._tool_configs
428
+ return None
429
+
430
+ @property
431
+ def mcps(self) -> list:
432
+ """MCPs (Model Context Protocols) available to this agent.
433
+
434
+ MCPs can be:
435
+ - glaip_sdk.models.MCP: SDK MCP object (uses mcp.id)
436
+ - str: MCP name or ID (resolved by platform)
437
+
438
+ Returns:
439
+ List of MCP references. Defaults to empty list.
440
+ """
441
+ return self._mcps or []
442
+
443
+ @property
444
+ def mcp_configs(self) -> dict[str, Any] | None:
445
+ """Per-MCP configuration overrides.
446
+
447
+ A mapping of MCP IDs to their configuration overrides.
448
+
449
+ Returns:
450
+ MCP configurations dict or None.
451
+ """
452
+ if self._mcp_configs is not self._UNSET:
453
+ return self._mcp_configs
454
+ return None
455
+
456
+ @property
457
+ def a2a_profile(self) -> dict[str, Any] | None:
458
+ """A2A (Agent-to-Agent) profile configuration.
459
+
460
+ Configuration for agent-to-agent communication capabilities.
461
+
462
+ Returns:
463
+ A2A profile dict or None.
464
+ """
465
+ if self._a2a_profile is not self._UNSET:
466
+ return self._a2a_profile
467
+ return None
468
+
469
+ def deploy(self) -> Agent:
470
+ """Deploy this agent (with tools and sub-agents) to GL AIP.
471
+
472
+ Performs the following steps:
473
+ 1. Upload custom tools (Tool classes) - cached by ToolRegistry
474
+ 2. Deploy sub-agents recursively (Agent classes) - cached by AgentRegistry
475
+ 3. Resolve tool_configs (requires tools to be in registry first)
476
+ 4. Create/update this agent
477
+
478
+ Tools and agents are cached globally by their respective registries
479
+ to avoid duplicate uploads across deployments.
480
+
481
+ After deployment, this Agent instance is updated in-place with:
482
+ - id: The agent's unique ID on the platform
483
+ - _client: A client reference for run/update/delete operations
484
+
485
+ Returns:
486
+ Self with id and _client set, ready for run() calls.
487
+
488
+ Raises:
489
+ Exception: If deployment fails due to API error.
490
+
491
+ Example:
492
+ >>> agent = Agent(
493
+ ... name="my_agent",
494
+ ... instruction="You are helpful.",
495
+ ... )
496
+ >>> agent.deploy()
497
+ >>> print(f"Deployed: {agent.name} (ID: {agent.id})")
498
+ >>> result = agent.run("Hello!")
499
+ """
500
+ logger.info("Deploying agent: %s", self.name)
501
+
502
+ # Resolve tools FIRST - this uploads them and populates the registry
503
+ tool_ids = self._resolve_tools(get_tool_registry())
504
+
505
+ # Resolve agents
506
+ agent_ids = self._resolve_agents(get_agent_registry())
507
+
508
+ # Now build config - tool_configs can be resolved because tools are in registry
509
+ config = self._build_config(get_tool_registry(), get_mcp_registry())
510
+ config["tools"] = tool_ids
511
+ config["agents"] = agent_ids
512
+
513
+ from glaip_sdk.utils.client import get_client # noqa: PLC0415
514
+
515
+ client = get_client()
516
+ from glaip_sdk.utils.discovery import find_agent # noqa: PLC0415
517
+
518
+ response = self._create_or_update_agent(config, client, find_agent)
519
+
520
+ # Update self with deployed info
521
+ self._id = response.id
522
+ self._client = client
523
+
524
+ return self
525
+
526
+ def _build_config(self, tool_registry: ToolRegistry, mcp_registry: MCPRegistry) -> dict[str, Any]:
527
+ """Build the base configuration dictionary.
528
+
529
+ Args:
530
+ tool_registry: The tool registry for resolving tool configs.
531
+ mcp_registry: The MCP registry for resolving MCPs.
532
+
533
+ Returns:
534
+ Dictionary with agent configuration.
535
+ """
536
+ config: dict[str, Any] = {
537
+ "name": self.name,
538
+ "instruction": self.instruction,
539
+ "description": self.description,
540
+ "framework": self.framework,
541
+ "version": self.version,
542
+ "agent_type": self.agent_type,
543
+ "model": self.model,
544
+ }
545
+
546
+ # Handle metadata (default to empty dict if None)
547
+ config["metadata"] = self.metadata or {}
548
+
549
+ # Handle agent_config with timeout
550
+ # The timeout property is a convenience that maps to agent_config.execution_timeout
551
+ agent_config = dict(self.agent_config) if self.agent_config else {}
552
+ if self.timeout and "execution_timeout" not in agent_config:
553
+ agent_config["execution_timeout"] = self.timeout
554
+ if agent_config:
555
+ config["agent_config"] = agent_config
556
+
557
+ # Handle tool_configs - resolve tool names/classes to IDs
558
+ if self.tool_configs:
559
+ config["tool_configs"] = self._resolve_tool_configs(tool_registry)
560
+
561
+ # Handle MCPs
562
+ if self.mcps:
563
+ config["mcps"] = self._resolve_mcps(mcp_registry)
564
+
565
+ # Handle mcp_configs - normalize keys to MCP IDs
566
+ if self.mcp_configs:
567
+ config["mcp_configs"] = self._resolve_mcp_configs(mcp_registry)
568
+
569
+ # Handle a2a_profile
570
+ if self.a2a_profile:
571
+ config["a2a_profile"] = self.a2a_profile
572
+
573
+ return config
574
+
575
+ def _resolve_mcps(self, registry: MCPRegistry) -> list[str]:
576
+ """Resolve MCP references to IDs using MCPRegistry.
577
+
578
+ Uses the global MCPRegistry to cache MCP objects across deployments.
579
+ The registry handles all MCP types: MCP helpers, strings, dicts,
580
+ and glaip_sdk.models.MCP objects.
581
+
582
+ Args:
583
+ registry: The MCP registry.
584
+
585
+ Returns:
586
+ List of resolved MCP IDs for the API payload.
587
+ """
588
+ if not self.mcps:
589
+ return []
590
+
591
+ return [registry.resolve(mcp_ref).id for mcp_ref in self.mcps]
592
+
593
+ def _resolve_tools(self, registry: ToolRegistry) -> list[str]:
594
+ """Resolve tool references to IDs using ToolRegistry.
595
+
596
+ Uses the global ToolRegistry to cache Tool objects across deployments.
597
+ The registry handles all tool types: Tool classes, LangChain BaseTool,
598
+ glaip_sdk.models.Tool, and string names.
599
+
600
+ Args:
601
+ registry: The tool registry.
602
+
603
+ Returns:
604
+ List of resolved tool IDs for the API payload.
605
+ """
606
+ if not self.tools:
607
+ return []
608
+
609
+ # Resolve each tool reference to a Tool object, extract ID
610
+ return [registry.resolve(tool_ref).id for tool_ref in self.tools]
611
+
612
+ def _resolve_tool_configs(self, registry: ToolRegistry) -> dict[str, Any]:
613
+ """Resolve tool_configs keys from tool names/classes to tool IDs.
614
+
615
+ Allows tool_configs to be defined with tool names, class names, or
616
+ Tool classes as keys. These are resolved to actual tool IDs using
617
+ the ToolRegistry.
618
+
619
+ Supported key formats:
620
+ - Tool class: SyncReportSchedulerTool
621
+ - Tool name string: "sync_report_scheduler"
622
+ - Tool ID (UUID): Passed through unchanged
623
+
624
+ Args:
625
+ registry: The tool registry.
626
+
627
+ Returns:
628
+ Dict with resolved tool IDs as keys and configs as values.
629
+
630
+ Example:
631
+ >>> class MyAgent(Agent):
632
+ ... @property
633
+ ... def tool_configs(self):
634
+ ... return {
635
+ ... SyncReportSchedulerTool: {"api_key": "xxx"},
636
+ ... "other_tool": {"setting": "value"},
637
+ ... }
638
+ """
639
+ if not self.tool_configs:
640
+ return {}
641
+
642
+ resolved: dict[str, Any] = {}
643
+
644
+ for key, config in self.tool_configs.items():
645
+ # If key is already a UUID-like string, pass through
646
+ if isinstance(key, str) and is_uuid(key):
647
+ resolved[key] = config
648
+ continue
649
+
650
+ try:
651
+ # Resolve key (tool name/class) to Tool object, get ID
652
+ tool = registry.resolve(key)
653
+ resolved[tool.id] = config
654
+ except (ValueError, KeyError) as e:
655
+ raise ValueError(f"Failed to resolve tool config key: {key}") from e
656
+
657
+ return resolved
658
+
659
+ def _resolve_mcp_configs(self, registry: MCPRegistry) -> dict[str, Any]:
660
+ """Resolve mcp_configs keys from MCP names/objects to MCP IDs.
661
+
662
+ Allows mcp_configs to be defined with MCP names, MCP objects, or UUIDs
663
+ as keys. Keys are resolved to MCP IDs using the MCPRegistry.
664
+
665
+ Supported key formats:
666
+ - MCP object (with id): uses id directly
667
+ - MCP name string: resolved via registry to ID
668
+ - MCP ID (UUID string): passed through unchanged
669
+
670
+ Args:
671
+ registry: The MCP registry.
672
+
673
+ Returns:
674
+ Dict with resolved MCP IDs as keys and configs as values.
675
+ """
676
+ if not self.mcp_configs:
677
+ return {}
678
+
679
+ resolved: dict[str, Any] = {}
680
+
681
+ for key, config in self.mcp_configs.items():
682
+ try:
683
+ # If key is already a UUID-like string, pass through
684
+ if isinstance(key, str) and is_uuid(key):
685
+ resolved_id = key
686
+ else:
687
+ mcp = registry.resolve(key)
688
+ resolved_id = mcp.id
689
+
690
+ if resolved_id in resolved:
691
+ raise ValueError(
692
+ f"Duplicate mcp_configs entries resolve to the same MCP id '{resolved_id}' (key={key!r})"
693
+ )
694
+
695
+ resolved[resolved_id] = config
696
+ except (ValueError, KeyError) as exc:
697
+ raise ValueError(
698
+ f"Failed to resolve mcp config key {key!r} (type={type(key).__name__}): {exc}"
699
+ ) from exc
700
+
701
+ return resolved
702
+
703
+ def _resolve_agents(self, registry: AgentRegistry) -> list:
704
+ """Resolve sub-agent references using AgentRegistry.
705
+
706
+ Uses the global AgentRegistry to cache Agent objects across deployments.
707
+ The registry handles all agent types: Agent classes, instances,
708
+ glaip_sdk.models.Agent, and string names.
709
+
710
+ Args:
711
+ registry: The agent registry.
712
+
713
+ Returns:
714
+ List of resolved agent IDs for the API payload.
715
+ """
716
+ if not self.agents:
717
+ return []
718
+
719
+ # Resolve each agent reference to a deployed Agent, extract ID
720
+ return [registry.resolve(agent_ref).id for agent_ref in self.agents]
721
+
722
+ def _create_or_update_agent(
723
+ self,
724
+ config: dict[str, Any],
725
+ client: Any,
726
+ find_agent_fn: Any,
727
+ ) -> AgentResponse:
728
+ """Create or update the agent on the platform.
729
+
730
+ Args:
731
+ config: The agent configuration dictionary.
732
+ client: The API client.
733
+ find_agent_fn: Function to find existing agent by name.
734
+
735
+ Returns:
736
+ The created or updated AgentResponse from the API.
737
+ """
738
+ existing = find_agent_fn(self.name)
739
+
740
+ if existing:
741
+ logger.info("Updating existing agent: %s", self.name)
742
+ updated = client.update_agent(agent_id=existing.id, **config)
743
+ logger.info("✓ Agent '%s' updated successfully", self.name)
744
+ return updated
745
+
746
+ logger.info("Creating new agent: %s", self.name)
747
+ created = client.create_agent(**config)
748
+ logger.info("✓ Agent '%s' created successfully", self.name)
749
+ return created
750
+
751
+ @staticmethod
752
+ def load_instruction_from_file(
753
+ path: str,
754
+ base_path: Path | None = None,
755
+ variables: dict[str, str] | None = None,
756
+ ) -> str:
757
+ """Load instruction text from a markdown file.
758
+
759
+ Args:
760
+ path: File path (absolute or relative to base_path).
761
+ base_path: Base directory for relative paths. If None, auto-detected
762
+ from the caller's file location.
763
+ variables: Template variables for {{variable}} substitution.
764
+
765
+ Returns:
766
+ Loaded instruction text with variables substituted.
767
+
768
+ Raises:
769
+ FileNotFoundError: If the instruction file doesn't exist.
770
+
771
+ Example:
772
+ >>> instruction = Agent.load_instruction_from_file(
773
+ ... "instructions/agent.md",
774
+ ... variables={"agent_name": "Weather Bot"}
775
+ ... )
776
+ """
777
+ file_path = Path(path)
778
+
779
+ if not file_path.is_absolute():
780
+ if base_path is None:
781
+ caller_frame = inspect.stack()[1]
782
+ base_path = Path(caller_frame.filename).parent
783
+ file_path = base_path / path
784
+
785
+ if not file_path.exists():
786
+ raise FileNotFoundError(f"Instruction file not found: {file_path}")
787
+
788
+ content = file_path.read_text(encoding="utf-8")
789
+
790
+ if variables:
791
+ for key, value in variables.items():
792
+ content = content.replace(f"{{{{{key}}}}}", value)
793
+
794
+ return content
795
+
796
+ # =========================================================================
797
+ # API Methods - Available after deploy()
798
+ # =========================================================================
799
+
800
+ def model_dump(self, *, exclude_none: bool = False) -> dict[str, Any]:
801
+ """Return a dict representation of the Agent.
802
+
803
+ Provides Pydantic-style serialization for backward compatibility.
804
+
805
+ Args:
806
+ exclude_none: If True, exclude None values from the output.
807
+
808
+ Returns:
809
+ Dictionary containing Agent attributes.
810
+ """
811
+ data = {
812
+ "id": self._id,
813
+ "name": self.name,
814
+ "instruction": self.instruction,
815
+ "description": self.description,
816
+ "type": self.agent_type,
817
+ "framework": self.framework,
818
+ "version": self.version,
819
+ "tools": self.tools,
820
+ "agents": self.agents,
821
+ "mcps": self.mcps,
822
+ "timeout": self.timeout,
823
+ "metadata": self.metadata,
824
+ "agent_config": self.agent_config,
825
+ "tool_configs": self.tool_configs,
826
+ "mcp_configs": self.mcp_configs,
827
+ "a2a_profile": self.a2a_profile,
828
+ "created_at": self._created_at,
829
+ "updated_at": self._updated_at,
830
+ }
831
+ if exclude_none:
832
+ return {k: v for k, v in data.items() if v is not None}
833
+ return data
834
+
835
+ def _set_client(self, client: Any) -> Agent:
836
+ """Set the client for API operations.
837
+
838
+ Args:
839
+ client: The Glaip client instance.
840
+
841
+ Returns:
842
+ Self for method chaining.
843
+ """
844
+ self._client = client
845
+ return self
846
+
847
+ def _prepare_run_kwargs(
848
+ self,
849
+ message: str,
850
+ verbose: bool,
851
+ runtime_config: dict[str, Any] | None,
852
+ **kwargs: Any,
853
+ ) -> tuple[Any, dict[str, Any]]:
854
+ """Prepare common arguments for run/arun methods.
855
+
856
+ Args:
857
+ message: The message to send to the agent.
858
+ verbose: If True, print streaming output to console.
859
+ runtime_config: Optional runtime configuration.
860
+ **kwargs: Additional arguments to pass to the run API.
861
+
862
+ Returns:
863
+ Tuple of (agent_client, call_kwargs).
864
+
865
+ Raises:
866
+ ValueError: If the agent hasn't been deployed yet.
867
+ RuntimeError: If client is not available.
868
+ """
869
+ if not self.id: # pragma: no cover - defensive: called only when self.id is truthy
870
+ raise ValueError(_AGENT_NOT_DEPLOYED_MSG)
871
+ if not self._client:
872
+ raise RuntimeError(_CLIENT_NOT_AVAILABLE_MSG)
873
+
874
+ agent_client = getattr(self._client, "agents", self._client)
875
+
876
+ call_kwargs: dict[str, Any] = {
877
+ "agent_id": self.id,
878
+ "message": message,
879
+ "verbose": verbose,
880
+ }
881
+
882
+ if runtime_config is not None:
883
+ from glaip_sdk.utils.runtime_config import ( # noqa: PLC0415
884
+ normalize_runtime_config_keys,
885
+ )
886
+
887
+ call_kwargs["runtime_config"] = normalize_runtime_config_keys(
888
+ runtime_config,
889
+ tool_registry=get_tool_registry(),
890
+ mcp_registry=get_mcp_registry(),
891
+ agent_registry=get_agent_registry(),
892
+ )
893
+
894
+ call_kwargs.update(kwargs)
895
+ return agent_client, call_kwargs
896
+
897
+ def _get_local_runner_or_raise(self) -> Any:
898
+ """Get the local runner if available, otherwise raise ValueError.
899
+
900
+ Returns:
901
+ The default local runner instance.
902
+
903
+ Raises:
904
+ ValueError: If local runtime is not available.
905
+ """
906
+ from glaip_sdk.runner import get_default_runner # noqa: PLC0415
907
+ from glaip_sdk.runner.deps import ( # noqa: PLC0415
908
+ check_local_runtime_available,
909
+ get_local_runtime_missing_message,
910
+ )
911
+
912
+ if check_local_runtime_available():
913
+ return get_default_runner()
914
+ raise ValueError(f"{_AGENT_NOT_DEPLOYED_MSG}\n\n{get_local_runtime_missing_message()}")
915
+
916
+ def _prepare_local_runner_kwargs(
917
+ self,
918
+ message: str,
919
+ verbose: bool,
920
+ runtime_config: dict[str, Any] | None,
921
+ chat_history: list[dict[str, str]] | None,
922
+ **kwargs: Any,
923
+ ) -> dict[str, Any]:
924
+ """Prepare kwargs for local runner execution.
925
+
926
+ Args:
927
+ message: The message to send to the agent.
928
+ verbose: If True, print streaming output to console.
929
+ runtime_config: Optional runtime configuration.
930
+ chat_history: Optional list of prior conversation messages.
931
+ **kwargs: Additional arguments.
932
+
933
+ Returns:
934
+ Dictionary of prepared kwargs for runner.run() or runner.arun().
935
+ """
936
+ return {
937
+ "agent": self,
938
+ "message": message,
939
+ "verbose": verbose,
940
+ "runtime_config": runtime_config,
941
+ "chat_history": chat_history,
942
+ **kwargs,
943
+ }
944
+
945
+ def run(
946
+ self,
947
+ message: str,
948
+ verbose: bool = False,
949
+ runtime_config: dict[str, Any] | None = None,
950
+ chat_history: list[dict[str, str]] | None = None,
951
+ **kwargs: Any,
952
+ ) -> str:
953
+ """Run the agent synchronously with a message.
954
+
955
+ Supports two execution modes:
956
+ - **Server-backed**: When the agent is deployed (has an ID), execution
957
+ happens via the AIP backend server.
958
+ - **Local**: When the agent is not deployed and glaip-sdk[local] is installed,
959
+ execution happens locally via aip-agents (no server required).
960
+
961
+ Args:
962
+ message: The message to send to the agent.
963
+ verbose: If True, print streaming output to console. Defaults to False.
964
+ runtime_config: Optional runtime configuration for tools, MCPs, and agents.
965
+ Keys can be SDK objects, UUIDs, or names. Example:
966
+ {
967
+ "tool_configs": {"tool-id": {"param": "value"}},
968
+ "mcp_configs": {"mcp-id": {"setting": "on"}},
969
+ "agent_config": {"planning": True},
970
+ }
971
+ Defaults to None.
972
+ chat_history: Optional list of prior conversation messages for context.
973
+ Each message is a dict with "role" and "content" keys.
974
+ Defaults to None.
975
+ **kwargs: Additional arguments to pass to the run API.
976
+
977
+ Returns:
978
+ The agent's response as a string.
979
+
980
+ Raises:
981
+ ValueError: If the agent is not deployed and local runtime is not available.
982
+ RuntimeError: If server-backed execution fails due to client issues.
983
+ """
984
+ # Backend routing: deployed agents use server, undeployed use local (if available)
985
+ if self.id:
986
+ # Server-backed execution path (agent is deployed)
987
+ agent_client, call_kwargs = self._prepare_run_kwargs(
988
+ message, verbose, runtime_config or kwargs.get("runtime_config"), **kwargs
989
+ )
990
+ if chat_history is not None:
991
+ call_kwargs["chat_history"] = chat_history
992
+ return agent_client.run_agent(**call_kwargs)
993
+
994
+ # Local execution path (agent is not deployed)
995
+ runner = self._get_local_runner_or_raise()
996
+ local_kwargs = self._prepare_local_runner_kwargs(message, verbose, runtime_config, chat_history, **kwargs)
997
+ return runner.run(**local_kwargs)
998
+
999
+ async def arun(
1000
+ self,
1001
+ message: str,
1002
+ verbose: bool = False,
1003
+ runtime_config: dict[str, Any] | None = None,
1004
+ chat_history: list[dict[str, str]] | None = None,
1005
+ **kwargs: Any,
1006
+ ) -> AsyncGenerator[dict, None]:
1007
+ """Run the agent asynchronously with streaming output.
1008
+
1009
+ Supports two execution modes:
1010
+ - **Server-backed**: When the agent is deployed (has an ID), execution
1011
+ happens via the AIP backend server with streaming.
1012
+ - **Local**: When the agent is not deployed and glaip-sdk[local] is installed,
1013
+ execution happens locally via aip-agents (no server required).
1014
+
1015
+ Args:
1016
+ message: The message to send to the agent.
1017
+ verbose: If True, print streaming output to console. Defaults to False.
1018
+ runtime_config: Optional runtime configuration for tools, MCPs, and agents.
1019
+ Keys can be SDK objects, UUIDs, or names. Example:
1020
+ {
1021
+ "tool_configs": {"tool-id": {"param": "value"}},
1022
+ "mcp_configs": {"mcp-id": {"setting": "on"}},
1023
+ "agent_config": {"planning": True},
1024
+ }
1025
+ Defaults to None.
1026
+ chat_history: Optional list of prior conversation messages for context.
1027
+ Each message is a dict with "role" and "content" keys.
1028
+ Defaults to None.
1029
+ **kwargs: Additional arguments to pass to the run API.
1030
+
1031
+ Yields:
1032
+ Streaming response chunks from the agent.
1033
+
1034
+ Raises:
1035
+ ValueError: If the agent is not deployed and local runtime is not available.
1036
+ RuntimeError: If server-backed execution fails due to client issues.
1037
+ """
1038
+ # Backend routing: deployed agents use server, undeployed use local (if available)
1039
+ if self.id:
1040
+ # Server-backed execution path (agent is deployed)
1041
+ agent_client, call_kwargs = self._prepare_run_kwargs(
1042
+ message, verbose, runtime_config or kwargs.get("runtime_config"), **kwargs
1043
+ )
1044
+ if chat_history is not None:
1045
+ call_kwargs["chat_history"] = chat_history
1046
+
1047
+ async for chunk in agent_client.arun_agent(**call_kwargs):
1048
+ yield chunk
1049
+ return
1050
+
1051
+ # Local execution path (agent is not deployed)
1052
+ runner = self._get_local_runner_or_raise()
1053
+ local_kwargs = self._prepare_local_runner_kwargs(message, verbose, runtime_config, chat_history, **kwargs)
1054
+ result = await runner.arun(**local_kwargs)
1055
+ # Yield a final_response event for consistency with server-backed execution
1056
+ # Include event_type for A2A event shape parity
1057
+ yield {
1058
+ "event_type": "final_response",
1059
+ "metadata": {"kind": "final_response"},
1060
+ "content": result,
1061
+ "is_final": True,
1062
+ }
1063
+
1064
+ def update(self, **kwargs: Any) -> Agent:
1065
+ """Update the deployed agent with new configuration.
1066
+
1067
+ Args:
1068
+ **kwargs: Agent properties to update (name, instruction, etc.).
1069
+
1070
+ Returns:
1071
+ Self with updated properties.
1072
+
1073
+ Raises:
1074
+ ValueError: If the agent hasn't been deployed yet.
1075
+ RuntimeError: If client is not available.
1076
+ """
1077
+ if not self.id:
1078
+ raise ValueError(_AGENT_NOT_DEPLOYED_MSG)
1079
+ if not self._client:
1080
+ raise RuntimeError(_CLIENT_NOT_AVAILABLE_MSG)
1081
+
1082
+ # _client can be either main Client or AgentClient
1083
+ agent_client = getattr(self._client, "agents", self._client)
1084
+ response = agent_client.update_agent(agent_id=self.id, **kwargs)
1085
+
1086
+ # Update local properties from response (read-only props via private attrs)
1087
+ name = getattr(response, "name", None)
1088
+ if name:
1089
+ self._name = name
1090
+
1091
+ instruction = getattr(response, "instruction", None)
1092
+ if instruction:
1093
+ self._instruction = instruction
1094
+
1095
+ # Populate remaining fields like description, metadata, updated_at, etc.
1096
+ type(self)._populate_from_response(self, response)
1097
+
1098
+ return self
1099
+
1100
+ def delete(self) -> None:
1101
+ """Delete the deployed agent.
1102
+
1103
+ Raises:
1104
+ ValueError: If the agent hasn't been deployed yet.
1105
+ RuntimeError: If client is not available.
1106
+ """
1107
+ if not self.id:
1108
+ raise ValueError(_AGENT_NOT_DEPLOYED_MSG)
1109
+ if not self._client:
1110
+ raise RuntimeError(_CLIENT_NOT_AVAILABLE_MSG)
1111
+
1112
+ # _client can be either main Client or AgentClient
1113
+ agent_client = getattr(self._client, "agents", self._client)
1114
+ agent_client.delete_agent(self.id)
1115
+ self.id = None
1116
+ self._client = None
1117
+
1118
+ @classmethod
1119
+ def _populate_from_response(cls, agent: Agent, response: AgentResponse) -> None:
1120
+ """Populate agent fields from API response."""
1121
+ # Field mappings: (response_attr, agent_attr, require_truthy)
1122
+ field_mappings = [
1123
+ ("description", "_description", True),
1124
+ ("model", "_model", True),
1125
+ ("type", "_agent_type", True),
1126
+ ("framework", "_framework", True),
1127
+ ("version", "_version", True),
1128
+ ("timeout", "_timeout", True),
1129
+ ("metadata", "_metadata", True),
1130
+ ("agent_config", "_agent_config", True),
1131
+ ("tool_configs", "_tool_configs", True),
1132
+ ("mcp_configs", "_mcp_configs", True),
1133
+ ("a2a_profile", "_a2a_profile", True),
1134
+ ("language_model_id", "_language_model_id", True),
1135
+ ("created_at", "_created_at", False),
1136
+ ("updated_at", "_updated_at", False),
1137
+ ]
1138
+
1139
+ for resp_attr, agent_attr, require_truthy in field_mappings:
1140
+ value = getattr(response, resp_attr, None)
1141
+ if require_truthy:
1142
+ if value:
1143
+ setattr(agent, agent_attr, value)
1144
+ else:
1145
+ if value is not None:
1146
+ setattr(agent, agent_attr, value)
1147
+
1148
+ # Copy relationship refs as-is (preserve full objects for serialization)
1149
+ # Registry resolution handles extracting IDs during deployment
1150
+ tools_val = getattr(response, "tools", None)
1151
+ if tools_val:
1152
+ agent._tools = tools_val
1153
+
1154
+ agents_val = getattr(response, "agents", None)
1155
+ if agents_val:
1156
+ agent._agents = agents_val
1157
+
1158
+ mcps_val = getattr(response, "mcps", None)
1159
+ if mcps_val:
1160
+ agent._mcps = mcps_val
1161
+
1162
+ @classmethod
1163
+ def from_response(
1164
+ cls,
1165
+ response: AgentResponse,
1166
+ client: Any = None,
1167
+ ) -> Agent:
1168
+ """Create an Agent instance from an API response.
1169
+
1170
+ This allows you to work with agents retrieved from the API
1171
+ as full Agent instances with all methods available.
1172
+
1173
+ Args:
1174
+ response: The AgentResponse from an API call.
1175
+ client: The Glaip client instance for API operations.
1176
+
1177
+ Returns:
1178
+ An Agent instance initialized from the response.
1179
+
1180
+ Example:
1181
+ >>> response = client.agents.get("agent-123")
1182
+ >>> agent = Agent.from_response(response, client)
1183
+ >>> result = agent.run("Hello!")
1184
+ """
1185
+ agent = cls(
1186
+ name=response.name,
1187
+ instruction=response.instruction or "",
1188
+ id=response.id,
1189
+ )
1190
+
1191
+ cls._populate_from_response(agent, response)
1192
+
1193
+ if client:
1194
+ agent._set_client(client)
1195
+
1196
+ return agent