目前百度文心一言的內(nèi)測資格申請相當(dāng)拉胯,提交申請快3個月,無任何音訊。不知道要等到什么時候。
百度適時開放了百度文心千帆大模型平臺,目前可以提交申請測試,貌似通過的很快,已取得測試申請資格,可以用起來。
申請測試網(wǎng)址
獲得測試資格后的頁面是這樣的:
點(diǎn)擊立即使用,可以在線測試:
使用千帆大模型API
點(diǎn)擊主頁右上角,控制臺,進(jìn)入百度云控制臺,創(chuàng)建應(yīng)用:
之后就可以得到調(diào)用API的 AppID,APIKey,SecretKey。API調(diào)用時,主要使用APIKey,SecretKey。
目前贈送代金券,測試用足夠了,按調(diào)用次數(shù)收費(fèi)。
API調(diào)用測試第一步:取得access_token
這里根據(jù)網(wǎng)友的代碼用于測試,有修改。
原始代碼參考-百度:文心千帆 網(wǎng)頁搭建和示例測評
假設(shè)調(diào)用ERNIE-Bot-turbo:
官方幫助文檔見:ERNIE-Bot-turbo
請求地址: https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant
請求方式: POST
access_token有效性測試(基于python):
# 填充API Key與Secret Key
import requests
import json
def main(APIKey,SecretKey):
url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APIKey+"&client_secret="+SecretKey
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__':
APIKey="6bWN69CoTBjgC**********" # 填入平臺申請的實(shí)際APIKey
SecretKey="wy1nU8UrnePKWm0***************" # 填入平臺申請的實(shí)際SecretKey
access_token = main(APIKey,SecretKey)
print(access_token)
如果打印得到access_token,則證明相關(guān)參數(shù)無誤:
可進(jìn)行下一步對話測試。
大模型回答測試代碼
import requests
import json
def get_access_token(APIKey, SecretKey):
"""
使用 API Key,Secret Key 獲取access_token,替換下列示例中的應(yīng)用API Key、應(yīng)用Secret Key
"""
url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APIKey+"&client_secret="+SecretKey
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(APIKey, SecretKey):
url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=" + get_access_token(APIKey, SecretKey)
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__':
APIKey="6bWN69CoTBjgC**********" # 填入平臺申請的實(shí)際APIKey
SecretKey="wy1nU8UrnePKWm0***************" # 填入平臺申請的實(shí)際SecretKey
main(APIKey, SecretKey)
大模型回復(fù)示例如下:
基于Flask輕量化工具測試
編寫app.py
from flask import Flask, render_template, request, jsonify, make_response
import requests
import uuid
app = Flask(__name__)
# 替換成您的API Key和Secret Key
API_KEY="6bWN69CoTBjgC**********" # 填入平臺申請的實(shí)際APIKey
SECRET_KEY="wy1nU8UrnePKWm0***************" # 填入平臺申請的實(shí)際SecretKey
# 獲取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():
# 從前端獲取用戶輸入的對話內(nèi)容和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})
# 調(diào)用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)
在app.py的同級目錄下,建立目錄templates,用來存放訪問頁面文件index.html。文章來源:http://www.zghlxwxcb.cn/news/detail-616913.html
index.html內(nèi)容:
<!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()">發(fā)送</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>
運(yùn)行app.py,本地客戶端運(yùn)行,本地訪問地址及端口:
瀏覽器中打開地址:http://127.0.0.1:1333/,打開index.html,顯示交互界面:
可以輸入信息,調(diào)用api進(jìn)行交互。文章來源地址http://www.zghlxwxcb.cn/news/detail-616913.html
到了這里,關(guān)于學(xué)習(xí)筆記|百度文心千帆大模型平臺測試及頁面交互簡易代碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!