Skip to content

DeepSeek API完全指南

DeepSeek以其卓越的性价比和强大的代码能力,成为国产AI的明星产品

概述

DeepSeek是国产大模型的杰出代表,以其极高的性价比、强大的代码能力和推理能力著称。本教程将带你全面掌握DeepSeek API的使用方法。

为什么选择DeepSeek?

优势说明
超高性价比价格仅为GPT-4的1/100
代码能力强代码生成和理解能力优秀
推理能力复杂推理任务表现出色
国产合规符合国内数据安全法规

DeepSeek模型概览

DeepSeek模型家族:

DeepSeek V3系列(最新)
├── deepseek-chat        # 通用对话模型
└── deepseek-reasoner    # 推理专用模型

DeepSeek V2系列(经典)
├── deepseek-v2.5        # 平衡版本
└── deepseek-coder-v2    # 代码专用模型

DeepSeek R1系列(推理)
└── deepseek-r1          # 强化学习推理模型

基本概念

API Key

php
<?php
// 在DeepSeek官网获取API Key
// https://platform.deepseek.com/

// API Key格式
// sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

$apiKey = getenv('DEEPSEEK_API_KEY');

兼容性

DeepSeek API完全兼容OpenAI API格式:

php
<?php
// DeepSeek API使用与OpenAI相同的接口格式
// 只需更改base_url即可
$baseUrl = 'https://api.deepseek.com';

环境准备

创建DeepSeek客户端

php
<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class DeepSeekClient
{
    private $client;
    private $apiKey;
    private $baseUrl = 'https://api.deepseek.com';

    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
        $this->client = new Client([
            'base_uri' => $this->baseUrl,
            'timeout' => 120,
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
        ]);
    }

    public function chat(
        array $messages,
        string $model = 'deepseek-chat',
        array $options = []
    ): array {
        $params = [
            'model' => $model,
            'messages' => $messages,
        ];

        if (isset($options['temperature'])) {
            $params['temperature'] = $options['temperature'];
        }

        if (isset($options['max_tokens'])) {
            $params['max_tokens'] = $options['max_tokens'];
        }

        if (isset($options['top_p'])) {
            $params['top_p'] = $options['top_p'];
        }

        try {
            $response = $this->client->post('/v1/chat/completions', [
                'json' => $params,
            ]);

            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $errorBody = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : 'Unknown error';
            throw new Exception('DeepSeek API Error: ' . $errorBody);
        }
    }
}

// 使用示例
$apiKey = getenv('DEEPSEEK_API_KEY');
$client = new DeepSeekClient($apiKey);

$result = $client->chat([
    ['role' => 'user', 'content' => '请用一句话介绍PHP语言']
]);

echo $result['choices'][0]['message']['content'];

运行结果:

PHP是一种开源的服务器端脚本语言,特别适合Web开发,可以嵌入HTML中执行。

推理模型使用

使用DeepSeek R1进行复杂推理

php
<?php
class DeepSeekReasoner
{
    private DeepSeekClient $client;

    public function __construct(DeepSeekClient $client)
    {
        $this->client = $client;
    }

    public function reason(string $problem): array
    {
        $result = $this->client->chat(
            [
                ['role' => 'user', 'content' => $problem]
            ],
            'deepseek-reasoner'
        );

        return [
            'reasoning' => $result['choices'][0]['message']['reasoning_content'] ?? '',
            'answer' => $result['choices'][0]['message']['content'],
        ];
    }

    public function solveMathProblem(string $problem): string
    {
        $result = $this->client->chat(
            [
                [
                    'role' => 'system',
                    'content' => '你是一个数学问题解决专家,请一步步推理并给出答案。'
                ],
                ['role' => 'user', 'content' => $problem]
            ],
            'deepseek-reasoner'
        );

        return $result['choices'][0]['message']['content'];
    }

    public function analyzeCode(string $code): string
    {
        $result = $this->client->chat(
            [
                [
                    'role' => 'user',
                    'content' => "请分析以下代码的时间复杂度和空间复杂度,并给出优化建议:\n```\n{$code}\n```"
                ]
            ],
            'deepseek-reasoner'
        );

        return $result['choices'][0]['message']['content'];
    }
}

// 使用示例
$reasoner = new DeepSeekReasoner($client);

$result = $reasoner->reason('一个房间里有3盏灯,门外有3个开关,每个开关对应一盏灯。你只能进入房间一次,如何确定每个开关对应哪盏灯?');
echo "推理过程:\n" . $result['reasoning'] . "\n\n";
echo "答案:\n" . $result['answer'];

高级参数配置

完整参数示例

php
<?php
class DeepSeekClient
{
    // ... 前面的代码 ...

    public function chatAdvanced(
        array $messages,
        string $model = 'deepseek-chat',
        array $options = []
    ): array {
        $params = [
            'model' => $model,
            'messages' => $messages,
        ];

        $optionalParams = [
            'temperature',
            'max_tokens',
            'top_p',
            'stop',
            'frequency_penalty',
            'presence_penalty',
        ];

        foreach ($optionalParams as $param) {
            if (isset($options[$param])) {
                $params[$param] = $options[$param];
            }
        }

        try {
            $response = $this->client->post('/v1/chat/completions', [
                'json' => $params,
            ]);

            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $errorBody = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : 'Unknown error';
            throw new Exception('DeepSeek API Error: ' . $errorBody);
        }
    }
}

// 使用示例
$result = $client->chatAdvanced(
    [['role' => 'user', 'content' => '写一首关于程序员的诗']],
    'deepseek-chat',
    [
        'temperature' => 0.8,
        'max_tokens' => 500,
    ]
);

参数详解

参数范围默认值说明
temperature0-21控制随机性
max_tokens1-模型上限4096最大输出Token
top_p0-11核采样参数
stop字符串或数组-停止序列
frequency_penalty0-20频率惩罚
presence_penalty0-20存在惩罚

流式响应处理

php
<?php
class DeepSeekClient
{
    // ... 前面的代码 ...

    public function chatStream(
        array $messages,
        string $model = 'deepseek-chat'
    ): Generator {
        $response = $this->client->post('/v1/chat/completions', [
            'json' => [
                'model' => $model,
                'messages' => $messages,
                'stream' => true,
            ],
            'stream' => true,
        ]);

        $body = $response->getBody();
        $buffer = '';

        while (!$body->eof()) {
            $chunk = $body->read(1024);
            $buffer .= $chunk;

            while (($pos = strpos($buffer, "\n")) !== false) {
                $line = substr($buffer, 0, $pos);
                $buffer = substr($buffer, $pos + 1);

                $line = trim($line);
                if (empty($line) || $line === 'data: [DONE]') {
                    continue;
                }

                if (strpos($line, 'data: ') === 0) {
                    $json = substr($line, 6);
                    $data = json_decode($json, true);

                    if (isset($data['choices'][0]['delta']['content'])) {
                        yield $data['choices'][0]['delta']['content'];
                    }
                }
            }
        }
    }
}

// 使用示例
echo "DeepSeek回复:";
foreach ($client->chatStream([['role' => 'user', 'content' => '讲一个程序员笑话']]) as $chunk) {
    echo $chunk;
    flush();
}

多轮对话实现

php
<?php
class DeepSeekChatSession
{
    private DeepSeekClient $client;
    private array $messages = [];
    private string $model;

    public function __construct(DeepSeekClient $client, string $model = 'deepseek-chat')
    {
        $this->client = $client;
        $this->model = $model;
    }

    public function setSystemPrompt(string $prompt): void
    {
        $this->messages = [
            ['role' => 'system', 'content' => $prompt]
        ];
    }

    public function chat(string $userMessage): string
    {
        $this->messages[] = ['role' => 'user', 'content' => $userMessage];

        $response = $this->client->chat($this->messages, $this->model);
        $assistantMessage = $response['choices'][0]['message']['content'];

        $this->messages[] = ['role' => 'assistant', 'content' => $assistantMessage];

        return $assistantMessage;
    }

    public function getHistory(): array
    {
        return $this->messages;
    }

    public function clearHistory(): void
    {
        $systemMessage = $this->messages[0] ?? null;
        $this->messages = $systemMessage ? [$systemMessage] : [];
    }
}

// 使用示例
$session = new DeepSeekChatSession($client);
$session->setSystemPrompt('你是一个专业的PHP开发工程师,用简洁的语言回答问题。');

echo "用户:PHP有哪些优点?\n";
echo "DeepSeek:" . $session->chat('PHP有哪些优点?') . "\n";

常见错误与踩坑点

错误1:模型名称错误

php
<?php
// ❌ 错误做法:使用不存在的模型
$result = $client->chat($messages, 'deepseek-v3');

// ✅ 正确做法:使用正确的模型名称
$result = $client->chat($messages, 'deepseek-chat');
$result = $client->chat($messages, 'deepseek-reasoner');

错误2:忽略推理模型的特殊输出

php
<?php
// ❌ 错误做法:只获取content
$result = $client->chat($messages, 'deepseek-reasoner');
echo $result['choices'][0]['message']['content'];

// ✅ 正确做法:同时获取推理过程
$result = $client->chat($messages, 'deepseek-reasoner');
if (isset($result['choices'][0]['message']['reasoning_content'])) {
    echo "推理过程:\n" . $result['choices'][0]['message']['reasoning_content'] . "\n\n";
}
echo "答案:\n" . $result['choices'][0]['message']['content'];

错误3:忽略余额不足

php
<?php
// ❌ 错误做法:不检查余额
$result = $client->chat($messages);

// ✅ 正确做法:处理余额不足错误
try {
    $result = $client->chat($messages);
} catch (Exception $e) {
    if (strpos($e->getMessage(), 'insufficient_balance') !== false) {
        echo '账户余额不足,请充值后继续使用';
    }
}

常见应用场景

场景1:代码生成助手

php
<?php
class DeepSeekCodeAssistant
{
    private DeepSeekClient $client;

    public function generateCode(string $description, string $language = 'PHP'): string
    {
        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => '你是一个专业的程序员,请生成简洁、高效的代码。'
            ],
            [
                'role' => 'user',
                'content' => "请生成{$language}代码:{$description}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function explainCode(string $code): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请解释以下代码的功能:\n```\n{$code}\n```"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function debugCode(string $code, string $error): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "以下代码出错,请帮我修复:\n代码:\n```\n{$code}\n```\n错误信息:{$error}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

场景2:数学问题求解

php
<?php
class MathProblemSolver
{
    private DeepSeekClient $client;

    public function solve(string $problem): array
    {
        $result = $this->client->chat(
            [
                [
                    'role' => 'system',
                    'content' => '你是一个数学专家,请详细推理并给出答案。'
                ],
                ['role' => 'user', 'content' => $problem]
            ],
            'deepseek-reasoner'
        );

        return [
            'reasoning' => $result['choices'][0]['message']['reasoning_content'] ?? '',
            'answer' => $result['choices'][0]['message']['content'],
        ];
    }
}

场景3:文档问答

php
<?php
class DocumentQA
{
    private DeepSeekClient $client;
    private string $document;

    public function __construct(DeepSeekClient $client, string $document)
    {
        $this->client = $client;
        $this->document = $document;
    }

    public function ask(string $question): string
    {
        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => '你是一个文档问答助手,请根据提供的文档内容回答问题。'
            ],
            [
                'role' => 'user',
                'content' => "文档内容:\n{$this->document}\n\n问题:{$question}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

场景4:内容创作

php
<?php
class ContentCreator
{
    private DeepSeekClient $client;

    public function generateArticle(string $topic, int $wordCount = 800): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请写一篇关于{$topic}的文章,字数约{$wordCount}字。"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function generateSummary(string $content, int $maxLength = 200): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请将以下内容总结为不超过{$maxLength}字:\n\n{$content}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

场景5:智能客服

php
<?php
class CustomerServiceBot
{
    private DeepSeekClient $client;
    private array $knowledgeBase = [];

    public function addKnowledge(string $category, string $content): void
    {
        $this->knowledgeBase[$category] = $content;
    }

    public function handleQuery(string $query): string
    {
        $context = '';
        foreach ($this->knowledgeBase as $category => $content) {
            $context .= "【{$category}】\n{$content}\n\n";
        }

        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => '你是一个友好的客服助手。请根据知识库回答问题,如果不知道答案,请诚实说明。'
            ],
            [
                'role' => 'user',
                'content' => "知识库:\n{$context}\n\n客户问题:{$query}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

企业级进阶应用场景

场景1:构建智能代码审查系统

php
<?php
class CodeReviewSystem
{
    private DeepSeekClient $client;

    public function review(string $code, string $language = 'PHP'): array
    {
        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => '你是一位资深代码审查专家。请从代码质量、安全性、性能三个维度审查代码。'
            ],
            [
                'role' => 'user',
                'content' => "请审查以下{$language}代码,以JSON格式返回结果:\n```\n{$code}\n```"
            ]
        ]);

        return json_decode($result['choices'][0]['message']['content'], true);
    }
}

场景2:构建复杂问题推理系统

php
<?php
class ComplexReasoningSystem
{
    private DeepSeekClient $client;

    public function analyze(string $problem): array
    {
        $result = $this->client->chat(
            [
                [
                    'role' => 'system',
                    'content' => '你是一个分析专家,请详细推理并给出结论。'
                ],
                ['role' => 'user', 'content' => $problem]
            ],
            'deepseek-reasoner'
        );

        return [
            'reasoning' => $result['choices'][0]['message']['reasoning_content'] ?? '',
            'conclusion' => $result['choices'][0]['message']['content'],
            'usage' => $result['usage'],
        ];
    }
}

常见问题答疑(FAQ)

Q1:DeepSeek的定价如何?

回答

模型输入价格输出价格相对GPT-4
deepseek-chat¥1/百万Token¥2/百万Token约1/100
deepseek-reasoner¥4/百万Token¥16/百万Token约1/20

Q2:deepseek-chat和deepseek-reasoner如何选择?

回答

场景推荐模型原因
日常对话deepseek-chat速度快,成本低
代码生成deepseek-chat代码能力强
复杂推理deepseek-reasoner推理能力强
数学问题deepseek-reasoner逐步推理

Q3:如何处理API错误?

回答

php
<?php
function handleDeepSeekError(Exception $e): string
{
    $message = $e->getMessage();

    if (strpos($message, 'invalid_api_key') !== false) {
        return 'API Key无效';
    }
    if (strpos($message, 'insufficient_balance') !== false) {
        return '账户余额不足';
    }
    if (strpos($message, 'rate_limit') !== false) {
        return '请求过于频繁';
    }

    return '服务暂时不可用';
}

Q4:如何获取推理过程?

回答

php
<?php
$result = $client->chat($messages, 'deepseek-reasoner');

// 推理过程
$reasoning = $result['choices'][0]['message']['reasoning_content'] ?? '';

// 最终答案
$answer = $result['choices'][0]['message']['content'];

Q5:如何优化Token使用?

回答

php
<?php
// 1. 使用deepseek-chat进行简单任务
$result = $client->chat($messages, 'deepseek-chat');

// 2. 限制max_tokens
$result = $client->chat($messages, 'deepseek-chat', ['max_tokens' => 500]);

// 3. 使用简洁的提示
$prompt = "用50字解释:{$topic}";

Q6:DeepSeek支持哪些功能?

回答

功能支持说明
文本生成支持各种文本生成任务
代码生成代码能力强
流式输出支持流式响应
推理模式deepseek-reasoner
函数调用支持Function Calling
多模态暂不支持

实战练习

基础练习

练习1:编写一个简单的DeepSeek聊天程序。

参考代码

php
<?php
$apiKey = getenv('DEEPSEEK_API_KEY');
$client = new DeepSeekClient($apiKey);

echo "DeepSeek聊天助手 (输入 'quit' 退出)\n";

while (true) {
    echo "\n你: ";
    $input = trim(fgets(STDIN));

    if ($input === 'quit') {
        break;
    }

    $result = $client->chat([['role' => 'user', 'content' => $input]]);
    echo "DeepSeek: " . $result['choices'][0]['message']['content'] . "\n";
}

进阶练习

练习2:实现一个代码生成器。

参考代码

php
<?php
class CodeGenerator
{
    private DeepSeekClient $client;

    public function generate(string $description, string $language = 'PHP'): string
    {
        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => '你是一个代码生成专家,只输出代码,不要解释。'
            ],
            [
                'role' => 'user',
                'content' => "生成{$language}代码:{$description}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

挑战练习

练习3:构建一个智能问题解答系统。

参考代码

php
<?php
class IntelligentQA
{
    private DeepSeekClient $client;

    public function answer(string $question): array
    {
        $result = $this->client->chat(
            [
                ['role' => 'user', 'content' => $question]
            ],
            'deepseek-reasoner'
        );

        return [
            'reasoning' => $result['choices'][0]['message']['reasoning_content'] ?? '',
            'answer' => $result['choices'][0]['message']['content'],
        ];
    }
}

知识点总结

核心要点

  1. 超高性价比:价格仅为GPT-4的1/100
  2. API兼容:完全兼容OpenAI API格式
  3. 推理能力:deepseek-reasoner提供强大的推理能力
  4. 代码能力:代码生成和理解能力优秀
  5. 国产合规:符合国内数据安全法规

易错点回顾

易错点正确做法
模型名称错误使用deepseek-chat或deepseek-reasoner
忽略推理过程获取reasoning_content
忽略余额不足处理insufficient_balance错误
不使用推理模型复杂问题使用deepseek-reasoner

拓展参考资料

官方文档

进阶学习路径

  1. 本知识点 → DeepSeek API基础使用
  2. 下一步阿里通义千问
  3. 进阶错误处理与重试
  4. 高级Token优化策略

💡 记住:DeepSeek以其超高性价比著称,是国内开发者的首选AI API之一。善用deepseek-reasoner可以解决复杂的推理问题。