aigency 0.0.1rc136602178__tar.gz → 0.0.1rc163779164__tar.gz

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 (32) hide show
  1. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/PKG-INFO +1 -1
  2. aigency-0.0.1rc163779164/aigency/agents/client.py +59 -0
  3. aigency-0.0.1rc163779164/aigency/agents/communicator.py +107 -0
  4. aigency-0.0.1rc163779164/aigency/agents/generator.py +134 -0
  5. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/agent/agent.py +2 -0
  6. aigency-0.0.1rc163779164/aigency/schemas/agent/remote_agent.py +9 -0
  7. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/utils/utils.py +19 -1
  8. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency.egg-info/PKG-INFO +1 -1
  9. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency.egg-info/SOURCES.txt +3 -0
  10. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/pyproject.toml +1 -1
  11. aigency-0.0.1rc136602178/aigency/agents/generator.py +0 -75
  12. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/README.md +0 -0
  13. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/__init__.py +0 -0
  14. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/agents/executor.py +0 -0
  15. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/agent/model.py +0 -0
  16. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/agent/skills.py +0 -0
  17. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/agent/tools.py +0 -0
  18. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/aigency_config.py +0 -0
  19. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/metadata/metadata.py +0 -0
  20. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/observability/observability.py +0 -0
  21. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/observability/phoenix.py +0 -0
  22. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/service/capabilities.py +0 -0
  23. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/service/interface.py +0 -0
  24. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/schemas/service/service.py +0 -0
  25. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/tools/generator.py +0 -0
  26. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/utils/config_service.py +0 -0
  27. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/utils/logger.py +0 -0
  28. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency/utils/singleton.py +0 -0
  29. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency.egg-info/dependency_links.txt +0 -0
  30. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency.egg-info/requires.txt +0 -0
  31. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/aigency.egg-info/top_level.txt +0 -0
  32. {aigency-0.0.1rc136602178 → aigency-0.0.1rc163779164}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aigency
3
- Version: 0.0.1rc136602178
3
+ Version: 0.0.1rc163779164
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.12
6
6
  Description-Content-Type: text/markdown
@@ -0,0 +1,59 @@
1
+ import httpx
2
+
3
+ from a2a.client.client import ClientConfig
4
+ from a2a.client.client_factory import ClientFactory
5
+ from a2a.types import AgentCard, Message, SendMessageResponse
6
+ #TODO: Enable when auth is implemented
7
+ #from a2a.client.auth.interceptor import AuthInterceptor
8
+
9
+
10
+ class AgentClient:
11
+ """A class to hold the connections to the remote agents.
12
+
13
+ This class manages connections to remote agents using the A2A protocol.
14
+ It provides methods for retrieving agent information and sending messages
15
+ to remote agents.
16
+
17
+ Attributes:
18
+ _httpx_client (httpx.AsyncClient): The HTTP client used for asynchronous requests.
19
+ agent_card (AgentCard): The agent card containing metadata about the remote agent.
20
+ """
21
+
22
+ def __init__(self, agent_card: AgentCard):
23
+ """Initialize a connection to a remote agent.
24
+
25
+ Args:
26
+ agent_card (AgentCard): The agent card containing metadata about the remote agent.
27
+
28
+ Raises:
29
+ None
30
+
31
+ Returns:
32
+ None
33
+ """
34
+ self._httpx_client = httpx.AsyncClient(timeout=60)
35
+ self.card = agent_card
36
+
37
+ config = ClientConfig(httpx_client=self._httpx_client)
38
+ factory = ClientFactory(config=config)
39
+ self.agent_client = factory.create(agent_card)
40
+
41
+ def get_agent(self) -> AgentCard:
42
+ """Get the agent card for this remote agent connection.
43
+
44
+ Returns:
45
+ AgentCard: The agent card containing metadata about the remote agent.
46
+ """
47
+ return self.card
48
+
49
+ async def send_message(self, message_request: Message) -> SendMessageResponse:
50
+ """Send a message to the remote agent.
51
+
52
+ Args:
53
+ message_request (Message): The message request to send to the remote agent.
54
+
55
+ Returns:
56
+ SendMessageResponse: The response from the remote agent.
57
+ """
58
+ async for response in self.agent_client.send_message(message_request):
59
+ yield response
@@ -0,0 +1,107 @@
1
+ import logging
2
+ import uuid
3
+ from typing import Any
4
+ from a2a.types import Message, Task
5
+ from google.adk.tools.tool_context import ToolContext
6
+
7
+ logging.basicConfig(level=logging.INFO)
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class Communicator:
12
+ """Base class for Agent-to-Agent communication."""
13
+
14
+ def __init__(self, remote_agent_connections=None):
15
+ self.remote_agent_connections = remote_agent_connections
16
+
17
+ async def send_message(self, agent_name: str, task: str, tool_context: ToolContext):
18
+ """Delegate a task to a specified remote agent.
19
+
20
+ This method sends a message to a remote agent, requesting it to perform a task.
21
+ It handles the creation of the message payload and manages the communication
22
+ with the remote agent.
23
+
24
+ Args:
25
+ agent_name: Name of the remote agent to send the task to.
26
+ task: Detailed description of the task for the remote agent to perform.
27
+ tool_context: Context object containing state and other information.
28
+
29
+ Returns:
30
+ Task object if successful, None otherwise.
31
+
32
+ Raises:
33
+ ValueError: If the specified agent is not found in the available connections.
34
+ """
35
+ logger.info(
36
+ f"`send_message` triggered with agent_name: {agent_name}, task: {task}"
37
+ )
38
+ if agent_name not in self.remote_agent_connections:
39
+ logger.error(
40
+ f"LLM tried to call '{agent_name}' but it was not found. "
41
+ f"Available agents: {list(self.remote_agent_connections.keys())}"
42
+ )
43
+ raise ValueError(f"Agent '{agent_name}' not found.")
44
+
45
+ state = tool_context.state
46
+ client = self.remote_agent_connections[agent_name]
47
+
48
+ if "remote_agent_contexts" not in state:
49
+ state["remote_agent_contexts"] = {}
50
+
51
+ if agent_name not in state["remote_agent_contexts"]:
52
+ logger.debug(f"Creating new context for agent: {agent_name}")
53
+ state["remote_agent_contexts"][agent_name] = {
54
+ "context_id": str(uuid.uuid4())
55
+ }
56
+ context_id = state["remote_agent_contexts"][agent_name]["context_id"]
57
+ task_id = state.get("task_id", None)
58
+ message_id = state.get("input_message_metadata", {}).get(
59
+ "message_id", str(uuid.uuid4())
60
+ )
61
+
62
+ payload = self.create_send_message_payload(task, task_id, context_id)
63
+ payload["message"]["message_id"] = message_id
64
+ logger.debug("`send_message` triggered with payload: %s", payload)
65
+
66
+ send_response = None
67
+ async for resp in client.send_message(
68
+ message_request=Message(**payload.get("message"))
69
+ ):
70
+ send_response = resp
71
+
72
+ if isinstance(send_response, tuple):
73
+ send_response, _ = send_response
74
+
75
+ if not isinstance(send_response, Task):
76
+ return None
77
+ return send_response
78
+
79
+ @staticmethod
80
+ def create_send_message_payload(
81
+ text: str,
82
+ task_id: str | None = None,
83
+ context_id: str | None = None,
84
+ ) -> dict[str, Any]:
85
+ """Create a message payload for sending to a remote agent.
86
+
87
+ Args:
88
+ text: The text content of the message.
89
+ task_id: Optional task ID to associate with the message.
90
+ context_id: Optional context ID to associate with the message.
91
+
92
+ Returns:
93
+ dict: A dictionary containing the formatted message payload ready
94
+ to be sent to a remote agent.
95
+ """
96
+ payload: dict[str, Any] = {
97
+ "message": {
98
+ "role": "user",
99
+ "parts": [{"type": "text", "text": text}],
100
+ "message_id": uuid.uuid4().hex,
101
+ },
102
+ }
103
+ if task_id:
104
+ payload["message"]["task_id"] = task_id
105
+ if context_id:
106
+ payload["message"]["context_id"] = context_id
107
+ return payload
@@ -0,0 +1,134 @@
1
+ import logging
2
+ import httpx
3
+ from google.adk.agents import Agent
4
+ from a2a.types import AgentCapabilities, AgentCard, AgentSkill
5
+
6
+ from aigency.agents.executor import AgentA2AExecutor
7
+ from aigency.agents.client import AgentClient
8
+ from aigency.schemas.aigency_config import AigencyConfig
9
+ from aigency.tools.generator import ToolGenerator
10
+ from aigency.utils.utils import generate_url, safe_async_run
11
+ from aigency.agents.communicator import Communicator
12
+
13
+ from google.adk.artifacts import InMemoryArtifactService
14
+ from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
15
+ from google.adk.runners import Runner
16
+ from google.adk.sessions import InMemorySessionService
17
+
18
+ from a2a.client import A2ACardResolver
19
+
20
+
21
+ class AgentA2AGenerator:
22
+
23
+ @staticmethod
24
+ def create_agent(agent_config: AigencyConfig) -> Agent:
25
+
26
+ tools = [
27
+ ToolGenerator.create_tool(tool_cfg) for tool_cfg in agent_config.agent.tools
28
+ ]
29
+
30
+ remote_agents = agent_config.agent.remote_agents
31
+ if remote_agents:
32
+ remote_agent_connections = AgentA2AGenerator.build_remote_agent_connections(
33
+ agent_config
34
+ )
35
+ logger.info(f"Remote agent connections: {remote_agent_connections}")
36
+ communicator = Communicator(
37
+ remote_agent_connections=remote_agent_connections
38
+ )
39
+ tools.append(communicator.send_message)
40
+
41
+ return Agent(
42
+ name=agent_config.metadata.name,
43
+ model=agent_config.agent.model.name,
44
+ instruction=agent_config.agent.instruction,
45
+ tools=tools,
46
+ )
47
+
48
+ @staticmethod
49
+ def build_agent_card(agent_config: AigencyConfig) -> AgentCard:
50
+
51
+ # TODO: Parse properly
52
+ capabilities = AgentCapabilities(
53
+ streaming=agent_config.service.capabilities.streaming
54
+ )
55
+
56
+ skills = [
57
+ AgentSkill(
58
+ id=skill.id,
59
+ name=skill.name,
60
+ description=skill.description,
61
+ tags=skill.tags,
62
+ examples=skill.examples,
63
+ )
64
+ for skill in agent_config.agent.skills
65
+ ]
66
+
67
+ return AgentCard(
68
+ name=agent_config.metadata.name,
69
+ description=agent_config.metadata.description,
70
+ url=agent_config.service.url,
71
+ version=agent_config.metadata.version,
72
+ default_input_modes=agent_config.service.interface.default_input_modes,
73
+ default_output_modes=agent_config.service.interface.default_output_modes,
74
+ capabilities=capabilities,
75
+ skills=skills,
76
+ )
77
+
78
+ @staticmethod
79
+ def build_executor(agent: Agent, agent_card: AgentCard) -> AgentA2AExecutor:
80
+
81
+ runner = Runner(
82
+ app_name=agent.name,
83
+ agent=agent,
84
+ artifact_service=InMemoryArtifactService(),
85
+ session_service=InMemorySessionService(),
86
+ memory_service=InMemoryMemoryService(),
87
+ )
88
+
89
+ return AgentA2AExecutor(runner=runner, card=agent_card)
90
+
91
+ @staticmethod
92
+ def build_remote_agent_connections(agent_config: AigencyConfig):
93
+ """Initialize connections to all remote agents asynchronously.
94
+
95
+ Tests each connection individually with detailed logging to help identify
96
+ any connection issues. It attempts to connect to each remote agent address,
97
+ retrieve its agent card, and store the connection for later use.
98
+
99
+ Raises:
100
+ No exceptions are raised, but errors are logged.
101
+ """
102
+
103
+ if not agent_config.agent.remote_agents:
104
+ return {}
105
+
106
+ remote_agent_configs = [
107
+ {"url": generate_url(host=remote_agent.host, port=remote_agent.port)}
108
+ for remote_agent in agent_config.agent.remote_agents
109
+ ]
110
+
111
+ async def _connect():
112
+ remote_agent_connections = {}
113
+ async with httpx.AsyncClient(timeout=60) as client:
114
+ for config in remote_agent_configs:
115
+ address = config.get("url")
116
+ logger.debug(f"--- Attempting connection to: {address} ---")
117
+ try:
118
+ card_resolver = A2ACardResolver(client, address)
119
+ card = await card_resolver.get_agent_card()
120
+ remote_connection = AgentClient(agent_card=card)
121
+ remote_agent_connections[card.name] = remote_connection
122
+ except Exception as e:
123
+ logger.error(
124
+ f"--- CRITICAL FAILURE for address: {address} ---",
125
+ exc_info=True,
126
+ )
127
+ raise e
128
+ return remote_agent_connections
129
+
130
+ try:
131
+ return safe_async_run(_connect())
132
+ except Exception as e:
133
+ logger.error("--- CRITICAL FAILURE", exc_info=True)
134
+ raise e
@@ -3,6 +3,7 @@ from typing import List, Optional
3
3
  from aigency.schemas.agent.model import AgentModel
4
4
  from aigency.schemas.agent.skills import Skill
5
5
  from aigency.schemas.agent.tools import Tool
6
+ from aigency.schemas.agent.remote_agent import RemoteAgent
6
7
 
7
8
 
8
9
  class Agent(BaseModel):
@@ -12,3 +13,4 @@ class Agent(BaseModel):
12
13
  instruction: str
13
14
  skills: List[Skill]
14
15
  tools: Optional[List[Tool]] = []
16
+ remote_agents: Optional[List[RemoteAgent]] = []
@@ -0,0 +1,9 @@
1
+ from pydantic import BaseModel, Field
2
+
3
+
4
+ class RemoteAgent(BaseModel):
5
+ """Remote agent configuration."""
6
+
7
+ name: str
8
+ host: str
9
+ port: int = Field(..., ge=1, le=65535)
@@ -11,6 +11,7 @@ from aigency.utils.logger import get_logger
11
11
 
12
12
  logger = get_logger()
13
13
 
14
+
14
15
  def convert_a2a_part_to_genai(part: Part) -> types.Part:
15
16
  """Convert a single A2A Part type into a Google Gen AI Part type.
16
17
 
@@ -54,6 +55,7 @@ def convert_genai_part_to_a2a(part: types.Part) -> Part:
54
55
  )
55
56
  raise ValueError(f"Unsupported part type: {part}")
56
57
 
58
+
57
59
  def expand_env_vars(env_dict):
58
60
  """
59
61
  Expande los valores del diccionario usando variables de entorno solo si el valor es una clave de entorno existente.
@@ -67,6 +69,21 @@ def expand_env_vars(env_dict):
67
69
  logger.warning(f"Environment variable {v} not found")
68
70
  return result
69
71
 
72
+
73
+ def generate_url(host: str, port: int, path: str = "") -> str:
74
+ """Generate a URL from host, port, and path components.
75
+
76
+ Args:
77
+ host (str): Hostname or IP address.
78
+ port (int): Port number.
79
+ path (str, optional): URL path. Defaults to "".
80
+
81
+ Returns:
82
+ str: Complete URL in the format http://host:port/path.
83
+ """
84
+ return f"http://{host}:{port}{path}"
85
+
86
+
70
87
  def safe_async_run(coro):
71
88
  """Simple wrapper to safely run async code."""
72
89
  try:
@@ -93,4 +110,5 @@ def safe_async_run(coro):
93
110
  else:
94
111
  return loop.run_until_complete(coro)
95
112
  except RuntimeError:
96
- return asyncio.run(coro)
113
+ return asyncio.run(coro)
114
+
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aigency
3
- Version: 0.0.1rc136602178
3
+ Version: 0.0.1rc163779164
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.12
6
6
  Description-Content-Type: text/markdown
@@ -6,11 +6,14 @@ aigency.egg-info/SOURCES.txt
6
6
  aigency.egg-info/dependency_links.txt
7
7
  aigency.egg-info/requires.txt
8
8
  aigency.egg-info/top_level.txt
9
+ aigency/agents/client.py
10
+ aigency/agents/communicator.py
9
11
  aigency/agents/executor.py
10
12
  aigency/agents/generator.py
11
13
  aigency/schemas/aigency_config.py
12
14
  aigency/schemas/agent/agent.py
13
15
  aigency/schemas/agent/model.py
16
+ aigency/schemas/agent/remote_agent.py
14
17
  aigency/schemas/agent/skills.py
15
18
  aigency/schemas/agent/tools.py
16
19
  aigency/schemas/metadata/metadata.py
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aigency"
3
- version = "0.0.1rc136602178"
3
+ version = "0.0.1rc163779164"
4
4
  description = "Add your description here"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -1,75 +0,0 @@
1
- """Agent generator module for creating A2A agents."""
2
-
3
- from typing import Any, Dict, List
4
-
5
- from a2a.types import AgentCapabilities, AgentCard, AgentSkill
6
- from google.adk.agents import Agent
7
- from google.adk.artifacts import InMemoryArtifactService
8
- from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
9
- from google.adk.runners import Runner
10
- from google.adk.sessions import InMemorySessionService
11
-
12
- from aigency.agents.executor import AgentA2AExecutor
13
- from aigency.schemas.aigency_config import AigencyConfig
14
- from aigency.tools.generator import ToolGenerator
15
-
16
-
17
- class AgentA2AGenerator:
18
- """Generator for creating A2A agents and related components."""
19
-
20
- @staticmethod
21
- def create_agent(agent_config: AigencyConfig) -> Agent:
22
-
23
- tools = [
24
- ToolGenerator.create_tool(tool_cfg) for tool_cfg in agent_config.agent.tools
25
- ]
26
-
27
- return Agent(
28
- name=agent_config.metadata.name,
29
- model=agent_config.agent.model.name,
30
- instruction=agent_config.agent.instruction,
31
- tools=tools,
32
- )
33
-
34
- @staticmethod
35
- def build_agent_card(agent_config: AigencyConfig) -> AgentCard:
36
-
37
- # TODO: Parse properly
38
- capabilities = AgentCapabilities(
39
- streaming=agent_config.service.capabilities.streaming
40
- )
41
-
42
- skills = [
43
- AgentSkill(
44
- id=skill.id,
45
- name=skill.name,
46
- description=skill.description,
47
- tags=skill.tags,
48
- examples=skill.examples,
49
- )
50
- for skill in agent_config.agent.skills
51
- ]
52
-
53
- return AgentCard(
54
- name=agent_config.metadata.name,
55
- description=agent_config.metadata.description,
56
- url=agent_config.service.url,
57
- version=agent_config.metadata.version,
58
- default_input_modes=agent_config.service.interface.default_input_modes,
59
- default_output_modes=agent_config.service.interface.default_output_modes,
60
- capabilities=capabilities,
61
- skills=skills,
62
- )
63
-
64
- @staticmethod
65
- def build_executor(agent: Agent, agent_card: AgentCard) -> AgentA2AExecutor:
66
-
67
- runner = Runner(
68
- app_name=agent.name,
69
- agent=agent,
70
- artifact_service=InMemoryArtifactService(),
71
- session_service=InMemorySessionService(),
72
- memory_service=InMemoryMemoryService(),
73
- )
74
-
75
- return AgentA2AExecutor(runner=runner, card=agent_card)