OpenAI 推出更低成本的语音模型API :gpt-4o-audio-preview (附代码)

科技   2024-11-04 21:36   福建  

OpenAI 推出了更低成本的语音模型API:

gpt-4o-audio-preview

价格:

我已经成功测试,附上代码给大家玩一下:

from flask import Flask, request, jsonify, url_forimport base64import openaiimport osimport uuid
app = Flask(__name__)
# 配置OpenAI的API密钥openai.api_key = "在这里填写OpenAI_API_KEY"
# 检查并创建 static 目录if not os.path.exists('static'): os.makedirs('static')
# 存储对话记录conversation_history = []
@app.route('/')def index(): return ''' <h1>GPT-4 Audio Web Application</h1> <form id="questionForm"> <label for="question">Enter your question:</label> <input type="text" id="question" name="question"> <button type="submit">Submit</button> </form> <div id="audioPlayer"> <h3>Response Audio:</h3> <ul id="audioList"></ul> </div> <script> document.getElementById('questionForm').addEventListener('submit', function(event) { event.preventDefault(); let formData = new FormData(this); fetch('/ask', { method: 'POST', body: formData }).then(response => response.json()) .then(data => { if (data.conversation_history) { let audioList = document.getElementById('audioList'); audioList.innerHTML = ''; // 清空列表 data.conversation_history.forEach(item => { let listItem = document.createElement('li'); let audioElement = document.createElement('audio'); audioElement.src = item.audio_url; audioElement.controls = true; listItem.textContent = item.question; listItem.appendChild(audioElement); audioList.appendChild(listItem); }); } else { alert('Error: ' + data.error); } }); }); </script> '''
@app.route('/ask', methods=['POST'])def ask_gpt(): try: # 获取用户输入的问题 question = request.form['question']
# 使用OpenAI API client = openai completion = client.ChatCompletion.create( model="gpt-4o-audio-preview", modalities=["text", "audio"], audio={"voice": "alloy", "format": "wav"}, messages=[ { "role": "user", "content": question } ] )
# 生成唯一的文件名 unique_filename = f"{uuid.uuid4()}.wav" audio_file_path = os.path.join('static', unique_filename)
# 提取音频数据并保存 wav_bytes = base64.b64decode(completion.choices[0].message['audio']['data']) with open(audio_file_path, "wb") as f: f.write(wav_bytes)
# 生成音频文件的URL audio_url = url_for('static', filename=unique_filename)
# 保存到对话历史 conversation_history.append({ "question": question, "audio_url": audio_url })
# 返回对话历史 return jsonify({"conversation_history": conversation_history})
except Exception as e: return jsonify({"error": str(e)}), 500
if __name__ == '__main__': app.run(debug=True)


本地运行,需要安装python及以下的库:

pip install Flask openai

运行:

python app.py


需要购买chatgpt api ,可以复制这个链接到浏览器:

https://aiapi.cxyquan.com

AI工具迷
搜罗全网好用的 AI 工具软件,手把手教你AI玩法变现实操教程
 最新文章