ChatGPT-generated Web Maps
Sat 25 March 2023I have been exploring OpenAI's API platform, which provides various services like image generation, code completion, and text processing. In this article, we will utilize the Chat API to generate JavaScript code for creating a web map from a text prompt.
Although the Chat API is not free, you can sign up for a 30-day trial. The pricing is reasonable, and you should carefully consider how you will use it. In our case, we will send individual chat requests and expect to receive a chat message with JavaScript code in response.
To get started, sign up for OpenAI's APIs here and create an API key. You can also set a monthly billing limit for added peace of mind.
For our app, we will use a single page static website as the front end and an API to obfuscate our OpenAI API key and make the request to OpenAI. Here are the basic steps:
Review the code available here, which includes providing a text area for the prompt code, an empty div element named "map," sending the prompt to an API, and using the eval()
method to execute the returned code, which will update the map div element with the response code. Note that there are well-documented reasons not to use the eval() method, so use it at your own risk.
Create an API, as detailed in the code available here. Remember to install the necessary modules (pip install "fastapi[all]" openai
), start the API locally (uvicorn main:app --reload
), update the origin to point at your running frontend to allow cross-origin requests, and update the OpenAI API key value with your own key. Make a note of the chat prompt and ensure the response from OpenAI is parsed to extract and return only the code block.
The final app will look like the GIF below.
That's it! Enjoy using ChatGPT to create LeafletJS maps. If you have any questions, reach out to me on Twitter or Mastodon.
PS - this blog post was also refined by ChatGPT.