Running Python Scripts in ChatCraft with Python-WASI
Tags: python, opensource, wasi, webapp
Published: 2024-03-08 18:14:47

In the ever-evolving landscape of web development, the ability to run various programming languages directly in the browser has opened up a lot of opportunities for creating more dynamic and interactive web applications. One such advancement is the integration of Python scripts into web applications, a feature that has long been desired by developers who prefer Python for its simplicity and power. Today, I'm excited to share how I've achieved this milestone in [ChatCraft](https://github.com/tarasglek/chatcraft.org) by leveraging Python-WASI.

- Introduction to Python-WASI

WebAssembly System Interface (WASI) is a modular system interface for WebAssembly (WASM). It provides a set of APIs that are designed to be portable across different computing environments, enabling WASM modules to interact with the underlying system (e.g., file system, network). Python-WASI is a project that compiles Python to WASM, allowing Python code to run in a WASM runtime, which can be embedded in web browsers. This means I can now execute Python scripts client-side, directly within the user's browser, without needing a server-side interpreter.

- Integrating Python-WASI in ChatCraft

ChatCraft, our innovative platform for interactive chat applications, has always supported JavaScript and TypeScript out of the box. However, we wanted to expand our language support to include Python, given its popularity and the vast ecosystem of libraries it offers. The integration of Python-WASI into ChatCraft was a game-changer, enabling users to run Python scripts seamlessly within the chat interface.

Step 1: Fetching the Python-WASI Module
The first step in integrating Python-WASI was to fetch the Python WASM module. I used the following URL to fetch the module:
`const pythonWasmUrl = "https://unpkg.com/@antonz/python-wasi/dist/python.wasm";`

This URL points to the compiled Python WASM module, which is hosted on the unpkg CDN. By fetching this module, I can load Python into the browser's WebAssembly runtime.

Step 2: Running Python Code
With the Python WASM module loaded, I can now execute Python code. I used the @antonz/runno package, which provides a convenient API for running Python code in a WASM environment. Here's a simplified version of how I run Python code in ChatCraft:

```
async function runPython(code: string) {
  const { WASI } = await import("@antonz/runno");
  const url = "https://unpkg.com/@antonz/python-wasi/dist/python.wasm";

  // Use captureConsole to capture console output
  const executionResult = await captureConsole(async () => {
    const executionPromise = new Promise<void>((resolve, reject) => {
      WASI.start(fetch(url), {
        args: ["python", "-c", code],
        stdout: (out) => {
          console.log(out);
        },
        stderr: (err) => {
          console.error(err);
        },
      })
        .then((result) => {
          if (result.exitCode === 0) {
            resolve(); // Resolves the promise with no value
          } else {
            reject(new Error("Script execution failed")); // Rejects the promise if execution failed
          }
        })
        .catch((error) => {
          reject(error); // Reject on error
        });
    });
    return executionPromise;
  });

  return executionResult;
}
```

In this function, I use WASI.start to execute the Python code. The stdout and stderr callbacks allow us to capture the output and errors, respectively, which I can then display in the ChatCraft interface.

Step 3: Enhancing User Experience
To enhance the user experience, I added a loading spinner to indicate when the Python script is being executed. This provides immediate feedback to the user that their code is running, improving the overall interactivity of the platform.

- Conclusion

The integration of Python-WASI into ChatCraft marks a significant milestone in our journey to create a versatile and interactive chat platform. Users can now run Python scripts directly in their browsers, opening up new possibilities for educational tools, data analysis applications, and interactive bots. This is just the beginning, and we're excited to explore further enhancements and language support in the future.

I believe that the ability to run Python in the browser, thanks to Python-WASI, will inspire developers and creators to build even more innovative and engaging web applications.