glaip-sdk 0.6.6__py3-none-any.whl → 0.6.9__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.
glaip_sdk/agents/base.py CHANGED
@@ -46,10 +46,17 @@ import inspect
46
46
  import logging
47
47
  import warnings
48
48
  from collections.abc import AsyncGenerator
49
+
50
+
49
51
  from pathlib import Path
50
52
  from typing import TYPE_CHECKING, Any
51
53
 
52
54
  from glaip_sdk.registry import get_agent_registry, get_mcp_registry, get_tool_registry
55
+ from glaip_sdk.runner import get_default_runner
56
+ from glaip_sdk.runner.deps import (
57
+ check_local_runtime_available,
58
+ get_local_runtime_missing_message,
59
+ )
53
60
  from glaip_sdk.utils.discovery import find_agent
54
61
  from glaip_sdk.utils.resource_refs import is_uuid
55
62
  from glaip_sdk.utils.runtime_config import normalize_runtime_config_keys
@@ -864,7 +871,7 @@ class Agent:
864
871
  ValueError: If the agent hasn't been deployed yet.
865
872
  RuntimeError: If client is not available.
866
873
  """
867
- if not self.id:
874
+ if not self.id: # pragma: no cover - defensive: called only when self.id is truthy
868
875
  raise ValueError(_AGENT_NOT_DEPLOYED_MSG)
869
876
  if not self._client:
870
877
  raise RuntimeError(_CLIENT_NOT_AVAILABLE_MSG)
@@ -888,18 +895,67 @@ class Agent:
888
895
  call_kwargs.update(kwargs)
889
896
  return agent_client, call_kwargs
890
897
 
898
+ def _get_local_runner_or_raise(self) -> Any:
899
+ """Get the local runner if available, otherwise raise ValueError.
900
+
901
+ Returns:
902
+ The default local runner instance.
903
+
904
+ Raises:
905
+ ValueError: If local runtime is not available.
906
+ """
907
+ if check_local_runtime_available():
908
+ return get_default_runner()
909
+ raise ValueError(f"{_AGENT_NOT_DEPLOYED_MSG}\n\n{get_local_runtime_missing_message()}")
910
+
911
+ def _prepare_local_runner_kwargs(
912
+ self,
913
+ message: str,
914
+ verbose: bool,
915
+ runtime_config: dict[str, Any] | None,
916
+ chat_history: list[dict[str, str]] | None,
917
+ **kwargs: Any,
918
+ ) -> dict[str, Any]:
919
+ """Prepare kwargs for local runner execution.
920
+
921
+ Args:
922
+ message: The message to send to the agent.
923
+ verbose: If True, print streaming output to console.
924
+ runtime_config: Optional runtime configuration.
925
+ chat_history: Optional list of prior conversation messages.
926
+ **kwargs: Additional arguments.
927
+
928
+ Returns:
929
+ Dictionary of prepared kwargs for runner.run() or runner.arun().
930
+ """
931
+ return {
932
+ "agent": self,
933
+ "message": message,
934
+ "verbose": verbose,
935
+ "runtime_config": runtime_config,
936
+ "chat_history": chat_history,
937
+ **kwargs,
938
+ }
939
+
891
940
  def run(
892
941
  self,
893
942
  message: str,
894
943
  verbose: bool = False,
895
944
  runtime_config: dict[str, Any] | None = None,
945
+ chat_history: list[dict[str, str]] | None = None,
896
946
  **kwargs: Any,
897
947
  ) -> str:
898
948
  """Run the agent synchronously with a message.
899
949
 
950
+ Supports two execution modes:
951
+ - **Server-backed**: When the agent is deployed (has an ID), execution
952
+ happens via the AIP backend server.
953
+ - **Local**: When the agent is not deployed and glaip-sdk[local] is installed,
954
+ execution happens locally via aip-agents (no server required).
955
+
900
956
  Args:
901
957
  message: The message to send to the agent.
902
- verbose: If True, print streaming output to console.
958
+ verbose: If True, print streaming output to console. Defaults to False.
903
959
  runtime_config: Optional runtime configuration for tools, MCPs, and agents.
904
960
  Keys can be SDK objects, UUIDs, or names. Example:
905
961
  {
@@ -907,32 +963,53 @@ class Agent:
907
963
  "mcp_configs": {"mcp-id": {"setting": "on"}},
908
964
  "agent_config": {"planning": True},
909
965
  }
966
+ Defaults to None.
967
+ chat_history: Optional list of prior conversation messages for context.
968
+ Each message is a dict with "role" and "content" keys.
969
+ Defaults to None.
910
970
  **kwargs: Additional arguments to pass to the run API.
911
971
 
912
972
  Returns:
913
973
  The agent's response as a string.
914
974
 
915
975
  Raises:
916
- ValueError: If the agent hasn't been deployed yet.
917
- RuntimeError: If client is not available.
976
+ ValueError: If the agent is not deployed and local runtime is not available.
977
+ RuntimeError: If server-backed execution fails due to client issues.
918
978
  """
919
- agent_client, call_kwargs = self._prepare_run_kwargs(
920
- message, verbose, runtime_config or kwargs.get("runtime_config"), **kwargs
921
- )
922
- return agent_client.run_agent(**call_kwargs)
979
+ # Backend routing: deployed agents use server, undeployed use local (if available)
980
+ if self.id:
981
+ # Server-backed execution path (agent is deployed)
982
+ agent_client, call_kwargs = self._prepare_run_kwargs(
983
+ message, verbose, runtime_config or kwargs.get("runtime_config"), **kwargs
984
+ )
985
+ if chat_history is not None:
986
+ call_kwargs["chat_history"] = chat_history
987
+ return agent_client.run_agent(**call_kwargs)
988
+
989
+ # Local execution path (agent is not deployed)
990
+ runner = self._get_local_runner_or_raise()
991
+ local_kwargs = self._prepare_local_runner_kwargs(message, verbose, runtime_config, chat_history, **kwargs)
992
+ return runner.run(**local_kwargs)
923
993
 
924
994
  async def arun(
925
995
  self,
926
996
  message: str,
927
997
  verbose: bool = False,
928
998
  runtime_config: dict[str, Any] | None = None,
999
+ chat_history: list[dict[str, str]] | None = None,
929
1000
  **kwargs: Any,
930
1001
  ) -> AsyncGenerator[dict, None]:
931
1002
  """Run the agent asynchronously with streaming output.
932
1003
 
1004
+ Supports two execution modes:
1005
+ - **Server-backed**: When the agent is deployed (has an ID), execution
1006
+ happens via the AIP backend server with streaming.
1007
+ - **Local**: When the agent is not deployed and glaip-sdk[local] is installed,
1008
+ execution happens locally via aip-agents (no server required).
1009
+
933
1010
  Args:
934
1011
  message: The message to send to the agent.
935
- verbose: If True, print streaming output to console.
1012
+ verbose: If True, print streaming output to console. Defaults to False.
936
1013
  runtime_config: Optional runtime configuration for tools, MCPs, and agents.
937
1014
  Keys can be SDK objects, UUIDs, or names. Example:
938
1015
  {
@@ -940,20 +1017,44 @@ class Agent:
940
1017
  "mcp_configs": {"mcp-id": {"setting": "on"}},
941
1018
  "agent_config": {"planning": True},
942
1019
  }
1020
+ Defaults to None.
1021
+ chat_history: Optional list of prior conversation messages for context.
1022
+ Each message is a dict with "role" and "content" keys.
1023
+ Defaults to None.
943
1024
  **kwargs: Additional arguments to pass to the run API.
944
1025
 
945
1026
  Yields:
946
1027
  Streaming response chunks from the agent.
947
1028
 
948
1029
  Raises:
949
- ValueError: If the agent hasn't been deployed yet.
950
- RuntimeError: If client is not available.
1030
+ ValueError: If the agent is not deployed and local runtime is not available.
1031
+ RuntimeError: If server-backed execution fails due to client issues.
951
1032
  """
952
- agent_client, call_kwargs = self._prepare_run_kwargs(
953
- message, verbose, runtime_config or kwargs.get("runtime_config"), **kwargs
954
- )
955
- async for chunk in agent_client.arun_agent(**call_kwargs):
956
- yield chunk
1033
+ # Backend routing: deployed agents use server, undeployed use local (if available)
1034
+ if self.id:
1035
+ # Server-backed execution path (agent is deployed)
1036
+ agent_client, call_kwargs = self._prepare_run_kwargs(
1037
+ message, verbose, runtime_config or kwargs.get("runtime_config"), **kwargs
1038
+ )
1039
+ if chat_history is not None:
1040
+ call_kwargs["chat_history"] = chat_history
1041
+
1042
+ async for chunk in agent_client.arun_agent(**call_kwargs):
1043
+ yield chunk
1044
+ return
1045
+
1046
+ # Local execution path (agent is not deployed)
1047
+ runner = self._get_local_runner_or_raise()
1048
+ local_kwargs = self._prepare_local_runner_kwargs(message, verbose, runtime_config, chat_history, **kwargs)
1049
+ result = await runner.arun(**local_kwargs)
1050
+ # Yield a final_response event for consistency with server-backed execution
1051
+ # Include event_type for A2A event shape parity
1052
+ yield {
1053
+ "event_type": "final_response",
1054
+ "metadata": {"kind": "final_response"},
1055
+ "content": result,
1056
+ "is_final": True,
1057
+ }
957
1058
 
958
1059
  def update(self, **kwargs: Any) -> Agent:
959
1060
  """Update the deployed agent with new configuration.
@@ -22,7 +22,7 @@ from glaip_sdk.branding import ACCENT_STYLE, ERROR_STYLE, INFO, NEUTRAL, SUCCESS
22
22
  # Optional import for gitignore support; warn when missing to avoid silent expansion
23
23
  try:
24
24
  import pathspec # type: ignore[import-untyped] # noqa: PLC0415
25
- except ImportError:
25
+ except ImportError: # pragma: no cover - optional dependency
26
26
  pathspec = None # type: ignore[assignment]
27
27
  from glaip_sdk.cli.account_store import get_account_store
28
28
  from glaip_sdk.cli.commands.common_config import check_connection, render_branding_header
@@ -160,19 +160,13 @@ class ToolRegistry(BaseRegistry["Tool"]):
160
160
  True if ref is a custom tool that needs uploading.
161
161
  """
162
162
  try:
163
- from langchain_core.tools import BaseTool # noqa: PLC0415
164
-
165
- # LangChain BaseTool class
166
- if isinstance(ref, type) and issubclass(ref, BaseTool):
167
- return True
168
-
169
- # LangChain BaseTool instance
170
- if isinstance(ref, BaseTool):
171
- return True
163
+ from glaip_sdk.utils.tool_detection import ( # noqa: PLC0415
164
+ is_langchain_tool,
165
+ )
172
166
  except ImportError:
173
- pass
167
+ return False
174
168
 
175
- return False
169
+ return is_langchain_tool(ref)
176
170
 
177
171
  def resolve(self, ref: Any) -> Tool:
178
172
  """Resolve a tool reference to a platform Tool object.
@@ -0,0 +1,59 @@
1
+ """Local agent execution runners.
2
+
3
+ This module provides runners for executing glaip-sdk agents locally
4
+ without requiring the AIP backend server. The primary runner is
5
+ LangGraphRunner which uses the aip-agents library.
6
+
7
+ To use local execution, install with the [local] extra:
8
+ pip install "glaip-sdk[local]"
9
+
10
+ Authors:
11
+ Christian Trisno Sen Long Chen (christian.t.s.l.chen@gdplabs.id)
12
+
13
+ Example:
14
+ >>> from glaip_sdk.runner import get_default_runner
15
+ >>> from glaip_sdk.agents import Agent
16
+ >>>
17
+ >>> agent = Agent(name="my-agent", instruction="You are helpful.")
18
+ >>> runner = get_default_runner()
19
+ >>> result = runner.run(agent, "Hello!")
20
+ """
21
+
22
+ from glaip_sdk.runner.deps import (
23
+ LOCAL_RUNTIME_AVAILABLE,
24
+ check_local_runtime_available,
25
+ get_local_runtime_missing_message,
26
+ )
27
+ from glaip_sdk.runner.langgraph import LangGraphRunner
28
+
29
+ # Default runner instance
30
+ _default_runner: LangGraphRunner | None = None
31
+
32
+
33
+ def get_default_runner() -> LangGraphRunner:
34
+ """Get the default runner instance for local agent execution.
35
+
36
+ Returns:
37
+ The default LangGraphRunner instance.
38
+
39
+ Raises:
40
+ RuntimeError: If local runtime dependencies are not available.
41
+ """
42
+ global _default_runner
43
+
44
+ if not check_local_runtime_available():
45
+ raise RuntimeError(get_local_runtime_missing_message())
46
+
47
+ if _default_runner is None:
48
+ _default_runner = LangGraphRunner()
49
+
50
+ return _default_runner
51
+
52
+
53
+ __all__ = [
54
+ "LOCAL_RUNTIME_AVAILABLE",
55
+ "LangGraphRunner",
56
+ "check_local_runtime_available",
57
+ "get_default_runner",
58
+ "get_local_runtime_missing_message",
59
+ ]
@@ -0,0 +1,84 @@
1
+ """Abstract base class for agent execution runners.
2
+
3
+ Authors:
4
+ Christian Trisno Sen Long Chen (christian.t.s.l.chen@gdplabs.id)
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from abc import ABC, abstractmethod
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ if TYPE_CHECKING:
13
+ from glaip_sdk.agents.base import Agent
14
+
15
+
16
+ class BaseRunner(ABC):
17
+ """Abstract base class for agent execution runners.
18
+
19
+ Runners are responsible for executing glaip-sdk Agent instances
20
+ and returning results. Different runner implementations may use
21
+ different execution backends (LangGraph, Google ADK, etc.).
22
+ """
23
+
24
+ @abstractmethod
25
+ def run(
26
+ self,
27
+ agent: Agent,
28
+ message: str,
29
+ verbose: bool = False,
30
+ runtime_config: dict[str, Any] | None = None,
31
+ chat_history: list[dict[str, str]] | None = None,
32
+ **kwargs: Any,
33
+ ) -> str:
34
+ """Execute agent synchronously and return final response text.
35
+
36
+ Args:
37
+ agent: The glaip_sdk Agent to execute.
38
+ message: The user message to send to the agent.
39
+ verbose: If True, emit debug trace output during execution.
40
+ Defaults to False.
41
+ runtime_config: Optional runtime configuration for tools, MCPs, etc.
42
+ Defaults to None.
43
+ chat_history: Optional list of prior conversation messages.
44
+ Defaults to None.
45
+ **kwargs: Additional keyword arguments passed to the backend.
46
+
47
+ Returns:
48
+ The final response text from the agent.
49
+
50
+ Raises:
51
+ RuntimeError: If execution fails.
52
+ """
53
+ ...
54
+
55
+ @abstractmethod
56
+ async def arun(
57
+ self,
58
+ agent: Agent,
59
+ message: str,
60
+ verbose: bool = False,
61
+ runtime_config: dict[str, Any] | None = None,
62
+ chat_history: list[dict[str, str]] | None = None,
63
+ **kwargs: Any,
64
+ ) -> str:
65
+ """Execute agent asynchronously and return final response text.
66
+
67
+ Args:
68
+ agent: The glaip_sdk Agent to execute.
69
+ message: The user message to send to the agent.
70
+ verbose: If True, emit debug trace output during execution.
71
+ Defaults to False.
72
+ runtime_config: Optional runtime configuration for tools, MCPs, etc.
73
+ Defaults to None.
74
+ chat_history: Optional list of prior conversation messages.
75
+ Defaults to None.
76
+ **kwargs: Additional keyword arguments passed to the backend.
77
+
78
+ Returns:
79
+ The final response text from the agent.
80
+
81
+ Raises:
82
+ RuntimeError: If execution fails.
83
+ """
84
+ ...
@@ -0,0 +1,115 @@
1
+ """Dependency detection utilities for the runner module.
2
+
3
+ This module provides helpers to detect whether the local runtime dependencies
4
+ (aip-agents) are installed and to generate actionable error messages when they
5
+ are not available.
6
+
7
+ Authors:
8
+ Christian Trisno Sen Long Chen (christian.t.s.l.chen@gdplabs.id)
9
+
10
+ Example:
11
+ >>> from glaip_sdk.runner.deps import check_local_runtime_available
12
+ >>> if not check_local_runtime_available():
13
+ ... print(get_local_runtime_missing_message())
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from gllm_core.utils import LoggerManager
19
+
20
+ logger = LoggerManager().get_logger(__name__)
21
+
22
+ # Module-level cache for import availability check
23
+ _local_runtime_available: bool | None = None
24
+
25
+
26
+ def _probe_aip_agents_import() -> bool:
27
+ """Attempt to import aip_agents and return success status.
28
+
29
+ Returns:
30
+ True if aip_agents can be imported successfully, False otherwise.
31
+ """
32
+ try:
33
+ import aip_agents # noqa: F401, PLC0415
34
+
35
+ return True
36
+ except ImportError:
37
+ return False
38
+
39
+
40
+ def check_local_runtime_available() -> bool:
41
+ """Check if the local runtime dependencies are installed and importable.
42
+
43
+ This function probes for the aip_agents module which provides the
44
+ LangGraphReactAgent for local execution. Results are cached for efficiency.
45
+
46
+ Returns:
47
+ True if local runtime is available, False otherwise.
48
+ """
49
+ global _local_runtime_available
50
+
51
+ if _local_runtime_available is None:
52
+ _local_runtime_available = _probe_aip_agents_import()
53
+ if _local_runtime_available:
54
+ logger.debug("Local runtime dependencies (aip-agents) detected")
55
+ else:
56
+ logger.debug("Local runtime dependencies (aip-agents) not available")
57
+
58
+ return _local_runtime_available
59
+
60
+
61
+ # Cached availability flag for use in conditions without function call overhead
62
+ LOCAL_RUNTIME_AVAILABLE: bool = check_local_runtime_available()
63
+
64
+
65
+ def get_local_runtime_missing_message() -> str:
66
+ """Generate an actionable error message when local runtime is not available.
67
+
68
+ Returns:
69
+ A user-friendly message explaining how to install local runtime dependencies
70
+ or how to use server-backed execution as an alternative.
71
+ """
72
+ return (
73
+ "Local runtime dependencies are not installed. "
74
+ "To run agents locally without an AIP server, install with:\n\n"
75
+ ' pip install "glaip-sdk[local]"\n\n'
76
+ "Alternatively, call deploy() to run this agent on the AIP server."
77
+ )
78
+
79
+
80
+ def get_local_mode_not_supported_for_tool_message(tool_ref: str) -> str:
81
+ """Generate an error message for tools that cannot be used in local mode.
82
+
83
+ Args:
84
+ tool_ref: A string identifier for the tool (name, ID, or type description).
85
+
86
+ Returns:
87
+ Error message explaining that the tool type is not supported locally.
88
+ """
89
+ return (
90
+ f"Tool '{tool_ref}' cannot be used in local mode. "
91
+ "Local runtime only supports LangChain-compatible tool classes/instances "
92
+ "and Tool.from_langchain(...) references. "
93
+ "Native platform tools (Tool.from_native()) require server-backed execution "
94
+ "via deploy()."
95
+ )
96
+
97
+
98
+ def get_uuid_not_supported_message(key_type: str, uuid_value: str) -> str:
99
+ """Generate an error message when a UUID is used in local mode.
100
+
101
+ In local mode, runtime_config keys must be tool/agent/MCP objects or names,
102
+ not UUIDs which require platform registry resolution.
103
+
104
+ Args:
105
+ key_type: The type of key (e.g., "tool", "agent", "mcp").
106
+ uuid_value: The UUID that was incorrectly provided.
107
+
108
+ Returns:
109
+ Error message explaining that UUIDs are not supported in local mode.
110
+ """
111
+ return (
112
+ f"UUID-like {key_type} key '{uuid_value}' is not supported in local mode. "
113
+ f"Local runtime cannot resolve {key_type} IDs - pass the {key_type} "
114
+ f"class/instance or name instead."
115
+ )