python-wrap 0.2.1__py3-none-any.whl → 0.4.0__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 (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,468 @@
1
+ """python-wrap for the OpenAI Agents SDK: guarded function tools and run hooks.
2
+
3
+ The SDK (``agents``) is never imported at module level. `AgentsGuard` holds the settings
4
+ and gives you:
5
+
6
+ * `AgentsGuard.function_tool` - ``agents.function_tool`` with python-wrap `tool`
7
+ semantics inside: per-attempt ``timeout``, ``retry``, `ToolPolicy` checks and
8
+ approval, and replay safety through an `EffectLedger` keyed on the SDK's
9
+ ``tool_call_id``;
10
+ * `AgentsGuard.wrap` - the same guards (limits, ledger, timeout, audit) around an
11
+ existing ``FunctionTool``, such as the one ``Agent.as_tool()`` returns for a
12
+ sub-agent;
13
+ * `AgentsGuard.hooks` / `AgentsGuard.agent_hooks` - ``RunHooks`` / ``AgentHooks`` that
14
+ feed every model response's usage into a python-wrap `Budget` (refusing the next model
15
+ call once it is spent), write tool and model calls to an `AuditTape`, and count tool
16
+ calls against ``max_tool_calls`` and ``max_repeats``.
17
+
18
+ Sub-agents used as tools run their own ``Runner.run`` with their own ``max_turns``, so
19
+ nothing in the SDK bounds the total work of an agent tree. The guard's counters are
20
+ shared by every tool that passes through it, at any depth: wrap the sub-agent tools with
21
+ `AgentsGuard.wrap` (and give sub-agents ``hooks=guard.agent_hooks()``) and one
22
+ ``max_tool_calls`` caps the whole tree.
23
+
24
+ Errors that should end the run (`LoopDetected`, `StepLimitExceeded`, a spent budget, an
25
+ `EffectUnknown`...) are re-raised even though the SDK turns tool exceptions into a
26
+ message for the model, also through sub-agent runs that would swallow them; a refused
27
+ tool (`ToolNotAllowed`) or a tool timeout is reported to the model as a tool error. The
28
+ SDK wraps a re-raised error in its ``UserError``; `AgentsGuard.run` / `run_sync` unwrap it
29
+ (`fatal_cause` does it for your own ``Runner.run`` calls).
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import contextvars
35
+ import copy
36
+ import functools
37
+ import importlib
38
+ import types
39
+ from collections.abc import Callable, Iterable
40
+ from typing import Any, TypeVar, cast
41
+
42
+ from python_wrap import _core
43
+ from python_wrap.adapters._frameworks import (
44
+ _LAYER_ATTR,
45
+ FATAL,
46
+ CallCounter,
47
+ UsageBridge,
48
+ record_llm,
49
+ record_tool,
50
+ usage_totals,
51
+ )
52
+ from python_wrap.adapters.pydantic_ai import _matcher, compose
53
+ from python_wrap.agents import (
54
+ EffectLedger,
55
+ ToolPolicy,
56
+ _effect_key,
57
+ canonical,
58
+ current_run,
59
+ run_id_var,
60
+ tool,
61
+ with_call_id,
62
+ )
63
+
64
+ __all__ = ["AgentsGuard", "fatal_cause"]
65
+
66
+ F = TypeVar("F", bound=Callable[..., Any])
67
+ FRAMEWORK = "openai-agents"
68
+ _GUARDED_ATTR = "__python_wrap_guarded__"
69
+
70
+
71
+ class _Box:
72
+ """Collects run-ending errors raised inside the SDK's own error handling."""
73
+
74
+ __slots__ = ("error", "parent")
75
+
76
+ def __init__(self, parent: _Box | None = None) -> None:
77
+ self.error: BaseException | None = None
78
+ self.parent = parent
79
+
80
+ def mark(self, error: BaseException) -> None:
81
+ """Record ``error`` here and in every enclosing guarded tool (sub-agent runs)."""
82
+ box: _Box | None = self
83
+ while box is not None:
84
+ if box.error is None:
85
+ box.error = error
86
+ box = box.parent
87
+
88
+
89
+ def _mark_fatal(error: BaseException) -> None:
90
+ box = _BOX.get()
91
+ if box is not None:
92
+ box.mark(error)
93
+
94
+
95
+ def fatal_cause(error: BaseException, fatal: tuple[type[BaseException], ...]) -> BaseException:
96
+ """The run-ending python-wrap error inside an SDK wrapper exception, else ``error``."""
97
+ seen: set[int] = set()
98
+ current: BaseException | None = error
99
+ while current is not None and id(current) not in seen:
100
+ if isinstance(current, fatal):
101
+ return current
102
+ seen.add(id(current))
103
+ current = current.__cause__ or current.__context__
104
+ return error
105
+
106
+
107
+ _BOX: contextvars.ContextVar[_Box | None] = contextvars.ContextVar(
108
+ "python_wrap_openai_agents_box", default=None
109
+ )
110
+
111
+
112
+ class AgentsGuard:
113
+ """python-wrap's tool safety, budget, audit and loop guards for the OpenAI Agents SDK.
114
+
115
+ Args:
116
+ timeout: Per-attempt time limit for every tool (seconds or ``"30s"``); None
117
+ leaves them unbounded (`doctor` reports PW020 for such tools).
118
+ retry: A retry decorator applied to each function tool, inside the ledger.
119
+ ledger: An `EffectLedger`: a call replayed with the same ``tool_call_id``
120
+ returns the stored result instead of running again.
121
+ read_only: Glob patterns of tools without side effects.
122
+ approval: Glob patterns of tools that need the approver's yes (``ToolPolicy`` of
123
+ the current run, or ``policy``).
124
+ policy: A `ToolPolicy` attached to every guarded run (`run` / `run_sync`).
125
+ budget: A python-wrap `Budget` fed by the hooks with each response's usage.
126
+ tape: An `AuditTape` receiving tool calls and model responses.
127
+ max_tool_calls: Most tool calls through this guard, sub-agents included
128
+ (`StepLimitExceeded`); `reset` (or `run`) starts a new count.
129
+ max_repeats: Most identical tool calls (same name and arguments).
130
+ fatal: Exception types that end the run instead of being shown to the model.
131
+ model: Model name used to price usage that does not name one.
132
+
133
+ Example:
134
+ ```python
135
+ from python_wrap.agents import EffectLedger
136
+ from python_wrap.adapters.openai_agents import AgentsGuard
137
+
138
+ guard = AgentsGuard(timeout=10, ledger=EffectLedger(), max_tool_calls=20)
139
+ hooks = guard.hooks() # a plain object with the RunHooks methods without the SDK
140
+ assert callable(hooks.on_tool_start) and callable(hooks.on_llm_end)
141
+ ```
142
+ """
143
+
144
+ def __init__(
145
+ self,
146
+ *,
147
+ timeout: float | str | None = None,
148
+ retry: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None,
149
+ ledger: EffectLedger | None = None,
150
+ read_only: Iterable[str] | str | None = None,
151
+ approval: Iterable[str] | str | None = None,
152
+ policy: ToolPolicy | None = None,
153
+ budget: Any = None,
154
+ tape: Any = None,
155
+ max_tool_calls: int | None = None,
156
+ max_repeats: int | None = None,
157
+ fatal: tuple[type[BaseException], ...] = FATAL,
158
+ model: str | None = None,
159
+ ) -> None:
160
+ if ledger is not None and not isinstance(ledger, EffectLedger):
161
+ raise TypeError("ledger must be an EffectLedger")
162
+ if policy is not None and not isinstance(policy, ToolPolicy):
163
+ raise TypeError("policy must be a ToolPolicy")
164
+ self.timeout = timeout
165
+ self.retry = retry
166
+ self.ledger = ledger
167
+ self.policy = policy
168
+ self.budget = budget
169
+ self.tape = tape
170
+ self.fatal = fatal
171
+ self.model = model
172
+ self.counter = CallCounter(max_tool_calls, max_repeats)
173
+ self.bridge = UsageBridge(budget, model)
174
+ self._read_only = _matcher(read_only)
175
+ self._approval = _matcher(approval)
176
+
177
+ # -- tools ----------------------------------------------------------------
178
+ def _catch_fatal(self, func: Callable[..., Any], box_of: Callable[[], _Box | None]) -> Any:
179
+ fatal = self.fatal
180
+ if _core.is_async(func):
181
+
182
+ @functools.wraps(func)
183
+ async def async_inner(*args: Any, **kwargs: Any) -> Any:
184
+ try:
185
+ return await func(*args, **kwargs)
186
+ except fatal as exc:
187
+ box = box_of()
188
+ if box is not None:
189
+ box.mark(exc)
190
+ raise
191
+
192
+ return async_inner
193
+
194
+ @functools.wraps(func)
195
+ def inner(*args: Any, **kwargs: Any) -> Any:
196
+ try:
197
+ return func(*args, **kwargs)
198
+ except fatal as exc:
199
+ box = box_of()
200
+ if box is not None:
201
+ box.mark(exc)
202
+ raise
203
+
204
+ return inner
205
+
206
+ def guard_function(self, func: F, *, name: str | None = None) -> F:
207
+ """``func`` with python-wrap `tool` semantics, ready for ``agents.function_tool``.
208
+
209
+ Keeps the signature, annotations and docstring (the SDK builds the schema from
210
+ them). A first ``RunContextWrapper`` / ``ToolContext`` parameter is left out of
211
+ the argument digest.
212
+ """
213
+ label = name or func.__name__
214
+ decorate = tool(
215
+ name=label,
216
+ read_only=self._read_only(label),
217
+ requires_approval=self._approval(label),
218
+ ledger=self.ledger,
219
+ idempotent_key=None if self.ledger is not None else False,
220
+ )
221
+ guarded = decorate(compose(func, timeout=self.timeout, retry=self.retry))
222
+ return cast(F, self._catch_fatal(guarded, _BOX.get))
223
+
224
+ def function_tool(self, func: F | None = None, /, **sdk_options: Any) -> Any:
225
+ """``agents.function_tool(func, **sdk_options)`` with the guards; needs the SDK."""
226
+ if func is None:
227
+ return functools.partial(self.function_tool, **sdk_options)
228
+ sdk = importlib.import_module("agents")
229
+ name = sdk_options.get("name_override") or func.__name__
230
+ made = sdk.function_tool(self.guard_function(func, name=name), **sdk_options)
231
+ return self._wrap(made, inner_guarded=True)
232
+
233
+ def wrap(self, function_tool: Any) -> Any:
234
+ """Guard an existing ``FunctionTool`` (``Agent.as_tool()`` included).
235
+
236
+ Returns a copy whose ``on_invoke_tool`` counts the call, applies the ledger
237
+ (keyed on the ``tool_call_id``), the timeout and the audit tape, then calls the
238
+ original. Works on any object with ``name`` and ``on_invoke_tool``.
239
+ """
240
+ return self._wrap(function_tool, inner_guarded=False)
241
+
242
+ def _wrap(self, function_tool: Any, *, inner_guarded: bool) -> Any:
243
+ original = getattr(function_tool, "on_invoke_tool", None)
244
+ name = getattr(function_tool, "name", None)
245
+ if not callable(original) or not isinstance(name, str):
246
+ raise TypeError("expected a FunctionTool (an object with name and on_invoke_tool)")
247
+ guard = self
248
+
249
+ async def call_original(ctx: Any, payload: Any) -> Any:
250
+ result = original(ctx, payload)
251
+ if hasattr(result, "__await__"):
252
+ result = await result
253
+ return result
254
+
255
+ limited = call_original
256
+ if not inner_guarded and self.timeout is not None:
257
+ limited = compose(call_original, timeout=self.timeout, retry=None)
258
+
259
+ async def on_invoke_tool(ctx: Any, payload: Any) -> Any:
260
+ try:
261
+ return await invoke(ctx, payload)
262
+ except guard.fatal as exc:
263
+ _mark_fatal(exc) # a sub-agent run may swallow it: tell the enclosing tools
264
+ raise
265
+
266
+ async def invoke(ctx: Any, payload: Any) -> Any:
267
+ call_id = getattr(ctx, "tool_call_id", None) or None
268
+ guard.counter.admit(name, payload)
269
+ guard.bridge.check(name)
270
+ if not inner_guarded:
271
+ run = current_run()
272
+ if run is not None:
273
+ run.step("tool", name, {"json": payload})
274
+ started = _core.monotonic()
275
+ box = _Box(_BOX.get())
276
+ reset = _BOX.set(box)
277
+ try:
278
+ with with_call_id(call_id):
279
+ if not inner_guarded and guard.ledger is not None:
280
+ digest = canonical({"json": payload})
281
+ result = await guard.ledger.aexecute(
282
+ name,
283
+ limited,
284
+ (ctx, payload),
285
+ key=_effect_key(name, call_id, digest, run_id_var.get(), None),
286
+ digest=digest,
287
+ call_id=call_id,
288
+ )
289
+ else:
290
+ result = await limited(ctx, payload)
291
+ except BaseException as exc:
292
+ guard._record(name, payload, None, exc, started, call_id)
293
+ raise
294
+ finally:
295
+ _BOX.reset(reset)
296
+ if box.error is not None:
297
+ guard._record(name, payload, None, box.error, started, call_id)
298
+ raise box.error
299
+ guard._record(name, payload, result, None, started, call_id)
300
+ return result
301
+
302
+ guarded = copy.copy(function_tool)
303
+ guarded.on_invoke_tool = on_invoke_tool
304
+ setattr(guarded, _GUARDED_ATTR, True)
305
+ setattr(
306
+ guarded,
307
+ _LAYER_ATTR,
308
+ (
309
+ "framework_tool",
310
+ {
311
+ "framework": FRAMEWORK,
312
+ "name": name,
313
+ # The SDK's own FunctionTool(timeout_seconds=...) counts too.
314
+ "timeout": self.timeout
315
+ if self.timeout is not None
316
+ else getattr(function_tool, "timeout_seconds", None),
317
+ },
318
+ ),
319
+ )
320
+ return guarded
321
+
322
+ def _record(
323
+ self,
324
+ name: str,
325
+ arguments: Any,
326
+ result: Any,
327
+ error: BaseException | None,
328
+ started: float,
329
+ call_id: str | None,
330
+ ) -> None:
331
+ record_tool(
332
+ self.tape,
333
+ framework=FRAMEWORK,
334
+ name=name,
335
+ arguments=arguments,
336
+ result=result,
337
+ error=error,
338
+ started=started,
339
+ call_id=call_id,
340
+ )
341
+
342
+ # -- hooks ----------------------------------------------------------------
343
+ async def _llm_start(self, agent: Any) -> None:
344
+ self.bridge.check(getattr(agent, "name", None) or FRAMEWORK)
345
+
346
+ async def _llm_end(self, agent: Any, response: Any) -> None:
347
+ tokens = usage_totals(response)
348
+ model = getattr(agent, "model", None)
349
+ model = model if isinstance(model, str) else self.model
350
+ if tokens is not None:
351
+ self.bridge.add(tokens[0], tokens[1], model)
352
+ record_llm(self.tape, framework=FRAMEWORK, model=model, tokens=tokens)
353
+
354
+ async def _tool_start(self, context: Any, tool_obj: Any) -> None:
355
+ if getattr(tool_obj, _GUARDED_ATTR, False):
356
+ return # counted (and recorded) by the wrapper itself
357
+ name = getattr(tool_obj, "name", None) or type(tool_obj).__name__
358
+ arguments = getattr(context, "tool_arguments", None)
359
+ self.counter.admit(name, arguments)
360
+ run = current_run()
361
+ if run is not None:
362
+ run.step("tool", name, None if arguments is None else {"json": arguments})
363
+
364
+ async def _tool_end(self, context: Any, tool_obj: Any, result: Any) -> None:
365
+ if getattr(tool_obj, _GUARDED_ATTR, False):
366
+ return
367
+ name = getattr(tool_obj, "name", None) or type(tool_obj).__name__
368
+ self._record(
369
+ name,
370
+ getattr(context, "tool_arguments", None),
371
+ result,
372
+ None,
373
+ _core.monotonic(),
374
+ getattr(context, "tool_call_id", None),
375
+ )
376
+
377
+ def hooks(self) -> Any:
378
+ """``RunHooks`` for ``Runner.run(..., hooks=...)`` (an ``agents.RunHooks`` subclass
379
+ when the SDK is installed, a plain object with the same methods otherwise)."""
380
+ return _hook_class("RunHooks")(self)
381
+
382
+ def agent_hooks(self) -> Any:
383
+ """``AgentHooks`` for ``Agent(hooks=...)``: use it on sub-agents run as tools."""
384
+ return _hook_class("AgentHooks")(self)
385
+
386
+ # -- runs ---------------------------------------------------------------------
387
+ def reset(self) -> None:
388
+ """Start a new run: zero the call counters."""
389
+ self.counter.reset()
390
+ self.bridge.reset()
391
+
392
+ async def run(self, agent: Any, prompt: Any, /, **options: Any) -> Any:
393
+ """``await Runner.run(agent, prompt, hooks=self.hooks(), **options)`` (SDK needed)."""
394
+ self.reset()
395
+ sdk = importlib.import_module("agents")
396
+ options.setdefault("hooks", self.hooks())
397
+ try:
398
+ return await sdk.Runner.run(agent, prompt, **options)
399
+ except Exception as exc:
400
+ found = fatal_cause(exc, self.fatal)
401
+ if found is exc:
402
+ raise
403
+ raise found from exc
404
+
405
+ def run_sync(self, agent: Any, prompt: Any, /, **options: Any) -> Any:
406
+ """``Runner.run_sync(agent, prompt, hooks=self.hooks(), **options)`` (SDK needed)."""
407
+ self.reset()
408
+ sdk = importlib.import_module("agents")
409
+ options.setdefault("hooks", self.hooks())
410
+ try:
411
+ return sdk.Runner.run_sync(agent, prompt, **options)
412
+ except Exception as exc:
413
+ found = fatal_cause(exc, self.fatal)
414
+ if found is exc:
415
+ raise
416
+ raise found from exc
417
+
418
+
419
+ class _RunHooksMixin:
420
+ """The ``RunHooks`` methods, delegating to an `AgentsGuard`."""
421
+
422
+ def __init__(self, guard: AgentsGuard) -> None:
423
+ self._guard = guard
424
+
425
+ async def on_agent_start(self, context: Any, agent: Any) -> None:
426
+ return None
427
+
428
+ async def on_agent_end(self, context: Any, agent: Any, output: Any) -> None:
429
+ return None
430
+
431
+ async def on_handoff(self, context: Any, from_agent: Any, to_agent: Any) -> None:
432
+ return None
433
+
434
+ async def on_llm_start(self, context: Any, agent: Any, *args: Any, **kwargs: Any) -> None:
435
+ await self._guard._llm_start(agent)
436
+
437
+ async def on_llm_end(self, context: Any, agent: Any, response: Any) -> None:
438
+ await self._guard._llm_end(agent, response)
439
+
440
+ async def on_tool_start(self, context: Any, agent: Any, tool: Any) -> None:
441
+ await self._guard._tool_start(context, tool)
442
+
443
+ async def on_tool_end(self, context: Any, agent: Any, tool: Any, result: Any) -> None:
444
+ await self._guard._tool_end(context, tool, result)
445
+
446
+
447
+ class _AgentHooksMixin(_RunHooksMixin):
448
+ """The ``AgentHooks`` methods (``on_start`` / ``on_end`` instead of the agent ones)."""
449
+
450
+ async def on_start(self, context: Any, agent: Any) -> None:
451
+ return None
452
+
453
+ async def on_end(self, context: Any, agent: Any, output: Any) -> None:
454
+ return None
455
+
456
+ async def on_handoff(self, context: Any, agent: Any, source: Any) -> None:
457
+ return None
458
+
459
+
460
+ @functools.lru_cache(maxsize=4)
461
+ def _hook_class(kind: str) -> Any:
462
+ mixin: type[_RunHooksMixin] = _AgentHooksMixin if kind == "AgentHooks" else _RunHooksMixin
463
+ try:
464
+ base = getattr(importlib.import_module("agents"), kind)
465
+ except (ImportError, AttributeError):
466
+ return mixin
467
+ # ``agents.RunHooks`` is a parametrised generic alias: new_class resolves it.
468
+ return types.new_class(f"PythonWrap{kind}", (mixin, base))