| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- <?php
- namespace app\utils\DeepSeek;
- class DeepSeekAiTools {
- const CHAR_API_URL = 'https://api.deepseek.com';
- // 获取access_token
- public static function test() {
- $ret = self::chat([
- 'apiKey' => 'sk-4d0415c08d',
- ], '小米手机 好看 好用');
- var_dump($ret);
- die;
- }
- /**
- * 发送消息
- */
- public static function chat($conf, $question, $task = '生成一个帖子文案:') {
- try {
- // 从环境变量获取API密钥(推荐安全做法)
- $apiKey = $conf['apiKey'];
- if (!$apiKey) {
- throw new \Exception('请先配置接口参数');
- }
- // 验证输入参数
- if (!isset($question) || empty(trim($question))) {
- throw new \Exception('请输入有效关键字');
- }
- $keyword = trim($task . $question);
- // 构造API请求
- $requestData = [
- 'model' => 'deepseek-chat',
- 'prompt' => $keyword,
- 'max_tokens' => 300,
- 'temperature' => 0.7,
- ];
- $res = http_post(static::CHAR_API_URL . '/beta/completions', [
- 'body' => json_encode($requestData),
- 'headers' => [
- 'Content-Type' => 'application/json',
- 'Authorization' => 'Bearer ' . $apiKey
- ],
- ]);
- if ($res->getStatusCode() != 200) {
- throw new \Exception('StatusCode Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
- }
- $data = json_decode((string) $res->getBody(), true);
- if (isset($data['error_code'])) {
- throw new \Exception('error_code Error: ' . $data['error_code'] . ' ' . $data['error_msg']);
- }
- $data['result'] = $data['choices'] ? $data['choices'][0]['text'] : '';
- return [
- 'code' => 0,
- 'data' => $data,
- ];
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
- public static function send($key, $question)
- {
- try {
- if (empty(trim($question))) {
- throw new \Exception('请输入有效问题');
- }
- $body = json_encode([
- 'model' => 'deepseek-chat',
- 'messages' => [
- [
- 'role' => 'user',
- 'content' => $question,
- ],
- ],
- 'temperature' => 1.3,
- ]);
-
- $res = http_post(static::CHAR_API_URL . '/chat/completions', [
- 'body' => $body,
- 'headers' => [
- 'Content-Type' => 'application/json',
- 'Authorization' => 'Bearer ' . $key,
- ],
- ]);
- if ($res->getStatusCode() != 200) {
- throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
- }
- $data = json_decode((string) $res->getBody(), true);
- if (isset($data['error_code'])) {
- throw new \Exception('error_code Error: ' . $data['error_code'] . ' ' . $data['error_msg']);
- }
- $result = $data['choices'] ? $data['choices'][0]['message']['content'] : '';
- return [
- 'code' => 0,
- 'data' => $result,
- ];
- } catch (\Throwable $e) {
- return [
- 'code' => 1,
- 'msg' => $e->getMessage(),
- ];
- }
- }
- }
|