简介:本文详细讲解PHP开发者如何调用DeepSeek API,涵盖环境准备、认证授权、API调用全流程及异常处理,助力开发者快速实现AI功能集成。
DeepSeek API官方推荐使用PHP 7.4及以上版本,建议开发者优先选择PHP 8.x版本以获得更好的性能和安全性。通过php -v命令可快速验证本地PHP环境版本。
核心依赖包括cURL扩展(用于HTTP请求)和JSON扩展(用于数据解析)。Linux服务器可通过以下命令安装:
sudo apt-get install php-curl php-json
Windows环境需在php.ini文件中取消注释extension=curl和extension=json配置项。
推荐使用Postman进行API接口测试,配合VS Code的PHP插件可提升开发效率。对于复杂项目,建议采用Composer管理依赖,示例composer.json配置:
{"require": {"guzzlehttp/guzzle": "^7.0"}}
DeepSeek API提供两种认证方式:
每次请求需在Header中添加认证信息:
$apiKey = getenv('DEEPSEEK_API_KEY');$headers = ['Authorization' => 'Bearer ' . $apiKey,'Content-Type' => 'application/json','X-API-Version' => '2023-08-01' // 指定API版本];
function callTextGeneration($prompt) {$client = new \GuzzleHttp\Client();$url = 'https://api.deepseek.com/v1/text-generation';$response = $client->post($url, ['headers' => $headers,'json' => ['prompt' => $prompt,'max_tokens' => 200,'temperature' => 0.7]]);return json_decode($response->getBody(), true);}
参数说明:
max_tokens:控制生成文本长度temperature:调节输出随机性(0-1)top_p:核采样参数(可选)
function callImageGeneration($prompt, $size = '1024x1024') {$client = new \GuzzleHttp\Client();$url = 'https://api.deepseek.com/v1/images/generations';$response = $client->post($url, ['headers' => $headers,'json' => ['prompt' => $prompt,'n' => 1,'size' => $size,'response_format' => 'url']]);return json_decode($response->getBody(), true);}
注意事项:
function fineTuneModel($trainingData) {$client = new \GuzzleHttp\Client();$url = 'https://api.deepseek.com/v1/fine-tunes';$response = $client->post($url, ['headers' => $headers,'json' => ['training_file' => $trainingData['file_id'],'model' => 'deepseek-v1.5','suffix' => $trainingData['suffix'] ?? null]]);return json_decode($response->getBody(), true);}
最佳实践:
function streamResponse($prompt) {$client = new \GuzzleHttp\Client();$url = 'https://api.deepseek.com/v1/text-generation/stream';$stream = $client->post($url, ['headers' => $headers,'json' => ['prompt' => $prompt],'stream' => true]);$body = $stream->getBody();while (!$body->eof()) {$line = $body->readLine();if (strpos($line, 'data: ') === 0) {$data = json_decode(substr($line, 6), true);echo $data['choices'][0]['text'];flush();}}}
function batchRequest($requests) {$client = new \GuzzleHttp\Client();$url = 'https://api.deepseek.com/v1/batch';$responses = [];$pool = new \GuzzleHttp\Promise\PromisePool(array_map(function($req) use ($client) {return $client->postAsync('https://api.deepseek.com/v1/text-generation', ['headers' => $headers,'json' => $req]);}, $requests),function($result) use (&$responses) {$responses[] = json_decode($result->getBody(), true);});$pool->promise()->wait();return $responses;}
| 错误码 | 原因 | 解决方案 |
|---|---|---|
| 401 | 认证失败 | 检查API Key有效性 |
| 429 | 速率限制 | 实现指数退避算法 |
| 500 | 服务器错误 | 重试3次后报错 |
function callWithRetry($callback, $maxRetries = 3) {$attempts = 0;while ($attempts < $maxRetries) {try {return $callback();} catch (\GuzzleHttp\Exception\RequestException $e) {$attempts++;if ($attempts >= $maxRetries) {throw $e;}usleep(1000000 * $attempts); // 指数退避}}}
.env文件存储敏感信息
function sanitizeInput($input) {$input = trim($input);$input = htmlspecialchars($input, ENT_QUOTES);// 添加更多业务规则验证return $input;}
function logApiCall($endpoint, $request, $response, $status) {$log = ['timestamp' => date('Y-m-d H:i:s'),'endpoint' => $endpoint,'request' => $request,'response' => $response,'status' => $status];file_put_contents('api_calls.log', json_encode($log) . PHP_EOL, FILE_APPEND);}
/deepseek-php├── composer.json├── .env├── src/│ ├── ApiClient.php│ └── Services/│ ├── TextGeneration.php│ └── ImageGeneration.php└── tests/└── ApiTest.php
namespace DeepSeek\Services;class TextGeneration {private $client;public function __construct(\GuzzleHttp\Client $client) {$this->client = $client;}public function generate($prompt, $params = []) {$defaultParams = ['max_tokens' => 200,'temperature' => 0.7];$response = $this->client->post('/v1/text-generation', ['json' => array_merge($defaultParams, $params, ['prompt' => $prompt])]);return json_decode($response->getBody(), true);}}
基础套餐通常提供:
| 场景 | 推荐模型 |
|---|---|
| 短文本生成 | deepseek-chat |
| 长文本创作 | deepseek-v1.5 |
| 代码生成 | deepseek-coder |
本指南提供了从基础到高级的完整实现路径,开发者可根据实际需求调整参数和架构。建议先在测试环境验证功能,再逐步迁移到生产环境。对于高并发场景,可考虑使用消息队列缓冲请求。