Try an interactive version of this dialog: Sign up at solve.it.com, click Upload, and pass this URL.
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:
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
@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'
)
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.
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")
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)
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'))
@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)
Specifics:
- When the user visits the
chatdemoroute, 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
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 ""
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')
@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'
)
@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'
)
users = db.create(User, transform=True)
dialogs = db.create(Dialog, transform=True)
users,dialogs
msgs = [{'content': '1+1', 'author': 'user'}, {'content': '2', 'author': 'computer'}]
d = dialogs.insert(uid=u.id, messages=json.dumps(msgs), name='my dlg')
d
@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'
)
@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'
)