Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 13 additions & 22 deletions aidialog/dlgskill.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
"""Read, search, and edit notebook and dialog content through aidialog's `Dialog` and `Message` APIs. Use for cell sources, stored outputs, prompt/reply pairs, and structural message operations.
"""Read, search, and edit notebook and dialog content through aidialog's `Dialog` and `Message` APIs (cell sources, stored outputs, prompt/reply pairs, structural ops).

NB: this file is designed for an LLM reader, not a human. Add it to your LLM's context and ask it to explain.

- first: `fastship.notebooks` (notebooks), `exhash.skill` (edits); cross-notebook search: `rgapi.skill` `nbrg`
- read: `summary_dlg` (unless reading it all) → `find_msgs` or `view_dlg(incl_out=True)`; neighbouring prose too, `ids=` lookups included
- `fastcore.nbio`: only for an operation this API lacks; propose adding it
- edit: exhash via fresh `lnhashview_msg` or `lnhashview_cell`; `msg_*` editors only where exhash can't; then `dlg.validate()`
- Python symbols, ASTs: structural `find_msgs` predicates
- first: `fastship.notebooks` (notebooks), `exhash.skill` (edits); cross-notebook search: `rgapi.skill` `nbrg`; `fastcore.nbio` only for missing ops (propose adding)
- read: `summary_dlg` (unless reading all) → `find_msgs` or `view_dlg(incl_out=True)`; read neighbouring prose too, `ids=` lookups included
- edit: exhash via fresh `lnhashview_msg`/`lnhashview_cell`; `msg_*` editors only where exhash can't; then `dlg.validate()`; Python symbols/ASTs: structural `find_msgs` predicates
- broken file: `validate_nb`, `validate_cell`, `read_nb`; raw text only if unparseable; never splice notebook JSON

- functions: `dlg=path`, else `set_dlg(path)`'s file; each call rereads, autosaves; methods: held `Dialog`, `dlg.save()`; otherwise as `fastcore.editskill`
- in memory: `d.mk_message`, `d.remove_msgs`; `Dialog(msgs)` wraps a list; `m.dlg` keeps ownership
- file `find_msgs`: fresh `Dialog`, apart from any held one; its messages' edits: `m.dlg.save()`
- current message: host sets it; writes never move it: successive `add_msg`: chain `after=`
- summary row: `id:t[directives]:content` (c code, n note, p prompt, r raw); reply after `>`; `…[N]`: N characters cut
- XML (`item2xml`): replies in `<out>`, directives as attributes; diffs: XML plus `meta:` line
- `m.exported`: content and meta directives; `m.meta_exported`: meta only, assignable
- `update_msg`, `Message.update`: replace attributes; `meta=` replaces whole dict; `mergemeta=` merges
- text editors' `out=True`: prompt replies only; other outputs: assign `m.output`
- target: functions take `dlg=path` (else `set_dlg(path)`), reread and autosave; methods act on held `Dialog` with `dlg.save()` (otherwise as `fastcore.editskill`); in memory: `d.mk_message`, `d.remove_msgs`, `Dialog(msgs)` wraps list, `m.dlg` keeps ownership; file `find_msgs` returns fresh `Dialog` (save via `m.dlg.save()`)
- current message: host sets it; writes never move it; successive `add_msg`: chain `after=`
- formats: summary row `id:t[directives]:content` (`c` code, `n` note, `p` prompt, `r` raw; reply after `>`; `…[N]` = N chars cut); XML (`item2xml`): replies in `<out>`, directives as attrs; diffs: XML + `meta:` line
- attrs/outputs: `m.exported` (content + meta), `m.meta_exported` (meta only, assignable); `update_msg`/`Message.update` replace attrs (`meta=` replaces dict, `mergemeta=` merges); `out=True` on text editors: prompt replies only (other outputs: assign `m.output`)

- magics: `%nbrun` (`nbrun_magic`), `%%add_msg` (`add_msg_magic`)
- `execute_dlg`, `Dialog.execute`, `Message.execute`: capture outputs (file or held)
- magics/exec: `%nbrun` (`nbrun_magic`), `%%add_msg` (`add_msg_magic`); `execute_dlg`, `Dialog.execute`, `Message.execute` capture outputs

Docs: https://AnswerDotAI.github.io/aidialog/dlgskill.md"""

Expand All @@ -31,8 +21,8 @@
'set_dlg', 'cur_dlg', 'set_cur_msg', 'cur_msg', 'summary_dlg', 'view_dlg', 'view_msg', 'view_msgs',
'FoundMsgs', 'find_msgs', 'move_msgs', 'split_msg', 'merge_msgs', 'copy_msgs', 'cut_msgs', 'paste_msgs',
'symdef_finder', 'symref_finder', 'ast_finder', 'lnhashview_msg', 'msg_exhash', 'add_msg', 'add_msgs',
'del_msgs', 'create_dlg', 'update_msg', 'add_msg_magic', 'nbrun_magic', 'load_ipython_extension',
'execute_dlg', 'Dialog', 'Message', 'read_ipynb']
'del_msgs', 'create_dlg', 'update_msg', 'add_msg_magic', 'nbrun_magic', 'execute_dlg', 'Dialog', 'Message',
'read_ipynb']

# %% #a0aeb3fe
import shlex, re, copy
Expand Down Expand Up @@ -356,6 +346,7 @@ def _set_out_text(m, s): m.output = s

# %% #3b31bc59
_msg_edit_doc = """

Be sure you've viewed the message (e.g. `view_msg`) so you know the line nums.

Message editing standard parameters:
Expand Down Expand Up @@ -408,7 +399,7 @@ def method(self, *args, out:bool=False, **kw):
return PrettyString(str_diff(text, new) or 'none: No changes.')
res = splice_sig(method, f, 'text')
res.__name__ = res.__qualname__ = f.__name__
res.__doc__ = (f.__doc__ or '') + "\nIn-memory edit of this message (`out=True` edits a prompt's reply), returning a diff; nothing is saved."
res.__doc__ = (f.__doc__ or '') + "\n\nIn-memory edit of this message (`out=True` edits a prompt's reply), returning a diff; nothing is saved."
return res

for _f in (insert_line, str_replace, strs_replace, replace_lines, del_lines, ast_replace): setattr(Message, _f.__name__, _msg_method(_f))
Expand Down
6 changes: 4 additions & 2 deletions aidialog/ipynb.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# %% #d3d0463b
from fastcore.utils import *
from fastcore.xtras import atomic_save
from fastcore.nbio import NbCell,mk_cell,new_nb,dict2nb,read_nb,nb2str,repair_cell,repair_nb
from fastcore.nbio import NbCell,mk_cell,new_nb,dict2nb,read_nb,nb2str,repair_cell,repair_nb,record_nb_edit
import json
from contextlib import suppress
from base64 import b64encode,b64decode
Expand Down Expand Up @@ -93,9 +93,11 @@ def write_ipynb(dlg:BaseDialog, fname=None, version=2, msgs=None, **kwargs):
"""Write `dlg` as a notebook, or return its JSON string if `fname` is None.

Pass `kwargs`, such as `uid` and `gid`, to `atomic_save`."""
res = nb2str(get_ipynb(dlg, version=version, msgs=msgs))
nb = get_ipynb(dlg, version=version, msgs=msgs)
res = nb2str(nb)
if not fname: return res
fname = Path(fname).expanduser()
if os.environ.get('EDIT_JOURNAL'): record_nb_edit(fname, fname.read_text(encoding='utf-8') if fname.exists() else None, nb)
with atomic_save(fname, mode='w', encoding='utf-8', **kwargs) as f: f.write(res)
dlg.mtime_ = safe_mtime(fname)

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
]
dependencies = ['fastcore>=2.2.48']
dependencies = ['fastcore>=2.3.15']

[project.optional-dependencies]
dev = ['exhash', 'execnb>=0.3.2', 'nbformat', 'remold']
Expand Down
23 changes: 21 additions & 2 deletions ship/02_ipynb.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"source": [
"from fastcore.utils import *\n",
"from fastcore.xtras import atomic_save\n",
"from fastcore.nbio import NbCell,mk_cell,new_nb,dict2nb,read_nb,nb2str,repair_cell,repair_nb\n",
"from fastcore.nbio import NbCell,mk_cell,new_nb,dict2nb,read_nb,nb2str,repair_cell,repair_nb,record_nb_edit\n",
"import json\n",
"from contextlib import suppress\n",
"from base64 import b64encode,b64decode\n",
Expand Down Expand Up @@ -445,9 +445,11 @@
" \"\"\"Write `dlg` as a notebook, or return its JSON string if `fname` is None.\n",
"\n",
" Pass `kwargs`, such as `uid` and `gid`, to `atomic_save`.\"\"\"\n",
" res = nb2str(get_ipynb(dlg, version=version, msgs=msgs))\n",
" nb = get_ipynb(dlg, version=version, msgs=msgs)\n",
" res = nb2str(nb)\n",
" if not fname: return res\n",
" fname = Path(fname).expanduser()\n",
" if os.environ.get('EDIT_JOURNAL'): record_nb_edit(fname, fname.read_text(encoding='utf-8') if fname.exists() else None, nb)\n",
" with atomic_save(fname, mode='w', encoding='utf-8', **kwargs) as f: f.write(res)\n",
" dlg.mtime_ = safe_mtime(fname)"
]
Expand Down Expand Up @@ -831,6 +833,23 @@
" write_ipynb(self, fname)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ce4a118a",
"metadata": {},
"outputs": [],
"source": [
"from fastcore.tools import journal\n",
"with modified_env(EDIT_JOURNAL=str(tstdir/'j'), EDIT_AUTHOR='ad'):\n",
" jd = Dialog(name='jtest')\n",
" jm = jd.mk_message('hello', msg_type=snote)\n",
" jd.save(tstdir/'jtest.ipynb')\n",
" jm.content = 'world'\n",
" jd.save(tstdir/'jtest.ipynb')\n",
" test_eq([(r['cell'], r['added'], r['removed']) for r in journal(author='ad')], [(jm.id, 1, 0), (jm.id, 1, 1)])"
]
},
{
"cell_type": "markdown",
"id": "ebfcc327",
Expand Down
38 changes: 13 additions & 25 deletions ship/04_dlgskill.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"metadata": {},
"source": [
"# dlgskill\n",
"> Read, search, and edit notebook and dialog content through aidialog's `Dialog` and `Message` APIs. Use for cell sources, stored outputs, prompt/reply pairs, and structural message operations."
"> Read, search, and edit notebook and dialog content through aidialog's `Dialog` and `Message` APIs (cell sources, stored outputs, prompt/reply pairs, structural ops)."
]
},
{
Expand All @@ -18,13 +18,9 @@
}
},
"source": [
"NB: this file is designed for an LLM reader, not a human. Add it to your LLM's context and ask it to explain.\n",
"\n",
"- first: `fastship.notebooks` (notebooks), `exhash.skill` (edits); cross-notebook search: `rgapi.skill` `nbrg`\n",
"- read: `summary_dlg` (unless reading it all) → `find_msgs` or `view_dlg(incl_out=True)`; neighbouring prose too, `ids=` lookups included\n",
"- `fastcore.nbio`: only for an operation this API lacks; propose adding it\n",
"- edit: exhash via fresh `lnhashview_msg` or `lnhashview_cell`; `msg_*` editors only where exhash can't; then `dlg.validate()`\n",
"- Python symbols, ASTs: structural `find_msgs` predicates\n",
"- first: `fastship.notebooks` (notebooks), `exhash.skill` (edits); cross-notebook search: `rgapi.skill` `nbrg`; `fastcore.nbio` only for missing ops (propose adding)\n",
"- read: `summary_dlg` (unless reading all) → `find_msgs` or `view_dlg(incl_out=True)`; read neighbouring prose too, `ids=` lookups included\n",
"- edit: exhash via fresh `lnhashview_msg`/`lnhashview_cell`; `msg_*` editors only where exhash can't; then `dlg.validate()`; Python symbols/ASTs: structural `find_msgs` predicates\n",
"- broken file: `validate_nb`, `validate_cell`, `read_nb`; raw text only if unparseable; never splice notebook JSON"
]
},
Expand All @@ -37,15 +33,10 @@
}
},
"source": [
"- functions: `dlg=path`, else `set_dlg(path)`'s file; each call rereads, autosaves; methods: held `Dialog`, `dlg.save()`; otherwise as `fastcore.editskill`\n",
"- in memory: `d.mk_message`, `d.remove_msgs`; `Dialog(msgs)` wraps a list; `m.dlg` keeps ownership\n",
"- file `find_msgs`: fresh `Dialog`, apart from any held one; its messages' edits: `m.dlg.save()`\n",
"- current message: host sets it; writes never move it: successive `add_msg`: chain `after=`\n",
"- summary row: `id:t[directives]:content` (c code, n note, p prompt, r raw); reply after `>`; `…[N]`: N characters cut\n",
"- XML (`item2xml`): replies in `<out>`, directives as attributes; diffs: XML plus `meta:` line\n",
"- `m.exported`: content and meta directives; `m.meta_exported`: meta only, assignable\n",
"- `update_msg`, `Message.update`: replace attributes; `meta=` replaces whole dict; `mergemeta=` merges\n",
"- text editors' `out=True`: prompt replies only; other outputs: assign `m.output`"
"- target: functions take `dlg=path` (else `set_dlg(path)`), reread and autosave; methods act on held `Dialog` with `dlg.save()` (otherwise as `fastcore.editskill`); in memory: `d.mk_message`, `d.remove_msgs`, `Dialog(msgs)` wraps list, `m.dlg` keeps ownership; file `find_msgs` returns fresh `Dialog` (save via `m.dlg.save()`)\n",
"- current message: host sets it; writes never move it; successive `add_msg`: chain `after=`\n",
"- formats: summary row `id:t[directives]:content` (`c` code, `n` note, `p` prompt, `r` raw; reply after `>`; `…[N]` = N chars cut); XML (`item2xml`): replies in `<out>`, directives as attrs; diffs: XML + `meta:` line\n",
"- attrs/outputs: `m.exported` (content + meta), `m.meta_exported` (meta only, assignable); `update_msg`/`Message.update` replace attrs (`meta=` replaces dict, `mergemeta=` merges); `out=True` on text editors: prompt replies only (other outputs: assign `m.output`)"
]
},
{
Expand All @@ -57,8 +48,7 @@
}
},
"source": [
"- magics: `%nbrun` (`nbrun_magic`), `%%add_msg` (`add_msg_magic`)\n",
"- `execute_dlg`, `Dialog.execute`, `Message.execute`: capture outputs (file or held)"
"- magics/exec: `%nbrun` (`nbrun_magic`), `%%add_msg` (`add_msg_magic`); `execute_dlg`, `Dialog.execute`, `Message.execute` capture outputs"
]
},
{
Expand Down Expand Up @@ -885,6 +875,7 @@
"outputs": [],
"source": [
"_msg_edit_doc = \"\"\"\n",
"\n",
"Be sure you've viewed the message (e.g. `view_msg`) so you know the line nums.\n",
"\n",
"Message editing standard parameters:\n",
Expand Down Expand Up @@ -937,7 +928,7 @@
" return PrettyString(str_diff(text, new) or 'none: No changes.')\n",
" res = splice_sig(method, f, 'text')\n",
" res.__name__ = res.__qualname__ = f.__name__\n",
" res.__doc__ = (f.__doc__ or '') + \"\\nIn-memory edit of this message (`out=True` edits a prompt's reply), returning a diff; nothing is saved.\"\n",
" res.__doc__ = (f.__doc__ or '') + \"\\n\\nIn-memory edit of this message (`out=True` edits a prompt's reply), returning a diff; nothing is saved.\"\n",
" return res\n",
"\n",
"for _f in (insert_line, str_replace, strs_replace, replace_lines, del_lines, ast_replace): setattr(Message, _f.__name__, _msg_method(_f))"
Expand Down Expand Up @@ -1672,13 +1663,10 @@
"cell_type": "code",
"execution_count": null,
"id": "56388a3a",
"metadata": {
"nbdev": {
"export": "true"
}
},
"metadata": {},
"outputs": [],
"source": [
"#| exporti\n",
"def load_ipython_extension(ipython):\n",
" ipython.register_magic_function(add_msg_magic, 'cell', 'add_msg')\n",
" ipython.register_magic_function(nbrun_magic, 'line', 'nbrun')\n",
Expand Down