SoFunction
Updated on 2025-04-14

A complete guide to calling the DeepSeek API by PHP

Introduction

This article will introduce how to use PHP to call the DeepSeek API, implement streaming conversations and save conversation records. The PHP version is implemented in an object-oriented manner, with clear code structure and easy to maintain.

1. Environmental preparation

1.1 System Requirements

  • PHP 7.0 or later
  • PHP cURL extension
  • File write permissions

1.2 Project Structure

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

2. Complete code implementation

<?php

class DeepSeekChat {
    private $url = '/v1/chat/completions';
    private $apiKey = 'YOUR_API_KEY';  // Replace with your API Key    private $logFile = '';

    public function __construct() {
        // Make sure the log file exists and is writable        if (!file_exists($this->logFile)) {
            touch($this->logFile);
        }
    }

    private function saveToFile($content, $isQuestion = false) {
        $timestamp = date('Y-m-d H:i:s');
        $text = $isQuestion 
            ? "\n[$timestamp] Question:\n$content\n\n[$timestamp] Answer:\n"
            : $content;
        
        file_put_contents($this->logFile, $text, FILE_APPEND);
    }

    private function processStreamingResponse($handle) {
        $buffer = '';
        while (!feof($handle)) {
            $chunk = fread($handle, 1024);
            $buffer .= $chunk;

            // Process every row in the buffer            while (($pos = strpos($buffer, "\n")) !== false) {
                $line = substr($buffer, 0, $pos);
                $buffer = substr($buffer, $pos + 1);

                if (strlen(trim($line)) > 0) {
                    if (strpos($line, 'data: ') === 0) {
                        $data = substr($line, 6); // Remove the "data: " prefix                        if ($data === '[DONE]') {
                            continue;
                        }

                        $json = json_decode($data, true);
                        if ($json && isset($json['choices'][0]['delta']['content'])) {
                            $content = $json['choices'][0]['delta']['content'];
                            echo $content;
                            flush();
                            $this->saveToFile($content);
                        }
                    }
                }
            }
        }
    }

    public function chat() {
        while (true) {
            echo "\nPlease enter your question (enter q quit): ";
            $question = trim(fgets(STDIN));

            if ($question === 'q') {
                echo "Program Exited\n";
                break;
            }

            // Save the problem            $this->saveToFile($question, true);

            // Prepare request data            $data = [
                'model' => 'deepseek-ai/DeepSeek-V3',
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $question
                    ]
                ],
                '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'
                ]
            ];

            // Prepare cURL request            $ch = curl_init($this->url);
            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $this->apiKey
                ],
                CURLOPT_WRITEFUNCTION => function($ch, $data) {
                    echo $data;
                    return strlen($data);
                }
            ]);

            try {
                // Send a request and process the response                $handle = curl_exec($ch);
                
                if (curl_errno($ch)) {
                    throw new Exception(curl_error($ch));
                }

                // Add a separator                echo "\n----------------------------------------\n";
                $this->saveToFile("\n----------------------------------------\n");

            } catch (Exception $e) {
                $error_msg = "Request Error: " . $e->getMessage() . "\n";
                echo $error_msg;
                $this->saveToFile($error_msg);
            } finally {
                curl_close($ch);
            }
        }
    }
}

// Run the program$chatbot = new DeepSeekChat();
$chatbot->chat();

3. Detailed code explanation

3.1 Class Structure

  • DeepSeekChat: Main class, encapsulate all functions
  • __construct: Constructor, initialize log file
  • saveToFile: Save conversation history
  • processStreamingResponse: Processing streaming response
  • chat: Main dialogue loop

3.2 Key functions

File Operation

private function saveToFile($content, $isQuestion = false) {
    $timestamp = date('Y-m-d H:i:s');
    $text = $isQuestion 
        ? "\n[$timestamp] Question:\n$content\n\n[$timestamp] Answer:\n"
        : $content;
    
    file_put_contents($this->logFile, $text, FILE_APPEND);
}

cURL configuration

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $this->apiKey
    ]
]);

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:

  • cURL Error Check
  • JSON parsing error handling
  • File operation error handling
  • Exception capture and logging

5. How to use

5.1 Modify the configuration

Replace in codeYOUR_API_KEYFor your actual API key.

5.2 Run the program

php 

5.3 Interaction method

  • Enter a question for a conversation
  • Enter ‘q’ to exit the program
  • View Get conversation history

6. Performance optimization suggestions

  1. Memory management

    • Use the appropriate buffer size
    • Clean up variables in a timely manner
    • Avoid a large amount of data accumulation
  2. File Operation

    • Use file locks to prevent concurrent writes
    • Regularly clean log files
    • Consider using database storage
  3. Network request

    • Set a reasonable timeout
    • Using persistent connection
    • Handle network exceptions

Summarize

The PHP version of DeepSeek API implementation adopts an object-oriented approach, with clear code structure and easy to maintain and expand. Streaming is implemented through cURL, providing a good interactive experience.

This is the end of this article about the complete guide to PHP calling the DeepSeek API. For more related content on PHP calling the DeepSeek API, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!