百度:文心千帆 网页搭建和示例测评

文章目录

官方文档

csharp 复制代码
https://cloud.baidu.com/doc/WENXINWORKSHOP/s/flfmc9do2

按照这个操作进行创建一个应用:

代码示例

token获取

csharp 复制代码
# 填充API Key与Secret Key
import requests
import json


def main():
        
    url = "https://aip.baidubce.com/oauth/2.0/token?client_id=【API Key】&client_secret=【Secret Key】&grant_type=client_credentials"
    
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    return response.json().get("access_token")
    

if __name__ == '__main__':
    access_token = main()
    print(access_token)

流式回答

csharp 复制代码
import requests
import json

def get_access_token():
    """
    使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
    """
        
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
    
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def main():
        
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/bloomz_7b1?access_token=" + get_access_token()
    
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "给我推荐一些自驾游路线"
            }
        ],
         "stream": True
    })
    headers = {
        'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    print(response.text)
    

if __name__ == '__main__':
    main()

官网完整示例

csharp 复制代码
# coding=gbk

import requests
import json


def get_access_token():
    """
    使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
    """

   url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
    

    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")


def chat():
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/bloomz_7b1?access_token=" + get_access_token()

    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "鲁迅和周树人是同一个人吗?"
            }
        ],
        "stream": True
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    print(response.text)

if __name__ == '__main__':
    chat()

回答如下:

csharp 复制代码
data: {"id":"as-8pi6hewpi6","object":"chat.completion","created":1690278115,"sentence_id":0,"is_end":false,"is_truncated":false,"result":"不是。鲁迅和周树人虽然都是著名的文学家,但他们是不同的人。鲁迅是现代文学史上的重要人物,他的作品具有思想性和艺术性,代表作品有《狂人日记》、《阿Q正传》、《","need_clear_history":false,"usage":{"prompt_tokens":12,"completion_tokens":66,"total_tokens":78}}

data: {"id":"as-8pi6hewpi6","object":"chat.completion","created":1690278115,"sentence_id":1,"is_end":true,"is_truncated":false,"result":"呐喊》等。而周树人则是现代文学史上的著名诗人,他的作品以抒情为主,代表作品有《离骚》、《望岳》等。","need_clear_history":false,"usage":{"prompt_tokens":12,"completion_tokens":39,"total_tokens":117}}

制作一个网页端

index.html如下:

csharp 复制代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>百度千帆</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        #chat-container {
            display: flex;
            flex-direction: column;
            height: 80vh;
            width: 50%;
            margin: auto;
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 10px;
        }

        #chat-history {
            flex-grow: 1;
            overflow-y: auto;
            margin-bottom: 10px;
        }

        #user-input {
            flex-grow: 0;
            margin-right: 10px;
        }

        h1 {
            text-align: center;
        }

        .send {
           text-align: center;
        }
    </style>
    <script src="https://www.hyluz.cn/marked.min.js"></script>
</head>
<body>
<h1>百度千帆</h1>
<div id="chat-container">
    <div id="chat-history"></div>
    <div class="send">
        <input type="text" id="user-input" placeholder="输入您的消息..."/>
        <button id="send-button" onclick="sendMessage()">发送</button>
    </div>
</div>

<script>
    const chatHistory = document.getElementById("chat-history");
    const userInput = document.getElementById("user-input");
    userInput.addEventListener("keydown", function (e) {
        if (e.key === "Enter") {
            e.preventDefault();
            sendMessage();
        }
    });

    function getCookie(name) {
        const value = "; " + document.cookie;
        const parts = value.split("; " + name + "=");
        if (parts.length === 2) return parts.pop().split(";").shift();
    }

    function addMessageToChatHistory(role, message) {
        const messageElement = document.createElement("div");
        messageElement.className = role;
        messageElement.innerHTML = marked.parse(message);
        chatHistory.appendChild(messageElement);
        chatHistory.scrollTop = chatHistory.scrollHeight;
    }

    function sendMessage() {
        const userMessage = userInput.value.trim();
        if (!userMessage) {
            return;
        }

        const userId = getCookie("sessionid");

        addMessageToChatHistory("user", "用户: " + userMessage);

        fetch("/chat", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({"user_id": userId, "user_input": userMessage}),
        })
            .then(response => response.json())
            .then(data => {
                const botResponse = data.response;
                addMessageToChatHistory("assistant", "百度AI: " + botResponse);
            })
            .catch(error => {
                console.error("Error:", error);
            });

        userInput.value = "";
    }
</script>
</body>
</html>

app.py如下:

csharp 复制代码
from flask import Flask, render_template, request, jsonify, make_response
import requests
import uuid

app = Flask(__name__)

# 替换成您的API Key和Secret Key
API_KEY = ""
SECRET_KEY = ""

# 获取access_token
TOKEN_URL = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_KEY}&client_secret={SECRET_KEY}"
response = requests.get(TOKEN_URL)
ACCESS_TOKEN = response.json()["access_token"]

# 定义ERNIE-Bot聊天接口地址
CHAT_API_URL = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token={ACCESS_TOKEN}"
user_chat_histories = {}


@app.route("/")
def index():
    sessionid = str(uuid.uuid4())[:16]
    resp = make_response(render_template("index.html"))
    resp.set_cookie("sessionid", sessionid)
    return resp


@app.route("/chat", methods=["POST"])
def chat_with_ernie_bot():
    # 从前端获取用户输入的对话内容和sessionid
    user_id = request.cookies.get("sessionid")
    user_input = request.json["user_input"]
    # 获取该用户的对话历史,如果用户是首次对话,则新建一个空列表作为其对话历史
    user_history = user_chat_histories.get(user_id, [])

    # 将用户输入添加到对话历史中
    user_history.append({"role": "user", "content": user_input})
    # 调用ERNIE-Bot聊天接口
    headers = {"Content-Type": "application/json"}
    data = {"messages": user_history}
    response = requests.post(CHAT_API_URL, headers=headers, json=data)
    result = response.json()["result"]
    print(result)
    user_history.append({"role": "assistant", "content": result})
    user_chat_histories[user_id] = user_history
    return jsonify({"response": result})


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=1333, debug=False)

经典问题回答能力:

代码能力:

路还长,慢慢来吧~

相关推荐
诗句藏于尽头7 小时前
基于百度飞桨paddle的paddlepaddle2.4.2等系列项目的运行
百度·paddlepaddle·paddle
陈思杰系统思考Jason12 小时前
系统思考—深层结构
百度·微信·微信公众平台·新浪微博·微信开放平台
一叶飘零_sweeeet1 天前
Dubbo 构建高效分布式服务架构
分布式·架构·dubbo
生命几十年3万天1 天前
百度的面试
百度·面试·职场和发展
Zilliz Planet4 天前
聊一聊:ChatGPT搜索引擎会取代谷歌和百度吗?
百度·chatgpt
webfunny20204 天前
前端埋点系统之如何用heatmap.js画网页热力图
前端·javascript·dubbo
菜鸟起航ing6 天前
Apache Dubbo (RPC框架)
rpc·apache·dubbo
飞升不如收破烂~6 天前
包括 Nginx、Gateway、Nacos、Dubbo、Sentinel、RocketMQ 和 Seata 的调用链路描述:
nginx·gateway·dubbo
飞桨PaddlePaddle7 天前
飞桨首创 FlashMask :加速大模型灵活注意力掩码计算,长序列训练的利器
人工智能·百度·paddlepaddle·飞桨
博洋科技7 天前
百度搜索引擎的工作原理
搜索引擎·百度·网站建设·保定响应式网站建设·保定h5网站建设·保定网站建设