使用JavaScript进行API交互初探
本文介绍了使用JSON与DeepSeek API进行交互的实战项目。通过查看官方文档了解API规范,包括请求参数、响应格式和请求头要求。项目使用JavaScript的fetch方法实现网络通信,结合Node.js的readline模块实现了控制台多轮对话功能。代码示例展示了如何构建请求消息、获取AI回复并维持对话上下文。该项目验证了JSON在API数据交互中的实际应用价值,成功实现了一个简单的对话
前言
在学习json之后,使用一个项目进行实战检验十分有必要。json常用于API数据交互,而和DeepSeekAPI进行交互便可以十分直观地展示我们的成果。
注:本文目的在于汇报学习进度,故对于涉及的内容只作必要说明,不作详细解释
一、API
API,全称Application Programming Interface,直译“程序之间的接口”
API是软件系统中不同部分之间通信的一套规则。它定义了请求的格式、传输方式、数据结构和操作规则,使得不同的软件应用能够相互交互和数据交换。
简单来说,我们可以把API简单类比为一个函数的输入参数的规范,它约定了你该以什么样的数据结构对特定端点进行访问。
二、DeepSeekAPI
1.查看文档
在进行一切API的访问之前,一定要先清楚API规范。
我们要接入DeepSeekAPI,便需要去到官网查看官方的文档。
2.基础格式
通过查看文档,我们可以发现如下常用参数:
1.输入
model(deepseek-chat \ deepseek-reasoner)响应模型messages 存储聊天记录的数组,每个元素包含role(user \ assistant \ system)和contentmax_tokens限制响应的最大token数stream是否流式传输响应
完整示例:
{
"messages": [
{
"content": "You are a helpful assistant",
"role": "system"
},
{
"content": "Hi",
"role": "user"
}
],
"model": "deepseek-chat",
"frequency_penalty": 0,
"max_tokens": 4096,
"presence_penalty": 0,
"response_format": {
"type": "text"
},
"stop": null,
"stream": false,
"stream_options": null,
"temperature": 1,
"top_p": 1,
"tools": null,
"tool_choice": "none",
"logprobs": false,
"top_logprobs": null
}
2.输出
id当前对话的唯一标识符model生成响应的模型choices可选的响应usage统计token的使用
完整示例:
{
"id": "bf505be8-4ccf-49ae-b67e-8cb4ed271796",
"object": "chat.completion",
"created": 1762692592,
"model": "deepseek-chat",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I assist you today? 😊"
},
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 11,
"total_tokens": 21,
"prompt_tokens_details": {
"cached_tokens": 0
},
"prompt_cache_hit_tokens": 0,
"prompt_cache_miss_tokens": 10
},
"system_fingerprint": "fp_ffc7281d48_prod0820_fp8_kvcache"
}
3.请求头
我们可以了解到,该API需要以POST方法进行请求,请求体是一个json数据,而请求头需要
这里Authorization项后面需要填充秘钥。
三.实现代码
由于c语言对于网络通信的原生支持度不足,而libcurl库的使用又非常复杂,我索性选择了对于网络通信支持良好的JavaScript语言。
1.技术方案
因为本次只是进行演示,故使用原生的fetch方法进行API请求。fetch接受请求端口和请求内容(包含请求头和请求体)作为输入参数,返回一个Response类型数据。
function fetch(
input: string | URL | Request,
init?: RequestInit,
): Promise<Response>;
由于JavaScript对于纯本地环境的支持度不高,所以我们引入基于Node.js的readline读取用户在控制台的输入
2.实现
const apiKey = "[这里是你自己的apiKey]";
const readline = require('readline');
class Message {
constructor(role, content) {
this.role = role;
this.content = content;
}
}
const url = "https://api.deepseek.com/chat/completions";
const messages = [new Message("system", "你是DEEPSEEK,你需要做user友好的朋友。")];
// 创建readline接口
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
async function fun() {
const response = await fetch(url,
{
method:"POST",
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: "deepseek-chat",
messages: messages
})
});
const data = await response.json();
const aiReply = data.choices[0].message.content;
console.log('[DEEPSEEK]\n', aiReply);
messages.push(new Message("assistant", aiReply));
}
function askUser() {
rl.question("[USER]\n", async (userInput) => {
if(userInput === "exit") {
rl.close();
return;
}
messages.push(new Message("user", userInput));
await fun();
//使用递归进行多次提问
askUser();
});
}
askUser();
3.运行效果
[USER]
你好
[DEEPSEEK]
你好!很高兴见到你!有什么我可以帮你的吗?
[USER]
你是谁啊?
[DEEPSEEK]
我是DeepSeek,一个由深度求索公司创造的AI助手!很高兴认识你~我可以帮你回答问题、聊天、解决各种问题,就像你的智能小伙伴一样。有什么想聊的或者需要 帮助的吗?😊
[USER]
exit
总结
本项目成功实现了基于控制台的多轮对话机器人,验证了JSON在实际数据交互中的应用价值。
更多推荐

所有评论(0)