前期准备
先在火山引擎那创建一个自定义推理接入点,地址:https://console.volcengine.com/ark/region:ark+cn-beijing/endpoint?config=%7B%7D
再点击右边 操作 的 api接入,复制粘贴自己的
API Key
效果
然后就可以去调用接口了
可以用jq模拟的方式,但是不推荐这种方式,因为要等完整的回答太慢了
建议开启流式传输,用Fetch API 实现逐字输出
我的API Key虽然贴出来了,方便大家测试,但是不建议大家直接用我的
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>火山引擎豆包Dome</title>
</head>
<body>
<div id="chat-box"></div>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
<script>
// 官网的例子
// curl https://ark.cn-beijing.volces.com/api/v3/chat/completions \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer $ARK_API_KEY" \
// -d '{
// "model": "doubao-1-5-pro-32k-250115",
// "messages": [
// {"role": "system","content": "你是人工智能助手."},
// {"role": "user","content": "你好"}
// ]
// }'
// 具体对话
let data = {
model: "doubao-1-5-pro-32k-250115",
stream: true, // 流式传输
messages: [
{ role: "system", content: "你是人工智能助手." },
{ role: "user", content: "你好,我是前端开发,请问我怎么找工作?" },
],
};
// 1.jquery的调用方式,不行,必须关闭流式传输,最多只能等接口全部加载成功后通过计时器模拟,不能逐字输出
// let fullResponse = "";
// let charIndex = 0;
// $.ajax({
// type: "post",
// url: "https://ark.cn-beijing.volces.com/api/v3/chat/completions",
// dataType: "json",
// contentType: "application/json", // 明确指定内容类型
// headers: {
// Authorization: "Bearer b3025ba7-2241-4794-b983-5089b0719ea6",
// },
// data: JSON.stringify(data),
// success: (res) => {
// console.log(res);
// const text = res.choices[0].message.content;
// const timer = setInterval(() => {
// if (charIndex < text.length) {
// fullResponse += text.charAt(charIndex);
// $("#chat-box").text(fullResponse);
// charIndex++;
// } else {
// clearInterval(timer);
// }
// }, 50); // 每50毫秒输出一个字
// },
// });
// 2.Fetch API 实现逐字输出
const chatBox = document.getElementById("chat-box");
let fullMessage = "";
async function streamChat() {
const response = await fetch(
"https://ark.cn-beijing.volces.com/api/v3/chat/completions",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer b3025ba7-2241-4794-b983-5089b0719ea6",
},
body: JSON.stringify(data),
}
);
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) {
document.querySelector(".typing-cursor")?.remove();
break;
}
const chunk = decoder.decode(value);
chunk.split("\n").forEach((line) => {
if (line.startsWith("data: ")) {
try {
const data = JSON.parse(line.slice(6));
if (data.choices?.[0]?.delta?.content) {
fullMessage += data.choices[0].delta.content;
renderMessage(fullMessage);
}
} catch (e) {}
}
});
}
}
function renderMessage(text) {
chatBox.innerHTML = `
<div class="message">${text}</div>
<span class="typing-cursor"></span>
`;
chatBox.scrollTop = chatBox.scrollHeight;
}
streamChat();
</script>
</html>