场景:类似ChatGPT的逐字显示效果。
流程:服务端我用Python的flask框架(向外提供API接口)实现,服务部署在replit上,Python调用azure 的chatgpt服务(需要申请),并以流式的形式返回,小程序再调用这个流式接口实现。
我会提供最小能运行的完整代码示例。
我本地的Python版本:3.10.11、Flask版本:2.3.2、openai版本:0.27.8。
python部分:
/main.py:
from data.chat_completion import ChatCompletion
@app.route("/chat", methods=['POST'])
@log_streaming_request
def love_chat():
message_list = request.json.get('message_list', [])
message = []
message.extend(message_list)
try:
response = ChatCompletion().create(message, True)
def generate():
for chunk in response:
if not chunk['id']:
continue
if 'delta' in chunk["choices"][0] and 'content' in chunk['choices'][0]['delta']:
yield chunk['choices'][0]['