Maojui

ChatGPT API | Python

2023-03-28

ChatGPT API

用途: 快速開發

有了這個 API ,你可以在你的網頁、APP、機器人中加個 Plugin,讓他有語言的能力,做到一些以前覺得不可能的事。

以往透過 Supervised learning 需要大量的資料及以及長時間的訓練才能製作出一個模型
如今有了 ChatGPT ,我們可以透過 Prompt-based 直接使用指令來呼叫模型,快速得到期望的結果
雖然每次存取都要扣錢就是了 … 但是很酷!!

1
2
3
4
5
6
7
8
9
10
11
12
import openai

openai.api_key = " ... "

def get_completion(prompt, model="gpt-3.5-turbo"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0, # this is the degree of randomness of the model's output
)
return response.choices[0].message["content"]

API Key?

從 OpenAI 自行申請: https://platform.openai.com/account/api-keys

要壓信用卡…

懶人腳本

最後附上一個會記住對話又會幫你算錢的懶人腳本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import openai
from secret import apikey

print("使用情形: https://platform.openai.com/account/usage")

message_history = []
openai.api_key = apikey
def talk_with(persona):
while True:
user_input = input('> ')
if user_input == "":
return message_history

message_history.append({"role": "user", "content": user_input})
query = [{"role": "system", "content": persona}]
query.extend(message_history)
result = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=query
)
gpt_message = result["choices"][0]["message"]
message_history.append({"role": gpt_message["role"], "content": gpt_message["content"]})
price = (result['usage']['total_tokens'] / 1000) * 0.002 * 31
print(f"諮詢費: {price}元", )
print("GPT: " + gpt_message["content"])

try:
talk_with(persona="""You are a helpful engineer expert. You answer question by providing a short explanation and a list of easy to follow steps.""")
except:
print(message_history)