在 PHP 中使用 DeepSeek API 的 stop 参数避免多余生成

随笔 zhaosay 59℃

   stop 参数是 DeepSeek API 中一个非常有用的功能,它可以指定一个或多个停止序列,当生成的文本中出现这些序列时,API 会立即停止生成。这能有效避免生成多余的内容,提高响应速度并节省 token 使用量。

基本用法

1. 简单示例

$data = [
    'model' => 'deepseek-chat',
    'messages' => [
        ['role' => 'user', 'content' => '写一篇关于人工智能的短文,不超过200字。']
    ],
    'stop' => ["\n\n", "###"], // 遇到两个换行或###时停止
    'max_tokens' => 1000
];

2. 完整 PHP 实现

function callDeepSeekApiWithStop($prompt) {
    $apiKey = 'your-api-key-here';
    $url = 'https://api.deepseek.com/v1/chat/completions';
    
    $data = [
        'model' => 'deepseek-chat',
        'messages' => [
            ['role' => 'system', 'content' => '你是一位专业的写作助手'],
            ['role' => 'user', 'content' => $prompt]
        ],
        'temperature' => 0.7,
        'max_tokens' => 1000,
        'stop' => ["\n\n", "###", "。"] // 可以指定多个停止序列
    ];
    
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey
        ],
        CURLOPT_TIMEOUT => 30
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if ($response === false) {
        throw new Exception('API请求失败: ' . curl_error($ch));
    }
    
    $result = json_decode($response, true);
    
    if ($httpCode !== 200) {
        $errorMsg = $result['error']['message'] ?? '未知错误';
        throw new Exception("API错误: {$errorMsg} (HTTP {$httpCode})");
    }
    
    return $result['choices'][0]['message']['content'];
}

// 使用示例
try {
    $content = callDeepSeekApiWithStop("用100字左右介绍北京故宫,不要超过这个字数限制。");
    echo $content;
} catch (Exception $e) {
    echo "错误: " . $e->getMessage();
}

实际应用场景

1. 生成列表时避免多余项

$data = [
    'model' => 'deepseek-chat',
    'messages' => [
        ['role' => 'user', 'content' => '列举5个中国著名的旅游景点:']
    ],
    'stop' => ["6."], // 生成到第5项后遇到"6."就停止
    'max_tokens' => 200
];

2. 生成结构化内容

$data = [
    'model' => 'deepseek-chat',
    'messages' => [
        ['role' => 'user', 'content' => '以Markdown格式写一篇关于Python的简介,包含## 标题和- 列表项,以---结束']
    ],
    'stop' => ["---"], // 遇到---就停止
    'temperature' => 0.3 // 降低随机性确保结构
];

3. 问答场景控制回答长度

$data = [
    'model' => 'deepseek-chat',
    'messages' => [
        ['role' => 'user', 'content' => '用一句话回答:地球到月球的距离是多少?']
    ],
    'stop' => ["。", "!", "?"], // 遇到标点符号就停止
    'max_tokens' => 50];

高级技巧

1. 动态设置 stop 参数

function generateContent($prompt, $stopSequences = ["\n\n"]) {
    $data = [
        'model' => 'deepseek-chat',
        'messages' => [['role' => 'user', 'content' => $prompt]],
        'stop' => $stopSequences,
        'max_tokens' => 1000
    ];
    
    // ...API调用代码...
}

// 根据不同需求使用不同的停止序列
$techArticle = generateContent("写一篇关于区块链的技术文章", ["\n\n", "## 结论"]);
$shortAnswer = generateContent("简述量子计算", ["。", "!", "?"]);

2. 结合 max_tokens 使用

$data = [
    'model' => 'deepseek-chat',
    'messages' => [/*...*/],
    'stop' => ["\n\n"],
    'max_tokens' => 500, // 双重保险
    'temperature' => 0.5
];

3. 处理可能的多余内容

即使使用了 stop 参数,有时仍可能生成多余内容,可以在客户端进行处理:

function cleanGeneratedText($text, $stopSequences) {
    foreach ($stopSequences as $seq) {
        $pos = strpos($text, $seq);
        if ($pos !== false) {
            $text = substr($text, 0, $pos);
        }
    }
    return trim($text);
}

// 使用
$generated = callDeepSeekApiWithStop($prompt);
$cleaned = cleanGeneratedText($generated, ["\n\n", "###"]);

注意事项

  1. stop 序列选择

    • 选择不会在正常内容中出现的序列

    • 中文常用:[“\n\n”, “。”, “!”, “?”, “###”]

  2. 与 max_tokens 的关系

    • stop 优先于 max_tokens

    • 建议同时设置 max_tokens 作为保护

  3. 性能影响

    • 合理的 stop 参数可以显著减少不必要的生成

    • 但过多的 stop 序列会增加API处理负担

  4. 语言差异

    • 中文和英文可能需要不同的 stop 序列

    • 例如中文更适合用句号而不是句点作为停止符

转载请注明:三五二萌文网 » 在 PHP 中使用 DeepSeek API 的 stop 参数避免多余生成

喜欢 (0)