AI大模型-流式处理 (以百度接口为例)

No bb , show code

效果

后端代码

python 复制代码
from flask import Flask, request, Response
import json
import requests
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

def get_access_token(ak, sk):
    auth_url = "https://aip.baidubce.com/oauth/2.0/token"
    resp = requests.get(auth_url, params={"grant_type": "client_credentials", "client_id": ak, 'client_secret': sk})
    return resp.json().get("access_token")

def get_stream_response(prompt):
    ak = "你的AK"
    sk = "你的SK"
    source = "&sourceVer=0.0.1&source=app_center&appName=streamDemo"
    # ERNIE-Bot-turbo
    base_url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant"
    # ERNIE-Bot 4.0
    # base_url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro"
    # base_url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/plugin/57wt8rb5b3kzhnrd"
    url = base_url + "?access_token=" + get_access_token(ak, sk) + source
    data = {
        "messages": [{"role": "user", "content": prompt}],
        "stream": True
    }
    payload = json.dumps(data)
    headers = {'Content-Type': 'application/json'}
    return requests.post(url, headers=headers, data=payload, stream=True)

def gen_stream(prompt):
    response = get_stream_response(prompt)
    for chunk in response.iter_lines():
        chunk = chunk.decode("utf8")
        if chunk[:5] == "data:":
            chunk = chunk[5:]
        yield chunk

@app.route('/eb_stream', methods=['POST'])
def eb_stream():
    body = request.json
    prompt = body.get("prompt")
    return Response(gen_stream(prompt), mimetype='text/event-stream')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)

前端代码

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sample</title>
</head>
<body>
  <label for="textInput">Prompt:</label>
  <input type="textarea" id="textInput" placeholder="您有什么问题">
  <button onclick="run_prompt()">执行prompt</button>
  <p><textarea id="answer" rows="10" cols="50" readonly></textarea></p>
<script>
  current_text = document.getElementById('answer');
  text = "";
  char_index = 0
  function run_prompt() {
    var inputValue = document.getElementById('textInput').value;
    document.getElementById('answer').value = "";
    // 调用服务端的流式接口, 修改为自己的服务器地址和端口号
    fetch('http://127.0.0.1:8000/eb_stream', {
      method: 'post',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({'prompt': inputValue})
    })
    .then(response => {
      return response.body;
    })
    .then(body => {
      const reader = body.getReader();
      const decoder = new TextDecoder();
      function read() {
        return reader.read().then(({ done, value }) => {
          if (done) { // 读取完成
            return;
          }
          data = decoder.decode(value, { stream: true });
          text += JSON.parse(data).result;
          type();  // 打字机效果输出
          return read();
        });
      }
      return read();
    })
    .catch(error => {
      console.error('发生错误:', error);
    });
  }

  function type() {
    let enableCursor = true;  // 启用光标效果
    if (char_index < text.length) {
      let txt = document.getElementById('answer').value;
      let cursor = enableCursor ? "|" : "";
      if (enableCursor && txt.endsWith("|")) {
        txt = txt.slice(0, -1);
      }
      document.getElementById('answer').value = txt + text.charAt(char_index) + cursor;
      char_index++;
      setTimeout(type, 1000/5);  // 打字机速度控制, 每秒5个字
    }
  }
</script>
</body>
</html>
相关推荐
科研小牛马2 分钟前
北航何静:Codex调用SketchUp实操,常见智能体均适用
人工智能
机器人梦想家4 分钟前
【AI工具】Task Kit:把 Spec Kit 的契约化思想搬来管日常工作
人工智能
ck0135795 分钟前
图片抠图怎么做?从背景去除到透明 PNG 的实用教程
人工智能·测试工具·音视频·媒体·视频
美狐美颜sdk13 分钟前
直播APP接入第三方视频美颜SDK安全吗?数据处理与隐私问题分析
人工智能·音视频·美颜sdk·第三方美颜sdk·视频美颜sdk·美颜api
liferecords15 分钟前
Xiaomi-OCR-0:小米把 1.7 亿样本灌进 0.8B 小模型,文档解析和 OCR 问答一把抓
人工智能·大模型·ocr·多模态
全栈开发圈15 分钟前
新书速览|让AI推荐你的品牌:GEO营销实践
人工智能
weixin_5118404716 分钟前
2026年10月14日 Cisco and Nvidia 联合 USFP 调研报告
网络·人工智能·市场分析
智圣新创0117 分钟前
消解教学质控供需错配:智圣新创AI智慧教学与督导管理平台全域效能升级建设指南
人工智能
霸道流氓气质22 分钟前
AI智能博客平台实战:RAG增强写作、多Agent协作与语义检索的Vue3 + Spring AI全栈实现
java·人工智能·spring
ting945200023 分钟前
Monid 深度技术解析:面向 AI 智能体的统一工具路由网关实现与工程实践
人工智能·架构