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,703 @@
1
+ {
2
+ "$comment": "Plain-language needs mapped to python-wrap APIs, used by `python -m python_wrap recipe` and the MCP recipe tool. `apis` are names printed by `python -m python_wrap api`; `snippet` must run as-is (tests execute it); `docs` is relative to docs/.",
3
+ "recipes": [
4
+ {
5
+ "need": "Retry flaky HTTP calls",
6
+ "keywords": [
7
+ "retry",
8
+ "http",
9
+ "https",
10
+ "request",
11
+ "requests",
12
+ "httpx",
13
+ "api",
14
+ "call",
15
+ "flaky",
16
+ "transient",
17
+ "network",
18
+ "5xx",
19
+ "429",
20
+ "503",
21
+ "backoff",
22
+ "jitter",
23
+ "client"
24
+ ],
25
+ "apis": [
26
+ "presets.http_client",
27
+ "retry",
28
+ "http.HttpRetryPolicy",
29
+ "retry_after_header"
30
+ ],
31
+ "snippet": "from python_wrap.presets import http_client\n\nusers_api = http_client(\"users\", timeout_seconds=3)\n\n@users_api\ndef get_user(user_id: int) -> dict[str, int]:\n return {\"id\": user_id} # call your HTTP client here\n\nassert get_user(7) == {\"id\": 7}\n",
32
+ "notes": "Retry only idempotent requests (GET, PUT, DELETE, or POST with an idempotency key). Never retry 4xx responses other than 408, 425 and 429. Keep a per-attempt timeout inside the retry.",
33
+ "docs": "features/resilience/http-clients.md"
34
+ },
35
+ {
36
+ "need": "Retry a function that raises a transient error",
37
+ "keywords": [
38
+ "retry",
39
+ "again",
40
+ "repeat",
41
+ "flaky",
42
+ "transient",
43
+ "error",
44
+ "exception",
45
+ "attempt",
46
+ "backoff"
47
+ ],
48
+ "apis": [
49
+ "retry",
50
+ "RetryBudget",
51
+ "attempt_history"
52
+ ],
53
+ "snippet": "from python_wrap import retry, timeout\n\n@retry(max_attempts=3, delay=0.01, on=ConnectionError)\n@timeout(2)\ndef fetch() -> str:\n return \"ok\"\n\nassert fetch() == \"ok\"\n",
54
+ "notes": "Name the transient exceptions in on=; the default on=Exception also retries bugs (doctor PW003). Always bound attempts or max_time.",
55
+ "docs": "features/resilience/retry.md"
56
+ },
57
+ {
58
+ "need": "Stop duplicate emails, charges or webhooks (run once per key)",
59
+ "keywords": [
60
+ "duplicate",
61
+ "dedupe",
62
+ "deduplicate",
63
+ "once",
64
+ "idempotent",
65
+ "idempotency",
66
+ "key",
67
+ "email",
68
+ "emails",
69
+ "charge",
70
+ "payment",
71
+ "webhook",
72
+ "double",
73
+ "twice",
74
+ "exactly"
75
+ ],
76
+ "apis": [
77
+ "idempotent",
78
+ "single_instance",
79
+ "presets.third_party_api"
80
+ ],
81
+ "snippet": "from python_wrap import idempotent\n\nsent: list[str] = []\n\n@idempotent(key=lambda order_id: f\"receipt:{order_id}\", ttl=\"1d\")\ndef send_receipt(order_id: int) -> str:\n sent.append(f\"order-{order_id}\")\n return \"sent\"\n\nassert send_receipt(1) == send_receipt(1) == \"sent\"\nassert sent == [\"order-1\"]\n",
82
+ "notes": "Never wrap a non-idempotent side effect in retry; deduplicate with idempotent keys and pass idempotent=False to presets. Across processes use a shared store (RedisStore) and a shared lease backend.",
83
+ "docs": "features/concurrency/leases-and-idempotency.md"
84
+ },
85
+ {
86
+ "need": "Limit LLM tokens or any spend budget",
87
+ "keywords": [
88
+ "llm",
89
+ "token",
90
+ "tokens",
91
+ "budget",
92
+ "spend",
93
+ "cost",
94
+ "quota",
95
+ "limit",
96
+ "openai",
97
+ "anthropic",
98
+ "model",
99
+ "prompt",
100
+ "completion",
101
+ "usage",
102
+ "allowance"
103
+ ],
104
+ "apis": [
105
+ "Quota",
106
+ "QuotaExhausted",
107
+ "rate_limit"
108
+ ],
109
+ "snippet": "from python_wrap import Quota, QuotaExhausted\n\nbudget = Quota(10_000, name=\"llm-tokens\")\nbudget.take(1_200) # tokens used by one completion\ntry:\n budget.take(20_000)\nexcept QuotaExhausted:\n pass\nassert budget.remaining == 8_800\n",
110
+ "notes": "Run `python -m python_wrap api search llm` for dedicated LLM helpers in this version. Use a Redis-backed Quota (client=, key=) to share a budget across processes.",
111
+ "docs": "api/quotas.md"
112
+ },
113
+ {
114
+ "need": "Rate limit calls to an API",
115
+ "keywords": [
116
+ "rate",
117
+ "limit",
118
+ "limiter",
119
+ "throttle",
120
+ "calls",
121
+ "per",
122
+ "second",
123
+ "minute",
124
+ "api",
125
+ "requests",
126
+ "sliding",
127
+ "window"
128
+ ],
129
+ "apis": [
130
+ "rate_limit",
131
+ "RateLimiter",
132
+ "shared_rate_limit",
133
+ "RedisWindow"
134
+ ],
135
+ "snippet": "from python_wrap import RateLimitExceeded, rate_limit\n\n@rate_limit(calls=2, period=60)\ndef ping() -> str:\n return \"pong\"\n\nping()\nping()\ntry:\n ping()\nexcept RateLimitExceeded:\n pass\n",
136
+ "notes": "Limits are per process by default; under several workers use shared_rate_limit with a RedisWindow (doctor PW012 with multiprocess=True).",
137
+ "docs": "features/concurrency/rate-limits.md"
138
+ },
139
+ {
140
+ "need": "Stop calling a dependency that is down (circuit breaker)",
141
+ "keywords": [
142
+ "circuit",
143
+ "breaker",
144
+ "down",
145
+ "outage",
146
+ "failing",
147
+ "dependency",
148
+ "fail",
149
+ "fast",
150
+ "trip",
151
+ "open"
152
+ ],
153
+ "apis": [
154
+ "circuit_breaker",
155
+ "CircuitBreaker",
156
+ "CircuitOpenError",
157
+ "SQLiteBreakerState",
158
+ "RedisBreakerState"
159
+ ],
160
+ "snippet": "from python_wrap import circuit_breaker\n\n@circuit_breaker(failure_threshold=5, recovery_timeout=30, on=ConnectionError)\ndef call_vendor() -> str:\n return \"ok\"\n\nassert call_vendor() == \"ok\"\n",
161
+ "notes": "Put the breaker outside retry so it counts calls whose retries were exhausted, not single attempts.",
162
+ "docs": "features/resilience/circuit-breaker.md"
163
+ },
164
+ {
165
+ "need": "Time out a slow call",
166
+ "keywords": [
167
+ "timeout",
168
+ "slow",
169
+ "hang",
170
+ "hung",
171
+ "deadline",
172
+ "time",
173
+ "limit",
174
+ "seconds",
175
+ "cancel",
176
+ "stuck"
177
+ ],
178
+ "apis": [
179
+ "timeout",
180
+ "deadline",
181
+ "checkpoint",
182
+ "TimeoutExpired"
183
+ ],
184
+ "snippet": "from python_wrap import timeout\n\n@timeout(2)\ndef compute() -> int:\n return 42\n\nassert compute() == 42\n",
185
+ "notes": "A sync timeout cannot interrupt code off the main thread or on Windows (doctor PW009); poll checkpoint() in long loops. Use deadline() for a budget shared by nested calls.",
186
+ "docs": "features/resilience/timeout.md"
187
+ },
188
+ {
189
+ "need": "Cache expensive results",
190
+ "keywords": [
191
+ "cache",
192
+ "caching",
193
+ "memoize",
194
+ "memo",
195
+ "expensive",
196
+ "result",
197
+ "ttl",
198
+ "lru",
199
+ "store",
200
+ "remember"
201
+ ],
202
+ "apis": [
203
+ "memoize",
204
+ "cache",
205
+ "amemoize",
206
+ "invalidate",
207
+ "RedisStore"
208
+ ],
209
+ "snippet": "from python_wrap import memoize\n\n@memoize(ttl=60, maxsize=1024)\ndef price(sku: str) -> int:\n return len(sku)\n\nassert price(\"A-1\") == price(\"A-1\") == 3\n",
210
+ "notes": "Failures are never cached unless you ask (cache_exceptions=). On methods use per_instance=True or a bound (doctor PW011).",
211
+ "docs": "features/caching/memoize.md"
212
+ },
213
+ {
214
+ "need": "Avoid a thundering herd of identical concurrent calls",
215
+ "keywords": [
216
+ "thundering",
217
+ "herd",
218
+ "stampede",
219
+ "concurrent",
220
+ "identical",
221
+ "simultaneous",
222
+ "coalesce",
223
+ "singleflight",
224
+ "dogpile"
225
+ ],
226
+ "apis": [
227
+ "singleflight",
228
+ "memoize"
229
+ ],
230
+ "snippet": "from python_wrap import singleflight\n\n@singleflight\ndef load(key: str) -> str:\n return key.upper()\n\nassert load(\"a\") == \"A\"\n",
231
+ "notes": "memoize(singleflight=True) combines caching with single-flight loading.",
232
+ "docs": "features/caching/singleflight.md"
233
+ },
234
+ {
235
+ "need": "Cap concurrent calls to a dependency",
236
+ "keywords": [
237
+ "concurrency",
238
+ "concurrent",
239
+ "parallel",
240
+ "bulkhead",
241
+ "semaphore",
242
+ "max",
243
+ "simultaneous",
244
+ "pool",
245
+ "isolate"
246
+ ],
247
+ "apis": [
248
+ "limit_concurrency",
249
+ "Bulkhead",
250
+ "gather_limit",
251
+ "AdaptiveLimiter"
252
+ ],
253
+ "snippet": "from python_wrap import limit_concurrency\n\n@limit_concurrency(4)\ndef query() -> str:\n return \"rows\"\n\nassert query() == \"rows\"\n",
254
+ "notes": "Bulkheads are per process unless given a shared lease backend.",
255
+ "docs": "features/concurrency/bulkheads.md"
256
+ },
257
+ {
258
+ "need": "Return a default value when a call fails",
259
+ "keywords": [
260
+ "fallback",
261
+ "default",
262
+ "degrade",
263
+ "graceful",
264
+ "suppress",
265
+ "ignore",
266
+ "error",
267
+ "value",
268
+ "instead"
269
+ ],
270
+ "apis": [
271
+ "fallback",
272
+ "suppress"
273
+ ],
274
+ "snippet": "from python_wrap import fallback\n\n@fallback([], on=ConnectionError)\ndef recommendations() -> list[str]:\n raise ConnectionError\n\nassert recommendations() == []\n",
275
+ "notes": "Narrow on= so programming errors are not hidden.",
276
+ "docs": "features/resilience/fallback.md"
277
+ },
278
+ {
279
+ "need": "Batch many small calls into one",
280
+ "keywords": [
281
+ "batch",
282
+ "batching",
283
+ "group",
284
+ "bulk",
285
+ "dataloader",
286
+ "n+1",
287
+ "many",
288
+ "small",
289
+ "calls",
290
+ "combine"
291
+ ],
292
+ "apis": [
293
+ "batch_calls",
294
+ "Batched",
295
+ "process_batches"
296
+ ],
297
+ "docs": "features/caching/batching.md"
298
+ },
299
+ {
300
+ "need": "Test code that sleeps, retries or caches without waiting",
301
+ "keywords": [
302
+ "test",
303
+ "tests",
304
+ "testing",
305
+ "pytest",
306
+ "fake",
307
+ "clock",
308
+ "time",
309
+ "sleep",
310
+ "fast",
311
+ "disable",
312
+ "retries",
313
+ "mock"
314
+ ],
315
+ "apis": [
316
+ "testing.fake_clock",
317
+ "testing.disabled",
318
+ "testing.assert_retried",
319
+ "testing.spy"
320
+ ],
321
+ "snippet": "from python_wrap import retry\nfrom python_wrap.testing import fake_clock\n\n@retry(max_attempts=3, delay=5, on=ValueError)\ndef flaky() -> None:\n raise ValueError\n\nwith fake_clock() as clock:\n try:\n flaky()\n except ValueError:\n pass\nassert len(clock.sleeps) == 2\n",
322
+ "docs": "cookbook/testing-your-code.md"
323
+ },
324
+ {
325
+ "need": "Check a resilience stack for risky combinations",
326
+ "keywords": [
327
+ "check",
328
+ "lint",
329
+ "review",
330
+ "audit",
331
+ "doctor",
332
+ "explain",
333
+ "policy",
334
+ "stack",
335
+ "risky",
336
+ "order",
337
+ "safe",
338
+ "ci"
339
+ ],
340
+ "apis": [
341
+ "doctor.explain",
342
+ "doctor.doctor",
343
+ "Policy"
344
+ ],
345
+ "snippet": "from python_wrap import policy, retry\nfrom python_wrap.doctor import explain\n\nrisky = policy(retry=retry(max_attempts=3, on=ConnectionError), name=\"charge\")\nassert not explain(risky, idempotent=False).ok # PW002: retrying a charge\n",
346
+ "notes": "Run `python -m python_wrap doctor module:attribute` in CI; add --non-idempotent for side effects and --multiprocess under worker pools.",
347
+ "docs": "features/resilience/presets-and-doctor.md"
348
+ },
349
+ {
350
+ "need": "Migrate from tenacity or backoff",
351
+ "keywords": [
352
+ "migrate",
353
+ "migration",
354
+ "tenacity",
355
+ "backoff",
356
+ "convert",
357
+ "rewrite",
358
+ "codemod",
359
+ "replace",
360
+ "port"
361
+ ],
362
+ "apis": [
363
+ "migrate.migrate_source"
364
+ ],
365
+ "snippet": "from python_wrap.migrate import migrate_source\n\nsource = \"import tenacity\\n\\n@tenacity.retry(stop=tenacity.stop_after_attempt(3))\\ndef f():\\n pass\\n\"\nassert \"python_wrap\" in migrate_source(source).text\n",
366
+ "notes": "`python -m python_wrap migrate PATH` is a dry run unless you pass --write.",
367
+ "docs": "project/migrate-tool.md"
368
+ },
369
+ {
370
+ "need": "Run a function in the background on a schedule",
371
+ "keywords": [
372
+ "periodic",
373
+ "schedule",
374
+ "interval",
375
+ "every",
376
+ "background",
377
+ "job",
378
+ "cron",
379
+ "loop",
380
+ "recurring"
381
+ ],
382
+ "apis": [
383
+ "periodic",
384
+ "Periodic",
385
+ "AsyncPeriodic"
386
+ ],
387
+ "docs": "features/concurrency/periodic.md"
388
+ },
389
+ {
390
+ "need": "Log or audit calls without leaking secrets",
391
+ "keywords": [
392
+ "log",
393
+ "logging",
394
+ "audit",
395
+ "trace",
396
+ "record",
397
+ "arguments",
398
+ "secrets",
399
+ "redact",
400
+ "password",
401
+ "token",
402
+ "mask"
403
+ ],
404
+ "apis": [
405
+ "log_args",
406
+ "audit",
407
+ "redact",
408
+ "log_context"
409
+ ],
410
+ "snippet": "from python_wrap import redact\n\nassert redact({\"user\": \"ann\", \"password\": \"hunter2\"})[\"password\"] != \"hunter2\"\n",
411
+ "notes": "Redaction matches by argument name; secrets under innocuous names are not detected.",
412
+ "docs": "features/observability/logging.md"
413
+ },
414
+ {
415
+ "need": "Inject faults to test resilience (chaos)",
416
+ "keywords": [
417
+ "chaos",
418
+ "fault",
419
+ "injection",
420
+ "inject",
421
+ "failure",
422
+ "latency",
423
+ "test",
424
+ "resilience",
425
+ "game",
426
+ "day"
427
+ ],
428
+ "apis": [
429
+ "chaos.fault_point",
430
+ "chaos.chaos"
431
+ ],
432
+ "snippet": "from python_wrap.chaos import fault_point\n\ndef load() -> str:\n fault_point(\"db.load\")\n return \"row\"\n\nassert load() == \"row\" # no rule armed: nothing happens\n",
433
+ "docs": "testing/chaos.md"
434
+ },
435
+ {
436
+ "need": "Shut down gracefully and drain in-flight work",
437
+ "keywords": [
438
+ "shutdown",
439
+ "graceful",
440
+ "drain",
441
+ "sigterm",
442
+ "stop",
443
+ "exit",
444
+ "lifecycle"
445
+ ],
446
+ "apis": [
447
+ "shutdown",
448
+ "ShutdownManager"
449
+ ],
450
+ "docs": "features/concurrency/graceful-shutdown.md"
451
+ },
452
+ {
453
+ "need": "Limit LLM token and dollar spend",
454
+ "keywords": [
455
+ "limit",
456
+ "llm",
457
+ "tokens",
458
+ "token",
459
+ "budget",
460
+ "spend",
461
+ "cost",
462
+ "dollars",
463
+ "usd",
464
+ "cap",
465
+ "quota",
466
+ "openai",
467
+ "anthropic",
468
+ "gemini",
469
+ "tpm",
470
+ "model"
471
+ ],
472
+ "apis": [
473
+ "Budget",
474
+ "token_rate_limit",
475
+ "BudgetExceeded",
476
+ "Quota"
477
+ ],
478
+ "snippet": "from python_wrap.llm import Budget, BudgetExceeded\n\nspend = Budget(tokens=100, name='demo')\n\n@spend\ndef ask(prompt: str) -> dict[str, object]:\n return {'usage': {'input_tokens': 80, 'output_tokens': 40}}\n\nask('first') # crosses the limit; the paid-for answer is returned\ntry:\n ask('second')\nexcept BudgetExceeded:\n pass\nelse:\n raise AssertionError('the second call should be refused')\n",
479
+ "notes": "Budget caps tokens or dollars (per total, key, run or chain); token_rate_limit caps tokens per minute against the provider's limit. Usage is read from Anthropic-style or OpenAI-style responses without importing an SDK.",
480
+ "docs": "features/ai/llm-calls.md"
481
+ },
482
+ {
483
+ "need": "Retry LLM API calls",
484
+ "keywords": [
485
+ "retry",
486
+ "llm",
487
+ "openai",
488
+ "anthropic",
489
+ "gemini",
490
+ "model",
491
+ "429",
492
+ "529",
493
+ "overloaded",
494
+ "rate",
495
+ "limit",
496
+ "completion",
497
+ "chat",
498
+ "messages",
499
+ "sdk",
500
+ "transient",
501
+ "flaky",
502
+ "api",
503
+ "call"
504
+ ],
505
+ "apis": [
506
+ "llm_retry",
507
+ "presets.llm_client",
508
+ "llm_transient"
509
+ ],
510
+ "snippet": "from python_wrap.llm import llm_retry\nfrom python_wrap.testing import fake_clock\n\nclass Overloaded(Exception):\n status_code = 529\n\ncalls: list[str] = []\n\n@llm_retry(max_attempts=3)\ndef complete(prompt: str) -> str:\n calls.append(prompt)\n if len(calls) < 3:\n raise Overloaded\n return 'done'\n\nwith fake_clock():\n assert complete('hi') == 'done'\nassert len(calls) == 3\n",
511
+ "notes": "llm_retry retries only rate limits, overloads, 5xx, timeouts and connection errors, honours Retry-After, and never retries other 4xx. presets.llm_client adds a breaker, budget and token limit in the right order.",
512
+ "docs": "features/ai/llm-calls.md"
513
+ },
514
+ {
515
+ "need": "Stop runaway agent loops",
516
+ "keywords": [
517
+ "stop",
518
+ "agent",
519
+ "loop",
520
+ "runaway",
521
+ "infinite",
522
+ "steps",
523
+ "max",
524
+ "limit",
525
+ "tool",
526
+ "tools",
527
+ "llm",
528
+ "autonomous",
529
+ "repeat",
530
+ "timeout",
531
+ "guard"
532
+ ],
533
+ "apis": [
534
+ "agent_run",
535
+ "RunGuard",
536
+ "record_step",
537
+ "StepLimitExceeded",
538
+ "LoopDetected"
539
+ ],
540
+ "snippet": "from python_wrap import StepLimitExceeded, agent_run, record_step\n\nwith agent_run(max_steps=3, max_seconds=30) as run:\n try:\n while True:\n record_step('llm', 'model')\n except StepLimitExceeded:\n pass\nassert run.steps == 3\n",
541
+ "notes": "Bound every agent loop with max_steps, max_seconds and max_repeats; pass a Budget to stop on spend. Tool calls count as steps automatically.",
542
+ "docs": "features/ai/agent-safety.md"
543
+ },
544
+ {
545
+ "need": "Make agent tool calls safe",
546
+ "keywords": [
547
+ "tool",
548
+ "tools",
549
+ "agent",
550
+ "safe",
551
+ "side",
552
+ "effects",
553
+ "approval",
554
+ "dry",
555
+ "run",
556
+ "idempotent",
557
+ "replay",
558
+ "function",
559
+ "calling",
560
+ "write",
561
+ "read"
562
+ ],
563
+ "apis": [
564
+ "tool",
565
+ "ToolRegistry",
566
+ "ToolPolicy",
567
+ "RunGuard"
568
+ ],
569
+ "snippet": "import json\n\nfrom python_wrap import RunGuard, ToolRegistry\n\nsent: list[str] = []\ntools = ToolRegistry(guard=RunGuard(max_steps=10))\n\n@tools.tool\ndef send_email(to: str) -> str:\n sent.append(to)\n return 'sent'\n\nwith tools.run(run_id='demo-run'):\n assert tools.call('send_email', json.dumps({'to': 'a@example.com'})) == 'sent'\n tools.call('send_email', json.dumps({'to': 'a@example.com'})) # replay: not sent again\nassert sent == ['a@example.com']\n",
570
+ "notes": "Side-effecting tools are replay-proof within a run; mark pure reads read_only=True, gate risky ones with requires_approval=True, and use ToolPolicy(dry_run=True) to plan without acting.",
571
+ "docs": "features/ai/agent-safety.md"
572
+ },
573
+ {
574
+ "need": "Test agents with a fake LLM and injected faults",
575
+ "keywords": [
576
+ "test",
577
+ "testing",
578
+ "agent",
579
+ "fake",
580
+ "llm",
581
+ "mock",
582
+ "provider",
583
+ "chaos",
584
+ "fault",
585
+ "rate",
586
+ "limit",
587
+ "overloaded",
588
+ "deterministic",
589
+ "pytest"
590
+ ],
591
+ "apis": [
592
+ "fake_llm",
593
+ "FakeProvider",
594
+ "LLMFaults",
595
+ "fake_clock"
596
+ ],
597
+ "snippet": "from python_wrap import fake_llm, retry\nfrom python_wrap.chaos import chaos\nfrom python_wrap.llm_testing import RateLimitError\nfrom python_wrap.testing import fake_clock\n\nllm = fake_llm(['ok'])\n\n@retry(max_attempts=3, delay=1, on=RateLimitError)\ndef ask() -> str:\n return llm.complete(messages=[{'role': 'user', 'content': 'hi'}]).text\n\nwith fake_clock():\n chaos.llm.rate_limit('llm.*', times=1, retry_after=1)\n try:\n assert ask() == 'ok'\n finally:\n chaos.clear()\n",
598
+ "notes": "No network and no SDK: fake_llm scripts replies, chaos.llm injects 429/529/timeouts/malformed JSON, fake_clock removes the waiting.",
599
+ "docs": "features/ai/testing-agents.md"
600
+ },
601
+ {
602
+ "need": "Audit LLM and tool calls",
603
+ "keywords": [
604
+ "audit",
605
+ "llm",
606
+ "tool",
607
+ "trace",
608
+ "tape",
609
+ "log",
610
+ "record",
611
+ "replay",
612
+ "redact",
613
+ "compliance",
614
+ "observability",
615
+ "agent",
616
+ "calls",
617
+ "cost"
618
+ ],
619
+ "apis": [
620
+ "AuditTape",
621
+ "traced_llm",
622
+ "traced_tool",
623
+ "replay"
624
+ ],
625
+ "snippet": "from python_wrap import AuditTape, traced_llm\n\ntape = AuditTape()\n\n@traced_llm(model='demo-1', tape=tape)\ndef ask(prompt: str) -> dict[str, object]:\n return {'text': 'ok', 'usage': {'input_tokens': 5, 'output_tokens': 2}}\n\nask('mail ada@example.com')\n[record] = tape.records()\nassert record.kind == 'llm' and record.input_tokens == 5\nassert 'ada@example.com' not in str(record.input)\n",
626
+ "notes": "The tape stores redacted inputs and outputs with tokens and cost; replay(tape) serves recorded results in tests without calling a provider or running tools.",
627
+ "docs": "features/ai/observability.md"
628
+ },
629
+ {
630
+ "need": "Fall back to another model when one fails",
631
+ "keywords": [
632
+ "fallback",
633
+ "fall",
634
+ "back",
635
+ "model",
636
+ "models",
637
+ "backup",
638
+ "secondary",
639
+ "outage",
640
+ "llm",
641
+ "provider",
642
+ "chain",
643
+ "failover",
644
+ "down"
645
+ ],
646
+ "apis": [
647
+ "fallback_models",
648
+ "llm_retry"
649
+ ],
650
+ "snippet": "from python_wrap.llm import fallback_models\n\nclass Down(Exception):\n status_code = 503\n\ndef large(q: str) -> str:\n raise Down\n\ndef small(q: str) -> str:\n return f'small: {q}'\n\nask = fallback_models([large, small], names=['large', 'small'])\nassert ask('hi') == 'small: hi'\n",
651
+ "notes": "Each model gets its own breaker, so a dead model is skipped quickly; an llm.fallback_served event names the model that answered.",
652
+ "docs": "features/ai/llm-calls.md"
653
+ },
654
+ {
655
+ "need": "Cache LLM responses",
656
+ "keywords": [
657
+ "cache",
658
+ "caching",
659
+ "llm",
660
+ "response",
661
+ "responses",
662
+ "prompt",
663
+ "repeat",
664
+ "same",
665
+ "question",
666
+ "save",
667
+ "cost",
668
+ "semantic",
669
+ "memoize"
670
+ ],
671
+ "apis": [
672
+ "llm_cache"
673
+ ],
674
+ "snippet": "from python_wrap.llm import llm_cache\n\ncalls: list[str] = []\n\n@llm_cache(ttl=600)\ndef ask(*, model: str, messages: list[dict[str, str]]) -> str:\n calls.append(model)\n return 'answer'\n\nmsgs = [{'role': 'user', 'content': 'Define idempotent.'}]\nassert ask(model='m', messages=msgs) == ask(model='m', messages=msgs)\nassert calls == ['m']\n",
675
+ "notes": "The key covers the model, messages and generation parameters. Cache only deterministic requests (temperature 0) and keep personal data out of shared caches.",
676
+ "docs": "features/ai/llm-calls.md"
677
+ },
678
+ {
679
+ "need": "Time out stalled LLM streams",
680
+ "keywords": [
681
+ "stream",
682
+ "streaming",
683
+ "timeout",
684
+ "stall",
685
+ "stalled",
686
+ "hang",
687
+ "chunk",
688
+ "token",
689
+ "first",
690
+ "llm",
691
+ "sse",
692
+ "slow"
693
+ ],
694
+ "apis": [
695
+ "stream_timeout",
696
+ "StreamTimeout"
697
+ ],
698
+ "snippet": "from python_wrap.llm import stream_timeout\n\nchunks = list(stream_timeout(iter(['a', 'b', 'c']), first_token=2, chunk_gap=1))\nassert chunks == ['a', 'b', 'c']\n",
699
+ "notes": "first_token bounds the wait for the first chunk and chunk_gap the silence between chunks; a stall raises StreamTimeout instead of hanging the request.",
700
+ "docs": "features/ai/llm-calls.md"
701
+ }
702
+ ]
703
+ }