纯前端接入deepseek api
【代码】纯前端接入deepseek api。
·
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>纯前端 OpenAI Chat</title>
</head>
<body>
<input type="text" id="apiKey" placeholder="输入你的 API Key" style="width: 300px;" /><br/><br/>
<textarea id="input" rows="3" cols="40" placeholder="输入你的问题"></textarea><br/>
<button id="sendBtn">发送</button>
<div id="output" style="white-space: pre-wrap; border: 1px solid #ccc; padding: 10px; margin-top: 10px;"></div>
<script>
document.getElementById("sendBtn").onclick = async () => {
const apiKey = document.getElementById("apiKey").value.trim();
const input = document.getElementById("input").value.trim();
const output = document.getElementById("output");
output.textContent = "";
if (!apiKey) return alert("请输入 API Key");
if (!input) return alert("请输入内容");
const response = await fetch("https://api.deepseek.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "deepseek-chat",
messages: [
{ role: "system", content: "你是一个有帮助的助手。" },
{ role: "user", content: input }
],
stream: true
})
});
if (!response.ok) {
output.textContent = `错误: ${response.status} ${response.statusText}`;
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
for (const line of lines) {
if (line.startsWith("data: ")) {
const data = line.slice(6);
if (data === "[DONE]") return;
try {
const json = JSON.parse(data);
const delta = json.choices?.[0]?.delta?.content;
if (delta) output.textContent += delta;
} catch (e) {
console.warn("解析出错", e);
}
}
}
buffer = lines[lines.length - 1];
}
};
</script>
</body>
</html>
更多推荐


所有评论(0)