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