---
# System prepended metadata

title: 其他OpenAI API可串接應用
tags: [openai, linebot, SideProject]

---

* Chat Edit 給予回應特殊要求(如英翻中)

![](https://i.imgur.com/gf7QzpP.png)

* 程式碼
```py=
import openai
import json

input("您好，這是翻譯互動服務，按下 Q (Enter) 可退出 ... (請按 Enter 繼續...)")
list_message = []
list_history = []

openai.api_key = ''

while True:
    input_value = input("")
    if input_value == 'Q':
        break
    else:
        list_history.append(input_value)
        sendmsg = {"role": "user", "content": input_value}
        list_message.append(sendmsg)
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=list_message
            )
        answer = json.loads(str(response))['choices'][0]['message']['content'].replace("\n","")
        #answer = json.dumps(response.choices[0].message["content"], ensure_ascii=False)可直接取值
        print(answer)
        list_history.append(answer)

print("英翻中...")
translation = ""
for i in list_history:
    translation = translation + i
responseEdit = openai.Edit.create(
    model="text-davinci-edit-001",
    input=translation,
    instruction="Translate into English."
    )
print(json.loads(str(responseEdit))['choices'][0]['text'])

print("摘要...")
responseSummary = openai.Edit.create(
    model="text-davinci-edit-001",
    input=translation,
    instruction="Rewrite into articles and translate into English."
    )
print(json.loads(str(responseSummary))['choices'][0]['text'])
```

* AI互動式生成客服退貨信，運用chat completion

![](https://hackmd.io/_uploads/SkfB6I743.png)

* 程式碼

```py=
import openai
import requests
import json

openai.organization = "org-qAgNTJTUtAfb2SH5Zrdo4bMI"
openai.api_key = ''

url = 'https://api.openai.com/v1/chat/completions'
headers = {"Content-Type":"application/json", "Authorization": f'Bearer {openai.api_key}'}

input1 = input("您好，歡迎使用客服機器人，請輸入您的退貨資訊... (請按 Enter 繼續...)")
input2 = input("訂單編號:")
input3 = input("姓名:")
input4 = input("地址:")
input5 = input("E-Mail:")

data1 = {"model": "gpt-3.5-turbo",
        "messages": [{"role": "user",
                      "content": f'我要退貨，請寫一封退貨回覆信件給我，內容要包含我的訂單編號{input2}、姓名{input3}、地址{input4}、Email{input5}'}]}

response = requests.post(url, headers=headers, json=data1)
b = response.json()
for i in b["choices"]:
    print(i['message']['content'])
```