|
| 1 | +<?php |
| 2 | + |
| 3 | + |
| 4 | +namespace Module\AigcBase\Util; |
| 5 | + |
| 6 | + |
| 7 | +use ModStart\Core\Exception\BizException; |
| 8 | +use ModStart\Core\Input\Response; |
| 9 | +use Module\AigcBase\Provider\AbstractAigcChatProvider; |
| 10 | +use Module\AigcBase\Provider\AigcChatProvider; |
| 11 | + |
| 12 | +class AigcChatUtil |
| 13 | +{ |
| 14 | + /** |
| 15 | + * 调用AI对话 |
| 16 | + * |
| 17 | + * @param string $systemPrompt 系统提示词 |
| 18 | + * @param string $userPrompt 用户消息 |
| 19 | + * @param array $option 选项 |
| 20 | + * - driver: 直接指定驱动全名(优先级最高) |
| 21 | + * - driverKey: 从配置读取驱动的 config key,默认 AigcBase_AdminDefaultChatDriver |
| 22 | + * @return array Response格式 |
| 23 | + * @throws BizException |
| 24 | + */ |
| 25 | + public static function chat($systemPrompt, $userPrompt, $option = []) |
| 26 | + { |
| 27 | + $driver = isset($option['driver']) ? $option['driver'] : null; |
| 28 | + if (empty($driver)) { |
| 29 | + $driverKey = isset($option['driverKey']) ? $option['driverKey'] : 'AigcBase_AdminDefaultChatDriver'; |
| 30 | + $driver = modstart_config($driverKey); |
| 31 | + } |
| 32 | + if (!$driver) { |
| 33 | + BizException::throws('机器人没有配置,请在 后台→系统设置→AI平台对接→功能设置 中配置'); |
| 34 | + } |
| 35 | + /** @var AbstractAigcChatProvider $provider */ |
| 36 | + $provider = AigcChatProvider::getByFullName($driver); |
| 37 | + if (empty($provider)) { |
| 38 | + BizException::throws('机器人没有配置'); |
| 39 | + } |
| 40 | + $chatOption = array_merge($option, [ |
| 41 | + 'systemPrompt' => $systemPrompt, |
| 42 | + 'markdown' => false, |
| 43 | + ]); |
| 44 | + unset($chatOption['driver']); |
| 45 | + unset($chatOption['driverKey']); |
| 46 | + $ret = $provider->chat(uniqid('chat_', true), $userPrompt, $chatOption); |
| 47 | + return $ret; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * 调用AI对话并返回文本内容 |
| 52 | + * |
| 53 | + * @param string $systemPrompt 系统提示词 |
| 54 | + * @param string $userPrompt 用户消息 |
| 55 | + * @param array $option 选项(同 chat()) |
| 56 | + * @return string |
| 57 | + * @throws BizException |
| 58 | + */ |
| 59 | + public static function chatText($systemPrompt, $userPrompt, $option = []) |
| 60 | + { |
| 61 | + $ret = self::chat($systemPrompt, $userPrompt, array_merge($option, ['markdown' => true])); |
| 62 | + if (!Response::isSuccess($ret)) { |
| 63 | + BizException::throws('AI对话失败:' . (isset($ret['msg']) ? $ret['msg'] : '未知错误')); |
| 64 | + } |
| 65 | + if (!empty($ret['data']['isError'])) { |
| 66 | + BizException::throws('AI对话失败'); |
| 67 | + } |
| 68 | + $content = isset($ret['data']['msg']['content']) ? $ret['data']['msg']['content'] : ''; |
| 69 | + return trim(strip_tags($content)); |
| 70 | + } |
| 71 | +} |
0 commit comments