一、Laravel项目安装EasyWeChat
首先,使用 Composer 安装 EasyWeChat 扩展:
composer require overtrue/easywechat
安装完成后,在 Laravel 的配置文件中,配置微信公众平台的相关信息,包括 AppID 和 AppSecret。这些信息可以在微信公众平台的开发者设置中获取。
二、扩展 EasyWeChat:创建 DeepSeekService
在 Laravel 中,创建一个新的服务类 DeepSeekService
,用于与 DeepSeek 的 API 进行交互。以下是代码实现:
namespace App\Services;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
class DeepSeekService
{
protected $apiKey;
protected $apiUrl;
protected $model;
public function __construct()
{
$this->apiKey = config('services.deepseek.api_key');
$this->apiUrl = config('services.deepseek.api_url');
$this->model = config('services.deepseek.model');
}
public function askQuestion($question)
{
Log::info('DeepSeekService: askQuestion method called with question:', ['question' => $question]);
$cacheKey = 'deepseek Question:' . md5($question);
if (cache()->has($cacheKey)) {
Log::info('DeepSeekService: Using cached response for:', ['question' => $question]);
return cache()->get($cacheKey);
}
$client = new Client();
try {
$data = [
'model' => $this->model,
'messages' => [
[
'role' => 'user',
'content' => $question,
],
],
'temperature' => 0.7
];
$response = $client->post($this->apiUrl . '/chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
'Content-Type' => 'application/json'
],
'json' => $data
]);
if ($response->getStatusCode() == 200) {
$data = json_decode($response->getBody(), true);
Log::info('DeepSeekService: Received response from API:', ['response' => $data]);
$answer = $data['choices'][0]['message']['content'] ?? '暂无回答';
cache()->put($cacheKey, $answer, 60); // 缓存1分钟
return $answer;
} else {
Log::warning('DeepSeekService: API returned non-200 status code:', ['status_code' => $response->getStatusCode()]);
return '问答服务暂时不可用';
}
} catch (\Exception $e) {
Log::error('DeepSeekService: Exception occurred while calling API:', ['exception' => $e]);
return '问答服务暂时不可用';
}
}
}
三、配置服务文件
在 config/services.php
中,添加 DeepSeek 的配置项:
'deepseek' => [
'api_key' => env('DEEPSEEK_API_KEY'),
'api_url' => env('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1/ask'),
'model' => env('DEEPSEEK_MODEL'),
],
在 .env
文件中,配置 DeepSeek 的接口信息:
扫码关注公众号,查看隐藏内容
六、总结
通过以上步骤,我们成功在 Laravel 框架中接入了 DeepSeek,实现了微信公众号的智能问答功能。借助队列机制,我们有效避免了微信请求超时的问题,确保用户体验的流畅性。希望本文能为开发者提供有价值的参考,助力更多智能应用的开发。
END