SoFunction
Updated on 2025-04-14

A complete guide to calling the DeepSeek API

Introduction

This article will introduce how to use the DeepSeek API to implement streaming conversations and save conversation records. The version is implemented using modern asynchronous programming, supporting streaming and error handling.

1. Environmental preparation

1.1 System Requirements

  • Version 14.0 or later
  • npm package manager

1.2 Project Structure

deepseek-project/
├──            # Main Program├──       # Project configuration file└──   # Dialogue record file

1.3 Installation dependencies

Open the command line in the project directory and execute:

# Install project dependenciesnpm install

# If there is a permission problem, you can try:sudo npm install  # Linux/Mac
# ornpm install --force  # Windows

This command installs all dependencies defined in:

  • axios: Used to send HTTP requests
  • moment: for time formatting

If you encounter network problems during installation, you can try using domestic mirroring:

# Set up Taobao mirrornpm config set registry 

# Then reinstallnpm install

1.4 Run the program

After installing the dependencies, start the program with the following command:

# Start using npmnpm start

# Or use node directlynode 

If you encounter permission problems:

# Linux/Mac
sudo npm start

# Windows (run command prompt as administrator)npm start

2. Complete code implementation

2.1

{
  "name": "deepseek-chat",
  "version": "1.0.0",
  "description": "DeepSeek API chat implementation in ",
  "main": "",
  "scripts": {
    "start": "node "
  },
  "dependencies": {
    "axios": "^1.6.2",
    "moment": "^2.29.4"
  }
}

2.2

const fs = require('fs').promises;
const readline = require('readline');
const axios = require('axios');
const moment = require('moment');

class DeepSeekChat {
    constructor() {
         = '/v1/chat/completions';
         = 'YOUR_API_KEY';  // Replace with your API Key         = '';
    }

    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 (, text);
    }

    async chat() {
        // Create a command line interface        const rl = ({
            input: ,
            output: 
        });

        // Use Promise to encapsulate problem input        const question = (prompt) => new Promise((resolve) => (prompt, resolve));

        try {
            while (true) {
                const userInput = await question('\nPlease enter your question (enter q quit): ');
                
                if (().toLowerCase() === 'q') {
                    ('Program Exited');
                    break;
                }

                // Save the problem                await (userInput, true);

                // Prepare request data                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 {
                    // Send streaming request                    const response = await axios({
                        method: 'post',
                        url: ,
                        data: data,
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${}`
                        },
                        responseType: 'stream'
                    });

                    // Handle streaming response                    ('data', async (chunk) => {
                        const lines = ().split('\n');
                        for (const line of lines) {
                            if (() === '') continue;
                            if (() === 'data: [DONE]') continue;

                            if (('data: ')) {
                                try {
                                    const json = ((6));
                                    if ([0].) {
                                        const content = [0].;
                                        (content);
                                        await (content);
                                    }
                                } catch (e) {
                                    continue;
                                }
                            }
                        }
                    });

                    // Wait for the response to complete                    await new Promise((resolve) => {
                        ('end', async () => {
                            ('\n----------------------------------------');
                            await ('\n----------------------------------------\n');
                            resolve();
                        });
                    });

                } catch (error) {
                    const errorMsg = `Request error: ${}\n`;
                    (errorMsg);
                    await (errorMsg);
                }
            }
        } finally {
            ();
        }
    }
}

// Run the programasync function main() {
    const chatbot = new DeepSeekChat();
    await ();
}

main().catch();

3. Detailed code explanation

3.1 Class Structure

  • DeepSeekChat: Main class, encapsulate all functions
  • constructor: Constructor, initialize configuration
  • saveToFile: Save conversation records asynchronously
  • chat: Main dialogue loop

3.2 Key functions

File Operation

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 (, text);
}

Streaming

('data', async (chunk) => {
    const lines = ().split('\n');
    for (const line of lines) {
        if (('data: ')) {
            const json = ((6));
            if ([0].) {
                const content = [0].;
                (content);
                await (content);
            }
        }
    }
});

3.3 Parameter description

  • model: The name of the model used
  • stream: Enable streaming output
  • max_tokens: Maximum output length (2048)
  • temperature: Control randomness (0.7)
  • top_ptop_k: Sampling parameters
  • frequency_penalty: Repeat penalty coefficient

4. Error handling

The code contains a complete error handling mechanism:

  • Network request error handling
  • JSON parsing error handling
  • File operation error handling
  • Elegant exit processing

5. How to use

5.1 Installation dependencies

Open the command line in the project directory and execute:

# Install project dependenciesnpm install

# If there is a permission problem, you can try:sudo npm install  # Linux/Mac
# ornpm install --force  # Windows

This command installs all dependencies defined in:

  • axios: Used to send HTTP requests
  • moment: for time formatting

If you encounter network problems during installation, you can try using domestic mirroring:

# Set up Taobao mirrornpm config set registry 

# Then reinstallnpm install

5.2 Modify the configuration

existReplacementYOUR_API_KEYFor your actual API key.

5.3 Running the program

After installing the dependencies, start the program with the following command:

# Start using npmnpm start

# Or use node directlynode 

If you encounter permission problems:

# Linux/Mac
sudo npm start

# Windows (run command prompt as administrator)npm start

5.4 Interaction method

  1. Enter a question for a conversation
  2. Enter ‘q’ to exit the program
  3. View Get conversation history

6. Performance optimization suggestions

  1. Memory management

    • Using streaming to process big data
    • Clean up event listeners in time
    • Avoid memory leaks
  2. Error handling

    • Implement the retry mechanism
    • Add timeout processing
    • Elegant downgrade strategy
  3. Concurrent control

    • Limit the number of concurrent requests
    • Implement request queue
    • Add rate limit

Summarize

The version of DeepSeek API implementation takes full advantage of asynchronous programming features, providing a smooth conversation experience and a complete error handling mechanism. The code is clear and easy to maintain and expand.

The above is the detailed content of the complete guide to calling the DeepSeek API. For more information about calling the DeepSeek API, please follow my other related articles!