# Chapter7. 網頁版聊天程式與文字生圖 Image API
:+1: 完整程式碼在 https://github.com/iamalex33329/chatgpt-develop-guide-zhtw
## 其他章節
[Chapter1. OpenAI API 入門](https://hackmd.io/@U3f2IzHERbymAst2-lDdjA/S1cNMYi6T)
[Chapter2. 使用 Python 呼叫 API](https://hackmd.io/@U3f2IzHERbymAst2-lDdjA/HyZBg5ia6)
[Chapter3. API 參數解析與錯誤處理](https://hackmd.io/@U3f2IzHERbymAst2-lDdjA/BJWNtsh6p)
[Chapter4. 打造自己的 ChatGPT](https://hackmd.io/@112356044/Hk81U96Tp)
[Chapter5. 突破時空限制 - 整合搜尋功能](https://hackmd.io/@112356044/HkbVM-ApT)
[Chapter6. 讓 AI 幫 AI - 自動串接流程](https://hackmd.io/@112356044/r1Ke-GR6T)
[Chapter8. 設計 LINE AI 聊天機器人](https://hackmd.io/@112356044/r1d6HsgAa)
[Chapter9. 自媒體業者必看!使用 AI 自動生成高品質字幕](https://hackmd.io/@112356044/rJ2T37V0T)
[Chapter10. 把 AI 帶到 Discord](https://hackmd.io/@112356044/Sy_L-B40T)
[Chapter11. AI 客製化投資理財應用實戰](https://hackmd.io/@112356044/HkUE0rER6)
[Chapter12. 用 LangChain 實作新書宣傳自動小編](https://hackmd.io/@112356044/SybvbdN0p)
## 目錄結構
[TOC]
## 使用 gradio 套件快速建立網頁程式
### 安裝與使用 gradio
[Gradio](https://www.gradio.app/) 是專為機器學習專案設計的套件,其實就是一個網頁伺服器。
> Gradio作為一個開源Python框架,其主要設計初衷是為了使機器學習模型的部署和共享變得更簡單。 透過Gradio,開發者可以快速創建一個交互式界面,讓用戶能夠輕鬆地與機器學習模型互動,這對於演示模型的能力和限制非常有幫助。
>
> ::: [Streamlit 與 Gradio:Python框架的深度比較](https://medium.com/@royhwang_78906/streamlit-%E8%88%87-gradio-python%E6%A1%86%E6%9E%B6%E7%9A%84%E6%B7%B1%E5%BA%A6%E6%AF%94%E8%BC%83-8d576560ff05#:~:text=Gradio%E4%BD%9C%E7%82%BA%E4%B8%80%E5%80%8B%E9%96%8B%E6%BA%90Python,%E5%92%8C%E9%99%90%E5%88%B6%E9%9D%9E%E5%B8%B8%E6%9C%89%E5%B9%AB%E5%8A%A9%E3%80%82) :::
``` python=
!pip install gradio
import gradio as gr
def chat(msg1, msg2):
return msg1+msg2
web_chat = gr.Interface(
fn=chat,
inputs=['text', 'text'],
outputs=['text']
)
web_chat.queue()
web_chat.launch(share=True)
```
這段程式碼使用 Gradio 庫來建立一個簡單的網頁聊天介面。以下是程式碼的主要功能:
1. `chat` 函式定義了一個簡單的聊天功能,它接收兩個文本訊息作為輸入,然後將這兩個訊息串聯在一起返回。
2. 使用 Gradio 的 `Interface` 類來建立網頁介面。`fn` 參數設置為 `chat` 函式,表示該介面的功能由 `chat` 函式提供。
3. `inputs` 參數設置為 `['text', 'text']`,表示輸入介面將包含兩個文本輸入框,分別用於輸入兩段文字。
4. `outputs` 參數設置為 `['text']`,表示輸出介面將包含一個文本框,用於顯示 `chat` 函式的返回結果。
5. `web_chat.queue()` 函式用於在本地啟動 Gradio 服務器,以便在本地預覽介面。
6. `web_chat.launch(share=True)` 函式用於在線上部署 Gradio 服務器,並通過分享連結來分享聊天介面給其他人使用。
### 使用串流方式顯示輸出
``` python=
import gradio as gr
from Chapter7 import chat
def wrapper_chat(sys_msg, user_msg, stream):
reply = ''
for chunk in chat(sys_msg, user_msg, stream):
reply += chunk
yield reply
web_chat = gr.Interface(
fn=wrapper_chat,
inputs=['text', 'text', 'checkbox'],
outputs=['text']
)
web_chat.queue()
web_chat.launch(share=True)
```
> 以上使用的 chat 函式,請到 [github專案](https://github.com/iamalex33329/chatgpt-develop-guide-zhtw) 上的 `Chapter7` -> `__init__.py` 複製下載
### 客製使用者介面

雖然有了網頁介面,但這裡有幾個缺點:
1. 輸入欄位的標題是函式的**參數名稱**,對使用者不直覺
2. 每次使用都要輸入 **`sys_msg`**,希望有預設值
3. 輸出區看不到之前的對話內容,只有當次回覆
透過以下更改,可以讓介面體驗更好:
``` python=
import gradio as gr
from Chapter7 import chat
messages = []
def wrapper_chat_bot(sys_msg, user_msg, stream):
messages.append([user_msg, ''])
for chunk in chat(sys_msg, user_msg, stream):
messages[-1][1] += chunk
yield messages
web_chat = gr.Interface(
fn=wrapper_chat_bot,
inputs=[
gr.Textbox(label='System', value='Assistance'),
gr.Textbox(label='User'),
gr.Checkbox(label='Streaming', value=False)
],
outputs=[gr.Chatbot(label='AI: ')]
)
web_chat.queue()
web_chat.launch(share=True)
```
## 使用 DALL・E 的 Image API
> DALL・E 是一個文字生產圖片的 API,也是 Microsoft 影像建立工具(Image Creator)背後的模型。
### Image API 用法
可以透過簡單的 Image.create() 來產生圖片
``` python=
import openai
import apikey
openai.api_key = apikey.OPENAI_API_KEY
openai.Image.create(
prompt='踩著金字塔的蜜蜂熊',
n=1,
size='1024x1024'
)
```
而圖片的 `size` 可以選擇的有:
| 尺寸 | 價格(美金/張) |
| -------- | -------- |
| 1024x1024 | $0.020 |
| 512x512 | $0.018 |
| 256x256 | $0.016 |
### 建立文字生圖像網址的函式
``` python=
def txt_to_img_url(prompt):
response = openai.Image.create(
prompt=prompt,
n=1,
size='1024x1024')
return response['data'][0]['url']
print(txt_to_img_url('踩著金字塔的蜜蜂熊'))
```
> 但其實 DALL・E 產生的圖片不會太精細

接著我們把這個函式加入 `func_table` 變成聊天程式可以使用的**外部函式工具**
``` python=+
func_table.append(
{
"chain": False, # 生圖後不需要傳回給 API
"func": txt_to_img_url,
"spec": {
"name": "txt_to_img_url",
"description": "由文字生圖並傳回圖像網址",
"parameters": {
"type": "object",
"properties": {
"prompt": {
"type": "string",
"description": "描述要產生圖像內容的文字",
}
},
"required": ["prompt"],
},
}
}
)
```

### 包裝成生成 markdown 語法的函式
現在能夠產生出圖片網址了!但其實 Chatbot 可以接受 `markdown` 語法,我們只需要將網址包裝在 markdown 中,就能夠自動讀取圖片,將網址轉成圖片的形式。
``` python=
def txt_to_img_url(prompt):
response = openai.Image.create(
prompt=prompt,
n=1,
size='1024x1024')
url = response['data'][0]['url']
return f''
```

> 根據不同的問法,現在我們的聊天機器人已經能夠自動挑選他所要使用的工具了~~