Try an interactive version of this dialog: Sign up at solve.it.com, click Upload, and pass this URL.

Code: 79 (12:23:56a)

from fastcore.utils import *
from fasthtml.common import *
from fasthtml.jupyter import *
from fastlite import *
import fasthtml.components as fc
import httpx,json
from toolslm.shell import get_shell
from lisette import *

Note: 190

Intro + Setup

In part 1, we built up a minimal little FastHTML app, playing with styling, making a wrapper function to save repeating cls='btn' and such, exploring HTMX for interactivity and finally prototyping a little minimal chat UI that sent code straight to ex() to execute. And along the way, learned why you shouldn't share a public URL to an app that executes arbitrary code on the internet, with some student hijinx but no serious damage :D

My plan now is to explore some ways we can build on this! First, let's include a minimal version of the app:

Code: 118 (12:23:56a)

daisy_hdrs = (
    Link(href='https://cdn.jsdelivr.net/npm/daisyui@5', rel='stylesheet', type='text/css'),
    Script(src='https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4'),
    Link(href='https://cdn.jsdelivr.net/npm/daisyui@5/themes.css', rel='stylesheet', type='text/css')
)

Note: 52

NB: Need to set a custom session cookie for FastHTML sessions to work in solveit since for now solveit uses the default one (we might change this?)

Code: 34 (12:23:56a)

app = FastHTML(hdrs=daisy_hdrs, session_cookie='mysessioncookie')
rt = app.route

Code: 18 (12:23:56a)

srv = JupyUvi(app)
# srv.stop()

Output: 2,127

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/uvicorn/protocols/http/httptools_impl.py", line 409, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/starlette/applications.py", line 107, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/errors.py", line 186, in __call__
    raise exc
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/errors.py", line 164, in __call__
    await self.app(scope, receive, _send)
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/cors.py", line 85, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/sessions.py", line 85, in __call__
    await self.app(scope, receive, send_wrapper)
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 63, in __call__
    await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
    raise exc
  File "/usr/local/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
    await app(scope, receive, sender)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 716, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 736, in app
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 290, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 78, in app
    await wrap_app_handling_exceptions(app, request)(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
    raise exc
  File "/usr/local/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
    await app(scope, receive, sender)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 75, in app
    response = await f(request)
               ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/fasthtml/core.py", line 626, in _f
    if not resp: resp = await _wrap_call(f, req, sig.parameters)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/fasthtml/core.py", line 476, in _wrap_call
    return await _handle(f, **wreq)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/fasthtml/core.py", line 235, in _handle
    return (await f(*args, **kwargs)) if is_async_callable(f) else await run_in_threadpool(f, *args, **kwargs)
                                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/starlette/concurrency.py", line 32, in run_in_threadpool
    return await anyio.to_thread.run_sync(func)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/to_thread.py", line 56, in run_sync
    return await get_async_backend().run_sync_in_worker_thread(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 2485, in run_sync_in_worker_thread
    return await future
           ^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 976, in run
    result = context.run(func, *args)
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/ipykernel_150/2330225430.py", line 7, in dlglist
    udlgs = dialogs('uid=?', user.id)
            ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/fastlite/core.py", line 143, in __call__
    return list(res)
           ^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/fastlite/core.py", line 142, in <genexpr>
    else: res = (self.cls(**o) for o in res)
                                        ^^^
  File "/usr/local/lib/python3.12/site-packages/apswutils/db.py", line 1300, in rows_where
    cursor = self.db.execute(sql, where_args or [])
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/apswutils/db.py", line 437, in execute
    if parameters: return self.conn.execute(sql, parameters)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: You must supply a dict or a sequence for execute

Code: 40 (12:23:56a)

def get_preview(app): return partial(HTMX, app=app, host=None, port=None)
preview = get_preview(app)

Code: 102 (12:23:56a)

def mk_comp(name, compcls):
    comp = getattr(fc, name)
    def wrapper(*args, cls='', **kwargs): return comp(*args, cls=f'{compcls} {cls}', **kwargs)
    globals()[name] = wrapper
mk_comp('Button', 'btn')
mk_comp('Input', 'input')

Code: 7 (12:23:56a)

sh = get_shell()

Code: 33 (12:23:56a)

def ex(s):
    res = sh.run_cell(s)
    return res.result if res.result else res.stdout

Code: 351 (12:23:56a)

@rt
def proc_code(code:str):
    res = ex(code)
    return (Div(Div(code, cls='chat-bubble chat-bubble-info'), cls='chat chat-end'),
            Div(Div(str(res), cls='chat-bubble chat-bubble-primary'), cls='chat chat-start') if res else "",
            Input(type='text', placeholder='Enter code...', id='code', hx_swap_oob='true', cls='flex-1'))

@rt
def chatdemo():
    return Div(
        H1('Code Chat', cls='text-3xl font-bold mb-4 text-center'),
        Div(id='chat', cls='mb-4 border rounded-lg p-4 h-[400px] overflow-y-auto'),
        Form(hx_post=proc_code, hx_target='#chat', hx_swap='beforeend', cls='flex gap-2')(
            Input(type='text', placeholder='Enter code...', id='code', cls='flex-1'),
            Button('Run', type='submit', cls='btn-primary')
        ),
        cls='p-4', style='max-width:600px'
    )

Code: 6 (12:23:57a)

preview(chatdemo)

Output: 270

Note: 120

Including an LLM

Next I thought it would be fun to check if the submitted message is valid python and, if not, send it as a question to an LLM instead. That way you don't even need a mode toggle or anything! This little snippet came from an AI chat somewhere, I lost the prompt but you can see it in action and get a feel for how it works.

Code: 135 (12:23:57a)

def is_code(code):
    try:
        compile(code, '<string>', 'eval')
        return True
    except SyntaxError:
        try:
            compile(code, '<string>', 'exec')
            return True
        except SyntaxError: return False

is_code("1+1"), is_code("print(1+1)"), is_code("print(1+1"), is_code("a"), is_code("Hello mr AI")

Output: 31

(True, True, False, True, False)

Note: 21

We can use lisette to set up the chat bits fairly easily:

Code: 85 (12:23:57a)

sysp = "You are a chat model, in a chat with a user that also includes code executions. Given the chat history as context, answer the user's current question concisely."
chat = Chat(model='claude-haiku-4-5', sp=sysp)

Code: 16 (12:23:58a)

chat.h = []
r = chat("Hello")
r

Output: 348

Hello! 👋 How can I help you today? Feel free to ask me questions, discuss topics, or if you'd like, I can help you with code execution and analysis.

  • id: chatcmpl-e2f60529-7246-4d74-9829-c7d69399e7ee
  • model: claude-haiku-4-5-20251001
  • finish_reason: stop
  • usage: Usage(completion_tokens=42, prompt_tokens=44, total_tokens=86, completion_tokens_details=None, prompt_tokens_details=PromptTokensDetailsWrapper(audio_tokens=None, cached_tokens=0, text_tokens=None, image_tokens=None, cache_creation_tokens=0, cache_creation_token_details=CacheCreationTokenDetails(ephemeral_5m_input_tokens=0, ephemeral_1h_input_tokens=0)), cache_creation_input_tokens=0, cache_read_input_tokens=0)

Code: 27 (12:23:58a)

def cts(r): return r.choices[0].message.content
cts(r)

Output: 84

"Hello! 👋 How can I help you today? Feel free to ask me questions, discuss topics, or if you'd like, I can help you with code execution and analysis."

Note: 60

For now, we'll store a history of messages in a global variable and update it when we process a message. I also made a convenience function for a pair of chat bubbles plus the cleared input box:

Code: 4 (12:23:58a)

h = []

Code: 150 (12:23:58a)

def bubbles(code, res, is_ai=False): 
    return (Div(Div(code, cls='chat-bubble chat-bubble-info'), cls='chat chat-end'),
                Div(Div(str(res), cls='chat-bubble chat-bubble-'+('accent' if is_ai else 'primary')), cls='chat chat-start') if res else "",
                Input(type='text', placeholder='Enter code...', id='code', hx_swap_oob='true', cls='input flex-1'))

Code: 21 (12:23:58a)

# preview(bubbles("Hi", "Hello", is_ai=True))

Code: 150 (12:23:58a)

@rt
def proc_code(code:str):
    global h
    c = is_code(code)
    res = ex(code) if c else cts(Chat(model='claude-haiku-4-5', sp=sysp)("Past context/conversation: " + "\n".join(h) + "\n\nCurrent question: " + code))
    h += [str(code), str(res) if res else ""]
    return bubbles(code, res, is_ai=not c)

Code: 6 (12:23:58a)

preview(chatdemo)

Output: 270

Note: 51

Notice we didn't even need to change the main page route at all! We just swapped out the proc_code route, although I guess it should now be called proc_message :)

Note: 48

Per-User Persistent Chats

No good just having one single shared history, which can go out of sync with the UI, and which every user modifies!

Note: 40

I'm thinking per message we store author (user, AI or computer). Then for each user we keep a separate shell and chat history.

Note: 120

Specifics:

  • When the user visits the chatdemo route, we look in the session for their username. If it's not there, we generate a new one and store it in the session.
  • Then we look in the global dict for their username. If it's not there, we create a new h and shell and store it in the global dict.
  • We render their chat on load

Code: 64 (12:23:58a)

import random
@rt
def sessiontest(session):
    if 'foo' not in session: session['foo'] = random.randint(0, 1_000_000)
    return session['foo']

Code: 12 (12:23:58a)

preview(sessiontest, height=40)

Output: 166

Code: 7 (12:23:58a)

user_chats = {}

Code: 139 (12:23:58a)

def render_message(msg):
    color = 'info' if msg['author'] == 'user' else 'accent' if msg['author'] == 'ai' else 'primary'
    align = 'end' if msg['author'] == 'user' else 'start'
    return Div(Div(msg['content'], cls=f'chat-bubble chat-bubble-{color}'), cls=f'chat chat-{align}') if msg['content'] else ""

Code: 358 (12:23:58a)

def ex(s, sh):
    res = sh.run_cell(s)
    return res.result if res.result else res.stdout

@rt
def proc_code(code:str, session):
    if not 'userid' in session: return
    h, sh = user_chats[session['userid']]
    c = is_code(code)
    if c: res = ex(code, sh)
    else:
        ctx = "Past context/conversation: " + "\n".join([str(msg['content']) for msg in h])
        res =  cts(Chat(model='claude-haiku-4-5', sp=sysp)(ctx + "\n\nCurrent question: " + code))
    h += {'content': code, 'author': 'user'}, {'content': res, 'author': 'ai' if not c else 'computer'}
    return render_message({'content': code, 'author': 'user'}), render_message({'content': res, 'author': 'ai' if not c else 'computer'}), Input(type='text', placeholder='Enter code...', id='code', hx_swap_oob='true', cls='input flex-1')

Code: 352 (12:23:58a)

@rt
def chatdemo(session):
    # Set up user if they don't already exist
    if 'userid' not in session: session['userid'] = random.randint(0, 1_000_000)
    if session['userid'] not in user_chats:
        user_chats[session['userid']] = ([], get_shell())
    h, _ = user_chats[session['userid']]
    bubs = [render_message(m) for m in h]
    return Div(
        H1('Code Chat', cls='text-3xl font-bold mb-4 text-center'),
        Div(*bubs, id='chat', cls='mb-4 border rounded-lg p-4 h-[400px] overflow-y-auto'),
        Form(hx_post=proc_code, hx_target='#chat', hx_swap='beforeend', cls='flex gap-2')(
            Input(type='text', placeholder='Enter code...', id='code', cls='flex-1'),
            Button('Run', type='submit', cls='btn-primary')
        ), cls='p-4', style='max-width:600px'
    )

Code: 6 (12:23:58a)

preview(chatdemo)

Output: 270

Code: 43 (12:23:58a)

@rt
def reset(session):
    user_chats = {}
    session.clear()
    return session
# preview(reset) # Useful for debugging

Note: 10

Adding A 'Clear' Button

Code: 114 (12:23:59a)

@rt
def clear_chat(session):
    if 'userid' not in session: return
    if session['userid'] not in user_chats: return
    user_chats[session['userid']] = ([], get_shell())
    return Div(id='chat', cls='mb-4 border rounded-lg p-4 h-[400px] overflow-y-auto')
    

Code: 396 (12:23:59a)

@rt
def chatdemo(session):
    # Set up user if they don't already exist
    if 'userid' not in session: session['userid'] = random.randint(0, 1000)
    if session['userid'] not in user_chats:
        user_chats[session['userid']] = ([], get_shell())
    h, _ = user_chats[session['userid']]
    bubs = [render_message(m) for m in h]
    return Div(
        H1('Code Chat', cls='text-3xl font-bold mb-4 text-center'),
        Div(*bubs, id='chat', cls='mb-4 border rounded-lg p-4 h-[400px] overflow-y-auto'),
        Form(hx_post=proc_code, hx_target='#chat', hx_swap='beforeend', cls='flex gap-2')(
            Input(type='text', placeholder='Enter code...', id='code', cls='flex-1'),
            Button('Run', type='submit', cls='btn-primary'), 
            Button('Clear', type='button', cls='btn-secondary', hx_post=clear_chat, hx_target='#chat', hx_swap='outerHTML')
        ), cls='p-4', style='max-width:600px'
    )

Code: 6 (12:24:51a)

preview(chatdemo)

Output: 270

Note: 4

DB support

Code: 7 (12:26:06a)

from fastlite import *

Code: 13 (12:30:52a)

db = database('solveish.db')
db

Output: 75

<Database <apsw.Connection object "/app/data/course2/solveish.db" at 0x7d16bbf9ce80>>

Code: 30 (12:35:26a)

class User: id:int
class Dialog: id:int; uid:int; messages:str; name:str

Code: 31 (12:35:48a)

users = db.create(User, transform=True)
dialogs = db.create(Dialog, transform=True)
users,dialogs

Output: 57

(<Table user (id)>, <Table dialog (id, uid, messages, name)>)

Code: 12 (12:50:08a)

users.delete_where()
dialogs.delete_where()

Output: 39

<Table dialog (id, uid, messages, name)>

Code: 12 (12:50:09a)

u = users.insert(id=561)

Code: 6 (12:50:10a)

users[561]

Output: 24

User(id=561)

Code: 73 (12:50:56a)

msgs = [{'content': '1+1', 'author': 'user'}, {'content': '2', 'author': 'computer'}]
d = dialogs.insert(uid=u.id, messages=json.dumps(msgs), name='my dlg')
d

Output: 151

Dialog(id=1, uid=561, messages='[{"content": "1+1", "author": "user"}, {"content": "2", "author": "computer"}]', name='my dlg')

Code: 6 (12:50:58a)

dialogs[1]

Output: 151

Dialog(id=1, uid=561, messages='[{"content": "1+1", "author": "user"}, {"content": "2", "author": "computer"}]', name='my dlg')

Code: 13 (12:51:03a)

dialogs('uid=?', [u.id])

Output: 154

[Dialog(id=1, uid=561, messages='[{"content": "1+1", "author": "user"}, {"content": "2", "author": "computer"}]', name='my dlg')]

Code: 13 (12:51:05a)

json.loads(dialogs[1].messages)

Output: 141

[{'content': '1+1', 'author': 'user'}, {'content': '2', 'author': 'computer'}]

Code: 315 (12:51:33a)

@rt
def showdlg(dlgid:int):
    dlg = dialogs[dlgid]
    h = json.loads(dlg.messages)
    bubs = [render_message(m) for m in h]
    return Div(
        H1('Code Chat', cls='text-3xl font-bold mb-4 text-center'),
        Div(*bubs, id='chat', cls='mb-4 border rounded-lg p-4 h-[400px] overflow-y-auto'),
        Form(hx_post=proc_code, hx_target='#chat', hx_swap='beforeend', cls='flex gap-2')(
            Input(type='text', placeholder='Enter code...', id='code', cls='flex-1'),
            Button('Run', type='submit', cls='btn-primary'), 
            Button('Clear', type='button', cls='btn-secondary', hx_post=clear_chat, hx_target='#chat', hx_swap='outerHTML')
        ), cls='p-4', style='max-width:600px'
    )

Code: 15 (12:51:59a)

preview(showdlg.to(dlgid=1))

Output: 277

Code: 40 (12:54:32a)

Div(*[Li(A(dlg.name, href=showdlg.to(dlgid=dlg.id))) for dlg in dialogs()])

Output: 88

<div>
  <li>
<a href="/showdlg?dlgid=1">my dlg</a>  </li>
</div>

Code: 192 (12:57:40a)

@rt
def dlglist(session):
    if 'userid' not in session: session['userid'] = random.randint(0, 1000)
    uid = session['userid']
    try: user = users[uid]
    except NotFoundError: user = users.insert(id=uid)
    udlgs = dialogs('uid=?', [user.id])
    return Ul(
        *[Li(
            A(dlg.name, href=showdlg.to(dlgid=dlg.id), cls='link'),
            cls='list-row'
        ) for dlg in udlgs],
        cls='list'
    )

Code: 7 (12:57:41a)

preview(dlglist)

Output: 270