agnt5 0.3.0a8__cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.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 agnt5 might be problematic. Click here for more details.

agnt5/function.py ADDED
@@ -0,0 +1,325 @@
1
+ """Function component implementation for AGNT5 SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import functools
7
+ import inspect
8
+ import uuid
9
+ from typing import Any, Awaitable, Callable, Dict, Optional, TypeVar, Union, cast
10
+
11
+ from ._retry_utils import execute_with_retry, parse_backoff_policy, parse_retry_policy
12
+ from ._schema_utils import extract_function_metadata, extract_function_schemas
13
+ from .context import Context, set_current_context
14
+ from .exceptions import RetryError
15
+ from .types import BackoffPolicy, BackoffType, FunctionConfig, HandlerFunc, RetryPolicy
16
+
17
+ T = TypeVar("T")
18
+
19
+ # Global function registry
20
+ _FUNCTION_REGISTRY: Dict[str, FunctionConfig] = {}
21
+
22
+ class FunctionContext(Context):
23
+ """
24
+ Lightweight context for stateless functions.
25
+
26
+ AGNT5 Philosophy: Context is a convenience, not a requirement.
27
+ The best function is one that doesn't need context at all!
28
+
29
+ Provides only:
30
+ - Quick logging (ctx.log())
31
+ - Execution metadata (run_id, attempt)
32
+ - Smart retry helper (should_retry())
33
+ - Non-durable sleep
34
+
35
+ Does NOT provide:
36
+ - Orchestration (task, parallel, gather) - use workflows
37
+ - State management (get, set, delete) - functions are stateless
38
+ - Checkpointing (step) - functions are atomic
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ run_id: str,
44
+ attempt: int = 0,
45
+ runtime_context: Optional[Any] = None,
46
+ retry_policy: Optional[Any] = None,
47
+ is_streaming: bool = False,
48
+ tenant_id: Optional[str] = None,
49
+ ) -> None:
50
+ """
51
+ Initialize function context.
52
+
53
+ Args:
54
+ run_id: Unique execution identifier
55
+ attempt: Retry attempt number (0-indexed)
56
+ runtime_context: RuntimeContext for trace correlation
57
+ retry_policy: RetryPolicy for should_retry() checks
58
+ is_streaming: Whether this is a streaming request (for real-time SSE log delivery)
59
+ tenant_id: Tenant ID for multi-tenant deployments
60
+ """
61
+ super().__init__(run_id, attempt, runtime_context, is_streaming, tenant_id)
62
+ self._retry_policy = retry_policy
63
+
64
+ # === Quick Logging ===
65
+
66
+ def log(self, message: str, **extra) -> None:
67
+ """
68
+ Quick logging shorthand with structured data.
69
+
70
+ Example:
71
+ ctx.log("Processing payment", amount=100.50, user_id="123")
72
+ """
73
+ self._logger.info(message, extra=extra)
74
+
75
+ # === Smart Execution ===
76
+
77
+ def should_retry(self, error: Exception) -> bool:
78
+ """
79
+ Check if error is retryable based on configured policy.
80
+
81
+ Example:
82
+ try:
83
+ result = await external_api()
84
+ except Exception as e:
85
+ if not ctx.should_retry(e):
86
+ raise # Fail fast for non-retryable errors
87
+ # Otherwise let retry policy handle it
88
+ raise
89
+
90
+ Returns:
91
+ True if error is retryable, False otherwise
92
+ """
93
+ # TODO: Implement retry policy checks
94
+ # For now, all errors are retryable (let retry policy handle it)
95
+ return True
96
+
97
+ async def sleep(self, seconds: float) -> None:
98
+ """
99
+ Non-durable async sleep.
100
+
101
+ For durable sleep across failures, use workflows.
102
+
103
+ Args:
104
+ seconds: Number of seconds to sleep
105
+ """
106
+ import asyncio
107
+ await asyncio.sleep(seconds)
108
+
109
+
110
+
111
+ class FunctionRegistry:
112
+ """Registry for function handlers."""
113
+
114
+ @staticmethod
115
+ def register(config: FunctionConfig) -> None:
116
+ """Register a function handler.
117
+
118
+ Args:
119
+ config: Function configuration to register
120
+
121
+ Raises:
122
+ ValueError: If a function with the same name is already registered
123
+ """
124
+ # Check for name collision
125
+ if config.name in _FUNCTION_REGISTRY:
126
+ existing_config = _FUNCTION_REGISTRY[config.name]
127
+ existing_module = existing_config.handler.__module__
128
+ new_module = config.handler.__module__
129
+
130
+ raise ValueError(
131
+ f"Function name collision: '{config.name}' is already registered.\n"
132
+ f" Existing: {existing_module}.{existing_config.handler.__name__}\n"
133
+ f" New: {new_module}.{config.handler.__name__}\n"
134
+ f"Please use a different function name or use name= parameter to specify a unique name."
135
+ )
136
+
137
+ _FUNCTION_REGISTRY[config.name] = config
138
+
139
+ @staticmethod
140
+ def get(name: str) -> Optional[FunctionConfig]:
141
+ """Get function configuration by name."""
142
+ return _FUNCTION_REGISTRY.get(name)
143
+
144
+ @staticmethod
145
+ def all() -> Dict[str, FunctionConfig]:
146
+ """Get all registered functions."""
147
+ return _FUNCTION_REGISTRY.copy()
148
+
149
+ @staticmethod
150
+ def clear() -> None:
151
+ """Clear all registered functions."""
152
+ _FUNCTION_REGISTRY.clear()
153
+
154
+
155
+ def function(
156
+ _func: Optional[Callable[..., Any]] = None,
157
+ *,
158
+ name: Optional[str] = None,
159
+ retries: Optional[Union[int, Dict[str, Any], RetryPolicy]] = None,
160
+ backoff: Optional[Union[str, Dict[str, Any], BackoffPolicy]] = None,
161
+ ) -> Callable[..., Any]:
162
+ """
163
+ Decorator to mark a function as an AGNT5 durable function.
164
+
165
+ Args:
166
+ name: Custom function name (default: function's __name__)
167
+ retries: Retry policy configuration. Can be:
168
+ - int: max attempts (e.g., 5)
169
+ - dict: RetryPolicy params (e.g., {"max_attempts": 5, "initial_interval_ms": 1000})
170
+ - RetryPolicy: full policy object
171
+ backoff: Backoff policy for retries. Can be:
172
+ - str: backoff type ("constant", "linear", "exponential")
173
+ - dict: BackoffPolicy params (e.g., {"type": "exponential", "multiplier": 2.0})
174
+ - BackoffPolicy: full policy object
175
+
176
+ Note:
177
+ Sync Functions: Synchronous functions are automatically executed in a thread pool
178
+ to prevent blocking the event loop. This is ideal for I/O-bound operations
179
+ (requests.get(), file I/O, etc.). For CPU-bound operations or when you need
180
+ explicit control over concurrency, use async functions instead.
181
+
182
+ Example:
183
+ # Basic function with context
184
+ @function
185
+ async def greet(ctx: FunctionContext, name: str) -> str:
186
+ ctx.log(f"Greeting {name}") # AGNT5 shorthand!
187
+ return f"Hello, {name}!"
188
+
189
+ # Simple function without context (optional)
190
+ @function
191
+ async def add(a: int, b: int) -> int:
192
+ return a + b
193
+
194
+ # With Pydantic models (automatic validation + rich schemas)
195
+ from pydantic import BaseModel
196
+
197
+ class UserInput(BaseModel):
198
+ name: str
199
+ age: int
200
+
201
+ class UserOutput(BaseModel):
202
+ greeting: str
203
+ is_adult: bool
204
+
205
+ @function
206
+ async def process_user(ctx: FunctionContext, user: UserInput) -> UserOutput:
207
+ ctx.log(f"Processing user {user.name}")
208
+ return UserOutput(
209
+ greeting=f"Hello, {user.name}!",
210
+ is_adult=user.age >= 18
211
+ )
212
+
213
+ # Simple retry count
214
+ @function(retries=5)
215
+ async def with_retries(data: str) -> str:
216
+ return data.upper()
217
+
218
+ # Dict configuration
219
+ @function(retries={"max_attempts": 5}, backoff="exponential")
220
+ async def advanced(a: int, b: int) -> int:
221
+ return a + b
222
+ """
223
+
224
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
225
+ # Get function name
226
+ func_name = name or func.__name__
227
+
228
+ # Validate function signature and check if context is needed
229
+ sig = inspect.signature(func)
230
+ params = list(sig.parameters.values())
231
+
232
+ # Check if function declares 'ctx' parameter
233
+ needs_context = params and params[0].name == "ctx"
234
+
235
+ # Convert sync to async if needed
236
+ # Note: Async generators should NOT be wrapped - they need to be returned as-is
237
+ if inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func):
238
+ handler_func = cast(HandlerFunc, func)
239
+ else:
240
+ # Wrap sync function to run in thread pool (prevents blocking event loop)
241
+ @functools.wraps(func)
242
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
243
+ loop = asyncio.get_running_loop()
244
+ # Run sync function in thread pool executor to prevent blocking
245
+ return await loop.run_in_executor(None, lambda: func(*args, **kwargs))
246
+
247
+ handler_func = cast(HandlerFunc, async_wrapper)
248
+
249
+ # Extract schemas from type hints
250
+ input_schema, output_schema = extract_function_schemas(func)
251
+
252
+ # Extract metadata (description, etc.)
253
+ metadata = extract_function_metadata(func)
254
+
255
+ # Parse retry and backoff policies from flexible formats
256
+ retry_policy = parse_retry_policy(retries)
257
+ backoff_policy = parse_backoff_policy(backoff)
258
+
259
+ # Register function
260
+ config = FunctionConfig(
261
+ name=func_name,
262
+ handler=handler_func,
263
+ retries=retry_policy,
264
+ backoff=backoff_policy,
265
+ input_schema=input_schema,
266
+ output_schema=output_schema,
267
+ metadata=metadata,
268
+ )
269
+ FunctionRegistry.register(config)
270
+
271
+ # Create wrapper with retry logic
272
+ @functools.wraps(func)
273
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
274
+ # Extract or create context based on function signature
275
+ if needs_context:
276
+ # Function declares ctx parameter - first argument must be FunctionContext
277
+ if not args or not isinstance(args[0], FunctionContext):
278
+ raise TypeError(
279
+ f"Function '{func_name}' requires FunctionContext as first argument. "
280
+ f"Usage: await {func_name}(ctx, ...)"
281
+ )
282
+ ctx = args[0]
283
+ func_args = args[1:]
284
+ else:
285
+ # Function doesn't use context - create a minimal one for internal use
286
+ # But first check if a context was passed anyway (for Worker execution)
287
+ if args and isinstance(args[0], FunctionContext):
288
+ # Context was provided by Worker - use it but don't pass to function
289
+ ctx = args[0]
290
+ func_args = args[1:]
291
+ else:
292
+ # No context provided - create a default one
293
+ ctx = FunctionContext(
294
+ run_id=f"local-{uuid.uuid4().hex[:8]}",
295
+ retry_policy=retry_policy
296
+ )
297
+ func_args = args
298
+
299
+ # Set context in task-local storage for automatic propagation
300
+ token = set_current_context(ctx)
301
+ try:
302
+ # Execute with retry
303
+ return await execute_with_retry(
304
+ handler_func,
305
+ ctx,
306
+ config.retries or RetryPolicy(),
307
+ config.backoff or BackoffPolicy(),
308
+ needs_context,
309
+ *func_args,
310
+ **kwargs,
311
+ )
312
+ finally:
313
+ # Always reset context to prevent leakage
314
+ from .context import _current_context
315
+ _current_context.reset(token)
316
+
317
+ # Store config on wrapper for introspection
318
+ wrapper._agnt5_config = config # type: ignore
319
+ return wrapper
320
+
321
+ # Handle both @function and @function(...) syntax
322
+ if _func is None:
323
+ return decorator
324
+ else:
325
+ return decorator(_func)