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.
- python_wrap/__init__.py +348 -1
- python_wrap/__main__.py +57 -0
- python_wrap/_backend.py +133 -0
- python_wrap/_buckets.py +162 -0
- python_wrap/_core.py +12 -3
- python_wrap/_data/agent_guide.md +103 -0
- python_wrap/_data/recipes.json +703 -0
- python_wrap/_fork.py +113 -0
- python_wrap/_integration.py +29 -0
- python_wrap/_runtime.py +157 -0
- python_wrap/adapters/__init__.py +101 -0
- python_wrap/adapters/_frameworks.py +251 -0
- python_wrap/adapters/_sdk.py +1978 -0
- python_wrap/adapters/anthropic.py +139 -0
- python_wrap/adapters/langchain.py +288 -0
- python_wrap/adapters/openai.py +169 -0
- python_wrap/adapters/openai_agents.py +468 -0
- python_wrap/adapters/pydantic_ai.py +459 -0
- python_wrap/adaptive.py +605 -0
- python_wrap/agents.py +2503 -0
- python_wrap/alerts.py +293 -0
- python_wrap/async_cache.py +745 -0
- python_wrap/batching.py +17 -4
- python_wrap/buffering.py +952 -0
- python_wrap/bulkhead.py +58 -6
- python_wrap/caching.py +425 -56
- python_wrap/celery.py +528 -0
- python_wrap/chaos.py +519 -0
- python_wrap/circuit.py +454 -23
- python_wrap/compat.py +267 -0
- python_wrap/concurrency.py +82 -1746
- python_wrap/config.py +25 -4
- python_wrap/coordination.py +638 -0
- python_wrap/credentials.py +126 -0
- python_wrap/dashboard.py +358 -0
- python_wrap/debounce.py +538 -0
- python_wrap/django.py +100 -0
- python_wrap/doctor.py +599 -0
- python_wrap/events.py +145 -4
- python_wrap/exporters.py +663 -0
- python_wrap/fastapi.py +81 -0
- python_wrap/flask.py +61 -0
- python_wrap/genai.py +1101 -0
- python_wrap/health.py +187 -0
- python_wrap/http.py +940 -0
- python_wrap/idempotency.py +446 -0
- python_wrap/introspect.py +738 -0
- python_wrap/lifecycle.py +620 -0
- python_wrap/llm.py +2574 -0
- python_wrap/llm_cassette.py +948 -0
- python_wrap/llm_http_chaos.py +326 -0
- python_wrap/llm_shared.py +772 -0
- python_wrap/llm_testing.py +990 -0
- python_wrap/llm_validate.py +383 -0
- python_wrap/local_state.py +395 -0
- python_wrap/logs.py +82 -26
- python_wrap/mcp.py +490 -0
- python_wrap/mcp_guard.py +357 -0
- python_wrap/metrics.py +6 -3
- python_wrap/migrate.py +1452 -0
- python_wrap/observability.py +484 -0
- python_wrap/periodic.py +24 -2
- python_wrap/policies.py +396 -0
- python_wrap/policy.py +14 -0
- python_wrap/predicates.py +276 -0
- python_wrap/presets.py +378 -0
- python_wrap/processing.py +227 -0
- python_wrap/propagation.py +62 -0
- python_wrap/pytest_plugin.py +85 -0
- python_wrap/quotas.py +319 -0
- python_wrap/ratelimit.py +560 -0
- python_wrap/redaction.py +228 -0
- python_wrap/retry.py +448 -70
- python_wrap/shared.py +653 -0
- python_wrap/singleflight.py +255 -0
- python_wrap/slow.py +72 -0
- python_wrap/stores.py +168 -0
- python_wrap/switches.py +164 -0
- python_wrap/testing.py +34 -8
- python_wrap/timeouts.py +874 -0
- python_wrap/timing.py +239 -17
- python_wrap/validation.py +187 -12
- python_wrap/web.py +723 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
- python_wrap-0.4.0.dist-info/RECORD +95 -0
- python_wrap-0.2.1.dist-info/RECORD +0 -29
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
"""A machine-readable index of the public API, plain-language recipes and the agent guide.
|
|
2
|
+
|
|
3
|
+
Everything here is generated at run time from ``__all__``, docstrings and signatures, so
|
|
4
|
+
new modules and names show up without editing this file. It backs the commands
|
|
5
|
+
|
|
6
|
+
* ``python -m python_wrap api [SYMBOL | search WORDS...] [--json]``
|
|
7
|
+
* ``python -m python_wrap recipe [NEED...] [--json]``
|
|
8
|
+
* ``python -m python_wrap guide``
|
|
9
|
+
|
|
10
|
+
and the read-only tools of `python_wrap.mcp`. Nothing is called: only ``__all__``,
|
|
11
|
+
docstrings and signatures are read. Importing a python-wrap submodule never imports an
|
|
12
|
+
optional dependency, so building the index needs only the standard library.
|
|
13
|
+
|
|
14
|
+
The recipe table lives in ``python_wrap/_data/recipes.json``; add an entry there to teach
|
|
15
|
+
``recipe`` (and the MCP ``recipe`` tool) a new need.
|
|
16
|
+
|
|
17
|
+
Example:
|
|
18
|
+
```python
|
|
19
|
+
from python_wrap.introspect import find_recipes, get_symbol, search
|
|
20
|
+
|
|
21
|
+
entry = get_symbol("retry")
|
|
22
|
+
assert entry is not None and entry.name == "retry"
|
|
23
|
+
assert "max_attempts" in [param.name for param in entry.params]
|
|
24
|
+
assert search("circuit breaker")[0].name in {"circuit_breaker", "CircuitBreaker"}
|
|
25
|
+
assert find_recipes("stop duplicate emails")[0].apis
|
|
26
|
+
```
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import argparse
|
|
32
|
+
import enum
|
|
33
|
+
import functools
|
|
34
|
+
import importlib
|
|
35
|
+
import inspect
|
|
36
|
+
import json
|
|
37
|
+
import pkgutil
|
|
38
|
+
import re
|
|
39
|
+
import sys
|
|
40
|
+
import textwrap
|
|
41
|
+
import types
|
|
42
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
43
|
+
from dataclasses import asdict, dataclass, field
|
|
44
|
+
from importlib import resources
|
|
45
|
+
from typing import Any
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"Param",
|
|
49
|
+
"Recipe",
|
|
50
|
+
"Symbol",
|
|
51
|
+
"api_index",
|
|
52
|
+
"find_recipes",
|
|
53
|
+
"get_symbol",
|
|
54
|
+
"guide_text",
|
|
55
|
+
"recipes",
|
|
56
|
+
"search",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
_PACKAGE = "python_wrap"
|
|
60
|
+
_SKIP_MODULES = {"__main__"}
|
|
61
|
+
_SECTION = re.compile(r"^(?P<name>[A-Z][A-Za-z ]*):\s*$")
|
|
62
|
+
_ITEM = re.compile(r"^(?P<name>\*{0,2}[A-Za-z_][A-Za-z0-9_]*)\s*(?:\([^)]*\))?\s*:\s*(?P<desc>.*)$")
|
|
63
|
+
_ADDRESS = re.compile(r" at 0x[0-9a-fA-F]+")
|
|
64
|
+
_FORWARD_REF = re.compile(r"ForwardRef\('([^']*)'(?:, [^)]*)?\)")
|
|
65
|
+
_WORD = re.compile(r"[a-z0-9]+")
|
|
66
|
+
_STOPWORDS = frozenset(
|
|
67
|
+
[
|
|
68
|
+
"a",
|
|
69
|
+
"an",
|
|
70
|
+
"and",
|
|
71
|
+
"are",
|
|
72
|
+
"as",
|
|
73
|
+
"at",
|
|
74
|
+
"be",
|
|
75
|
+
"by",
|
|
76
|
+
"can",
|
|
77
|
+
"do",
|
|
78
|
+
"for",
|
|
79
|
+
"from",
|
|
80
|
+
"how",
|
|
81
|
+
"i",
|
|
82
|
+
"in",
|
|
83
|
+
"into",
|
|
84
|
+
"is",
|
|
85
|
+
"it",
|
|
86
|
+
"its",
|
|
87
|
+
"make",
|
|
88
|
+
"me",
|
|
89
|
+
"my",
|
|
90
|
+
"of",
|
|
91
|
+
"on",
|
|
92
|
+
"or",
|
|
93
|
+
"so",
|
|
94
|
+
"that",
|
|
95
|
+
"the",
|
|
96
|
+
"their",
|
|
97
|
+
"them",
|
|
98
|
+
"this",
|
|
99
|
+
"to",
|
|
100
|
+
"too",
|
|
101
|
+
"up",
|
|
102
|
+
"use",
|
|
103
|
+
"want",
|
|
104
|
+
"we",
|
|
105
|
+
"when",
|
|
106
|
+
"with",
|
|
107
|
+
"without",
|
|
108
|
+
"you",
|
|
109
|
+
"your",
|
|
110
|
+
]
|
|
111
|
+
)
|
|
112
|
+
_MAX_QUERY = 500
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True)
|
|
116
|
+
class Param:
|
|
117
|
+
"""One parameter of a callable.
|
|
118
|
+
|
|
119
|
+
Attributes:
|
|
120
|
+
name: Parameter name (``*args`` and ``**kwargs`` keep their stars).
|
|
121
|
+
kind: ``positional_only``, ``positional_or_keyword``, ``var_positional``,
|
|
122
|
+
``keyword_only`` or ``var_keyword``.
|
|
123
|
+
annotation: The annotation as written, or ``""``.
|
|
124
|
+
default: A stable rendering of the default, or ``None`` when there is none.
|
|
125
|
+
description: The text from the docstring's ``Args:`` section, or ``""``.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
name: str
|
|
129
|
+
kind: str
|
|
130
|
+
annotation: str = ""
|
|
131
|
+
default: str | None = None
|
|
132
|
+
description: str = ""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass(frozen=True)
|
|
136
|
+
class Symbol:
|
|
137
|
+
"""One public name.
|
|
138
|
+
|
|
139
|
+
Attributes:
|
|
140
|
+
name: Short name used for lookups: ``"retry"`` for top-level names,
|
|
141
|
+
``"doctor.explain"`` for names public only in a submodule.
|
|
142
|
+
qualname: Full import path, such as ``"python_wrap.doctor.explain"``.
|
|
143
|
+
kind: ``class``, ``function``, ``module``, ``alias`` (a type alias) or
|
|
144
|
+
``constant``.
|
|
145
|
+
signature: ``name(params) -> return`` for callables, ``""`` otherwise.
|
|
146
|
+
summary: First line of the docstring.
|
|
147
|
+
params: Parameters merged with their ``Args:`` descriptions.
|
|
148
|
+
returns: The docstring's ``Returns:`` section.
|
|
149
|
+
raises: ``(exception, description)`` pairs from ``Raises:``.
|
|
150
|
+
example: A minimal example: the first python code block of the docstring.
|
|
151
|
+
doc: The full docstring (dedented).
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
name: str
|
|
155
|
+
qualname: str
|
|
156
|
+
kind: str
|
|
157
|
+
signature: str
|
|
158
|
+
summary: str
|
|
159
|
+
params: tuple[Param, ...] = ()
|
|
160
|
+
returns: str = ""
|
|
161
|
+
raises: tuple[tuple[str, str], ...] = ()
|
|
162
|
+
example: str = ""
|
|
163
|
+
doc: str = ""
|
|
164
|
+
|
|
165
|
+
def to_dict(self, *, full: bool = True) -> dict[str, Any]:
|
|
166
|
+
"""Return a JSON-serialisable dict; ``full=False`` keeps only the headline fields."""
|
|
167
|
+
if not full:
|
|
168
|
+
return {
|
|
169
|
+
"name": self.name,
|
|
170
|
+
"qualname": self.qualname,
|
|
171
|
+
"kind": self.kind,
|
|
172
|
+
"signature": self.signature,
|
|
173
|
+
"summary": self.summary,
|
|
174
|
+
}
|
|
175
|
+
data = asdict(self)
|
|
176
|
+
data["raises"] = [{"exception": exc, "description": desc} for exc, desc in self.raises]
|
|
177
|
+
return data
|
|
178
|
+
|
|
179
|
+
def render(self) -> str:
|
|
180
|
+
"""Human-readable detail: signature, summary, parameters, raises and example."""
|
|
181
|
+
lines = [self.qualname, "", self.signature or self.kind, "", self.summary]
|
|
182
|
+
if self.params:
|
|
183
|
+
lines += ["", "Parameters:"]
|
|
184
|
+
for param in self.params:
|
|
185
|
+
head = f" {param.name}"
|
|
186
|
+
if param.annotation:
|
|
187
|
+
head += f": {param.annotation}"
|
|
188
|
+
if param.default is not None:
|
|
189
|
+
head += f" = {param.default}"
|
|
190
|
+
lines.append(head)
|
|
191
|
+
if param.description:
|
|
192
|
+
lines.append(textwrap.indent(param.description, " "))
|
|
193
|
+
if self.returns:
|
|
194
|
+
lines += ["", "Returns:", textwrap.indent(self.returns, " ")]
|
|
195
|
+
if self.raises:
|
|
196
|
+
lines += ["", "Raises:"]
|
|
197
|
+
lines += [f" {exc}: {desc}" if desc else f" {exc}" for exc, desc in self.raises]
|
|
198
|
+
if self.example:
|
|
199
|
+
lines += ["", "Example:", textwrap.indent(self.example, " ")]
|
|
200
|
+
return "\n".join(lines).rstrip() + "\n"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass(frozen=True)
|
|
204
|
+
class Recipe:
|
|
205
|
+
"""A plain-language need mapped to the APIs that solve it.
|
|
206
|
+
|
|
207
|
+
Attributes:
|
|
208
|
+
need: The need, phrased the way someone would ask for it.
|
|
209
|
+
apis: Index names to use (see `Symbol.name`); names that do not exist in this
|
|
210
|
+
installation are dropped.
|
|
211
|
+
snippet: A minimal, runnable example.
|
|
212
|
+
notes: Pitfalls and what not to do.
|
|
213
|
+
docs: Path of the docs page, relative to the docs root.
|
|
214
|
+
keywords: Extra words that should match this recipe.
|
|
215
|
+
score: How well it matched the query (0 when listed without a query).
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
need: str
|
|
219
|
+
apis: tuple[str, ...]
|
|
220
|
+
snippet: str = ""
|
|
221
|
+
notes: str = ""
|
|
222
|
+
docs: str = ""
|
|
223
|
+
keywords: tuple[str, ...] = field(default=(), repr=False)
|
|
224
|
+
score: int = 0
|
|
225
|
+
|
|
226
|
+
def to_dict(self) -> dict[str, Any]:
|
|
227
|
+
"""Return a JSON-serialisable dict, with a one-line summary of each API."""
|
|
228
|
+
data = asdict(self)
|
|
229
|
+
data["apis"] = [_api_brief(name) for name in self.apis]
|
|
230
|
+
data.pop("keywords")
|
|
231
|
+
return data
|
|
232
|
+
|
|
233
|
+
def render(self) -> str:
|
|
234
|
+
"""Human-readable recipe."""
|
|
235
|
+
lines = [self.need, ""]
|
|
236
|
+
for name in self.apis:
|
|
237
|
+
brief = _api_brief(name)
|
|
238
|
+
lines.append(f" {brief['qualname']}: {brief['summary']}")
|
|
239
|
+
if self.snippet:
|
|
240
|
+
lines += ["", textwrap.indent(self.snippet.rstrip(), " ")]
|
|
241
|
+
if self.notes:
|
|
242
|
+
lines += ["", textwrap.fill(self.notes, 88, initial_indent="Note: ")]
|
|
243
|
+
if self.docs:
|
|
244
|
+
lines += ["", f"Docs: {self.docs}"]
|
|
245
|
+
return "\n".join(lines) + "\n"
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
# --------------------------------------------------------------------------- rendering
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _render_value(value: Any) -> str:
|
|
252
|
+
"""A stable repr: no memory addresses, sorted sets, classes and functions by name."""
|
|
253
|
+
if isinstance(value, (set, frozenset)):
|
|
254
|
+
items = ", ".join(sorted(_render_value(item) for item in value))
|
|
255
|
+
if not value:
|
|
256
|
+
return f"{type(value).__name__}()"
|
|
257
|
+
return f"{{{items}}}" if type(value) is set else f"frozenset({{{items}}})"
|
|
258
|
+
if isinstance(value, tuple):
|
|
259
|
+
inner = ", ".join(_render_value(item) for item in value)
|
|
260
|
+
return f"({inner},)" if len(value) == 1 else f"({inner})"
|
|
261
|
+
if isinstance(value, list):
|
|
262
|
+
return "[" + ", ".join(_render_value(item) for item in value) + "]"
|
|
263
|
+
if isinstance(value, dict):
|
|
264
|
+
pairs = (f"{_render_value(k)}: {_render_value(v)}" for k, v in value.items())
|
|
265
|
+
return "{" + ", ".join(pairs) + "}"
|
|
266
|
+
if isinstance(value, enum.Enum):
|
|
267
|
+
return f"{type(value).__name__}.{value.name}"
|
|
268
|
+
if inspect.isclass(value) or inspect.isroutine(value):
|
|
269
|
+
return str(getattr(value, "__qualname__", getattr(value, "__name__", repr(value))))
|
|
270
|
+
if type(value) is object:
|
|
271
|
+
return "<unset>"
|
|
272
|
+
text = repr(value)
|
|
273
|
+
return _ADDRESS.sub("", text) if len(text) <= 200 else f"<{type(value).__name__}>"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _render_annotation(annotation: Any) -> str:
|
|
277
|
+
if annotation is inspect.Parameter.empty:
|
|
278
|
+
return ""
|
|
279
|
+
if isinstance(annotation, str):
|
|
280
|
+
return annotation
|
|
281
|
+
text = _FORWARD_REF.sub(r"\1", inspect.formatannotation(annotation))
|
|
282
|
+
return _ADDRESS.sub("", text)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
_KINDS = {
|
|
286
|
+
inspect.Parameter.POSITIONAL_ONLY: "positional_only",
|
|
287
|
+
inspect.Parameter.POSITIONAL_OR_KEYWORD: "positional_or_keyword",
|
|
288
|
+
inspect.Parameter.VAR_POSITIONAL: "var_positional",
|
|
289
|
+
inspect.Parameter.KEYWORD_ONLY: "keyword_only",
|
|
290
|
+
inspect.Parameter.VAR_KEYWORD: "var_keyword",
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _signature(obj: Any) -> inspect.Signature | None:
|
|
295
|
+
if not callable(obj):
|
|
296
|
+
return None
|
|
297
|
+
try:
|
|
298
|
+
return inspect.signature(obj)
|
|
299
|
+
except (TypeError, ValueError):
|
|
300
|
+
return None
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
_STARS: dict[Any, str] = {
|
|
304
|
+
inspect.Parameter.VAR_POSITIONAL: "*",
|
|
305
|
+
inspect.Parameter.VAR_KEYWORD: "**",
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _format_signature(name: str, sig: inspect.Signature) -> str:
|
|
310
|
+
parts: list[str] = []
|
|
311
|
+
seen_kw_only = False
|
|
312
|
+
params = list(sig.parameters.values())
|
|
313
|
+
for index, param in enumerate(params):
|
|
314
|
+
if param.kind is inspect.Parameter.KEYWORD_ONLY and not seen_kw_only:
|
|
315
|
+
if not any(p.kind is inspect.Parameter.VAR_POSITIONAL for p in params):
|
|
316
|
+
parts.append("*")
|
|
317
|
+
seen_kw_only = True
|
|
318
|
+
prefix = _STARS.get(param.kind, "")
|
|
319
|
+
text = prefix + param.name
|
|
320
|
+
annotation = _render_annotation(param.annotation)
|
|
321
|
+
if annotation:
|
|
322
|
+
text += f": {annotation}"
|
|
323
|
+
if param.default is not inspect.Parameter.empty:
|
|
324
|
+
default = _render_value(param.default)
|
|
325
|
+
text += f" = {default}" if annotation else f"={default}"
|
|
326
|
+
parts.append(text)
|
|
327
|
+
is_last_positional_only = param.kind is inspect.Parameter.POSITIONAL_ONLY and (
|
|
328
|
+
index + 1 == len(params) or params[index + 1].kind is not param.kind
|
|
329
|
+
)
|
|
330
|
+
if is_last_positional_only:
|
|
331
|
+
parts.append("/")
|
|
332
|
+
out = f"{name}({', '.join(parts)})"
|
|
333
|
+
returns = _render_annotation(sig.return_annotation)
|
|
334
|
+
return f"{out} -> {returns}" if returns else out
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# --------------------------------------------------------------------------- docstrings
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _sections(doc: str) -> dict[str, str]:
|
|
341
|
+
"""Split a Google-style docstring into ``{"": body, "Args": ..., ...}``."""
|
|
342
|
+
out: dict[str, list[str]] = {"": []}
|
|
343
|
+
current = ""
|
|
344
|
+
for line in doc.splitlines():
|
|
345
|
+
match = _SECTION.match(line)
|
|
346
|
+
if match and not line.startswith(" "):
|
|
347
|
+
current = match.group("name")
|
|
348
|
+
out.setdefault(current, [])
|
|
349
|
+
continue
|
|
350
|
+
out[current].append(line)
|
|
351
|
+
return {key: textwrap.dedent("\n".join(value)).strip("\n") for key, value in out.items()}
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _items(section: str) -> list[tuple[str, str]]:
|
|
355
|
+
"""Parse ``name: description`` items with indented continuation lines."""
|
|
356
|
+
items: list[tuple[str, list[str]]] = []
|
|
357
|
+
for line in section.splitlines():
|
|
358
|
+
match = _ITEM.match(line) if line and not line[0].isspace() else None
|
|
359
|
+
if match:
|
|
360
|
+
items.append((match.group("name").lstrip("*"), [match.group("desc").strip()]))
|
|
361
|
+
elif items and line.strip():
|
|
362
|
+
items[-1][1].append(line.strip())
|
|
363
|
+
return [(name, " ".join(part for part in desc if part)) for name, desc in items]
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _example(sections: Mapping[str, str], doc: str) -> str:
|
|
367
|
+
for key in ("Example", "Examples"):
|
|
368
|
+
text = sections.get(key, "")
|
|
369
|
+
if text:
|
|
370
|
+
fenced = _first_fence(text)
|
|
371
|
+
return fenced if fenced is not None else text
|
|
372
|
+
fenced = _first_fence(doc)
|
|
373
|
+
return fenced or ""
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _first_fence(text: str) -> str | None:
|
|
377
|
+
match = re.search(r"```(?:python|py|pycon)?[^\n]*\n(.*?)\n\s*```", text, re.DOTALL)
|
|
378
|
+
return textwrap.dedent(match.group(1)).strip("\n") if match else None
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _kind(obj: Any) -> str:
|
|
382
|
+
if inspect.ismodule(obj):
|
|
383
|
+
return "module"
|
|
384
|
+
if isinstance(obj, types.GenericAlias) or type(obj).__module__ in {"typing", "types"}:
|
|
385
|
+
return "alias" # before isclass: ``tuple[int, float]`` is a class on 3.10
|
|
386
|
+
if inspect.isclass(obj):
|
|
387
|
+
return "class"
|
|
388
|
+
if callable(obj):
|
|
389
|
+
return "function"
|
|
390
|
+
return "constant"
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _describe(name: str, qualname: str, obj: Any) -> Symbol:
|
|
394
|
+
kind = _kind(obj)
|
|
395
|
+
raw_doc = inspect.getdoc(obj) if kind not in {"constant", "alias"} else None
|
|
396
|
+
doc = raw_doc or ""
|
|
397
|
+
sections = _sections(doc)
|
|
398
|
+
summary = sections[""].strip().split("\n\n", 1)[0].replace("\n", " ") if doc else ""
|
|
399
|
+
if kind == "constant":
|
|
400
|
+
summary = summary or f"Constant: {_render_value(obj)}"
|
|
401
|
+
if kind == "alias":
|
|
402
|
+
summary = f"Type alias: {_render_annotation(obj)}"
|
|
403
|
+
sig = _signature(obj) if kind in {"class", "function"} else None
|
|
404
|
+
if kind == "class" and (
|
|
405
|
+
issubclass(obj, enum.Enum) or getattr(obj, "_is_protocol", False)
|
|
406
|
+
): # their call signatures are machinery that differs between Python versions
|
|
407
|
+
sig = None
|
|
408
|
+
described = dict(_items(sections.get("Args", sections.get("Arguments", ""))))
|
|
409
|
+
params: tuple[Param, ...] = ()
|
|
410
|
+
signature = ""
|
|
411
|
+
if sig is not None:
|
|
412
|
+
if kind == "class": # a class "returns" an instance; versions disagree on how
|
|
413
|
+
sig = sig.replace(return_annotation=inspect.Signature.empty)
|
|
414
|
+
signature = _format_signature(name.rsplit(".", 1)[-1], sig)
|
|
415
|
+
params = tuple(
|
|
416
|
+
Param(
|
|
417
|
+
name=param.name,
|
|
418
|
+
kind=_KINDS[param.kind],
|
|
419
|
+
annotation=_render_annotation(param.annotation),
|
|
420
|
+
default=None
|
|
421
|
+
if param.default is inspect.Parameter.empty
|
|
422
|
+
else _render_value(param.default),
|
|
423
|
+
description=described.get(param.name, ""),
|
|
424
|
+
)
|
|
425
|
+
for param in sig.parameters.values()
|
|
426
|
+
)
|
|
427
|
+
return Symbol(
|
|
428
|
+
name=name,
|
|
429
|
+
qualname=qualname,
|
|
430
|
+
kind=kind,
|
|
431
|
+
signature=signature,
|
|
432
|
+
summary=summary,
|
|
433
|
+
params=params,
|
|
434
|
+
returns=sections.get("Returns", ""),
|
|
435
|
+
raises=tuple(_items(sections.get("Raises", ""))),
|
|
436
|
+
example=_example(sections, doc),
|
|
437
|
+
doc=doc,
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
# --------------------------------------------------------------------------- the index
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _public_modules() -> list[str]:
|
|
445
|
+
package = importlib.import_module(_PACKAGE)
|
|
446
|
+
names = []
|
|
447
|
+
for info in pkgutil.iter_modules(package.__path__):
|
|
448
|
+
if info.name.startswith("_") or info.name in _SKIP_MODULES:
|
|
449
|
+
continue
|
|
450
|
+
names.append(info.name)
|
|
451
|
+
return sorted(names)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
@functools.lru_cache(maxsize=1)
|
|
455
|
+
def _index() -> tuple[Symbol, ...]:
|
|
456
|
+
package = importlib.import_module(_PACKAGE)
|
|
457
|
+
entries: list[Symbol] = []
|
|
458
|
+
seen: set[int] = set()
|
|
459
|
+
top_level = set(getattr(package, "__all__", ()))
|
|
460
|
+
for name in sorted(top_level):
|
|
461
|
+
obj = getattr(package, name)
|
|
462
|
+
if not isinstance(obj, (str, int, float, bool)):
|
|
463
|
+
seen.add(id(obj))
|
|
464
|
+
entries.append(_describe(name, f"{_PACKAGE}.{name}", obj))
|
|
465
|
+
for module_name in _public_modules():
|
|
466
|
+
try:
|
|
467
|
+
module = importlib.import_module(f"{_PACKAGE}.{module_name}")
|
|
468
|
+
except Exception: # an optional extra that cannot import here: skip it
|
|
469
|
+
continue
|
|
470
|
+
if module_name not in top_level: # e.g. the ``retry`` module vs ``retry()``
|
|
471
|
+
entries.append(_describe(module_name, f"{_PACKAGE}.{module_name}", module))
|
|
472
|
+
for name in sorted(getattr(module, "__all__", ())):
|
|
473
|
+
obj = getattr(module, name, None)
|
|
474
|
+
if obj is None or id(obj) in seen or inspect.ismodule(obj):
|
|
475
|
+
continue
|
|
476
|
+
seen.add(id(obj))
|
|
477
|
+
entries.append(_describe(f"{module_name}.{name}", f"{module.__name__}.{name}", obj))
|
|
478
|
+
return tuple(entries)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def api_index() -> tuple[Symbol, ...]:
|
|
482
|
+
"""Every public name: the package ``__all__`` first, then submodule-only names.
|
|
483
|
+
|
|
484
|
+
Submodules are found with `pkgutil`; each contributes its own ``__all__`` (names
|
|
485
|
+
already exported at the top level are not repeated) and an entry for the module.
|
|
486
|
+
|
|
487
|
+
Returns:
|
|
488
|
+
A tuple of `Symbol`, computed once per process.
|
|
489
|
+
"""
|
|
490
|
+
return _index()
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def get_symbol(name: str) -> Symbol | None:
|
|
494
|
+
"""Look up a public name.
|
|
495
|
+
|
|
496
|
+
Args:
|
|
497
|
+
name: ``"retry"``, ``"doctor.explain"``, ``"python_wrap.doctor.explain"``, a
|
|
498
|
+
short name that is unique among submodule names (``"explain"``), or
|
|
499
|
+
``Class.attribute`` (``"CircuitBreaker.reset"``).
|
|
500
|
+
|
|
501
|
+
Returns:
|
|
502
|
+
The `Symbol`, or ``None`` when nothing matches.
|
|
503
|
+
"""
|
|
504
|
+
name = name.strip()
|
|
505
|
+
if name.startswith(f"{_PACKAGE}."):
|
|
506
|
+
name = name[len(_PACKAGE) + 1 :]
|
|
507
|
+
by_name = {entry.name: entry for entry in api_index()}
|
|
508
|
+
if name in by_name:
|
|
509
|
+
return by_name[name]
|
|
510
|
+
tails = [entry for entry in api_index() if entry.name.rsplit(".", 1)[-1] == name]
|
|
511
|
+
if len(tails) == 1:
|
|
512
|
+
return tails[0]
|
|
513
|
+
head, _, attr = name.rpartition(".")
|
|
514
|
+
parent = by_name.get(head)
|
|
515
|
+
if parent is not None and attr and not attr.startswith("_"):
|
|
516
|
+
module_name, _, obj_path = parent.qualname.rpartition(".")
|
|
517
|
+
obj: Any = importlib.import_module(module_name)
|
|
518
|
+
for part in [*obj_path.split("."), attr]:
|
|
519
|
+
obj = getattr(obj, part, None)
|
|
520
|
+
if obj is None:
|
|
521
|
+
return None
|
|
522
|
+
return _describe(name, f"{parent.qualname}.{attr}", obj)
|
|
523
|
+
return None
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _tokens(text: str) -> list[str]:
|
|
527
|
+
words = _WORD.findall(text[:_MAX_QUERY].lower().replace("_", " "))
|
|
528
|
+
return [_stem(word) for word in words if word not in _STOPWORDS]
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _stem(word: str) -> str:
|
|
532
|
+
for suffix in ("ing", "ies", "es", "ed", "s"):
|
|
533
|
+
if len(word) > len(suffix) + 2 and word.endswith(suffix):
|
|
534
|
+
return word[: -len(suffix)] + ("y" if suffix == "ies" else "")
|
|
535
|
+
return word
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def search(query: str, *, limit: int = 10) -> list[Symbol]:
|
|
539
|
+
"""Rank public names by how well their name and docstring match ``query``.
|
|
540
|
+
|
|
541
|
+
Words in the name weigh most, then the summary, then the rest of the docstring.
|
|
542
|
+
|
|
543
|
+
Args:
|
|
544
|
+
query: Free text, such as ``"rate limit per user"``.
|
|
545
|
+
limit: Maximum number of results.
|
|
546
|
+
|
|
547
|
+
Returns:
|
|
548
|
+
Matching symbols, best first; empty when no word matches.
|
|
549
|
+
"""
|
|
550
|
+
words = set(_tokens(query))
|
|
551
|
+
if not words:
|
|
552
|
+
return []
|
|
553
|
+
scored: list[tuple[int, str, Symbol]] = []
|
|
554
|
+
for entry in api_index():
|
|
555
|
+
name_words = set(_tokens(re.sub(r"(?<=[a-z])(?=[A-Z])", " ", entry.name)))
|
|
556
|
+
summary_words = set(_tokens(entry.summary))
|
|
557
|
+
doc_words = set(_tokens(entry.doc))
|
|
558
|
+
name_hits = len(words & name_words)
|
|
559
|
+
top_level = "." not in entry.name and entry.kind != "module"
|
|
560
|
+
score = 6 * name_hits + 3 * len(words & summary_words) + len(words & doc_words)
|
|
561
|
+
if score and name_hits and top_level:
|
|
562
|
+
score += 2
|
|
563
|
+
if name_words and name_words <= words: # every word of the name was asked for
|
|
564
|
+
score += 4
|
|
565
|
+
if score:
|
|
566
|
+
scored.append((-score, entry.name, entry))
|
|
567
|
+
scored.sort(key=lambda item: (item[0], item[1]))
|
|
568
|
+
return [entry for _, _, entry in scored[: max(limit, 0)]]
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
# --------------------------------------------------------------------------- recipes
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _data(name: str) -> str:
|
|
575
|
+
return resources.files(_PACKAGE).joinpath("_data").joinpath(name).read_text(encoding="utf-8")
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
@functools.lru_cache(maxsize=1)
|
|
579
|
+
def _recipes() -> tuple[Recipe, ...]:
|
|
580
|
+
raw = json.loads(_data("recipes.json"))
|
|
581
|
+
known = {entry.name for entry in api_index()}
|
|
582
|
+
out = []
|
|
583
|
+
for item in raw["recipes"]:
|
|
584
|
+
apis = tuple(name for name in item["apis"] if name in known or get_symbol(name))
|
|
585
|
+
out.append(
|
|
586
|
+
Recipe(
|
|
587
|
+
need=item["need"],
|
|
588
|
+
apis=apis,
|
|
589
|
+
snippet=item.get("snippet", ""),
|
|
590
|
+
notes=item.get("notes", ""),
|
|
591
|
+
docs=item.get("docs", ""),
|
|
592
|
+
keywords=tuple(item.get("keywords", ())),
|
|
593
|
+
)
|
|
594
|
+
)
|
|
595
|
+
return tuple(out)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def recipes() -> tuple[Recipe, ...]:
|
|
599
|
+
"""Every recipe in ``python_wrap/_data/recipes.json``, in file order."""
|
|
600
|
+
return _recipes()
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def find_recipes(need: str, *, limit: int = 3) -> list[Recipe]:
|
|
604
|
+
"""Map a plain-language need to recipes, best first.
|
|
605
|
+
|
|
606
|
+
A recipe matches on the words of its ``need`` and its ``keywords``; plurals and
|
|
607
|
+
``-ing``/``-ed`` forms are folded, so "retrying requests" matches "retry request".
|
|
608
|
+
|
|
609
|
+
Args:
|
|
610
|
+
need: Free text, such as ``"stop duplicate emails"``.
|
|
611
|
+
limit: Maximum number of recipes.
|
|
612
|
+
|
|
613
|
+
Returns:
|
|
614
|
+
Matching recipes with their `Recipe.score`, best first; empty when nothing
|
|
615
|
+
matches (use `search` then).
|
|
616
|
+
"""
|
|
617
|
+
words = set(_tokens(need))
|
|
618
|
+
scored = []
|
|
619
|
+
for position, recipe in enumerate(recipes()):
|
|
620
|
+
keywords = set(_tokens(" ".join(recipe.keywords)))
|
|
621
|
+
need_words = set(_tokens(recipe.need))
|
|
622
|
+
score = 2 * len(words & keywords) + len(words & need_words)
|
|
623
|
+
if score:
|
|
624
|
+
scored.append((-score, position, recipe))
|
|
625
|
+
scored.sort(key=lambda item: (item[0], item[1]))
|
|
626
|
+
best = -scored[0][0] if scored else 0
|
|
627
|
+
return [ # weak matches far behind the best one are noise
|
|
628
|
+
Recipe(r.need, r.apis, r.snippet, r.notes, r.docs, r.keywords, -s)
|
|
629
|
+
for s, _, r in scored[: max(limit, 0)]
|
|
630
|
+
if -s * 2 >= best
|
|
631
|
+
]
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def _api_brief(name: str) -> dict[str, str]:
|
|
635
|
+
entry = get_symbol(name)
|
|
636
|
+
if entry is None:
|
|
637
|
+
return {"name": name, "qualname": name, "summary": ""}
|
|
638
|
+
return {"name": entry.name, "qualname": entry.qualname, "summary": entry.summary}
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def guide_text() -> str:
|
|
642
|
+
"""The agent guide shipped in the wheel (``python_wrap/_data/agent_guide.md``)."""
|
|
643
|
+
return _data("agent_guide.md")
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
# --------------------------------------------------------------------------- CLI
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _emit(data: Any) -> None:
|
|
650
|
+
print(json.dumps(data, indent=2, sort_keys=False))
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _symbol_list(entries: Iterable[Symbol]) -> str:
|
|
654
|
+
rows = [(entry.name, entry.summary) for entry in entries]
|
|
655
|
+
width = min(max((len(name) for name, _ in rows), default=0), 32)
|
|
656
|
+
return "\n".join(f"{name:<{width}} {summary}".rstrip() for name, summary in rows)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def api_main(argv: Sequence[str] | None = None) -> int:
|
|
660
|
+
"""``python -m python_wrap api``: list, describe or search public names."""
|
|
661
|
+
parser = argparse.ArgumentParser(
|
|
662
|
+
prog="python -m python_wrap api",
|
|
663
|
+
description="List public names, describe one, or search them: "
|
|
664
|
+
"'api', 'api SYMBOL', 'api search WORDS...'.",
|
|
665
|
+
)
|
|
666
|
+
parser.add_argument("words", nargs="*", help="a symbol, or 'search' followed by words")
|
|
667
|
+
parser.add_argument("--json", action="store_true", help="machine-readable output")
|
|
668
|
+
parser.add_argument("--limit", type=int, default=10, help="maximum search results")
|
|
669
|
+
args = parser.parse_args(argv)
|
|
670
|
+
words: list[str] = args.words
|
|
671
|
+
if not words:
|
|
672
|
+
entries = api_index()
|
|
673
|
+
if args.json:
|
|
674
|
+
_emit([entry.to_dict(full=False) for entry in entries])
|
|
675
|
+
else:
|
|
676
|
+
print(_symbol_list(entries))
|
|
677
|
+
return 0
|
|
678
|
+
if words[0] == "search":
|
|
679
|
+
found = search(" ".join(words[1:]), limit=args.limit)
|
|
680
|
+
if args.json:
|
|
681
|
+
_emit([entry.to_dict(full=False) for entry in found])
|
|
682
|
+
elif found:
|
|
683
|
+
print(_symbol_list(found))
|
|
684
|
+
else:
|
|
685
|
+
print("no match", file=sys.stderr)
|
|
686
|
+
return 0 if found else 1
|
|
687
|
+
status = 0
|
|
688
|
+
for name in words:
|
|
689
|
+
entry = get_symbol(name)
|
|
690
|
+
if entry is None:
|
|
691
|
+
hints = ", ".join(item.name for item in search(name, limit=5))
|
|
692
|
+
print(
|
|
693
|
+
f"unknown symbol {name!r}" + (f"; try: {hints}" if hints else ""), file=sys.stderr
|
|
694
|
+
)
|
|
695
|
+
status = 1
|
|
696
|
+
elif args.json:
|
|
697
|
+
_emit(entry.to_dict())
|
|
698
|
+
else:
|
|
699
|
+
print(entry.render())
|
|
700
|
+
return status
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def recipe_main(argv: Sequence[str] | None = None) -> int:
|
|
704
|
+
"""``python -m python_wrap recipe NEED...``: which API solves a plain-language need."""
|
|
705
|
+
parser = argparse.ArgumentParser(
|
|
706
|
+
prog="python -m python_wrap recipe",
|
|
707
|
+
description="Map a need ('retry http calls', 'stop duplicate emails') to the API.",
|
|
708
|
+
)
|
|
709
|
+
parser.add_argument("need", nargs="*", help="what you want to do; omit to list recipes")
|
|
710
|
+
parser.add_argument("--json", action="store_true", help="machine-readable output")
|
|
711
|
+
parser.add_argument("--limit", type=int, default=3, help="maximum recipes")
|
|
712
|
+
args = parser.parse_args(argv)
|
|
713
|
+
if not args.need:
|
|
714
|
+
listed = list(recipes())
|
|
715
|
+
if args.json:
|
|
716
|
+
_emit([item.to_dict() for item in listed])
|
|
717
|
+
else:
|
|
718
|
+
print("\n".join(item.need for item in listed))
|
|
719
|
+
return 0
|
|
720
|
+
found = find_recipes(" ".join(args.need), limit=args.limit)
|
|
721
|
+
if args.json:
|
|
722
|
+
_emit([item.to_dict() for item in found])
|
|
723
|
+
elif found:
|
|
724
|
+
print("\n".join(item.render() for item in found).rstrip())
|
|
725
|
+
else:
|
|
726
|
+
hints = ", ".join(item.name for item in search(" ".join(args.need), limit=5))
|
|
727
|
+
print("no recipe matched" + (f"; related APIs: {hints}" if hints else ""), file=sys.stderr)
|
|
728
|
+
return 0 if found else 1
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def guide_main(argv: Sequence[str] | None = None) -> int:
|
|
732
|
+
"""``python -m python_wrap guide``: print the agent guide."""
|
|
733
|
+
argparse.ArgumentParser(
|
|
734
|
+
prog="python -m python_wrap guide",
|
|
735
|
+
description="Print a concise guide to using python-wrap correctly.",
|
|
736
|
+
).parse_args(argv)
|
|
737
|
+
print(guide_text().rstrip())
|
|
738
|
+
return 0
|