# OpenAI API (Python)
[Overview - OpenAI API](https://platform.openai.com/docs/overview)
以下都是使用Python測試。
1. 安裝OpenAI Python Library
```
pip install --upgrade openai
```
2. 生成API Key
在個人API Keys頁面(https://platform.openai.com/api-keys)生成,以供後續使用。
## Text Generation
https://platform.openai.com/docs/guides/text-generation
**Chat Completions API**
Model:**GPT-3.5**
### English Chat
```python
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
completion = client.chat.completions.create(
model='gpt-3.5-turbo',
messages=[
{"role": "system", "content": "You are a travel assistant."},
{"role": "user", "content": "Please suggest my trip to Tokyo."}
]
)
print(completion.choices[0].message.content)
```
```!
Experience the vibrant city of Tokyo, where ancient traditions seamlessly blend with modern innovation.
Start your journey by exploring the historic neighborhoods of Asakusa and Meiji Shrine, transporting you back in time.
Immerse yourself in the bustling streets of Shibuya and Shinjuku, renowned for their shopping and entertainment.
Don't miss the iconic Tokyo Tower and the awe-inspiring skyline from the observation deck.
Indulge in delectable sushi and street food in Tsukiji Market and dine at a traditional izakaya for an authentic culinary adventure.
Unwind in tranquil gardens like Ueno Park and Hamarikyu Gardens, offering a peaceful escape in the midst of the metropolis.
Tokyo awaits you!
```
### Translate English to Chinese
將上面的回答翻譯成中文
```python
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
completion = client.chat.completions.create(
model='gpt-3.5-turbo',
messages=[
{"role": "user", "content": "Please translate to Traditional Chinese: Experience the vibrant city of Tokyo, where ancient traditions seamlessly blend with modern innovation. Start your journey by exploring the historic neighborhoods of Asakusa and Meiji Shrine, transporting you back in time. Immerse yourself in the bustling streets of Shibuya and Shinjuku, renowned for their shopping and entertainment. Don't miss the iconic Tokyo Tower and the awe-inspiring skyline from the observation deck. Indulge in delectable sushi and street food in Tsukiji Market and dine at a traditional izakaya for an authentic culinary adventure. Unwind in tranquil gardens like Ueno Park and Hamarikyu Gardens, offering a peaceful escape in the midst of the metropolis. Tokyo awaits you!"}
]
)
print(completion.choices[0].message.content)
```
```!
體驗充滿活力的東京城市,古老的傳統與現代創新無縫融合。
從探索淺草和明治神宮的歷史街區開始你的旅程,時光倒流。
沉浸在擁擠繁華的澀谷和新宿街道中,以其購物和娛樂聞名。
不要錯過標誌性的東京塔和觀景台上令人驚嘆的天際線。在築地市場品嚐美味的壽司和街頭小吃,在傳統的居酒屋用餐,享受地道的烹飪冒險。
在宁靜的植物園如上野公園和浜離宮庭園中放鬆身心,在大都市中尋找平靜的避風港。
東京等待著你!
```
### Chinese Chat
```python
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
completion = client.chat.completions.create(
model='gpt-3.5-turbo',
messages=[
{"role": "system", "content": "妳是一位旅行社導遊"},
{"role": "user", "content": "我想在春天去大阪旅遊,請推薦景點與行程。"}
]
)
print(completion.choices[0].message.content)
```
```!
在春天造訪大阪,你可以欣賞櫻花盛開的美景。以下是我為你推薦的景點和行程:
1. 大阪城公園:這個廣闊的公園是一個完美的地方,來觀賞櫻花盛開。你可以在城堡周圍的櫻花樹下散步,並欣賞城堡的美麗風景。此外,公園還有許多湖泊和花園,可以讓你愜意地度過一天。
2. 通天閣:這是大阪的地標之一,是日本最古老的摩天大樓。你可以搭乘電梯上到觀景台,從那裡欣賞整個大阪市的美景。在樓下的商店街,你也可以品嚐當地的美食和購物。
3. 道頓堀:這個繁華的區域是大阪最著名的觀光景點之一。這條運河沿著商業街,有許多餐廳、購物中心和劇院。此外,道頓堀的招牌是龍的雕像,絕對值得一看。
4. 美國村:這是大阪最時尚和潮流的區域之一,有許多時尚的商店、咖啡館和音樂表演場所。你可以在這裡購物、品嚐當地美味的食物和體驗獨特的文化。
5. 新世界:這是大阪的娛樂區,有著許多遊樂場、劇院和餐館。你可以在這裡體驗充滿活力的夜生活,並品嚐當地的美食。
這些只是我為你推薦的一些景點和行程,當然還有很多其他有趣的地方等著你去探索。希望你在大阪旅遊愉快!
```
### Instruction for Assistant
可以在對話一開始對system下指示,例如:只回答某些領域問題或限制回答長度。
以下範例指示系統只回答籃球相關問題,並且要精簡在30字以內。
```python
from openai import OpenAI
client = OpenAI(api_key='YOUT_OPENAI_API_KEY')
# instruction for system
conversation=[{"role": "system", "content": "You are a helpful assistant only answering questions of basketball. Keep every answer in 30 words."}]
while True:
user_input = input("User: ")
conversation.append({"role": "user", "content": user_input})
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=conversation
)
conversation.append({"role": "assistant", "content": response.choices[0].message.content})
print("\nAssistant: " + response.choices[0].message.content + "\n")
```
```!
User: Who is the GOAT of Basketball?
Assistant: Michael Jordan is widely considered the greatest of all time (GOAT) in basketball. With his illustrious career, 6 championships, and unmatched skills, he continues to be a basketball icon.
User: Who is the best shooter in NBA history?
Assistant: Steph Curry is widely regarded as the best shooter in NBA history. With his incredible shooting range, accuracy, and ability to make difficult shots, he has revolutionized the game of basketball.
User: Who is the best pitcher in MLB?
Assistant: As an AI specializing in basketball, I'm not equipped to answer questions about MLB or baseball in general. I apologize for any inconvenience. Is there anything else basketball-related I can help you with?
User: How far is the three point line for NBA?
Assistant: The three-point line in the NBA is positioned approximately 23 feet 9 inches (7.24 meters) away from the center of the basket.
```
## Image Generation
https://platform.openai.com/docs/guides/images
Model:**DALL·E**
目前免費版只能用DALL·E 2,付費版才有最新的DALL·E 3。
- DALL·E 2:https://openai.com/blog/dall-e-api-now-available-in-public-beta
- DALL·E 3:https://openai.com/dall-e-3
以下測試使用**DALL·E 2**
### Generations
輸入文字描述來生成圖片。
```python
from openai import OpenAI
client = OpenAI(api_key='YOUT_OPENAI_API_KEY')
response = client.images.generate(
model="dall-e-2",
prompt="spider-man is drinking coffee",
size="1024x1024",
n=1,
)
image_url = response.data[0].url
```

### Variations
對原始圖片做變體
:::warning
輸入必須是正方形的PNG圖檔,且需小於4MB
:::
```python
from openai import OpenAI
client = OpenAI(api_key='YOUT_OPENAI_API_KEY')
response = client.images.create_variation(
image=open("cat_and_dog.png", "rb"),
size="1024x1024",
n=2
)
image_urls = [i.url for i in response.data]
```

## Text-to-Speech
https://platform.openai.com/docs/guides/text-to-speech
Model:**TTS**
此模型有6種內建聲音,用途如下:
- 將文章內容語音化
- 產生不同語言的口說語音
- 實時語音輸出
#### English
```python
from pathlib import Path
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
speech_file_path = "speech_tts.mp3"
response = client.audio.speech.create(
model="tts-1",
voice="alloy",
input="Start your journey by exploring the historic neighborhoods of Asakusa and Meiji Shrine, transporting you back in time."
)
response.stream_to_file(speech_file_path)
```
輸出語音:[speech_tts.mp3](https://drive.google.com/file/d/1JdRL6OtNHczPg4sRlgJaeju3dXvn8djK/view?usp=sharing)
#### Chinese
```python
from pathlib import Path
from openai import OpenAI
client = OpenAI(api_key='')
speech_file_path = "speech_tts_chinese.mp3"
response = client.audio.speech.create(
model="tts-1",
voice="onyx",
input="臺灣的教育是令人擔心的 因為當前的教育喪失了以下三個功能 第一無法促進社會階級的流動 在以前不管你的出身如何 你只要願意努力 你就有機會在這個社會當中力爭上游 但是現在在目前的升學制度之下 窮人家的小孩子反而沒有更好的機會 第二無法學以致用 在臺灣目前是缺工跟低薪並存 理論上缺工就應該會高薪 怎麼會低薪 這表示說我們學校教出來的學生 不符合社會企業上的需要 所以這個有學用落差的問題"
)
response.stream_to_file(speech_file_path)
```
輸出語音:[speech_tts_chinese.mp3](https://drive.google.com/file/d/1_70AiMydUg3kXUScgg9FUxaPHOLrYRex/view?usp=sharing)
## Speech-to-Text
https://platform.openai.com/docs/guides/speech-to-text
Model:[**Whisper**](https://platform.openai.com/docs/guides/speech-to-text)
此模型是免費且開源的,目前有兩種用法:
- 將語音轉換成文字
- 將語音轉換並翻譯成英文
:::warning
語音檔必須小於25MB,目前支援的格式有`mp3`、`mp4`、`mpeg`、`mpga`、`m4a`、`wav`和`webm`。
:::
### Transcriptions
#### English
```python
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
audio_file = open('audio_test.mp3', 'rb')
transcript = client.audio.transcriptions.create(
model='whisper-1',
file=audio_file
)
print(transcript.text)
```
```
Test for Whisper. My name is Kevin.
```
輸入音檔:[audio_test.mp3](https://drive.google.com/file/d/13c0_8MuUUwIDA2Z51tCbwg-AaK-0TXSd/view?usp=sharing)
#### Chinese
```python
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
audio_file = open('audio_chinese.mp3', 'rb')
transcript = client.audio.transcriptions.create(
model='whisper-1',
file=audio_file
)
print(transcript.text)
```
```!
臺灣的教育是令人擔心的 因為當前的教育喪失了以下三個功能 第一無法促進社會階級的流動 在以前不管你的出身如何 你只要願意努力 你就有機會在這個社會當中力爭上游 但是現在在目前的升學制度之下 求人家的小孩子反而沒有更好的機會 第二無法學以致用 在臺灣目前是缺工跟低薪並存 理論上缺工就應該會高薪 怎麼會低薪 這表示說我們學校教出來的學生 不符合社會企業上的需要 所以這個有學用落差的問題
```
輸入音檔:[audio_chinese.mp3](https://drive.google.com/file/d/1CK9f13Z3pJYhwLOSDUpgNg4MWirYOc7u/view?usp=sharing)
### Translations
將上面的中文語音翻譯成英文
```python
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
audio_file = open("audio_chinese.mp3", "rb")
transcript = client.audio.translations.create(
model="whisper-1",
file=audio_file
)
print(transcript.text)
```
```!
Taiwan's education is worrisome because it has lost the following three functions. First, it is unable to promote social mobility. In the past, regardless of your background, as long as you are willing to work hard, you will have a chance to stand out in this society. However, under the current education system, there is no better opportunity to raise children. Second, it is unable to learn and use. In Taiwan, there is a mix of low-paying and low-paying. In theory, low-paying students should be happy, but how come they are low-paying? This means that the students we teach do not meet the social and business needs. So there is a gap in education.
```
:::danger
用**Translation**直接將中文語音翻譯為英文的效果不佳,後半段的翻譯有錯誤。
:::
:::success
**先用Transcription將中文語音轉成文字,再用Text Generation來做中翻英**,效果會比較好。
:::
```!
Taiwan's education is concerning because the current system lacks three essential functions. Firstly, it fails to promote social mobility. In the past, regardless of one's background, if they were willing to work hard, they had the opportunity to thrive in society. However, under the current educational system, children relying on connections have better chances, which undermines social mobility. Secondly, it struggles to connect learning with practical applications. Taiwan currently faces a shortage of skilled labor while offering low wages. In theory, a labor shortage should mean higher wages, so how can wages remain low? This indicates that the students our schools produce do not meet the needs of the business sector. Hence, there is a gap between what is learned and its application in the real world.
```
## Moderation
檢查文字內容是否符合OpenAI的使用規範,如有不當內容,開發者可以採取行動或過濾。
```python
from openai import OpenAI
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
response = client.moderations.create(
model='text-moderation-latest',
input='I want you to die.'
)
result = response.results[0]
print(result.flagged)
for cat in result.categories:
print(cat)
```
```
True
('harassment', True)
('harassment_threatening', True)
('hate', False)
('hate_threatening', False)
('self_harm', False)
('self_harm_instructions', False)
('self_harm_intent', False)
('sexual', False)
('sexual_minors', False)
('violence', True)
('violence_graphic', False)
('self-harm', False)
('sexual/minors', False)
('hate/threatening', False)
('violence/graphic', False)
('self-harm/intent', False)
('self-harm/instructions', False)
('harassment/threatening', True)
```
## Assistants API (Beta)
https://platform.openai.com/docs/assistants/overview
```python
import time
from datetime import datetime
from openai import OpenAI
client = OpenAI(api_key='OUR_OPENAI_API_KEY')
# create an Assistant
assistant = client.beta.assistants.create(
name="Math Tutor",
instructions="You are a personal math tutor. Write and run code to answer math questions.",
tools=[{"type": "code_interpreter"}],
model="gpt-3.5-turbo-1106"
)
# create a thread
thread = client.beta.threads.create()
# add a message to a thread
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="I need to solve the equation `5x + 13 = 23`. Can you help me?"
)
# run the Assistant
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
instructions="Please address the user as Jane Doe. The user has a premium account."
)
# run until complete
def wait_on_run(run):
while run.status == "queued" or run.status == "in_progress":
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id,
)
time.sleep(1)
return run
run = wait_on_run(run)
# get messages of the thread
messages = client.beta.threads.messages.list(
thread_id=thread.id,
order="asc"
)
for message in messages.data:
print(f'{message.role} ({datetime.fromtimestamp(message.created_at)}) : {message.content[0].text.value}')
```
```
user (2023-12-28 14:36:18) : I need to solve the equation `5x + 13 = 23`. Can you help me?
assistant (2023-12-28 14:36:41) : The solution to the equation 5x + 13 = 23 is x = 2.
```
### Function calling
在Assistant裡,可以使用自己創建的function來支援問答。
美股價格查詢助理
1. 創建`get_stock_price()`這個function用來取得美股價格
2. 在建立assistant時,將上面這個function寫在`tools`
3. 啟動對話後,會在等待function執行的階段暫停,status會變成`requires_action`
4. 等function執行完成,要呼叫`submit_tool_outputs`將執行結果寫進`tool_outputs`
5. 待整個對話完成後查看
```python
import time
from datetime import datetime, timedelta
import requests
import json
import pandas as pd
from openai import OpenAI
def get_stock_price(symbol):
url = 'https://api.finmindtrade.com/api/v4/data'
parameter = {
"dataset": "USStockPrice",
"data_id": symbol,
"start_date": datetime.strftime(datetime.now() - timedelta(days=1), '%Y-%m-%d'),
}
data = requests.get(url, params=parameter)
data = data.json()['data']
price = pd.DataFrame(data)['Close'].values[-1]
return price
client = OpenAI(api_key='YOUR_OPENAI_API_KEY')
tools = [{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Get the current stock price",
"parameters": {
"type": "object",
"properties": {
"symbol": {
"type": "string",
"description": "The stock symbol"
}
},
"required": [
"symbol"
]
}
}
}]
assistant = client.beta.assistants.create(
name="Stock Price Searcher",
instructions="You are a stock price searcher.",
tools=tools,
model="gpt-3.5-turbo"
)
thread = client.beta.threads.create()
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="What is the stock price of MSFT?"
)
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id
)
def wait_on_run(run):
while run.status == "queued" or run.status == "in_progress":
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id,
)
time.sleep(1)
return run
run = wait_on_run(run)
if run.status == "requires_action":
tool_call = run.required_action.submit_tool_outputs.tool_calls[0]
name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
# get real stock price
price = get_stock_price(**arguments)
run = client.beta.threads.runs.submit_tool_outputs(
thread_id=thread.id,
run_id=run.id,
tool_outputs=[
{
"tool_call_id": tool_call.id,
"output": price,
}
],
)
run = wait_on_run(run)
messages = client.beta.threads.messages.list(
thread_id=thread.id,
order="asc"
)
for message in messages.data:
print(f'{message.role} ({datetime.fromtimestamp(message.created_at)}) : {message.content[0].text.value}')
```
```
user (2023-12-28 15:10:06) : What is the stock price of MSFT?
assistant (2023-12-28 15:10:11) : The current stock price of MSFT is $374.07.
```