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