简介:本文详解如何通过Node.js快速接入Deepseek API,构建支持自然语言交互的命令行工具。涵盖环境配置、API调用、错误处理等核心环节,提供完整代码示例与调试技巧。
作为基于Chrome V8引擎的JavaScript运行时,Node.js 16+版本能完美支持异步API调用。建议通过nvm(Node Version Manager)进行版本管理:
# 安装nvm(Linux/macOS)curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash# 安装LTS版本Node.jsnvm install --ltsnvm use --lts
Windows用户可通过Node.js官网下载安装包,验证安装成功:
node -vnpm -v
创建项目目录并初始化npm:
mkdir deepseek-cli && cd deepseek-clinpm init -y
安装核心依赖包:
npm install axios dotenv readline-sync
axios:轻量级HTTP客户端,支持Promise APIdotenv:环境变量管理工具readline-sync:同步命令行交互库在项目根目录创建.env文件,存储认证信息:
DEEPSEEK_API_KEY=your_api_key_hereDEEPSEEK_ENDPOINT=https://api.deepseek.com/v1
通过dotenv加载环境变量:
require('dotenv').config();const { DEEPSEEK_API_KEY, DEEPSEEK_ENDPOINT } = process.env;
创建deepseekClient.js封装API调用逻辑:
const axios = require('axios');class DeepseekClient {constructor(apiKey, endpoint) {this.instance = axios.create({baseURL: endpoint,headers: {'Authorization': `Bearer ${apiKey}`,'Content-Type': 'application/json'}});}async chat(messages, model = 'deepseek-chat') {try {const response = await this.instance.post('/chat/completions', {model,messages,temperature: 0.7,max_tokens: 2000});return response.data.choices[0].message.content;} catch (error) {console.error('API Error:', error.response?.data || error.message);throw error;}}}module.exports = DeepseekClient;
实现用户输入处理逻辑:
const readlineSync = require('readline-sync');const DeepseekClient = require('./deepseekClient');const client = new DeepseekClient(process.env.DEEPSEEK_API_KEY,process.env.DEEPSEEK_ENDPOINT);async function main() {console.log('Deepseek AI 命令行工具 (输入exit退出)');const history = [{ role: 'system', content: '你是一个友好的AI助手' }];while (true) {const userInput = readlineSync.question('\n你: ');if (userInput.toLowerCase() === 'exit') break;history.push({ role: 'user', content: userInput });try {console.log('AI: 正在思考...');const response = await client.chat(history);history.push({ role: 'assistant', content: response });console.log(`AI: ${response.substring(0, 100)}${response.length > 100 ? '...' : ''}`);} catch (error) {console.error('交互失败:', error.message);}}}main().catch(console.error);
实现分级错误处理:
async function safeChat(client, messages) {try {return await client.chat(messages);} catch (error) {if (error.response?.status === 429) {console.warn('请求过于频繁,请稍后再试');await new Promise(resolve => setTimeout(resolve, 5000));return safeChat(client, messages);} else if (error.response?.status === 401) {throw new Error('认证失败,请检查API密钥');} else {throw error;}}}
async function cachedChat(client, messages) {
const cacheKey = JSON.stringify(messages);
const cached = cache.get(cacheKey);
if (cached) return cached;
const response = await client.chat(messages);
cache.set(cacheKey, response);
return response;
}
# 四、完整部署流程## 4.1 开发环境调试使用`nodemon`实现热重载:```bashnpm install --save-dev nodemon
在package.json中添加:
"scripts": {"dev": "nodemon index.js"}
启动开发服务器:
npm run dev
创建可执行文件(需安装pkg):
npm install -g pkgpkg package.json --targets node16-linux-x64,node16-win-x64,node16-macos-x64
生成的可执行文件可直接分发,无需安装Node.js环境。
创建Dockerfile:
FROM node:16-alpineWORKDIR /appCOPY package*.json ./RUN npm install --productionCOPY . .CMD ["node", "index.js"]
构建并运行容器:
docker build -t deepseek-cli .docker run -it --rm -e DEEPSEEK_API_KEY=your_key deepseek-cli
npm config set proxy http://proxy.company.com:8080
const client = axios.create({timeout: 30000, // 30秒超时// ...其他配置});
model: 'deepseek-base'实现自动续写机制:
async function getCompleteResponse(client, messages, partial) {if (partial.length < 50) return partial;const lastSentence = extractLastSentence(partial);messages.push({ role: 'user', content: `续写:"${lastSentence}"` });const continuation = await client.chat(messages);return partial + '\n' + continuation;}
实现上下文记忆:
class Conversation {constructor() {this.history = [];this.systemPrompt = '你是一个专业的AI助手';}addMessage(role, content) {this.history.push({ role, content });}getMessages() {return [{ role: 'system', content: this.systemPrompt }, ...this.history];}}
通过中间件模式扩展功能:
const plugins = [];function usePlugin(plugin) {plugins.push(plugin);}async function processWithPlugins(input) {let context = { input };for (const plugin of plugins) {context = await plugin(context);}return context;}
使用cross-env处理环境变量差异:
npm install --save-dev cross-env
修改启动脚本:
"scripts": {"start": "cross-env NODE_ENV=production node index.js"}
本文提供的实现方案经过实际生产环境验证,开发者可根据具体需求调整参数配置。建议首次使用时在测试环境验证API调用限额,避免产生意外费用。完整代码库已上传至GitHub,包含详细注释和单元测试用例。