
如何快速實(shí)現(xiàn)REST API集成以?xún)?yōu)化業(yè)務(wù)流程
OpenAI 最新的開(kāi)發(fā)為我們帶來(lái)了?實(shí)時(shí) API,旨在允許開(kāi)發(fā)者在他們的應(yīng)用中創(chuàng)建?快速、無(wú)縫的語(yǔ)音到語(yǔ)音體驗(yàn)。該 API 旨在簡(jiǎn)化多模態(tài)對(duì)話(huà)功能的開(kāi)發(fā),使構(gòu)建自然的實(shí)時(shí)語(yǔ)音交互變得更加容易。
在這篇博客中, 我將涵蓋有關(guān)此新 API 的 主要問(wèn)題,包括
實(shí)時(shí) API 是 OpenAI 提供的公共測(cè)試功能,允許付費(fèi)開(kāi)發(fā)者在他們的應(yīng)用中集成實(shí)時(shí)語(yǔ)音交互。它是一個(gè)多模態(tài) API,能夠?qū)?nbsp;音頻輸入轉(zhuǎn)換為語(yǔ)音響應(yīng),并使用先進(jìn)的 GPT-4o 模型來(lái)實(shí)現(xiàn)這一目的。本質(zhì)上,它允許進(jìn)行 低延遲對(duì)話(huà),類(lèi)似于自然的人際交互,類(lèi)似于 ChatGPT 的高級(jí)語(yǔ)音模式中看到的功能。
之前,開(kāi)發(fā)者需要將多個(gè)模型拼接在一起以實(shí)現(xiàn)?語(yǔ)音識(shí)別、文本處理和文本轉(zhuǎn)語(yǔ)音生成。實(shí)時(shí) API 將這一切都整合在一次 API 調(diào)用中,從而減少延遲,提供更豐富的響應(yīng),并更一致地處理口音和重音。
聊天完成 API 也引入了音頻輸入和輸出,但它沒(méi)有實(shí)時(shí) API 的低延遲體驗(yàn)。因此,對(duì)于語(yǔ)言學(xué)習(xí)或語(yǔ)音啟用助手等體驗(yàn),實(shí)時(shí) API 是更優(yōu)選擇。
對(duì) Realtime API 的訪(fǎng)問(wèn)目前作為 公開(kāi)測(cè)試版 提供給付費(fèi)開(kāi)發(fā)者。
雖然說(shuō)在歐洲的訪(fǎng)問(wèn)受到限制,但我通過(guò)我的第5層OpenAI賬戶(hù)能夠使用它。
該API使用 WebSocket 連接,確保音頻輸入和輸出的流暢體驗(yàn)。
目前,需要注意以下 限制:
定價(jià)結(jié)構(gòu)分為 文本令牌 和 音頻令牌:
這一定價(jià)使得開(kāi)發(fā)者能夠負(fù)擔(dān)得起創(chuàng)建強(qiáng)大的 語(yǔ)音到語(yǔ)音 體驗(yàn),盡管音頻功能的成本顯著高于基于文本的交互。在擴(kuò)展具有語(yǔ)音功能的應(yīng)用時(shí),這一點(diǎn)非常重要。
這仍然比外包給某些國(guó)家稍貴,但我們可以期待在接下來(lái)的六個(gè)月內(nèi)價(jià)格會(huì)顯著下降。
這是一個(gè)基本的?Colab 指南,幫助您開(kāi)始上傳文件、向 Realtime API 發(fā)送請(qǐng)求并生成音頻響應(yīng)。
在這個(gè)演示中,我們選擇上傳一系列音頻片段,以模擬對(duì)話(huà)。
完整的 Colab 代碼:?鏈接在這里,只需將您的 “openai” 密鑰添加到 Colab 的秘密中并運(yùn)行該 Colab。
#Setup
!pip install websockets pydub --quiet
import base64
import numpy as np
import soundfile as sf
import json
import websockets
from google.colab import files
from pydub import AudioSegment
from tqdm import tqdm
import io
在 Colab 中,您可以使用?google.colab?的?files
?模塊來(lái)上傳音頻文件。
#Upload audio
def upload_audio():
uploaded = files.upload()
for file_name in uploaded.keys():
return file_name
audio_file = upload_audio()
tqdm
顯示上傳流的進(jìn)度。#Helper functions
## Function to convert Float32Array to PCM16 format
def float_to_pcm16(float32_array):
return np.clip(float32_array * 32767, -32768, 32767).astype(np.int16).tobytes()
## Function to split audio into base64-encoded PCM16 chunks
def float32_to_base64_chunks(float32_array, chunk_size=32000):
pcm16_data = float_to_pcm16(float32_array)
for i in range(0, len(pcm16_data), chunk_size):
yield base64.b64encode(pcm16_data[i:i+chunk_size]).decode('utf-8')
## WebSocket connection and streaming audio with text prompt
## Main function to call OpenAI Realtime API
async def stream_audio_to_realtime_api(audio_file, text_prompt, openai_key, verbose = False):
data, samplerate = sf.read(audio_file, dtype='float32')
if data.ndim > 1:
data = data[:, 0]
if samplerate != 24000:
raise ValueError(f"Audio must be sampled at 24kHz, but it is {samplerate}Hz")
url = "wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01"
headers = {"Authorization": "Bearer " + openai_key, "OpenAI-Beta": "realtime=v1"}
async with websockets.connect(url, extra_headers=headers) as ws:
await ws.send(json.dumps({
"type": "conversation.item.create",
"item": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": text_prompt}]}
}))
with tqdm(total=(len(float_to_pcm16(data)) + 32000 - 1) // 32000, desc="Sending Audio Chunks") as pbar:
for chunk in float32_to_base64_chunks(data):
await ws.send(json.dumps({"type": "input_audio_buffer.append", "audio": chunk}))
pbar.update(1)
await ws.send(json.dumps({"type": "input_audio_buffer.commit"}))
await ws.send(json.dumps({"type": "response.create"}))
all_events = []
while True:
response = await ws.recv()
event = json.loads(response)
all_events.append(event)
if verbose:
print(event)
if event["type"] == "response.output_item.done" and "item" in event and "content" in event["item"]:
for content in event["item"]["content"]:
if content["type"] == "audio" and "transcript" in content:
transcript = content["transcript"]
break
if event["type"] == "rate_limits.updated":
break
return all_events, transcript
#Add a prompt and call OpenAI Realtime API
text_prompt = "Summarize this audio content"
events, transcript = await stream_audio_to_realtime_api(
audio_file,
text_prompt,
openai_key,
verbose = False
#to display OpenAI's response as they arrive, use verbose = True
)
## Function to decode and concatenate audio chunks into a full audio file
def generate_audio_from_chunks(audio_chunks, output_filename=None):
# Concatenate the base64-encoded audio chunks from the 'delta' field
full_audio_base64 = ''.join(audio_chunks)
# Decode the concatenated base64 string to raw PCM16 audio bytes
audio_bytes = base64.b64decode(full_audio_base64)
# Load the bytes as a pydub AudioSegment (assuming 24kHz, 1 channel, PCM16)
audio_segment = AudioSegment.from_raw(
io.BytesIO(audio_bytes),
sample_width=2,
frame_rate=24000,
channels=1)
# Optionally save the audio to a file
if output_filename:
audio_segment.export(output_filename, format="wav")
print(f"Audio saved to {output_filename}")
return audio_segment
#Extract audio chunks from the collected events
audio_output_chunks = [event['delta'] for event in events if event['type'] == 'response.audio.delta']
## Generate the full audio from the collected chunks
generated_audio = generate_audio_from_chunks(audio_output_chunks, output_filename="output_audioo.wav")
通過(guò)上述步驟,您可以將 OpenAI 的實(shí)時(shí) API 集成到 Colab 筆記本中,實(shí)現(xiàn)無(wú)縫的語(yǔ)音指令。
本指南應(yīng)為您提供一個(gè)堅(jiān)實(shí)的基礎(chǔ),以便您實(shí)驗(yàn)實(shí)時(shí)音頻到音頻的交互,并構(gòu)建創(chuàng)新的語(yǔ)音驅(qū)動(dòng)應(yīng)用程序。
文章轉(zhuǎn)自微信公眾號(hào)@barry的異想世界
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)