Deploy sketch on streamlit

Hi @alessandro_ciciarell, welcome to the forum! :wave: :smile:

You’re encountering the error because the library you’re importing (sketch) imports another library (lambdaprompt) that uses async functions. But Streamlit runs in a separate thread that doesn’t have an event loop by default. To make it work, you’ll need to create an event loop and run the async functions inside it.

The lambdaprompt library runs some async code during the import process itself. So you can try creating an event loop before importing the library. Here’s an example:

import asyncio
from contextlib import contextmanager
import streamlit as st

# Create a context manager to run an event loop
@contextmanager
def setup_event_loop():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        yield loop
    finally:
        loop.close()
        asyncio.set_event_loop(None)

# Use the context manager to create an event loop
with setup_event_loop() as loop:
    import sketch

# Now you can use the 'sketch' library in your Streamlit app
st.write("The 'sketch' library has been successfully imported.")

I’m not 100% sure this is the right approach as I don’t have prior experience running async code in Streamlit. I’ll defer to the community to correct me.

3 Likes