Fetch the repository succeeded.
const fs = require('fs').promises;
const readline = require('readline');
const axios = require('axios');
const moment = require('moment');
class DeepSeekChat {
constructor() {
this.url = 'https://api.siliconflow.cn/v1/chat/completions';
this.apiKey = 'Your-Api-Key'; // 替换为你的 API Key,如何获取自己的 API Key? 在文章下面有链接
this.logFile = 'conversation.txt';
}
async saveToFile(content, isQuestion = false) {
const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
const text = isQuestion
? `\n[${timestamp}] Question:\n${content}\n\n[${timestamp}] Answer:\n`
: content;
await fs.appendFile(this.logFile, text);
}
async chat() {
// 创建命令行接口
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// 使用 Promise 封装问题输入
const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
try {
while (true) {
const userInput = await question('\n请输入您的问题 (输入 q 退出): ');
if (userInput.trim().toLowerCase() === 'q') {
console.log('程序已退出');
break;
}
// 保存问题
await this.saveToFile(userInput, true);
// 准备请求数据
const data = {
model: 'deepseek-ai/DeepSeek-V3',
messages: [
{
role: 'user',
content: userInput
}
],
stream: true,
max_tokens: 2048,
temperature: 0.7,
top_p: 0.7,
top_k: 50,
frequency_penalty: 0.5,
n: 1,
response_format: {
type: 'text'
}
};
try {
// 发送流式请求
const response = await axios({
method: 'post',
url: this.url,
data: data,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
responseType: 'stream'
});
// 处理流式响应
response.data.on('data', async (chunk) => {
const lines = chunk.toString().split('\n');
for (const line of lines) {
if (line.trim() === '') continue;
if (line.trim() === 'data: [DONE]') continue;
if (line.startsWith('data: ')) {
try {
const json = JSON.parse(line.slice(6));
if (json.choices[0].delta.content) {
const content = json.choices[0].delta.content;
process.stdout.write(content);
await this.saveToFile(content);
}
} catch (e) {
continue;
}
}
}
});
// 等待响应完成
await new Promise((resolve) => {
response.data.on('end', async () => {
console.log('\n----------------------------------------');
await this.saveToFile('\n----------------------------------------\n');
resolve();
});
});
} catch (error) {
const errorMsg = `请求错误: ${error.message}\n`;
console.error(errorMsg);
await this.saveToFile(errorMsg);
}
}
} finally {
rl.close();
}
}
}
// 运行程序
async function main() {
const chatbot = new DeepSeekChat();
await chatbot.chat();
}
main().catch(console.error);
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。