o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
流式数据第一包中role值为"assistant",且content值为空 后续的流式中间包role值为空,且content值不为空 请求参数中的ID和响应参数的ID为同一ID…
- User
流式数据第一包中role值为"assistant",且content值为空 后续的流式中间包role值为空,且content值不为空 请求参数中的ID和响应参数的ID为同一ID
根据以上文档修改此代码: import time
from flask import Flask, request, Response import requests import json
app = Flask(name)
FastGPT 的 URL
FASTGPT_URL = 'https://xyai.cloud/api/v1/chat/completions'
FastGPT 的授权头
FASTGPT_AUTH_HEADER = { 'Authorization': 'Bearer openapi-uahpmhgrpdvxjPwZQhNSEwhPW86MVWf7AZYL2iJwojouC3UTwZ9OouwGUFL', 'Content-Type': 'application/json' }
@app.route('/api/robot', methods=['POST']) def robot_endpoint(): try: # 获取机器人请求的参数 robot_request = request.json
code# 构建 FastGPT 请求的参数 fastgpt_request = { 'chatId': robot_request['id'], # 使用机器人的请求 ID 作为 chatId 'stream': True, 'detail': False, 'variables': {}, # 根据需要添加变量 'messages': robot_request['messages'] } start_time = time.time() # 发送请求到 FastGPT fastgpt_response = requests.post(FASTGPT_URL, json=fastgpt_request, headers=FASTGPT_AUTH_HEADER, stream=True) # 设置响应头,使用 SSE 协议 def generate(): id_counter = 1 for line in fastgpt_response.iter_lines(): if line: # 解析 FastGPT 的响应 decoded_line = line.decode('utf-8') if decoded_line.startswith('data:'): try: data = json.loads(decoded_line[5:]) # 使用机器人传入的 id data['id'] = robot_request['id'] # 设置 model 为 "希言大模型" data['model'] = "希言大模型" # 为每个响应块生成一个唯一的 id unique_id = f"test_id_{id_counter}" id_counter += 1 # 构建 SSE 格式的响应,确保非 ASCII 字符不被转换为 Unicode 编码 sse_response = f"id: {unique_id}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n" yield sse_response except json.JSONDecodeError as e: print(f"Error decoding JSON: {e}") print(f"Line: {decoded_line}") end_time = time.time() print(f"Total Response Time: {end_time - start_time:.2f} seconds") return Response(generate(), content_type='text/event-stream') except Exception as e: print('Error:', e) return Response('Internal Server Error', status=500) - Assistant