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>
相关推荐
万物智能信息科技14 小时前
LVDS屏幕输出桌面—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
人工智能·华为·开源·harmonyos·鸿蒙
高升说14 小时前
手眼 3D 相机选型:先定工作距离,再谈精度,最后定安装
人工智能·数码相机·3d
张彦峰ZYF14 小时前
从会话工具到常驻执行系统:重新理解 Prime Agent 的 RLM、Continual Harness 与长程 Agent 工程化
人工智能·ai agent·harness·openhands·智能体评测·prime agent·swe-agent
音视频牛哥14 小时前
从视频接入到灵活转推:SmartMediaKit 跨平台 RTSP 转RTMP 技术解析
人工智能·音视频·rtsp转rtmp·跨平台音视频sdk·边缘视频网关·多路视频转发·多路rtsp流转rtmp推送
海宇服务14 小时前
零信任架构实战:基于海宇天远入职背调报告构建自动化微服务准入网关
人工智能·微服务·架构·自动化
外域速览14 小时前
亚马逊600亿美元押注高通AI芯片
人工智能
71777714 小时前
开源代码审计平台推荐:Gitee 在企业代码审计流程中的定位与选型建议
人工智能·gitee
大模型任我行14 小时前
Meta:AI让推荐系统自动化持续优化
人工智能·语言模型·自然语言处理·论文笔记
wordbaby14 小时前
TF-IDF 是什么?从零理解检索算法的核心直觉
人工智能
七爷数码AI14 小时前
语音合成工具提升声音自然度的七步闭环调优方案
人工智能