glaip-sdk 0.5.5__py3-none-any.whl → 0.6.0__py3-none-any.whl

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