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