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

文章目录

官方文档

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)

经典问题回答能力:

代码能力:

路还长,慢慢来吧~

相关推荐
刘Java6 小时前
Dubbo 3.x源码(28)—Dubbo服务发布导出源码(7)应用级服务接口元数据发布
java·dubbo·dubbo源码
陈思杰系统思考Jason19 小时前
系统思考—全局思维
百度·微信·微信公众平台·新浪微博·微信开放平台
QQ同步助手2 天前
如何正确使用人工智能:开启智慧学习与创新之旅
人工智能·学习·百度
刘Java3 天前
Dubbo 3.x源码(26)—Dubbo服务引用源码(9)应用级服务发现订阅refreshServiceDiscoveryInvoker
java·dubbo·dubbo源码
正在走向自律3 天前
AI Agent案例全解析:百度营销智能体(8/30)
人工智能·百度·ai agent·工作流模式
小风来临的时候5 天前
手机银行模拟器,一款高仿真银行app的模拟器,可以修改姓名 卡号 余额 做转账记录 做流水
笔记·百度·微信小程序·小程序·百度小程序
百度智能云5 天前
百度智能云千帆AppBuilder升级,百度AI搜索组件上线,RAG支持无限容量向量存储!
人工智能·百度
kaoyaoyao5 天前
打通全网SEO优化:提高百度、B站、抖音等平台搜索排名
大数据·百度·seo·公众号排名优化·公众号排名
lin_AIOS7 天前
OpenAI 发布会 9 天技术总结
人工智能·百度
陈思杰系统思考Jason7 天前
系统思考—持续修炼
百度·微信·微信公众平台·新浪微博·微信开放平台