aixtools 0.2.7__py3-none-any.whl → 0.2.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.

Potentially problematic release.


This version of aixtools might be problematic. Click here for more details.

aixtools/_version.py CHANGED
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '0.2.7'
32
- __version_tuple__ = version_tuple = (0, 2, 7)
31
+ __version__ = version = '0.2.9'
32
+ __version_tuple__ = version_tuple = (0, 2, 9)
33
33
 
34
34
  __commit_id__ = commit_id = None
@@ -1,3 +1,4 @@
1
+ import asyncio
1
2
  from pathlib import Path
2
3
 
3
4
  from a2a.server.agent_execution import AgentExecutor, RequestContext
@@ -54,10 +55,23 @@ def _task_failed_event(text: str, context_id: str | None, task_id: str | None) -
54
55
  )
55
56
 
56
57
 
58
+ def _task_cancelled_event(text: str, context_id: str | None, task_id: str | None) -> TaskStatusUpdateEvent:
59
+ """Creates a TaskStatusUpdateEvent indicating task cancellation."""
60
+ return TaskStatusUpdateEvent(
61
+ status=TaskStatus(
62
+ state=TaskState.canceled, message=new_agent_text_message(text=text, context_id=context_id, task_id=task_id)
63
+ ),
64
+ final=True,
65
+ context_id=context_id,
66
+ task_id=task_id,
67
+ )
68
+
69
+
57
70
  class PydanticAgentExecutor(AgentExecutor):
58
71
  def __init__(self, agent_parameters: AgentParameters):
59
72
  self._agent_parameters = agent_parameters
60
73
  self.history_storage = InMemoryHistoryStorage()
74
+ self._running_tasks: dict[str, asyncio.Task] = {} # Track running agent tasks for cancellation
61
75
 
62
76
  def _convert_message_to_pydantic_parts(
63
77
  self,
@@ -102,11 +116,27 @@ class PydanticAgentExecutor(AgentExecutor):
102
116
  prompt = self._convert_message_to_pydantic_parts(session_tuple, message)
103
117
  history_message = self.history_storage.get(task.id)
104
118
 
105
- try:
106
- result = await agent.run(
119
+ # Create and track the agent run task for cancellation
120
+ agent_task = asyncio.create_task(
121
+ agent.run(
107
122
  user_prompt=prompt,
108
123
  message_history=history_message,
109
124
  )
125
+ )
126
+ self._running_tasks[task.id] = agent_task
127
+
128
+ try:
129
+ result = await agent_task
130
+ except asyncio.CancelledError:
131
+ # Task was cancelled, send cancellation event
132
+ await event_queue.enqueue_event(
133
+ _task_cancelled_event(
134
+ text="Task was cancelled",
135
+ context_id=context.context_id,
136
+ task_id=task.id,
137
+ )
138
+ )
139
+ return
110
140
  except Exception as e:
111
141
  await event_queue.enqueue_event(
112
142
  _task_failed_event(
@@ -116,6 +146,9 @@ class PydanticAgentExecutor(AgentExecutor):
116
146
  )
117
147
  )
118
148
  return
149
+ finally:
150
+ # Clean up the task from tracking
151
+ self._running_tasks.pop(task.id, None)
119
152
 
120
153
  self.history_storage.store(task.id, result.all_messages())
121
154
 
@@ -158,7 +191,7 @@ class PydanticAgentExecutor(AgentExecutor):
158
191
  return
159
192
 
160
193
  for idx, artifact in enumerate(run_output.created_artifacts_paths):
161
- image_file = FileWithUri(uri=str(artifact), name=f"image_{idx}")
194
+ artifact_file = FileWithUri(uri=str(artifact), name=f"art_{idx}")
162
195
  await event_queue.enqueue_event(
163
196
  TaskArtifactUpdateEvent(
164
197
  append=False,
@@ -166,8 +199,8 @@ class PydanticAgentExecutor(AgentExecutor):
166
199
  task_id=task.id,
167
200
  last_chunk=True,
168
201
  artifact=Artifact(
169
- artifact_id=f"image_{idx}",
170
- parts=[Part(root=FilePart(file=image_file))],
202
+ artifact_id=f"art_{idx}",
203
+ parts=[Part(root=FilePart(file=artifact_file))],
171
204
  ),
172
205
  )
173
206
  )
@@ -185,9 +218,45 @@ class PydanticAgentExecutor(AgentExecutor):
185
218
  )
186
219
  )
187
220
 
188
- async def cancel(self, ctx: RequestContext, event_queue: EventQueue) -> None:
189
- """Cancel"""
190
- raise Exception("cancel not supported")
221
+ async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
222
+ """Cancel the ongoing task identified by the task_id in the context.
223
+
224
+ Attempts to stop the running agent task and publishes a TaskStatusUpdateEvent
225
+ with state TaskState.canceled to the event_queue as per A2A SDK specification.
226
+
227
+ Args:
228
+ context: The request context containing the task ID to cancel.
229
+ event_queue: The queue to publish the cancellation status update to.
230
+ """
231
+ task = context.current_task
232
+ if not task:
233
+ logger.warning("No task to cancel in context")
234
+ return
235
+
236
+ task_id = task.id
237
+
238
+ # Check if we have a running task to cancel
239
+ if task_id in self._running_tasks:
240
+ agent_task = self._running_tasks[task_id]
241
+ if not agent_task.done():
242
+ logger.info("Cancelling running agent task: %s", task_id)
243
+ agent_task.cancel()
244
+ # The cancellation event will be sent by the execute method's except block
245
+ return
246
+
247
+ # If no running task found, check if task is already in terminal state
248
+ if is_in_terminal_state(task):
249
+ logger.info("Task %s is already in terminal state: %s", task_id, task.status.state)
250
+ return
251
+
252
+ # Send cancellation event for tasks that aren't currently running
253
+ await event_queue.enqueue_event(
254
+ _task_cancelled_event(
255
+ text="Task cancelled",
256
+ context_id=context.context_id,
257
+ task_id=task_id,
258
+ )
259
+ )
191
260
 
192
261
  def _build_agent(self, session_tuple: SessionIdTuple) -> Agent:
193
262
  params = self._agent_parameters
@@ -1,10 +1,12 @@
1
1
  import asyncio
2
+ from typing import Callable
2
3
 
3
4
  from a2a.client import Client
4
5
  from a2a.types import (
5
6
  AgentCard,
6
7
  Message,
7
8
  Task,
9
+ TaskIdParams,
8
10
  TaskQueryParams,
9
11
  TaskState,
10
12
  )
@@ -63,6 +65,7 @@ class RemoteAgentConnection:
63
65
  *,
64
66
  sleep_time: float = 0.2,
65
67
  max_iter=1000,
68
+ on_task_submitted: Callable[[str], None] | None = None,
66
69
  ) -> Task | Message:
67
70
  """
68
71
  Sends a message to the remote agent and polls for the task status at regular intervals.
@@ -75,6 +78,9 @@ class RemoteAgentConnection:
75
78
  if isinstance(last_task, Message):
76
79
  return last_task
77
80
 
81
+ if on_task_submitted:
82
+ on_task_submitted(last_task.id)
83
+
78
84
  if is_in_terminal_or_interrupted_state(last_task):
79
85
  return last_task
80
86
  task_id = last_task.id
@@ -86,3 +92,13 @@ class RemoteAgentConnection:
86
92
 
87
93
  timeout_seconds = max_iter * sleep_time
88
94
  raise Exception(f"Task did not complete in {timeout_seconds} seconds") # pylint: disable=broad-exception-raised
95
+
96
+ async def cancel_task(self, task_id: str) -> Task:
97
+ """
98
+ Cancels a task by its ID.
99
+ """
100
+ try:
101
+ return await self._client.cancel_task(TaskIdParams(id=task_id))
102
+ except Exception as e:
103
+ logger.error("Exception found in cancel_task: %s", str(e))
104
+ raise e
@@ -40,7 +40,7 @@ class _AgentCardResolver:
40
40
 
41
41
  def __init__(self, client: httpx.AsyncClient):
42
42
  self._httpx_client = client
43
- self._a2a_client_factory = ClientFactory(ClientConfig(httpx_client=self._httpx_client))
43
+ self._a2a_client_factory = ClientFactory(ClientConfig(httpx_client=self._httpx_client, polling=True))
44
44
  self.clients: dict[str, RemoteAgentConnection] = {}
45
45
 
46
46
  def register_agent_card(self, card: AgentCard):
@@ -76,6 +76,14 @@ async def get_a2a_clients(
76
76
  return await _AgentCardResolver(httpx_client).get_a2a_clients(agent_hosts)
77
77
 
78
78
 
79
+ def card2description(card: AgentCard) -> str:
80
+ """Convert agent card to a description string."""
81
+ descr = f"{card.name}: {card.description}\n"
82
+ for skill in card.skills:
83
+ descr += f"\t - {skill.name}: {skill.description}\n"
84
+ return descr
85
+
86
+
79
87
  def get_session_id_tuple(context: RequestContext) -> SessionIdTuple:
80
88
  """Get the user_id, session_id tuple from the request context."""
81
89
  headers = context.call_context.state.get("headers", {})
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aixtools
3
- Version: 0.2.7
3
+ Version: 0.2.9
4
4
  Summary: Tools for AI exploration and debugging
5
5
  Requires-Python: >=3.11.2
6
6
  Description-Content-Type: text/markdown
@@ -1,5 +1,5 @@
1
1
  aixtools/__init__.py,sha256=9NGHm7LjsQmsvjTZvw6QFJexSvAU4bCoN_KBk9SCa00,260
2
- aixtools/_version.py,sha256=yXzK2akXKIKUAfJk0WCQothqygqvndys6GBuXxo-wk0,704
2
+ aixtools/_version.py,sha256=051on7ZmwGNyKvbO1AXKoElw7RjLuRmeJqVOApytNd4,704
3
3
  aixtools/app.py,sha256=JzQ0nrv_bjDQokllIlGHOV0HEb-V8N6k_nGQH-TEsVU,5227
4
4
  aixtools/chainlit.md,sha256=yC37Ly57vjKyiIvK4oUvf4DYxZCwH7iocTlx7bLeGLU,761
5
5
  aixtools/context.py,sha256=I_MD40ZnvRm5WPKAKqBUAdXIf8YaurkYUUHSVVy-QvU,598
@@ -20,10 +20,9 @@ aixtools/.chainlit/translations/zh-CN.json,sha256=EWxhT2_6CW9z0F6SI2llr3RsaL2omH
20
20
  aixtools/a2a/app.py,sha256=p18G7fAInl9dcNYq6RStBjv1C3aD6oilQq3WXtBuk30,5069
21
21
  aixtools/a2a/utils.py,sha256=EHr3IyyBJn23ni-JcfAf6i3VpQmPs0g1TSnAZazvY_8,4039
22
22
  aixtools/a2a/google_sdk/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
- aixtools/a2a/google_sdk/card.py,sha256=P0L3bKbm28HaRkcIxIvjuSGUKOOc0ymyRAFHKm3a5GQ,996
24
- aixtools/a2a/google_sdk/remote_agent_connection.py,sha256=oDCRSN3gfONY1Ibp8BrtysIVqfQQ-lWe5N7lr1ymHxY,2819
25
- aixtools/a2a/google_sdk/utils.py,sha256=kag7KWNRatpw9bf9ThqBdDlyn0QuBx8-Pja1id1Gk30,3242
26
- aixtools/a2a/google_sdk/pydantic_ai_adapter/agent_executor.py,sha256=MMbhbEnUL6NwSYnisJrDdHW8zJoSyJ3Pzzkt8jqwNdI,7066
23
+ aixtools/a2a/google_sdk/remote_agent_connection.py,sha256=gFsIja_nIQsAzxElv3A7_hG9GpDI5pkV-B_KDlcYlnc,3329
24
+ aixtools/a2a/google_sdk/utils.py,sha256=4VIPV2GtG5IRY-KSZN6iRMS3ntxG2uKgd_d5tQvnZHw,3515
25
+ aixtools/a2a/google_sdk/pydantic_ai_adapter/agent_executor.py,sha256=8VuU2WXeSHUK3_rRm_mjX6elqdC9NA2uz1aELzeC8BU,9784
27
26
  aixtools/a2a/google_sdk/pydantic_ai_adapter/storage.py,sha256=nGoVL7MPoZJW7iVR71laqpUYP308yFKZIifJtvUgpiU,878
28
27
  aixtools/agents/__init__.py,sha256=MAW196S2_G7uGqv-VNjvlOETRfuV44WlU1leO7SiR0A,282
29
28
  aixtools/agents/agent.py,sha256=tceQByn-RGBIhW8BOjKoP0yhNzZLwAa6CxwhPhRe3PU,7270
@@ -89,8 +88,8 @@ aixtools/utils/chainlit/cl_agent_show.py,sha256=vaRuowp4BRvhxEr5hw0zHEJ7iaSF_5bo
89
88
  aixtools/utils/chainlit/cl_utils.py,sha256=fxaxdkcZg6uHdM8uztxdPowg3a2f7VR7B26VPY4t-3c,5738
90
89
  aixtools/vault/__init__.py,sha256=fsr_NuX3GZ9WZ7dGfe0gp_5-z3URxAfwVRXw7Xyc0dU,141
91
90
  aixtools/vault/vault.py,sha256=9dZLWdZQk9qN_Q9Djkofw9LUKnJqnrX5H0fGusVLBhA,6037
92
- aixtools-0.2.7.dist-info/METADATA,sha256=V3-mduY2Z8lURHq7Vhe4KVyieG1snJAHeSMmvVL2k5k,27229
93
- aixtools-0.2.7.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
94
- aixtools-0.2.7.dist-info/entry_points.txt,sha256=q8412TG4T0S8K0SKeWp2vkVPIDYQs0jNoHqcQ7qxOiA,155
95
- aixtools-0.2.7.dist-info/top_level.txt,sha256=wBn-rw9bCtxrR4AYEYgjilNCUVmKY0LWby9Zan2PRJM,9
96
- aixtools-0.2.7.dist-info/RECORD,,
91
+ aixtools-0.2.9.dist-info/METADATA,sha256=jWcF3SX9eos7TLkvD4UaurdbD4x9JEcQApycD2u_kB8,27229
92
+ aixtools-0.2.9.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
93
+ aixtools-0.2.9.dist-info/entry_points.txt,sha256=q8412TG4T0S8K0SKeWp2vkVPIDYQs0jNoHqcQ7qxOiA,155
94
+ aixtools-0.2.9.dist-info/top_level.txt,sha256=wBn-rw9bCtxrR4AYEYgjilNCUVmKY0LWby9Zan2PRJM,9
95
+ aixtools-0.2.9.dist-info/RECORD,,
@@ -1,27 +0,0 @@
1
- import httpx
2
- from a2a.client import A2ACardResolver
3
- from a2a.types import AgentCard
4
-
5
- from aixtools.logging.logging_config import get_logger
6
-
7
- logger = get_logger(__name__)
8
-
9
-
10
- async def get_agent_card(httpx_client: httpx.AsyncClient, agent_url: str) -> AgentCard:
11
- resolver = A2ACardResolver(
12
- httpx_client=httpx_client,
13
- base_url=agent_url,
14
- )
15
-
16
- try:
17
- _public_card = await resolver.get_agent_card() # Fetches from default public path
18
- logger.info("Successfully fetched public agent card:")
19
- logger.info(_public_card.model_dump_json(indent=2, exclude_none=True))
20
- final_agent_card_to_use = _public_card
21
- except Exception as e:
22
- logger.error(f"Critical error fetching public agent card: {e}", exc_info=True)
23
- raise RuntimeError("Failed to fetch the public agent card. Cannot continue.") from e
24
-
25
- # Set the URL which is accessible from the container
26
- final_agent_card_to_use.url = agent_url
27
- return final_agent_card_to_use