mistralai / platform-docs-public

Apache License 2.0
24 stars 54 forks source link

Add pyodide execution support #126

Open philippjfr opened 1 month ago

philippjfr commented 1 month ago

As discussed in our meeting today, here's my prototype of adding live code execution to the docs along with my notes:

Live Code Execution

API Token Problem

ToDo

The patch looks something like this (

import httpx
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import json

class URLLib3Transport(httpx.BaseTransport):
    def __init__(self):
        self.pool = urllib3.PoolManager()

    def handle_request(self, request: httpx.Request):
        body = json.loads(request.content.decode('utf-8'))  # Decode the data and load as JSON
        urllib3_response = self.pool.request(request.method, str(request.url), body=request.content, headers=dict(request.headers))  # Convert httpx.URL to string
        content = json.loads(urllib3_response.data.decode('utf-8'))  # Decode the data and load as JSON
        stream = httpx.ByteStream(json.dumps(content).encode("utf-8"))  # Convert back to JSON and encode
        headers = [(b"content-type", b"application/json")]
        return httpx.Response(200, headers=headers, stream=stream)

httpx_client = httpx.Client(transport=URLLib3Transport())

client = Mistral(api_key=api_key, client=httpx_client)
philippjfr commented 1 month ago

Oh, one more thing, you have to manually patch the pyodide version by editing:

/node_modules/react-py/dist/workers/service-worker.js

and changing the pyodide version to 0.25.0.