OpenAI API實作網頁自動生成器

Ivan Chiou
The Messiah Code 神碼技術共筆
8 min readFeb 18, 2023

還是要趕一下流行,串接了OpenAI的API GPT-3來簡單實作一個網站生成器。這裡是source code

使用python的flask後端框架,搭配預設的jinja2前端框架。

OpenAI的官方文件寫得很清楚,OpenAI API 3的版本可以透過以下openai.Completion.create產生如同在ChatGPT的bar上與之聊天的結果。其中n代表The number of completions to generate,代表著其過程透過幾次對話完成,因為一次對話最多只能回傳4096個tokens(字元長度),因此這邊設定2次,以增加回傳程式碼的長度。

def generate_gpt3_response(user_text, print_output=False):
"""
Query OpenAI GPT-3 for the specific key and get back a response
:type user_text: str the user's text to query for
:type print_output: boolean whether or not to print the raw output JSON
"""
completions = openai.Completion.create(
engine='text-davinci-003', # Determines the quality, speed, and cost.
temperature=0.5, # Level of creativity in the response
prompt=user_text, # What the user typed in
max_tokens=4080, # Maximum tokens in the prompt AND response
n=2, # The number of completions to generate
stop=None, # An optional setting to control response generation
)

# Displaying the output can be helpful if things go wrong
if print_output:
print(completions)

# Return the first choice's text
return completions.choices[0].text

OpenAI API 3.5版本則是使用openai.ChatCompletion.create,prompt變成messages,其他參數大致相同。

def generate_gpt35_response(text, print_output=False):
"""
Query OpenAI GPT-4 for the specific key and get back a response
:type text: str the user's text to query for
:type print_output: boolean whether or not to print the raw output JSON
"""
completions = openai.ChatCompletion.create(
model='gpt-3.5-turbo', # Determines the quality, speed, and cost.
messages=[
{"role": "system", "content": "You are professional developer on Javascript, html and css."},
{"role": "user", "content": text}
],
n=2,
temperature=0.8
)

# Displaying the output can be helpful if things go wrong
if print_output:
print(completions)

# Return the first choice's text
return completions.choices[0].message.content

然後當按下Generate Website後,頁面轉向/app/<uuid>,其中uuid是在按下按鈕的時候產生的。

return redirect(url_for('generate_app', uuid=str(uuid.uuid4())))

然後將輸入的訊息加上前贅字 ’Tell me the whole code…” 組成餵給GPT-3的prompt。如果該uuid頁面已經有了,則直接導向該頁面顯示出來;若還未產生出來,則丟入generate_gpt3_response執行GPT-3 API自動產生網站程式碼。

@app.route("/app/<uuid>", methods = ['GET', 'POST'])
@nocache
def generate_app(uuid):
if 'prompt' in session:
prompt = 'Tell me the whole code to create a website of ' + session['prompt']
path =app_path+uuid+'.html'
if os.path.isfile(path) is False:
response = generate_gpt3_response(prompt)
print(response)
f = open(path, "w+")
f.write(response)
f.close()
return render_template("apps/"+uuid+'.html')

同樣的,對於圖片生成也是同樣的方式。使用openai.Image.create API。

def generate_img(img_name):
response = openai.Image.create(
prompt="A cartoon "+img_name,
n=1,
size="256x256"
)
image_url = response['data'][0]['url']

另外建議多使用copilot(背後也是OpenAI),與AI一起pair programming。

比如以下創建指定folder底下的檔案清單,只要打出function name,就會出現建議的程式碼:

copilot大部份function裡面的程式碼都能自動搜尋到,對於開發速度以及程式碼的學習很有幫助。

然後再使用CKEditor編輯產生出來的網站程式碼。

@app.route('/edit/<uuid>', methods=['GET', 'POST'])
@nocache
def edit_page(uuid):
form = PostForm()

//read original html content
path =app_path+uuid+'.html'
f = open(path, "r")
body = f.read()
f.close()

form.title.data = uuid
form.body.data = body
return render_template('flask_ckeditor.html', form=form)

view(template)呈現html的title與body(safe字眼是escape特殊字元)

  <form method="post">
{{ form.csrf_token }}
<label for="title">Title</label><br>
<input type="text" name="title" value="{{ form.title.data }}"><br><br>
<label for="body">Body</label>
{{ ckeditor.create(value=form.body.data|safe, name="body") }}<br>
<input type="submit" value="Submit">
</form>

放置AI產生的圖片,完成細部修改後將網站release。(網站路徑為<host_url>/app/<uuid>)

--

--

Ivan Chiou
The Messiah Code 神碼技術共筆

Rich experience in multimedia integration, cross-functional collaboration, and dedicated to be a mentor for young developers.