Search code examples
pythonhtmlmoduleopenai-apipyscript

How can I use "pip install" when using PyScript?


I am trying to code an html file that is able to contact with chat gpt.

this is the start of the code:

<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>

<py-script>
import openai
</py-script>

but when I run it it says:

ModuleNotFoundError: No module named 'openai'

any idea how I can install it just on the html file?

I tried to find out how to use:

pip install openai ,

but I dont know how to run bash commands from the python.

I also tried to use <py-env>, but it had no effect on the code whatsoever.

+ it could be blocked by my proxy, + I'm a beginner to python, so please explain it in simple terms.


Solution

  • According to the Getting Started documentation, you import external modules using a <py-config> tag:

    <py-config>
        packages = ["openai"]
    </py-config>
    

    However, even with that, this code:

    <html>
    <head>
        <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
        <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    </head>
    <body>
        <py-config>
            packages = ["openai"]
        </py-config>
        <py-script>
            import openai
        </py-script>
    </body>
    </html>
    

    gives the following error message:

    (PY1001): Unable to install package(s) 'openai'. Reason: Can't find a pure Python 3 Wheel for package(s) 'openai'. See: https://pyodide.org/en/stable/usage/faq.html#micropip-can-t-find-a-pure-python-wheel for more information.

    At the Pyodide link above is the following:

    Why can’t I just use urllib or requests?

    We currently can’t use such packages since sockets are not available in Pyodide. See Write http.client in terms of Web APIs for more information.

    openai requires requests, so until sockets are implemented in Pyodide (which is used by PyScript), you won't be able to use the openai module, or many others, in PyScript.

    However, it is possible to make an async HTTP request using PyScript/Pyodide: see this part of the docs.