DeepSeek作为国内领先的大模型服务提供商,其API接口为开发者提供了强大的自然语言处理能力。本文将全面介绍如何使用PHP调用DeepSeek API,涵盖环境配置、基础调用、高级功能、错误处理及性能优化等核心内容。
一、环境准备与API密钥获取
1.1 系统要求
在开始之前,确保您的开发环境满足以下要求:
- PHP 7.4或更高版本
- 启用cURL扩展
- 启用JSON扩展
- 有效的DeepSeek API密钥
1.2 获取API密钥
访问DeepSeek官方开发者平台(https://platform.deepseek.com)完成注册后,进入控制台创建API密钥:
- 登录DeepSeek开发者平台
- 点击”API Keys”或”API密钥管理”
- 点击”Create new secret key”创建新密钥
- 复制并妥善保存生成的API密钥
安全建议:API密钥应通过环境变量存储,避免硬编码在代码中:
# Linux/MacOS
export DEEPSEEK_API_KEY="sk-xxxxxxxxxxxxxxxx"
# Windows PowerShell
$env:DEEPSEEK_API_KEY="sk-xxxxxxxxxxxxxxxx"
1.3 安装依赖
虽然可以直接使用PHP原生函数调用API,但推荐使用Guzzle HTTP客户端简化开发:
composer require guzzlehttp/guzzle
二、基础API调用
2.1 文本生成接口
DeepSeek的核心接口是文本生成,支持对话和补全两种模式。以下是基础调用示例:
<?php
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
class DeepSeekClient {
private $client;
private $apiKey;
private $baseUrl = 'https://api.deepseek.com/v1';
public function __construct($apiKey) {
$this->apiKey = $apiKey;
$this->client = new Client([
'base_uri' => $this->baseUrl,
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
'Content-Type' => 'application/json',
]
]);
}
/**
* 文本生成接口
*/
public function generateText($prompt, $model = 'deepseek-chat', $maxTokens = 1000, $temperature = 0.7) {
try {
$response = $this->client->post('/chat/completions', [
'json' => [
'model' => $model,
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'max_tokens' => $maxTokens,
'temperature' => $temperature,
'stream' => false
]
]);
$result = json_decode($response->getBody(), true);
return $result['choices'][0]['message']['content'];
} catch (Exception $e) {
throw new Exception("API调用失败: " . $e->getMessage());
}
}
}
// 使用示例
$apiKey = getenv('DEEPSEEK_API_KEY');
$client = new DeepSeekClient($apiKey);
$response = $client->generateText("请用中文解释量子计算的基本原理");
echo $response;
?>
2.2 核心参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| model | string | 是 | 模型名称,如deepseek-chat |
| messages | array | 是 | 对话消息列表 |
| max_tokens | int | 否 | 生成内容的最大长度(默认1000) |
| temperature | float | 否 | 生成内容的随机性(0.0-2.0,默认0.7) |
| top_p | float | 否 | 核采样参数(0.0-1.0,默认1.0) |
| stream | bool | 否 | 是否流式返回(默认false) |
三、多轮对话实现
3.1 对话上下文管理
DeepSeek支持多轮对话,通过维护对话历史实现上下文理解:
class DialogueManager {
private $history = [];
private $maxHistory = 10; // 保留最近10轮对话
/**
* 添加消息到对话历史
*/
public function addMessage($role, $content) {
$this->history[] = [
'role' => $role,
'content' => $content
];
// 限制历史记录长度
if (count($this->history) > $this->maxHistory * 2) {
$this->history = array_slice($this->history, -$this->maxHistory * 2);
}
}
/**
* 获取对话历史
*/
public function getHistory() {
return $this->history;
}
/**
* 清空对话历史
*/
public function clearHistory() {
$this->history = [];
}
}
// 扩展DeepSeekClient类
class DeepSeekChatClient extends DeepSeekClient {
private $dialogueManager;
public function __construct($apiKey) {
parent::__construct($apiKey);
$this->dialogueManager = new DialogueManager();
}
/**
* 多轮对话
*/
public function chat($message) {
// 添加用户消息
$this->dialogueManager->addMessage('user', $message);
// 获取对话历史
$messages = $this->dialogueManager->getHistory();
try {
$response = $this->client->post('/chat/completions', [
'json' => [
'model' => 'deepseek-chat',
'messages' => $messages,
'max_tokens' => 1000,
'temperature' => 0.7
]
]);
$result = json_decode($response->getBody(), true);
$reply = $result['choices'][0]['message']['content'];
// 添加AI回复到历史
$this->dialogueManager->addMessage('assistant', $reply);
return $reply;
} catch (Exception $e) {
throw new Exception("对话失败: " . $e->getMessage());
}
}
/**
* 重置对话
*/
public function reset() {
$this->dialogueManager->clearHistory();
}
}
// 使用示例
$client = new DeepSeekChatClient($apiKey);
echo $client->chat("你好,我是小明"); // 第一轮对话
echo $client->chat("刚才我们聊了什么?"); // 第二轮对话,保持上下文
3.2 系统提示词配置
通过system角色设置AI的行为模式:
// 设置系统提示词
$this->dialogueManager->addMessage('system', '你是一个专业的编程助手,请用中文回答所有问题。');
// 完整的消息结构
$messages = [
['role' => 'system', 'content' => '你是一个专业的编程助手'],
['role' => 'user', 'content' => '如何用PHP连接MySQL数据库?'],
['role' => 'assistant', 'content' => '可以使用PDO或mysqli扩展...'],
['role' => 'user', 'content' => '请给出PDO的示例代码']
];
四、流式输出实现
4.1 流式响应处理
流式输出可以实时显示生成内容,提升用户体验:
class DeepSeekStreamClient extends DeepSeekClient {
/**
* 流式文本生成
*/
public function generateTextStream($prompt, $callback, $model = 'deepseek-chat', $maxTokens = 1000) {
try {
$response = $this->client->post('/chat/completions', [
'json' => [
'model' => $model,
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'max_tokens' => $maxTokens,
'temperature' => 0.7,
'stream' => true
],
'stream' => true
]);
$stream = $response->getBody();
$buffer = '';
while (!$stream->eof()) {
$chunk = $stream->read(1024);
$buffer .= $chunk;
// 解析SSE格式
$events = explode("\n\n", $buffer);
$buffer = array_pop($events);
foreach ($events as $event) {
if (strpos($event, 'data: ') === 0) {
$data = substr($event, 6);
if ($data === '[DONE]') {
break 2;
}
$json = json_decode($data, true);
if (isset($json['choices'][0]['delta']['content'])) {
$content = $json['choices'][0]['delta']['content'];
call_user_func($callback, $content);
}
}
}
}
} catch (Exception $e) {
throw new Exception("流式调用失败: " . $e->getMessage());
}
}
}
// 使用示例
$client = new DeepSeekStreamClient($apiKey);
$client->generateTextStream("请用中文介绍PHP的面向对象特性", function($chunk) {
echo $chunk;
flush(); // 立即输出到浏览器
});
4.2 Web应用中的流式输出
在Web应用中实现流式输出:
// 流式输出控制器
public function streamAction() {
// 设置响应头
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no'); // 禁用Nginx缓冲
$prompt = $_POST['prompt'] ?? '';
$client = new DeepSeekStreamClient(getenv('DEEPSEEK_API_KEY'));
$client->generateTextStream($prompt, function($chunk) {
echo "data: " . json_encode(['content' => $chunk]) . "\n\n";
flush();
});
echo "data: [DONE]\n\n";
flush();
exit;
}
五、文件上传与解析
5.1 文件上传接口
DeepSeek支持上传PDF、Word、Excel等文档进行内容解析:
class DeepSeekFileClient extends DeepSeekClient {
/**
* 上传文件
*/
public function uploadFile($filePath, $purpose = 'assistants') {
try {
$response = $this->client->post('/files', [
'multipart' => [
[
'name' => 'file',
'contents' => fopen($filePath, 'r'),
'filename' => basename($filePath)
],
[
'name' => 'purpose',
'contents' => $purpose
]
]
]);
return json_decode($response->getBody(), true);
} catch (Exception $e) {
throw new Exception("文件上传失败: " . $e->getMessage());
}
}
/**
* 基于文件内容对话
*/
public function chatWithFile($fileId, $question) {
try {
$response = $this->client->post('/chat/completions', [
'json' => [
'model' => 'deepseek-chat',
'messages' => [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => $question
],
[
'type' => 'file',
'file_id' => $fileId
]
]
]
],
'max_tokens' => 1000
]
]);
$result = json_decode($response->getBody(), true);
return $result['choices'][0]['message']['content'];
} catch (Exception $e) {
throw new Exception("文件对话失败: " . $e->getMessage());
}
}
}
// 使用示例
$client = new DeepSeekFileClient($apiKey);
$fileInfo = $client->uploadFile('/path/to/document.pdf');
$fileId = $fileInfo['id'];
$response = $client->chatWithFile($fileId, "请总结这篇文档的主要内容");
echo $response;
5.2 多文件支持
DeepSeek支持同时处理多个文件:
$messages = [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => '请对比这两个文档的异同点'
],
[
'type' => 'file',
'file_id' => $fileId1
],
[
'type' => 'file',
'file_id' => $fileId2
]
]
]
];
六、图片理解功能
6.1 图片上传与识别
DeepSeek支持图片内容识别和描述生成:
class DeepSeekVisionClient extends DeepSeekClient {
/**
* 图片理解
*/
public function analyzeImage($imagePath, $prompt) {
try {
// 将图片转换为Base64
$imageData = base64_encode(file_get_contents($imagePath));
$imageType = mime_content_type($imagePath);
$response = $this->client->post('/chat/completions', [
'json' => [
'model' => 'deepseek-vision',
'messages' => [
[
'role' => 'user',
'content' => [
[
'type' => 'image_url',
'image_url' => [
'url' => "data:{$imageType};base64,{$imageData}"
]
],
[
'type' => 'text',
'text' => $prompt
]
]
]
],
'max_tokens' => 1000
]
]);
$result = json_decode($response->getBody(), true);
return $result['choices'][0]['message']['content'];
} catch (Exception $e) {
throw new Exception("图片分析失败: " . $e->getMessage());
}
}
}
// 使用示例
$client = new DeepSeekVisionClient($apiKey);
$response = $client->analyzeImage('/path/to/image.jpg', '请描述这张图片的内容');
echo $response;
6.2 多模态对话
结合图片和文本进行多模态对话:
$messages = [
[
'role' => 'user',
'content' => [
[
'type' => 'image_url',
'image_url' => [
'url' => "data:image/jpeg;base64,{$imageData}"
]
],
[
'type' => 'text',
'text' => '这张图片中的人物在做什么?'
]
]
]
];
七、错误处理与重试机制
7.1 常见错误码处理
DeepSeek API返回的标准错误码:
class DeepSeekErrorHandler {
public static function handleError($errorCode, $errorMessage) {
switch ($errorCode) {
case 401:
return "认证失败,请检查API密钥是否正确";
case 403:
return "权限不足,请检查API密钥权限";
case 429:
return "请求频率超限,请稍后重试";
case 500:
return "服务器内部错误,请稍后重试";
case 503:
return "服务不可用,请稍后重试";
default:
return "未知错误: " . $errorMessage;
}
}
}
// 在调用方法中添加错误处理
try {
$response = $this->client->post('/chat/completions', $options);
$result = json_decode($response->getBody(), true);
if (isset($result['error'])) {
$error = $result['error'];
throw new Exception(DeepSeekErrorHandler::handleError($error['code'], $error['message']));
}
return $result;
} catch (GuzzleHttp\Exception\RequestException $e) {
if ($e->hasResponse()) {
$response = $e->getResponse();
$statusCode = $response->getStatusCode();
$error = json_decode($response->getBody(), true);
throw new Exception(DeepSeekErrorHandler::handleError($statusCode, $error['message'] ?? ''));
}
throw new Exception("网络请求失败: " . $e->getMessage());
}
7.2 指数退避重试机制
对于429等可重试错误,实现指数退避重试:
class DeepSeekRetryClient extends DeepSeekClient {
private $maxRetries = 3;
private $retryDelay = 1000; // 1秒
/**
* 带重试机制的API调用
*/
public function callWithRetry($method, $endpoint, $options = []) {
$retries = 0;
while ($retries < $this->maxRetries) {
try {
return $this->client->request($method, $endpoint, $options);
} catch (GuzzleHttp\Exception\RequestException $e) {
$retries++;
if ($retries >= $this->maxRetries) {
throw $e;
}
// 检查是否为可重试错误
if ($e->hasResponse()) {
$statusCode = $e->getResponse()->getStatusCode();
if ($statusCode == 429 || $statusCode >= 500) {
// 指数退避
$delay = $this->retryDelay * pow(2, $retries - 1);
usleep($delay * 1000);
continue;
}
}
throw $e;
}
}
}
}
八、性能优化与最佳实践
8.1 批量请求处理
对于需要处理多个独立请求的场景,使用批量接口减少网络开销:
class DeepSeekBatchClient extends DeepSeekClient {
/**
* 批量文本生成
*/
public function batchGenerate($prompts, $model = 'deepseek-chat') {
try {
$requests = [];
foreach ($prompts as $prompt) {
$requests[] = [
'model' => $model,
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'max_tokens' => 500
];
}
$response = $this->client->post('/batch', [
'json' => [
'requests' => $requests
]
]);
$result = json_decode($response->getBody(), true);
return array_map(function($item) {
return $item['choices'][0]['message']['content'];
}, $result['responses']);
} catch (Exception $e) {
throw new Exception("批量调用失败: " . $e->getMessage());
}
}
}
// 使用示例
$client = new DeepSeekBatchClient($apiKey);
$prompts = [
"请介绍PHP的面向对象特性",
"如何用PHP连接MySQL数据库",
"PHP的异常处理机制是什么"
];
$results = $client->batchGenerate($prompts);
8.2 响应缓存机制
对重复查询结果进行缓存,减少API调用:
class DeepSeekCacheClient extends DeepSeekClient {
private $cache;
private $cacheTtl = 3600; // 缓存1小时
public function __construct($apiKey) {
parent::__construct($apiKey);
// 使用Redis或文件缓存
$this->cache = new RedisCache(); // 假设的缓存类
}
public function generateTextWithCache($prompt, $model = 'deepseek-chat') {
$cacheKey = md5($prompt . $model);
// 检查缓存
$cached = $this->cache->get($cacheKey);
if ($cached !== false) {
return $cached;
}
// 调用API
$result = parent::generateText($prompt, $model);
// 写入缓存
$this->cache->set($cacheKey, $result, $this->cacheTtl);
return $result;
}
}
8.3 连接池管理
使用连接池复用HTTP连接,提升性能:
class DeepSeekPoolClient {
private static $clients = [];
private $apiKey;
private $maxConnections = 10;
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
private function getClient() {
$key = md5($this->apiKey);
if (!isset(self::$clients[$key]) {
self::$clients[$key] = [];
}
if (count(self::$clients[$key]) < $this->maxConnections) {
$client = new Client([
'base_uri' => 'https://api.deepseek.com/v1',
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
'Content-Type' => 'application/json',
]
]);
self::$clients[$key][] = $client;
}
return array_pop(self::$clients[$key]);
}
private function releaseClient($client) {
$key = md5($this->apiKey);
self::$clients[$key][] = $client;
}
public function generateText($prompt) {
$client = $this->getClient();
try {
$response = $client->post('/chat/completions', [
'json' => [
'model' => 'deepseek-chat',
'messages' => [
['role' => 'user', 'content' => $prompt]
]
]
]);
$result = json_decode($response->getBody(), true);
return $result['choices'][0]['message']['content'];
} finally {
$this->releaseClient($client);
}
}
}
九、安全与合规
9.1 数据脱敏处理
处理用户输入时,对敏感信息进行脱敏:
class DataSanitizer {
/**
* 脱敏敏感信息
*/
public static function sanitize($text) {
// 脱敏手机号
$text = preg_replace('/(1[3-9]\d)\d{4}(\d{4})/', '$1****$2', $text);
// 脱敏身份证号
$text = preg_replace('/(\d{6})\d{8}(\d{4})/', '$1********$2', $text);
// 脱敏邮箱
$text = preg_replace('/([^@\s]+)@([^@\s]+)/', function($matches) {
$username = $matches[1];
$domain = $matches[2];
$masked = substr($username, 0, 3) . '****' . substr($username, -1);
return $masked . '@' . $domain;
}, $text);
return $text;
}
}
// 使用示例
$userInput = "我的手机号是13812345678,邮箱是example@example.com";
$sanitized = DataSanitizer::sanitize($userInput);
// 输出: 我的手机号是138****5678,邮箱是exa****e@example.com
9.2 内容安全过滤
对API返回内容进行安全过滤:
class ContentFilter {
private $forbiddenWords = [
'暴力', '赌博', '色情', '诈骗', '毒品'
];
/**
* 检查内容是否安全
*/
public function isSafe($content) {
foreach ($this->forbiddenWords as $word) {
if (strpos($content, $word) !== false) {
return false;
}
}
return true;
}
/**
* 过滤不安全内容
*/
public function filter($content) {
if (!$this->isSafe($content)) {
return "抱歉,该内容不符合安全规范";
}
return $content;
}
}
// 在API调用后添加过滤
$response = $client->generateText($prompt);
$filtered = $contentFilter->filter($response);
十、完整示例项目
10.1 智能客服系统
基于DeepSeek API构建的智能客服系统:
<?php
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
class DeepSeekCustomerService {
private $client;
private $apiKey;
private $sessionManager;
public function __construct($apiKey) {
$this->apiKey = $apiKey;
$this->client = new Client([
'base_uri' => 'https://api.deepseek.com/v1',
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
'Content-Type' => 'application/json',
]
]);
$this->sessionManager = new SessionManager();
}
/**
* 处理用户问题
*/
public function handleQuestion($userId, $question) {
// 获取对话历史
$session = $this->sessionManager->getSession($userId);
$messages = $session->getMessages();
// 添加用户消息
$messages[] = ['role' => 'user', 'content' => $question];
try {
$response = $this->client->post('/chat/completions', [
'json' => [
'model' => 'deepseek-chat',
'messages' => $messages,
'max_tokens' => 1000,
'temperature' => 0.7
]
]);
$result = json_decode($response->getBody(), true);
$reply = $result['choices'][0]['message']['content'];
// 保存对话历史
$session->addMessage('user', $question);
$session->addMessage('assistant', $reply);
return $reply;
} catch (Exception $e) {
error_log("DeepSeek API调用失败: " . $e->getMessage());
return "抱歉,系统暂时无法处理您的请求,请稍后重试";
}
}
}
// 会话管理类
class SessionManager {
private $sessions = [];
private $maxHistory = 10;
public function getSession($userId) {
if (!isset($this->sessions[$userId])) {
$this->sessions[$userId] = new Session($userId, $this->maxHistory);
}
return $this->sessions[$userId];
}
}
class Session {
private $userId;
private $messages = [];
private $maxHistory;
public function __construct($userId, $maxHistory) {
$this->userId = $userId;
$this->maxHistory = $maxHistory;
// 添加系统提示词
$this->messages[] = [
'role' => 'system',
'content' => '你是一个专业的客服助手,请用友好、专业的语气回答用户问题。'
];
}
public function addMessage($role, $content) {
$this->messages[] = ['role' => $role, 'content' => $content];
// 限制历史记录长度
if (count($this->messages) > $this->maxHistory + 1) {
$this->messages = array_slice($this->messages, -$this->maxHistory - 1);
}
}
public function getMessages() {
return $this->messages;
}
public function clear() {
$this->messages = [];
}
}
// 使用示例
$apiKey = getenv('DEEPSEEK_API_KEY');
$service = new DeepSeekCustomerService($apiKey);
// 模拟用户对话
$userId = 'user123';
echo $service->handleQuestion($userId, "你好,我想咨询产品信息");
echo $service->handleQuestion($userId, "有哪些产品类型?");
?>
10.2 文件解析助手
基于DeepSeek文件解析功能的文档助手:
class DocumentAssistant {
private $client;
private $apiKey;
public function __construct($apiKey) {
$this->apiKey = $apiKey;
$this->client = new Client([
'base_uri' => 'https://api.deepseek.com/v1',
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
'Content-Type' => 'application/json',
]
]);
}
/**
* 上传并解析文档
*/
public function uploadAndParse($filePath) {
try {
// 上传文件
$response = $this->client->post('/files', [
'multipart' => [
[
'name' => 'file',
'contents' => fopen($filePath, 'r'),
'filename' => basename($filePath)
],
[
'name' => 'purpose',
'contents' => 'assistants'
]
]
]);
$fileInfo = json_decode($response->getBody(), true);
$fileId = $fileInfo['id'];
// 解析文档内容
$summary = $this->summarizeDocument($fileId);
$keywords = $this->extractKeywords($fileId);
return [
'file_id' => $fileId,
'summary' => $summary,
'keywords' => $keywords
];
} catch (Exception $e) {
throw new Exception("文档解析失败: " . $e->getMessage());
}
}
/**
* 总结文档内容
*/
private function summarizeDocument($fileId) {
$response = $this->client->post('/chat/completions', [
'json' => [
'model' => 'deepseek-chat',
'messages' => [
[
'role' => 'user',
'content' => [
[
'type' => 'file',
'file_id' => $fileId
],
[
'type' => 'text',
'text' => '请用中文总结这篇文档的主要内容,不超过200字'
]
]
]
],
'max_tokens' => 500
]
]);
$result = json_decode($response->getBody(), true);
return $result['choices'][0]['message']['content'];
}
/**
* 提取关键词
*/
private function extractKeywords($fileId) {
$response = $this->client->post('/chat/completions', [
'json' => [
'model' => 'deepseek-chat',
'messages' => [
[
'role' => 'user',
'content' => [
[
'type' => 'file',
'file_id' => $fileId
],
[
'type' => 'text',
'text' => '请提取这篇文档的关键词,用逗号分隔'
]
]
]
],
'max_tokens' => 200
]
]);
$result = json_decode($response->getBody(), true);
return $result['choices'][0]['message']['content'];
}
}
// 使用示例
$apiKey = getenv('DEEPSEEK_API_KEY');
$assistant = new DocumentAssistant($apiKey);
$result = $assistant->uploadAndParse('/path/to/document.pdf');
print_r($result);
?>
总结
本文详细介绍了PHP调用DeepSeek API的完整流程,从基础调用到高级功能实现,涵盖了文本生成、多轮对话、流式输出、文件解析、图片理解等核心功能。通过合理的错误处理、性能优化和安全措施,可以构建稳定、高效的AI应用。
关键要点总结:
- 环境配置:确保PHP版本和扩展满足要求,正确配置API密钥
- 基础调用:掌握文本生成接口的核心参数和响应格式
- 高级功能:实现多轮对话上下文管理、流式输出实时显示
- 文件处理:支持文档上传和基于文件内容的智能问答
- 错误处理:完善的错误码处理和指数退避重试机制
- 性能优化:批量请求、响应缓存、连接池管理等优化策略
- 安全合规:数据脱敏、内容过滤、API密钥安全管理
通过本文的指导,开发者可以快速上手DeepSeek API,构建各类AI驱动的应用,如智能客服、文档助手、内容生成工具等,为业务场景提供智能化解决方案。
若内容若侵犯到您的权益,请发送邮件至:platform_service@jienda.com我们将第一时间处理!
所有资源仅限于参考和学习,版权归JienDa作者所有,更多请访问JienDa首页。





