agno 2.3.19__py3-none-any.whl → 2.3.21__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 (39) hide show
  1. agno/agent/agent.py +2466 -2048
  2. agno/db/dynamo/utils.py +26 -3
  3. agno/db/firestore/utils.py +25 -10
  4. agno/db/gcs_json/utils.py +14 -2
  5. agno/db/in_memory/utils.py +14 -2
  6. agno/db/json/utils.py +14 -2
  7. agno/db/mysql/utils.py +13 -3
  8. agno/db/postgres/utils.py +13 -3
  9. agno/db/redis/utils.py +26 -10
  10. agno/db/schemas/memory.py +15 -19
  11. agno/db/singlestore/utils.py +13 -3
  12. agno/db/sqlite/utils.py +15 -3
  13. agno/db/utils.py +22 -0
  14. agno/eval/agent_as_judge.py +24 -14
  15. agno/knowledge/embedder/mistral.py +1 -1
  16. agno/models/litellm/chat.py +6 -0
  17. agno/os/routers/evals/evals.py +0 -9
  18. agno/os/routers/evals/utils.py +6 -6
  19. agno/os/routers/knowledge/schemas.py +1 -1
  20. agno/os/routers/memory/schemas.py +14 -1
  21. agno/os/routers/metrics/schemas.py +1 -1
  22. agno/os/schema.py +11 -9
  23. agno/run/__init__.py +2 -4
  24. agno/run/agent.py +19 -19
  25. agno/run/cancel.py +65 -52
  26. agno/run/cancellation_management/__init__.py +9 -0
  27. agno/run/cancellation_management/base.py +78 -0
  28. agno/run/cancellation_management/in_memory_cancellation_manager.py +100 -0
  29. agno/run/cancellation_management/redis_cancellation_manager.py +236 -0
  30. agno/run/team.py +19 -19
  31. agno/team/team.py +1217 -1136
  32. agno/utils/response.py +1 -13
  33. agno/vectordb/weaviate/__init__.py +1 -1
  34. agno/workflow/workflow.py +23 -16
  35. {agno-2.3.19.dist-info → agno-2.3.21.dist-info}/METADATA +60 -129
  36. {agno-2.3.19.dist-info → agno-2.3.21.dist-info}/RECORD +39 -35
  37. {agno-2.3.19.dist-info → agno-2.3.21.dist-info}/WHEEL +0 -0
  38. {agno-2.3.19.dist-info → agno-2.3.21.dist-info}/licenses/LICENSE +0 -0
  39. {agno-2.3.19.dist-info → agno-2.3.21.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,236 @@
1
+ """Redis-based run cancellation management."""
2
+
3
+ from typing import TYPE_CHECKING, Any, Dict, Optional, Union
4
+
5
+ from agno.exceptions import RunCancelledException
6
+ from agno.run.cancellation_management.base import BaseRunCancellationManager
7
+ from agno.utils.log import logger
8
+
9
+ # Defer import error until class instantiation
10
+ _redis_available = True
11
+ _redis_import_error: Optional[str] = None
12
+
13
+ try:
14
+ from redis import Redis, RedisCluster
15
+ from redis.asyncio import Redis as AsyncRedis
16
+ from redis.asyncio import RedisCluster as AsyncRedisCluster
17
+ except ImportError:
18
+ _redis_available = False
19
+ _redis_import_error = "`redis` not installed. Please install it using `pip install redis`"
20
+ # Type hints for when redis is not installed
21
+ if TYPE_CHECKING:
22
+ from redis import Redis, RedisCluster
23
+ from redis.asyncio import Redis as AsyncRedis
24
+ from redis.asyncio import RedisCluster as AsyncRedisCluster
25
+ else:
26
+ Redis = Any
27
+ RedisCluster = Any
28
+ AsyncRedis = Any
29
+ AsyncRedisCluster = Any
30
+
31
+
32
+ class RedisRunCancellationManager(BaseRunCancellationManager):
33
+ """Redis-based cancellation manager for distributed run cancellation.
34
+ This manager stores run cancellation state in Redis, enabling cancellation
35
+ across multiple processes or services.
36
+
37
+ To use: call the set_cancellation_manager function to set the cancellation manager.
38
+ Args:
39
+ redis_client: Sync Redis client for sync methods. Can be Redis or RedisCluster.
40
+ async_redis_client: Async Redis client for async methods. Can be AsyncRedis or AsyncRedisCluster.
41
+ key_prefix: Prefix for Redis keys. Defaults to "agno:run:cancellation:".
42
+ ttl_seconds: TTL for keys in seconds. Defaults to 86400 (1 day).
43
+ Keys auto-expire to prevent orphaned keys if runs aren't cleaned up.
44
+ Set to None to disable expiration.
45
+ """
46
+
47
+ DEFAULT_TTL_SECONDS = 60 * 60 * 24 # 1 day
48
+
49
+ def __init__(
50
+ self,
51
+ redis_client: Optional[Union[Redis, RedisCluster]] = None,
52
+ async_redis_client: Optional[Union[AsyncRedis, AsyncRedisCluster]] = None,
53
+ key_prefix: str = "agno:run:cancellation:",
54
+ ttl_seconds: Optional[int] = DEFAULT_TTL_SECONDS,
55
+ ):
56
+ if not _redis_available:
57
+ raise ImportError(_redis_import_error)
58
+
59
+ super().__init__()
60
+ self.redis_client = redis_client
61
+ self.async_redis_client = async_redis_client
62
+ self.key_prefix = key_prefix
63
+ self.ttl_seconds = ttl_seconds
64
+
65
+ if redis_client is None and async_redis_client is None:
66
+ raise ValueError("At least one of redis_client or async_redis_client must be provided")
67
+
68
+ def _get_key(self, run_id: str) -> str:
69
+ """Get the Redis key for a run ID."""
70
+ return f"{self.key_prefix}{run_id}"
71
+
72
+ def _ensure_sync_client(self) -> Union[Redis, RedisCluster]:
73
+ """Ensure sync client is available."""
74
+ if self.redis_client is None:
75
+ raise RuntimeError("Sync Redis client not provided. Use async methods or provide a sync client.")
76
+ return self.redis_client
77
+
78
+ def _ensure_async_client(self) -> Union[AsyncRedis, AsyncRedisCluster]:
79
+ """Ensure async client is available."""
80
+ if self.async_redis_client is None:
81
+ raise RuntimeError("Async Redis client not provided. Use sync methods or provide an async client.")
82
+ return self.async_redis_client
83
+
84
+ def register_run(self, run_id: str) -> None:
85
+ """Register a new run as not cancelled."""
86
+ client = self._ensure_sync_client()
87
+ key = self._get_key(run_id)
88
+ client.set(key, "0", ex=self.ttl_seconds)
89
+
90
+ async def aregister_run(self, run_id: str) -> None:
91
+ """Register a new run as not cancelled (async version)."""
92
+ client = self._ensure_async_client()
93
+ key = self._get_key(run_id)
94
+ await client.set(key, "0", ex=self.ttl_seconds)
95
+
96
+ def cancel_run(self, run_id: str) -> bool:
97
+ """Cancel a run by marking it as cancelled.
98
+
99
+ Returns:
100
+ bool: True if run was found and cancelled, False if run not found.
101
+ """
102
+ client = self._ensure_sync_client()
103
+ key = self._get_key(run_id)
104
+
105
+ # Atomically set to "1" only if key exists (XX flag)
106
+ result = client.set(key, "1", ex=self.ttl_seconds, xx=True)
107
+
108
+ if result:
109
+ logger.info(f"Run {run_id} marked for cancellation")
110
+ return True
111
+ else:
112
+ logger.warning(f"Attempted to cancel unknown run {run_id}")
113
+ return False
114
+
115
+ async def acancel_run(self, run_id: str) -> bool:
116
+ """Cancel a run by marking it as cancelled (async version).
117
+
118
+ Returns:
119
+ bool: True if run was found and cancelled, False if run not found.
120
+ """
121
+ client = self._ensure_async_client()
122
+ key = self._get_key(run_id)
123
+
124
+ # Atomically set to "1" only if key exists (XX flag)
125
+ result = await client.set(key, "1", ex=self.ttl_seconds, xx=True)
126
+
127
+ if result:
128
+ logger.info(f"Run {run_id} marked for cancellation")
129
+ return True
130
+ else:
131
+ logger.warning(f"Attempted to cancel unknown run {run_id}")
132
+ return False
133
+
134
+ def is_cancelled(self, run_id: str) -> bool:
135
+ """Check if a run is cancelled."""
136
+ client = self._ensure_sync_client()
137
+ key = self._get_key(run_id)
138
+ value = client.get(key)
139
+ if value is None:
140
+ return False
141
+ # Redis returns bytes, handle both bytes and str
142
+ if isinstance(value, bytes):
143
+ return value == b"1"
144
+ return value == "1"
145
+
146
+ async def ais_cancelled(self, run_id: str) -> bool:
147
+ """Check if a run is cancelled (async version)."""
148
+ client = self._ensure_async_client()
149
+ key = self._get_key(run_id)
150
+ value = await client.get(key)
151
+ if value is None:
152
+ return False
153
+ # Redis returns bytes, handle both bytes and str
154
+ if isinstance(value, bytes):
155
+ return value == b"1"
156
+ return value == "1"
157
+
158
+ def cleanup_run(self, run_id: str) -> None:
159
+ """Remove a run from tracking (called when run completes)."""
160
+ client = self._ensure_sync_client()
161
+ key = self._get_key(run_id)
162
+ client.delete(key)
163
+
164
+ async def acleanup_run(self, run_id: str) -> None:
165
+ """Remove a run from tracking (called when run completes) (async version)."""
166
+ client = self._ensure_async_client()
167
+ key = self._get_key(run_id)
168
+ await client.delete(key)
169
+
170
+ def raise_if_cancelled(self, run_id: str) -> None:
171
+ """Check if a run should be cancelled and raise exception if so."""
172
+ if self.is_cancelled(run_id):
173
+ logger.info(f"Cancelling run {run_id}")
174
+ raise RunCancelledException(f"Run {run_id} was cancelled")
175
+
176
+ async def araise_if_cancelled(self, run_id: str) -> None:
177
+ """Check if a run should be cancelled and raise exception if so (async version)."""
178
+ if await self.ais_cancelled(run_id):
179
+ logger.info(f"Cancelling run {run_id}")
180
+ raise RunCancelledException(f"Run {run_id} was cancelled")
181
+
182
+ def get_active_runs(self) -> Dict[str, bool]:
183
+ """Get all currently tracked runs and their cancellation status.
184
+
185
+ Note: Uses scan_iter which works correctly with both standalone Redis
186
+ and Redis Cluster (scans all nodes in cluster mode).
187
+ """
188
+ client = self._ensure_sync_client()
189
+ result: Dict[str, bool] = {}
190
+
191
+ # scan_iter handles cluster mode correctly (scans all nodes)
192
+ pattern = f"{self.key_prefix}*"
193
+ for key in client.scan_iter(match=pattern, count=100):
194
+ # Extract run_id from key
195
+ if isinstance(key, bytes):
196
+ key = key.decode("utf-8")
197
+ run_id = key[len(self.key_prefix) :]
198
+
199
+ # Get value
200
+ value = client.get(key)
201
+ if value is not None:
202
+ if isinstance(value, bytes):
203
+ is_cancelled = value == b"1"
204
+ else:
205
+ is_cancelled = value == "1"
206
+ result[run_id] = is_cancelled
207
+
208
+ return result
209
+
210
+ async def aget_active_runs(self) -> Dict[str, bool]:
211
+ """Get all currently tracked runs and their cancellation status (async version).
212
+
213
+ Note: Uses scan_iter which works correctly with both standalone Redis
214
+ and Redis Cluster (scans all nodes in cluster mode).
215
+ """
216
+ client = self._ensure_async_client()
217
+ result: Dict[str, bool] = {}
218
+
219
+ # scan_iter handles cluster mode correctly (scans all nodes)
220
+ pattern = f"{self.key_prefix}*"
221
+ async for key in client.scan_iter(match=pattern, count=100):
222
+ # Extract run_id from key
223
+ if isinstance(key, bytes):
224
+ key = key.decode("utf-8")
225
+ run_id = key[len(self.key_prefix) :]
226
+
227
+ # Get value
228
+ value = await client.get(key)
229
+ if value is not None:
230
+ if isinstance(value, bytes):
231
+ is_cancelled = value == b"1"
232
+ else:
233
+ is_cancelled = value == "1"
234
+ result[run_id] = is_cancelled
235
+
236
+ return result
agno/run/team.py CHANGED
@@ -51,8 +51,11 @@ class TeamRunInput:
51
51
  return self.input_content.model_dump_json(exclude_none=True)
52
52
  elif isinstance(self.input_content, Message):
53
53
  return json.dumps(self.input_content.to_dict())
54
- elif isinstance(self.input_content, list) and self.input_content and isinstance(self.input_content[0], Message):
55
- return json.dumps([m.to_dict() for m in self.input_content])
54
+ elif isinstance(self.input_content, list):
55
+ try:
56
+ return json.dumps(self.to_dict().get("input_content"))
57
+ except Exception:
58
+ return str(self.input_content)
56
59
  else:
57
60
  return str(self.input_content)
58
61
 
@@ -67,22 +70,15 @@ class TeamRunInput:
67
70
  result["input_content"] = self.input_content.model_dump(exclude_none=True)
68
71
  elif isinstance(self.input_content, Message):
69
72
  result["input_content"] = self.input_content.to_dict()
70
-
71
- # Handle input_content provided as a list of Message objects
72
- elif (
73
- isinstance(self.input_content, list)
74
- and self.input_content
75
- and isinstance(self.input_content[0], Message)
76
- ):
77
- result["input_content"] = [m.to_dict() for m in self.input_content]
78
-
79
- # Handle input_content provided as a list of dicts
80
- elif (
81
- isinstance(self.input_content, list) and self.input_content and isinstance(self.input_content[0], dict)
82
- ):
83
- for content in self.input_content:
84
- # Handle media input
85
- if isinstance(content, dict):
73
+ elif isinstance(self.input_content, list):
74
+ serialized_items: List[Any] = []
75
+ for item in self.input_content:
76
+ if isinstance(item, Message):
77
+ serialized_items.append(item.to_dict())
78
+ elif isinstance(item, BaseModel):
79
+ serialized_items.append(item.model_dump(exclude_none=True))
80
+ elif isinstance(item, dict):
81
+ content = dict(item)
86
82
  if content.get("images"):
87
83
  content["images"] = [
88
84
  img.to_dict() if isinstance(img, Image) else img for img in content["images"]
@@ -99,7 +95,11 @@ class TeamRunInput:
99
95
  content["files"] = [
100
96
  file.to_dict() if isinstance(file, File) else file for file in content["files"]
101
97
  ]
102
- result["input_content"] = self.input_content
98
+ serialized_items.append(content)
99
+ else:
100
+ serialized_items.append(item)
101
+
102
+ result["input_content"] = serialized_items
103
103
  else:
104
104
  result["input_content"] = self.input_content
105
105