千帆官网:https://console.bce.baidu.com/qianfan/overview
完成的demo:https://dog-tired.github.io/spage_ai/
这篇博客主要讲述使用千帆免费的大模型接口+简单的html页面创建一个AI问答机器人
平台能力
选择使用千帆的speed系列模型,免费对外开发
创建一个应用,重点关注API Key和 Secret Key,用来申请accessToken
创建自己应用并调用
模型服务>应用接入>创建应用
步骤:
- 创建一个应用
- 选定指定的大模型对应的接口
- 接口调用
curl --location --request GET 'https://aip.baidubce.com/oauth/2.0/token?client_id=dJUnpjhSdmNeXf9WKIw1o5tv&client_secret=CgbBfIfKXI7*****&grant_type=client_credentials' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Accept: */*' \
--header 'Host: aip.baidubce.com' \
--header 'Connection: keep-alive'
curl --location --request POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed?access_token=你的token' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Content-Type: application/json' \
--header 'Accept: */*' \
--header 'Host: aip.baidubce.com' \
--header 'Connection: keep-alive' \
--header 'Cookie: BAIDUID=A4B13A3A1D51C4DB2D2F76E1CD2EA3F2:FG=1' \
--data-raw '{
"messages": [
{
"role": "user",
"content": "写一个java程序,快速排序,要求可以运行"
}
],
"temperature": 0.95,
"top_p": 0.8,
"penalty_score": 1,
"disable_search": false,
"enable_citation": false,
"response_format": "text"
}'
手写一个应用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AI问答</title>
<script src="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script>
</head>
<body>
<div id="app">
<input type = "text" v-model = "input1">
<button @click="fetchData">AI回答</button>
<h2>回答: </h2>
<p>{{ message }}</p>
</div>
<script>
const app = {
data() {
return {
input1: '',
message: '你问,我答!'
}
},
methods: {
async fetchData() {
try {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Accept", "*/*");
myHeaders.append("Host", "aip.baidubce.com");
myHeaders.append("Connection", "keep-alive");
var raw = JSON.stringify({
"messages": [
{
"role": "user",
"content": this.input1 + ", 尽量简单陈述。"
}
],
"temperature": 0.95,
"top_p": 0.8,
"penalty_score": 1,
"disable_search": false,
"enable_citation": false,
"response_format": "text"
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
const response = await fetch(
'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed?access_token=自己的token',
requestOptions
);
if (!response.ok) {
// 检查响应是否成功
throw new Error('Network response was not ok');
}
const result = await response.json(); // 或者 response.json() 如果响应是 JSON
this.message = result["result"];
this.error = ''; // 清除之前的错误信息
} catch (error) {
// 处理任何在请求过程中抛出的错误
console.error('Error fetching data:', error);
this.error = error.message; // 将错误信息设置到组件的数据中
this.message = ''; // 清除之前的数据
}
},
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>
线上应用:https://dog-tired.github.io/spage_ai/