checkChatInformation(); $modelType = trim(Request::input('model_type', '')); $modelName = trim(Request::input('model_name', '')); $contextInput = Request::input('context', []); if ($modelType === '' || $modelName === '') { return Base::retError('参数错误'); } if (is_string($contextInput)) { $decoded = json_decode($contextInput, true); if (json_last_error() === JSON_ERROR_NONE) { $contextInput = $decoded; } } if (!is_array($contextInput)) { return Base::retError('context 参数格式错误'); } $context = []; foreach ($contextInput as $item) { if (!is_array($item) || count($item) < 2) { continue; } $role = trim((string)($item[0] ?? '')); $message = trim((string)($item[1] ?? '')); if ($role === '' || $message === '') { continue; } $context[] = [$role, $message]; } $contextJson = json_encode($context, JSON_UNESCAPED_UNICODE); if ($contextJson === false) { return Base::retError('context 参数格式错误'); } $setting = Base::setting('aibotSetting'); $apiKey = Base::val($setting, $modelType . '_key'); if ($modelType === 'wenxin') { $wenxinSecret = Base::val($setting, 'wenxin_secret'); if ($wenxinSecret) { $apiKey = trim(($apiKey ?: '') . ':' . $wenxinSecret); } } if ($modelType === 'ollama' && empty($apiKey)) { $apiKey = Base::strRandom(6); } if (empty($apiKey)) { return Base::retError('模型未启用'); } $remoteModelType = match ($modelType) { 'qianwen' => 'qwen', default => $modelType, }; $authResult = Ihttp::ihttp_post('http://nginx/ai/invoke/auth', [ 'api_key' => $apiKey, 'model_type' => $remoteModelType, 'model_name' => $modelName, 'context' => $contextJson, ], 30); if (Base::isError($authResult)) { return Base::retError($authResult['msg']); } $body = Base::json2array($authResult['data']); if ($body['code'] !== 200) { return Base::retError($body['error'] ?: 'AI 接口返回异常', $body); } $streamKey = Base::val($body, 'data.stream_key'); if (empty($streamKey)) { return Base::retError('AI 接口返回数据异常'); } return Base::retSuccess('success', [ 'stream_key' => $streamKey, ]); } }