LocalAIAnalysisService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Str;
  7. /**
  8. * 本地AI分析服务
  9. * 直接调用QuestionBankService的AI分析API,不依赖LearningAnalytics项目
  10. */
  11. class LocalAIAnalysisService
  12. {
  13. protected string $questionBankApiUrl;
  14. protected int $timeout = 60;
  15. public function __construct(
  16. private readonly QuestionBankService $questionBankService
  17. ) {
  18. $this->questionBankApiUrl = config('services.question_bank.url', env('QUESTION_BANK_API_URL', 'http://localhost:5015'));
  19. }
  20. /**
  21. * 分析学生答案
  22. *
  23. * @param array $answerData 包含 question_text, student_answer, score, max_score, kp_code 等
  24. * @return array 分析结果
  25. */
  26. public function analyzeAnswer(array $answerData): array
  27. {
  28. try {
  29. Log::info('LocalAIAnalysisService: 开始分析答案', [
  30. 'question_id' => $answerData['question_id'] ?? 'unknown',
  31. 'kp_code' => $answerData['kp_code'] ?? 'unknown',
  32. ]);
  33. // 构建请求数据
  34. $requestData = [
  35. 'question_text' => $answerData['question_text'] ?? '',
  36. 'student_answer' => $answerData['student_answer'] ?? '',
  37. 'score_value' => (float) ($answerData['score'] ?? 0),
  38. 'full_score' => (float) ($answerData['max_score'] ?? 10),
  39. 'kp_code' => $answerData['kp_code'] ?? '',
  40. 'model' => 'deepseek', // 可配置
  41. ];
  42. // 调用QuestionBankService的AI分析API
  43. $response = Http::timeout($this->timeout)
  44. ->post($this->questionBankApiUrl . '/api/ai/analyze-answer', $requestData);
  45. if ($response->successful()) {
  46. $result = $response->json();
  47. if ($result['success'] ?? false) {
  48. Log::info('LocalAIAnalysisService: AI分析成功', [
  49. 'question_id' => $answerData['question_id'] ?? 'unknown',
  50. 'model_used' => $result['model_used'] ?? 'unknown',
  51. ]);
  52. return [
  53. 'success' => true,
  54. 'data' => $result['data'] ?? [],
  55. 'model_used' => $result['model_used'] ?? 'unknown',
  56. ];
  57. }
  58. }
  59. Log::warning('LocalAIAnalysisService: AI分析失败,使用规则分析', [
  60. 'status' => $response->status(),
  61. 'response' => $response->body(),
  62. ]);
  63. // 回退到规则分析
  64. return [
  65. 'success' => true,
  66. 'data' => $this->ruleBasedAnalysis($answerData),
  67. 'model_used' => 'fallback-rules',
  68. 'fallback' => true,
  69. ];
  70. } catch (\Exception $e) {
  71. Log::error('LocalAIAnalysisService: 分析异常,使用规则分析', [
  72. 'error' => $e->getMessage(),
  73. 'question_id' => $answerData['question_id'] ?? 'unknown',
  74. ]);
  75. return [
  76. 'success' => true,
  77. 'data' => $this->ruleBasedAnalysis($answerData),
  78. 'model_used' => 'fallback-rules',
  79. 'fallback' => true,
  80. 'fallback_reason' => $e->getMessage(),
  81. ];
  82. }
  83. }
  84. /**
  85. * 批量分析学生答案
  86. *
  87. * @param array $answers 答案数组
  88. * @return array 分析结果数组
  89. */
  90. public function analyzeBatchAnswers(array $answers): array
  91. {
  92. $results = [];
  93. foreach ($answers as $answer) {
  94. $results[] = $this->analyzeAnswer($answer);
  95. }
  96. return $results;
  97. }
  98. /**
  99. * 基于规则的答案分析(备用方案)
  100. */
  101. private function ruleBasedAnalysis(array $answerData): array
  102. {
  103. $studentAnswer = $answerData['student_answer'] ?? '';
  104. $score = (float) ($answerData['score'] ?? 0);
  105. $maxScore = (float) ($answerData['max_score'] ?? 10);
  106. // 无答案情况
  107. if (empty(trim($studentAnswer))) {
  108. return [
  109. 'correct' => false,
  110. 'score' => 0,
  111. 'full_score' => $maxScore,
  112. 'partial_score_ratio' => 0.0,
  113. 'mistake_type' => '未作答',
  114. 'mistake_category' => '态度/习惯',
  115. 'reason' => '学生未作答',
  116. 'correct_solution' => '请参考标准答案',
  117. 'suggestions' => '建议鼓励学生尝试作答,不要留白',
  118. 'next_steps' => ['复习相关知识点', '尝试从已知条件入手'],
  119. 'analysis_confidence' => 1.0,
  120. 'analysis_tokens' => 0,
  121. ];
  122. }
  123. $scoreRatio = $maxScore > 0 ? $score / $maxScore : 0;
  124. // 满分
  125. if ($scoreRatio == 1.0) {
  126. return [
  127. 'correct' => true,
  128. 'score' => $score,
  129. 'full_score' => $maxScore,
  130. 'partial_score_ratio' => 1.0,
  131. 'mistake_type' => '无',
  132. 'mistake_category' => '无',
  133. 'reason' => '回答正确',
  134. 'correct_solution' => '回答正确',
  135. 'suggestions' => '继续保持',
  136. 'next_steps' => ['尝试更高难度的题目'],
  137. 'analysis_confidence' => 1.0,
  138. 'analysis_tokens' => 0,
  139. ];
  140. }
  141. // 零分或低分
  142. return [
  143. 'correct' => false,
  144. 'score' => $score,
  145. 'full_score' => $maxScore,
  146. 'partial_score_ratio' => $scoreRatio,
  147. 'mistake_type' => $scoreRatio < 0.3 ? '概念错误' : '计算错误/步骤缺失',
  148. 'mistake_category' => $scoreRatio < 0.3 ? '知识掌握' : '解题技巧',
  149. 'reason' => $scoreRatio < 0.3
  150. ? '学生对题目理解存在偏差或知识掌握不牢固,需要系统复习'
  151. : '解题方向有误,需要学习正确的解题方法',
  152. 'correct_solution' => '需要从基础概念开始,系统学习相关知识',
  153. 'suggestions' => '建议从基础概念开始,系统复习相关知识,多做基础练习',
  154. 'next_steps' => ['学习基础概念', '理解公式原理', '从简单题开始练习', '逐步提升难度'],
  155. 'analysis_confidence' => 0.7,
  156. 'analysis_tokens' => 100,
  157. ];
  158. }
  159. /**
  160. * 更新学生掌握度
  161. *
  162. * @param string $studentId 学生ID
  163. * @param string $kpCode 知识点编码
  164. * @param float $currentMastery 当前掌握度
  165. * @param bool $isCorrect 是否正确
  166. * @param float $difficulty 题目难度
  167. * @return array 更新后的掌握度
  168. */
  169. public function updateMastery(string $studentId, string $kpCode, float $currentMastery, bool $isCorrect, float $difficulty = 0.5): array
  170. {
  171. try {
  172. // 简化的掌握度更新算法
  173. // 基于BKT(贝叶斯知识追踪)模型的简化版本
  174. $learningRate = 0.1; // 学习速率
  175. $forgettingRate = 0.05; // 遗忘速率
  176. // 根据正确性和难度调整学习速率
  177. $adjustedLearningRate = $learningRate * (1 + (1 - $difficulty));
  178. $adjustedForgettingRate = $forgettingRate * (1 - (1 - $difficulty));
  179. $newMastery = $currentMastery;
  180. if ($isCorrect) {
  181. // 答对了,增加掌握度
  182. $newMastery = $currentMastery + ($adjustedLearningRate * (1 - $currentMastery));
  183. } else {
  184. // 答错了,遗忘一些
  185. $newMastery = $currentMastery * (1 - $adjustedForgettingRate);
  186. }
  187. // 确保在[0,1]范围内
  188. $newMastery = max(0, min(1, $newMastery));
  189. // 保存到数据库
  190. $this->saveMasteryToDatabase($studentId, $kpCode, $newMastery);
  191. return [
  192. 'kp_code' => $kpCode,
  193. 'old_mastery' => $currentMastery,
  194. 'new_mastery' => $newMastery,
  195. 'change' => $newMastery - $currentMastery,
  196. 'is_correct' => $isCorrect,
  197. ];
  198. } catch (\Exception $e) {
  199. Log::error('LocalAIAnalysisService: 更新掌握度失败', [
  200. 'student_id' => $studentId,
  201. 'kp_code' => $kpCode,
  202. 'error' => $e->getMessage(),
  203. ]);
  204. return [
  205. 'kp_code' => $kpCode,
  206. 'old_mastery' => $currentMastery,
  207. 'new_mastery' => $currentMastery,
  208. 'change' => 0,
  209. 'is_correct' => $isCorrect,
  210. 'error' => $e->getMessage(),
  211. ];
  212. }
  213. }
  214. /**
  215. * 保存掌握度到数据库
  216. */
  217. private function saveMasteryToDatabase(string $studentId, string $kpCode, float $mastery): void
  218. {
  219. try {
  220. // 尝试更新现有记录
  221. $updated = DB::connection('pgsql')
  222. ->table('student_knowledge_mastery')
  223. ->where('student_id', $studentId)
  224. ->where('kp_code', $kpCode)
  225. ->update([
  226. 'mastery_level' => $mastery,
  227. 'updated_at' => now(),
  228. ]);
  229. // 如果没有更新任何记录,插入新记录
  230. if ($updated === 0) {
  231. DB::connection('pgsql')
  232. ->table('student_knowledge_mastery')
  233. ->insert([
  234. 'student_id' => $studentId,
  235. 'kp_code' => $kpCode,
  236. 'mastery_level' => $mastery,
  237. 'confidence_level' => 0.5, // 默认置信度
  238. 'created_at' => now(),
  239. 'updated_at' => now(),
  240. ]);
  241. }
  242. Log::debug('LocalAIAnalysisService: 掌握度已保存', [
  243. 'student_id' => $studentId,
  244. 'kp_code' => $kpCode,
  245. 'mastery' => $mastery,
  246. ]);
  247. } catch (\Exception $e) {
  248. Log::warning('LocalAIAnalysisService: 保存掌握度失败', [
  249. 'student_id' => $studentId,
  250. 'kp_code' => $kpCode,
  251. 'error' => $e->getMessage(),
  252. ]);
  253. }
  254. }
  255. /**
  256. * 获取学生掌握度
  257. *
  258. * @param string $studentId 学生ID
  259. * @param string|null $kpCode 知识点编码(可选)
  260. * @return array 掌握度数据
  261. */
  262. public function getStudentMastery(string $studentId, ?string $kpCode = null): array
  263. {
  264. try {
  265. $query = DB::connection('pgsql')
  266. ->table('student_knowledge_mastery')
  267. ->where('student_id', $studentId);
  268. if ($kpCode) {
  269. $query->where('kp_code', $kpCode);
  270. }
  271. $masteries = $query->get()->toArray();
  272. return [
  273. 'success' => true,
  274. 'data' => $masteries,
  275. ];
  276. } catch (\Exception $e) {
  277. Log::error('LocalAIAnalysisService: 获取掌握度失败', [
  278. 'student_id' => $studentId,
  279. 'kp_code' => $kpCode,
  280. 'error' => $e->getMessage(),
  281. ]);
  282. return [
  283. 'success' => false,
  284. 'message' => $e->getMessage(),
  285. 'data' => [],
  286. ];
  287. }
  288. }
  289. /**
  290. * 创建掌握度快照
  291. *
  292. * @param string $studentId 学生ID
  293. * @param string|null $paperId 关联试卷ID(可选)
  294. * @param string|null $answerRecordId 关联作答记录ID(可选)
  295. * @return array|null 快照数据
  296. */
  297. public function createMasterySnapshot(string $studentId, ?string $paperId = null, ?string $answerRecordId = null): ?array
  298. {
  299. try {
  300. // 获取最新掌握度数据
  301. $masteryData = $this->getStudentMastery($studentId);
  302. if (empty($masteryData['data'])) {
  303. Log::warning('LocalAIAnalysisService: 没有掌握度数据,无法创建快照', [
  304. 'student_id' => $studentId,
  305. ]);
  306. return null;
  307. }
  308. $snapshotId = 'snap_' . Str::uuid()->toString();
  309. $masteryItems = $masteryData['data'];
  310. $overallMastery = 0;
  311. $weakCount = 0;
  312. $strongCount = 0;
  313. foreach ($masteryItems as $item) {
  314. $level = (float) ($item->mastery_level ?? 0);
  315. $overallMastery += $level;
  316. if ($level < 0.6) {
  317. $weakCount++;
  318. } elseif ($level > 0.8) {
  319. $strongCount++;
  320. }
  321. }
  322. $overallMastery = count($masteryItems) > 0
  323. ? round($overallMastery / count($masteryItems), 4)
  324. : 0;
  325. // 保存快照
  326. DB::connection('pgsql')
  327. ->table('knowledge_point_mastery_snapshots')
  328. ->insert([
  329. 'snapshot_id' => $snapshotId,
  330. 'student_id' => $studentId,
  331. 'paper_id' => $paperId,
  332. 'answer_record_id' => $answerRecordId,
  333. 'mastery_data' => json_encode($masteryItems),
  334. 'overall_mastery' => $overallMastery,
  335. 'weak_knowledge_points_count' => $weakCount,
  336. 'strong_knowledge_points_count' => $strongCount,
  337. 'snapshot_time' => now(),
  338. 'created_at' => now(),
  339. 'updated_at' => now(),
  340. ]);
  341. Log::info('LocalAIAnalysisService: 掌握度快照已创建', [
  342. 'student_id' => $studentId,
  343. 'snapshot_id' => $snapshotId,
  344. 'overall_mastery' => $overallMastery,
  345. ]);
  346. return [
  347. 'snapshot_id' => $snapshotId,
  348. 'student_id' => $studentId,
  349. 'paper_id' => $paperId,
  350. 'answer_record_id' => $answerRecordId,
  351. 'overall_mastery' => $overallMastery,
  352. 'weak_count' => $weakCount,
  353. 'strong_count' => $strongCount,
  354. ];
  355. } catch (\Exception $e) {
  356. Log::error('LocalAIAnalysisService: 创建掌握度快照失败', [
  357. 'student_id' => $studentId,
  358. 'paper_id' => $paperId,
  359. 'error' => $e->getMessage(),
  360. ]);
  361. return null;
  362. }
  363. }
  364. }