https://cloud.baidu.com/doc/WENXINWORKSHOP/s/flfmc9do2
# 填充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)
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()
# 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()
回答如下:
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如下:
<!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如下:
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)