ipyllm 0.4.0__tar.gz → 0.5.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipyllm
3
- Version: 0.4.0
3
+ Version: 0.5.0
4
4
  Summary: Interact with LLM models from your IPython REPL
5
5
  Author: Juan Pablo de la Cruz Gutiérrez
6
6
  Author-email: Juan Pablo de la Cruz Gutiérrez <juampatronics@gmail.com>
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.14
16
16
  Requires-Dist: ipython>=9.17.1
17
17
  Requires-Dist: llm>=0.36
18
18
  Requires-Dist: llm-ollama>=0.17.1
19
+ Requires-Dist: rapidfuzz>=3.0
19
20
  Requires-Dist: pyyaml>=6.0
20
21
  Requires-Python: >=3.11
21
22
  Project-URL: Homepage, https://github.com/juampatronics/ipyllm
@@ -25,7 +26,7 @@ Project-URL: Issues, https://github.com/juampatronics/ipyllm/issues
25
26
  Description-Content-Type: text/markdown
26
27
 
27
28
  <div align="center">
28
- <img src="docs/ipyllm_logo.svg" alt="Synaptic Prompt Logo" width="150"/>
29
+ <img src="https://juampatronics.com/images/ipyllm_logo.svg" alt="Synaptic Prompt Logo" width="150"/>
29
30
  <br/>
30
31
  <a href="https://github.com/juampatronics/ipyllm/actions/workflows/ci.yml?query=job%3Abuild" alt="Build">
31
32
  <img src="https://github.com/juampatronics/ipyllm/actions/workflows/ci.yml/badge.svg?job=build" alt="Build"/>
@@ -44,7 +45,8 @@ Description-Content-Type: text/markdown
44
45
  # ipyllm
45
46
 
46
47
  An IPython extension for discussing your interactive Python session with models
47
- supported by the [`llm`](https://llm.datasette.io/) Python package.
48
+ supported by the [`llm`](https://llm.datasette.io/) Python package. For a detailed description,
49
+ as well as a discussion of use cases, please refer to the [blog](https://juampatronics.com/tags/ipyllm/).
48
50
 
49
51
  ## Install and load
50
52
 
@@ -82,3 +84,6 @@ approval settings, and safety. Preview or build the site with:
82
84
  uv run mkdocs serve
83
85
  uv run mkdocs build
84
86
  ```
87
+
88
+ An online version is available at the [homepage](https://juampatronics.com/ipyllm/).
89
+
@@ -1,5 +1,5 @@
1
1
  <div align="center">
2
- <img src="docs/ipyllm_logo.svg" alt="Synaptic Prompt Logo" width="150"/>
2
+ <img src="https://juampatronics.com/images/ipyllm_logo.svg" alt="Synaptic Prompt Logo" width="150"/>
3
3
  <br/>
4
4
  <a href="https://github.com/juampatronics/ipyllm/actions/workflows/ci.yml?query=job%3Abuild" alt="Build">
5
5
  <img src="https://github.com/juampatronics/ipyllm/actions/workflows/ci.yml/badge.svg?job=build" alt="Build"/>
@@ -18,7 +18,8 @@
18
18
  # ipyllm
19
19
 
20
20
  An IPython extension for discussing your interactive Python session with models
21
- supported by the [`llm`](https://llm.datasette.io/) Python package.
21
+ supported by the [`llm`](https://llm.datasette.io/) Python package. For a detailed description,
22
+ as well as a discussion of use cases, please refer to the [blog](https://juampatronics.com/tags/ipyllm/).
22
23
 
23
24
  ## Install and load
24
25
 
@@ -56,3 +57,6 @@ approval settings, and safety. Preview or build the site with:
56
57
  uv run mkdocs serve
57
58
  uv run mkdocs build
58
59
  ```
60
+
61
+ An online version is available at the [homepage](https://juampatronics.com/ipyllm/).
62
+
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ipyllm"
3
- version = "0.4.0"
3
+ version = "0.5.0"
4
4
  description = "Interact with LLM models from your IPython REPL"
5
5
  readme = "README.md"
6
6
  license-files = ["LICENSE"]
@@ -10,6 +10,7 @@ dependencies = [
10
10
  "ipython>=9.17.1",
11
11
  "llm>=0.36",
12
12
  "llm-ollama>=0.17.1",
13
+ "rapidfuzz>=3.0",
13
14
  "pyyaml>=6.0",
14
15
  ]
15
16
  classifiers = [
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ipyllm"
3
- version = "0.4.0"
3
+ version = "0.5.0"
4
4
  description = "Interact with LLM models from your IPython REPL"
5
5
  readme = "README.md"
6
6
  license-files = ["LICENSE"]
@@ -13,6 +13,7 @@ dependencies = [
13
13
  "ipython>=9.17.1",
14
14
  "llm>=0.36",
15
15
  "llm-ollama>=0.17.1",
16
+ "rapidfuzz>=3.0",
16
17
  "pyyaml>=6.0",
17
18
  ]
18
19
  classifiers = [
@@ -0,0 +1,252 @@
1
+ # Copyright 2026 Juan Pablo de la Cruz Gutiérrez
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Autocomplete local file and directory names for ``@`` prompt references.
16
+
17
+ When the user types ``@`` at the start of a word, IPython offers the entries
18
+ of the referenced directory (files and subdirectories, the latter with a
19
+ trailing ``/``) so paths can be assembled one tab at a time.
20
+
21
+ Typing ``@@`` instead triggers a fuzzy search over the whole current
22
+ directory tree (via ``rapidfuzz``); the chosen match replaces the ``@@``
23
+ trigger and the loose query with a single ``@`` reference.
24
+ """
25
+
26
+ import os
27
+ import re
28
+
29
+ from rapidfuzz import fuzz, process, utils
30
+
31
+
32
+ def _word_at(line: str, index: int) -> bool:
33
+ """Return True when the character at ``index`` starts a word in ``line``."""
34
+ return index == 0 or line[index - 1].isspace()
35
+
36
+
37
+ def _completion(text: str, kind: str = "file"):
38
+ from IPython.core.completer import SimpleCompletion
39
+
40
+ return SimpleCompletion(text=text, type=kind)
41
+
42
+
43
+ def _list_matches(base: str, fragment: str) -> list:
44
+ try:
45
+ entries = sorted(os.listdir(base))
46
+ except OSError:
47
+ return []
48
+ matches = []
49
+ for entry in entries:
50
+ if not entry.startswith(fragment):
51
+ continue
52
+ full = os.path.join(base, entry) if base != os.curdir else entry
53
+ if os.path.isdir(full):
54
+ matches.append(_completion(entry + "/"))
55
+ else:
56
+ matches.append(_completion(entry))
57
+ return matches
58
+
59
+
60
+ class AtFileMatcher:
61
+ """An IPython completion matcher (API v2) that completes ``@`` paths.
62
+
63
+ A no-op (empty result, other matchers proceed) unless the token being
64
+ completed is directly preceded by an ``@`` that starts a word. This keeps
65
+ emails and other in-word ``@`` characters untouched.
66
+ """
67
+
68
+ matcher_api_version = 2
69
+ matcher_identifier = "ipyllm.at_file_matcher"
70
+
71
+ def __init__(self) -> None:
72
+ # _get_matcher_id falls back to ``__qualname__`` when reading the id,
73
+ # which is evaluated eagerly; provide it so instances resolve cleanly.
74
+ self.__qualname__ = "ipyllm.completer.AtFileMatcher"
75
+
76
+ def __call__(self, context) -> dict:
77
+ token = context.token
78
+ prefix = context.text_until_cursor
79
+ before = prefix[:-len(token)] if token else prefix
80
+
81
+ if not before.endswith("@"):
82
+ return self._result([])
83
+ at_index = len(before) - 1
84
+ if not _word_at(before, at_index):
85
+ return self._result([])
86
+
87
+ if token:
88
+ base = os.path.dirname(token) or os.curdir
89
+ fragment = os.path.basename(token)
90
+ else:
91
+ base = os.curdir
92
+ fragment = ""
93
+
94
+ matches = _list_matches(base, fragment)
95
+ return self._result(matches)
96
+
97
+ @staticmethod
98
+ def _result(completions: list) -> dict:
99
+ return {
100
+ "completions": completions,
101
+ "suppress": bool(completions),
102
+ "ordered": True,
103
+ }
104
+
105
+
106
+ at_file_matcher = AtFileMatcher()
107
+
108
+
109
+ # Directories that never hold files a user would reference; skipped while
110
+ # scanning for the fuzzy index.
111
+ _IGNORED_DIRS = {
112
+ ".git",
113
+ "__pycache__",
114
+ "node_modules",
115
+ ".venv",
116
+ "venv",
117
+ ".mypy_cache",
118
+ ".pytest_cache",
119
+ ".ipynb_checkpoints",
120
+ ".idea",
121
+ "site-packages",
122
+ "dist-packages",
123
+ }
124
+ _MAX_INDEXED_ENTRIES = 20_000
125
+ _SCORE_CUTOFF = 45
126
+ _DEFAULT_LIMIT = 25
127
+
128
+ # The double-@ trigger followed by a loose query (spaces allowed) up to the
129
+ # cursor, optionally inside quotes; anchored so the query ends at the cursor.
130
+ _FUZZY_TRIGGER = re.compile(r"@@([^'\"\n]*)$")
131
+
132
+ _index_root: str | None = None
133
+ _index_paths: list[str] = []
134
+
135
+
136
+ def _scan_tree(root: str) -> list[str]:
137
+ """Collect relative paths under ``root``: files, and dirs with a trailing ``/``."""
138
+ paths: list[str] = []
139
+ for dirpath, dirnames, filenames in os.walk(root):
140
+ dirnames[:] = sorted(d for d in dirnames if d not in _IGNORED_DIRS)
141
+ base = os.path.relpath(dirpath, root)
142
+ if base == os.curdir:
143
+ base = ""
144
+ for name in sorted(filenames):
145
+ paths.append(os.path.join(base, name).replace(os.sep, "/") if base else name)
146
+ if len(paths) >= _MAX_INDEXED_ENTRIES:
147
+ return paths
148
+ for name in dirnames:
149
+ rel = os.path.join(base, name) if base else name
150
+ paths.append(rel.replace(os.sep, "/") + "/")
151
+ return paths
152
+
153
+
154
+ def _fuzzy_search(query: str, limit: int) -> list[tuple[str, str]]:
155
+ """Fuzzy-match ``query`` against the current directory tree.
156
+
157
+ Returns ``(path, kind)`` pairs best match first; kind is ``"dir"`` when
158
+ the path is a directory (marked with a trailing ``/``).
159
+ """
160
+ global _index_root, _index_paths
161
+ root = os.getcwd()
162
+ if root != _index_root: # first use or the working directory changed
163
+ _index_root = root
164
+ _index_paths = _scan_tree(root)
165
+
166
+ if not query.strip():
167
+ return [(p, "dir" if p.endswith("/") else "file") for p in _index_paths[:limit]]
168
+
169
+ hits = process.extract(
170
+ query,
171
+ _index_paths,
172
+ scorer=fuzz.WRatio,
173
+ processor=utils.default_process,
174
+ limit=limit,
175
+ score_cutoff=_SCORE_CUTOFF,
176
+ )
177
+ return [
178
+ (_index_paths[i], "dir" if _index_paths[i].endswith("/") else "file")
179
+ for _, _score, i in hits
180
+ ]
181
+
182
+
183
+ class FuzzyFileMatcher:
184
+ """An IPython completion matcher (API v2) for fuzzy ``@@`` references.
185
+
186
+ A no-op (empty result, other matchers proceed) unless the text before the
187
+ cursor ends with a word-leading ``@@``. In that case the query after the
188
+ trigger (which may contain spaces) is fuzzy-matched against the whole
189
+ current directory tree, and each candidate replaces the trigger and query
190
+ with a single-``@`` reference so ``%llm`` resolves it as a file.
191
+ """
192
+
193
+ matcher_api_version = 2
194
+ matcher_identifier = "ipyllm.fuzzy_file_matcher"
195
+
196
+ def __init__(self) -> None:
197
+ # _get_matcher_id falls back to ``__qualname__`` when reading the id,
198
+ # which is evaluated eagerly; provide it so instances resolve cleanly.
199
+ self.__qualname__ = "ipyllm.completer.FuzzyFileMatcher"
200
+
201
+ def __call__(self, context) -> dict:
202
+ text = context.text_until_cursor
203
+ match = _FUZZY_TRIGGER.search(text)
204
+ if not match:
205
+ return self._result([])
206
+ if text[: match.start()] and not text[match.start() - 1].isspace():
207
+ return self._result([]) # not word-leading; e.g. a double-@ in a word
208
+
209
+ query = match.group(1)
210
+ limit = context.limit or _DEFAULT_LIMIT
211
+ hits = _fuzzy_search(query, limit)
212
+ completions = [_completion("@" + path, kind) for path, kind in hits]
213
+ return self._result(
214
+ completions,
215
+ matched_fragment=text[match.start():], # replace "@@query"
216
+ )
217
+
218
+ @staticmethod
219
+ def _result(completions: list, matched_fragment: str | None = None) -> dict:
220
+ result = {
221
+ "completions": completions,
222
+ "suppress": bool(completions),
223
+ "ordered": True,
224
+ }
225
+ if matched_fragment is not None:
226
+ result["matched_fragment"] = matched_fragment
227
+ return result
228
+
229
+
230
+ fuzzy_file_matcher = FuzzyFileMatcher()
231
+
232
+
233
+ def install_completer(shell) -> None:
234
+ """Register the ``@`` and ``@@`` file matchers on ``shell``'s completer."""
235
+ completer = getattr(shell, "Completer", None)
236
+ if completer is None:
237
+ return
238
+ for matcher in (at_file_matcher, fuzzy_file_matcher):
239
+ if matcher not in completer.custom_matchers:
240
+ completer.custom_matchers.append(matcher)
241
+
242
+
243
+ def uninstall_completer(shell) -> None:
244
+ """Remove the ``@`` and ``@@`` file matchers from ``shell``, if present."""
245
+ completer = getattr(shell, "Completer", None)
246
+ if completer is None:
247
+ return
248
+ for matcher in (at_file_matcher, fuzzy_file_matcher):
249
+ try:
250
+ completer.custom_matchers.remove(matcher)
251
+ except ValueError:
252
+ pass
@@ -164,7 +164,8 @@ class IpyllmMagics(Magics):
164
164
  exception in this session. Start a
165
165
  prompt with ``/skill-name`` to load a local skill. Reference local
166
166
  files with ``@path`` to add them to the context (``@`` autocompletes
167
- file and directory names); several files may be referenced. A
167
+ file and directory names; ``@@`` fuzzy-searches the whole tree);
168
+ several files may be referenced. A
168
169
  single-line prompt must not end in ``?`` (IPython reserves that for
169
170
  object help); use ``%%llm`` for such questions.
170
171
  """
@@ -343,7 +344,7 @@ class IpyllmMagics(Magics):
343
344
  if command == "--help" and len(args) == 1:
344
345
  print(
345
346
  "%llm PROMPT | %%llm PROMPT\n"
346
- " (reference files with @path; @ autocompletes names)\n"
347
+ " (reference files with @path; @ autocompletes names; @@ fuzzy-searches)\n"
347
348
  " (a single-line prompt must not end in '?'; use %%llm for it)\n"
348
349
  "%%llm --run [diagnostic request]\n"
349
350
  "%llm --last-error [diagnostic request]\n"
@@ -1,119 +0,0 @@
1
- # Copyright 2026 Juan Pablo de la Cruz Gutiérrez
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- """Autocomplete local file and directory names for ``@`` prompt references.
16
-
17
- When the user types ``@`` at the start of a word, IPython offers the entries
18
- of the referenced directory (files and subdirectories, the latter with a
19
- trailing ``/``) so paths can be assembled one tab at a time.
20
- """
21
-
22
- import os
23
-
24
-
25
- def _word_at(line: str, index: int) -> bool:
26
- """Return True when the character at ``index`` starts a word in ``line``."""
27
- return index == 0 or line[index - 1].isspace()
28
-
29
-
30
- def _completion(text: str):
31
- from IPython.core.completer import SimpleCompletion
32
-
33
- return SimpleCompletion(text=text, type="file")
34
-
35
-
36
- def _list_matches(base: str, fragment: str) -> list:
37
- try:
38
- entries = sorted(os.listdir(base))
39
- except OSError:
40
- return []
41
- matches = []
42
- for entry in entries:
43
- if not entry.startswith(fragment):
44
- continue
45
- full = os.path.join(base, entry) if base != os.curdir else entry
46
- if os.path.isdir(full):
47
- matches.append(_completion(entry + "/"))
48
- else:
49
- matches.append(_completion(entry))
50
- return matches
51
-
52
-
53
- class AtFileMatcher:
54
- """An IPython completion matcher (API v2) that completes ``@`` paths.
55
-
56
- A no-op (empty result, other matchers proceed) unless the token being
57
- completed is directly preceded by an ``@`` that starts a word. This keeps
58
- emails and other in-word ``@`` characters untouched.
59
- """
60
-
61
- matcher_api_version = 2
62
- matcher_identifier = "ipyllm.at_file_matcher"
63
-
64
- def __init__(self) -> None:
65
- # _get_matcher_id falls back to ``__qualname__`` when reading the id,
66
- # which is evaluated eagerly; provide it so instances resolve cleanly.
67
- self.__qualname__ = "ipyllm.completer.AtFileMatcher"
68
-
69
- def __call__(self, context) -> dict:
70
- token = context.token
71
- prefix = context.text_until_cursor
72
- before = prefix[:-len(token)] if token else prefix
73
-
74
- if not before.endswith("@"):
75
- return self._result([])
76
- at_index = len(before) - 1
77
- if not _word_at(before, at_index):
78
- return self._result([])
79
-
80
- if token:
81
- base = os.path.dirname(token) or os.curdir
82
- fragment = os.path.basename(token)
83
- else:
84
- base = os.curdir
85
- fragment = ""
86
-
87
- matches = _list_matches(base, fragment)
88
- return self._result(matches)
89
-
90
- @staticmethod
91
- def _result(completions: list) -> dict:
92
- return {
93
- "completions": completions,
94
- "suppress": bool(completions),
95
- "ordered": True,
96
- }
97
-
98
-
99
- at_file_matcher = AtFileMatcher()
100
-
101
-
102
- def install_completer(shell) -> None:
103
- """Register the ``@`` file matcher on ``shell``'s completer."""
104
- completer = getattr(shell, "Completer", None)
105
- if completer is None:
106
- return
107
- if at_file_matcher not in completer.custom_matchers:
108
- completer.custom_matchers.append(at_file_matcher)
109
-
110
-
111
- def uninstall_completer(shell) -> None:
112
- """Remove the ``@`` file matcher from ``shell``'s completer, if present."""
113
- completer = getattr(shell, "Completer", None)
114
- if completer is None:
115
- return
116
- try:
117
- completer.custom_matchers.remove(at_file_matcher)
118
- except ValueError:
119
- pass
File without changes
File without changes
File without changes
File without changes
File without changes