from fastcore import tools
dialoghelper
Re-export asdict:
find_var
find_var (var:str)
Search for var in all frames of the call stack
= 1
a 'a') find_var(
1
call_endp
call_endp (path, dname='', json=False, raiseex=False, **data)
find_dname
find_dname ()
*Get the message id by searching the call stack for __dialog_id.*
find_msg_id
find_msg_id ()
*Get the message id by searching the call stack for __dialog_id.*
find_msg_id()
'_9cbd170d'
curr_dialog
curr_dialog (with_messages:bool=False, dname:str='')
Get the current dialog info.
Type | Default | Details | |
---|---|---|---|
with_messages | bool | False | Include messages as well? |
dname | str | Running dialog to get info for; defaults to current dialog |
find_msgs
find_msgs (re_pattern:str='', msg_type:str=None, limit:int=None, include_output:bool=True, dname:str='')
Find list[dict]
of messages in current specific dialog that contain the given information. To refer to a message found later, use its id
field.
Type | Default | Details | |
---|---|---|---|
re_pattern | str | Optional regex to search for (re.DOTALL+re.MULTILINE is used) | |
msg_type | str | None | optional limit by message type (‘code’, ‘note’, or ‘prompt’) |
limit | int | None | Optionally limit number of returned items |
include_output | bool | True | Include output in returned dict? |
dname | str | Running dialog to get info for; defaults to current dialog |
# NB: must have a dialogue open including a message with this text in its content
= 'tools'
txt = find_msgs(txt)
found 0]['content'] found[
'from fastcore import tools'
msg_idx
msg_idx (msgid=None, dname:str='')
Get absolute index of message in dialog.
Type | Default | Details | |
---|---|---|---|
msgid | NoneType | None | Message id to find (defaults to current message) |
dname | str | Running dialog to get info for; defaults to current dialog |
msg_idx()
16
read_msg
read_msg (n:int=-1, msgid=None, relative:bool=True, dname:str='')
Get the Message
object indexed in the current dialog.
Type | Default | Details | |
---|---|---|---|
n | int | -1 | Message index (if relative, +ve is downwards) |
msgid | NoneType | None | Message id to find (defaults to current message) |
relative | bool | True | Is n relative to current message (True) or absolute (False)? |
dname | str | Running dialog to get info for; defaults to current dialog |
This message should be found.
# Previous message relative to current
print(read_msg(-1)['content'])
This message should be found.
# Last message in dialog
-1, relative=False)['content'] read_msg(
'#| hide\nfrom nbdev import nbdev_export\nnbdev_export()'
add_html
add_html (content:str, dname:str='')
Send HTML to the browser to be swapped into the DOM
Type | Default | Details | |
---|---|---|---|
content | str | The HTML to send to the client (generally should include hx-swap-oob) | |
dname | str | Running dialog to get info for; defaults to current dialog |
from fasthtml.common import *
'Hi'), hx_swap_oob='beforeend:#dialog-container')) add_html(Div(P(
run_msg
run_msg (msgid:str=None, dname:str='')
Adds a message to the run queue. Use read_msg to see the output once it runs.
Type | Default | Details | |
---|---|---|---|
msgid | str | None | id of message to execute |
dname | str | Running dialog to get info for; defaults to current dialog |
1+1
2
= read_msg()['id'] codeid
run_msg(codeid)
'{"status":"queued"}'
add_msg
add_msg (content:str, placement:str='add_after', msgid:str=None, msg_type:str='note', output:str='', time_run:str|None='', is_exported:int|None=0, skipped:int|None=0, i_collapsed:int|None=0, o_collapsed:int|None=0, heading_collapsed:int|None=0, pinned:int|None=0, dname:str='')
Add/update a message to the queue to show after code execution completes.
Type | Default | Details | |
---|---|---|---|
content | str | Content of the message (i.e the message prompt, code, or note text) | |
placement | str | add_after | Can be ‘add_after’, ‘add_before’, ‘at_start’, ‘at_end’ |
msgid | str | None | id of message that placement is relative to (if None, uses current message) |
msg_type | str | note | Message type, can be ‘code’, ‘note’, or ‘prompt’ |
output | str | For prompts/code, initial output | |
time_run | str | None | When was message executed | |
is_exported | int | None | 0 | Export message to a module? |
skipped | int | None | 0 | Hide message from prompt? |
i_collapsed | int | None | 0 | Collapse input? |
o_collapsed | int | None | 0 | Collapse output? |
heading_collapsed | int | None | 0 | Collapse heading section? |
pinned | int | None | 0 | Pin to context? |
dname | str | Running dialog to get info for; defaults to current dialog |
= add_msg('testing') _id
del_msg
del_msg (msgid:str=None, dname:str='')
Delete a message from the dialog.
Type | Default | Details | |
---|---|---|---|
msgid | str | None | id of message to delete |
dname | str | Running dialog to get info for; defaults to current dialog |
del_msg(_id)
= _add_msg_unsafe('1+1', run=True, msg_type='code') _id
del_msg(_id)
= _add_msg_unsafe('Hi', run=True, msg_type='prompt') _id
del_msg(_id)
update_msg
update_msg (msgid:str=None, msg:Optional[Dict]=None, dname:str='', content:str|None=None, msg_type:str|None=None, output:str|None=None, time_run:str|None=None, is_exported:int|None=None, skipped:int|None=None, i_collapsed:int|None=None, o_collapsed:int|None=None, heading_collapsed:int|None=None, pinned:int|None=None)
Update an existing message. Provide either msg
OR field key/values to update. Use content
param to update contents. Only include parameters to update–missing ones will be left unchanged.
Type | Default | Details | |
---|---|---|---|
msgid | str | None | id of message to update (if None, uses current message) |
msg | Optional | None | Dictionary of field keys/values to update |
dname | str | Running dialog to get info for; defaults to current dialog | |
content | str | None | None | Content of the message (i.e the message prompt, code, or note text) |
msg_type | str | None | None | Message type, can be ‘code’, ‘note’, or ‘prompt’ |
output | str | None | None | For prompts/code, the output |
time_run | str | None | None | When was message executed |
is_exported | int | None | None | Export message to a module? |
skipped | int | None | None | Hide message from prompt? |
i_collapsed | int | None | None | Collapse input? |
o_collapsed | int | None | None | Collapse output? |
heading_collapsed | int | None | None | Collapse heading section? |
pinned | int | None | None | Pin to context? |
= add_msg('testing')
_id _id
'_766c3c49'
='toasting') update_msg(_id, content
'_766c3c49'
=1) update_msg(_id, skipped
'_766c3c49'
del_msg(_id)
url2note
url2note (url:str, extract_section:bool=True, selector:str=None)
Read URL as markdown, and add a note below current message with the result
Type | Default | Details | |
---|---|---|---|
url | str | URL to read | |
extract_section | bool | True | If url has an anchor, return only that section |
selector | str | None | Select section(s) using BeautifulSoup.select (overrides extract_section) |
= url2note('https://www.example.org') _id
del_msg(_id)
ast_py
ast_py (code:str)
Get an SgRoot root node for python code
= ast_py("print('hello world')")
node = node.find(pattern="print($A)")
stmt = stmt.get_match('A')
res range() res.text(),res.
("'hello world'",
Range(start=Pos(line=0, col=6, index=6), end=Pos(line=0, col=19, index=19)))
ast_grep
ast_grep (pattern:str, path='.', lang='python')
Use the ast-grep
command to find pattern
in path
Type | Default | Details | |
---|---|---|---|
pattern | str | ast-grep pattern to search | |
path | str | . | path to recursively search for files |
lang | str | python | language to search/scan |
= ast_grep(r"xpost($A, data=$B)", '..')
res 'text'],o['metaVariables']['single'],o['file']) for o in res] [(o[
[("xpost(f'http://localhost:5001/{path}', data=data)",
{'A': {'text': "f'http://localhost:5001/{path}'",
'range': {'byteOffset': {'start': 1556, 'end': 1587},
'start': {'line': 43, 'column': 16},
'end': {'line': 43, 'column': 47}}},
'B': {'text': 'data',
'range': {'byteOffset': {'start': 1594, 'end': 1598},
'start': {'line': 43, 'column': 54},
'end': {'line': 43, 'column': 58}}}},
'dialoghelper/core.py')]
Gists
load_gist
load_gist (gist_id:str)
Retrieve a gist
= 'jph00/e7cfd4ded593e8ef6217e78a0131960c'
gistid = load_gist(gistid)
gist gist.html_url
'https://gist.github.com/jph00/e7cfd4ded593e8ef6217e78a0131960c'
gist_file
gist_file (gist_id:str)
Get the first file from a gist
= gist_file(gistid)
gfile print(gfile.content[:100]+"…")
"This is a test module which makes some simple tools available."
__all__ = ["hi","whoami"]
testfoo=…
import_string
import_string (code:str, name:str)
Type | Details | |
---|---|---|
code | str | Code to import as a module |
name | str | Name of module to create |
is_usable_tool
is_usable_tool (func:<built-infunctioncallable>)
True if the function has a docstring and all parameters have types, meaning that it can be used as an LLM tool.
def hi(who:str):
"Say hi to `who`"
return f"Hello {who}"
def hi2(who):
"Say hi to `who`"
return f"Hello {who}"
def hi3(who:str):
return f"Hello {who}"
= "bye" bye
assert is_usable_tool(hi)
assert not is_usable_tool(hi2)
assert not is_usable_tool(hi3)
assert not is_usable_tool(bye)
mk_toollist
mk_toollist (syms)
Markdown(mk_toollist([hi]))
- &
hi
: Say hi towho
import_gist
import_gist (gist_id:str, mod_name:str=None, add_global:bool=True, import_wildcard:bool=False, create_msg:bool=False)
Import gist directly from string without saving to disk
Type | Default | Details | |
---|---|---|---|
gist_id | str | user/id or just id of gist to import as a module | |
mod_name | str | None | module name to create (taken from gist filename if not passed) |
add_global | bool | True | add module to caller’s globals? |
import_wildcard | bool | False | import all exported symbols to caller’s globals |
create_msg | bool | False | Add a message that lists usable tools |
import_gist(gistid) importtest.testfoo
'testbar'
import_gist.__doc__
'Import gist directly from string without saving to disk'
=True)
import_gist(gistid, import_wildcard importtest.testfoo
'testbar'
"Sarah") hi(
'Hello Sarah'
__all__ importtest.
['hi', 'whoami']
Tool info
This is how we get a superset of tools to include:
tool_info
tool_info ()
for o in _all:
= globals()[o]
s if s.__name__[0]=='_' or not s.__doc__: continue
print(f'- &`{s.__name__}`: {s.__doc__}')
- &`find_var`: Search for var in all frames of the call stack
- &`find_dname`: Get the message id by searching the call stack for __dialog_id.
- &`find_msg_id`: Get the message id by searching the call stack for __dialog_id.
- &`curr_dialog`: Get the current dialog info.
- &`find_msgs`: Find `list[dict]` of messages in current specific dialog that contain the given information. To refer to a message found later, use its `id` field.
- &`msg_idx`: Get absolute index of message in dialog.
- &`read_msg`: Get the `Message` object indexed in the current dialog.
- &`add_html`: Send HTML to the browser to be swapped into the DOM
- &`run_msg`: Adds a message to the run queue. Use read_msg to see the output once it runs.
- &`add_msg`: Add/update a message to the queue to show after code execution completes.
- &`del_msg`: Delete a message from the dialog.
- &`update_msg`: Update an existing message. Provide either `msg` OR field key/values to update.
Use `content` param to update contents.
Only include parameters to update--missing ones will be left unchanged.
- &`url2note`: Read URL as markdown, and add a note below current message with the result
- &`ast_py`: Get an SgRoot root node for python `code`
- &`ast_grep`: Use the `ast-grep` command to find `pattern` in `path`
- &`load_gist`: Retrieve a gist
- &`gist_file`: Get the first file from a gist
- &`is_usable_tool`: True if the function has a docstring and all parameters have types, meaning that it can be used as an LLM tool.
- &`import_gist`: Import gist directly from string without saving to disk
- &`asdict`: Convert `o` to a `dict`, supporting dataclasses, namedtuples, iterables, and `__dict__` attrs.
fc_tool_info
fc_tool_info ()
for o in tools.__all__:
= getattr(tools, o)
s print(f'- &`{s.__name__}`: {s.__doc__}')
- &`run_cmd`: Run `cmd` passing split `argstr`, optionally checking for allowed argstr
- &`rg`: Run the `rg` command with the args in `argstr` (no need to backslash escape)
- &`sed`: Run the `sed` command with the args in `argstr` (e.g for reading a section of a file)
- &`view`: View directory or file contents with optional line range and numbers
- &`create`: Creates a new file with the given content at the specified path
- &`insert`: Insert new_str at specified line number
- &`str_replace`: Replace first occurrence of old_str with new_str in file
- &`strs_replace`: Replace for each str pair in old_strs,new_strs call `str_replace
- &`replace_lines`: Replace lines in file using start and end line-numbers (index starting at 1)