LocalAIAnalysisService.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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::table('student_knowledge_mastery')
  222. ->where('student_id', $studentId)
  223. ->where('kp_code', $kpCode)
  224. ->update([
  225. 'mastery_level' => $mastery,
  226. 'updated_at' => now(),
  227. ]);
  228. // 如果没有更新任何记录,插入新记录
  229. if ($updated === 0) {
  230. DB::table('student_knowledge_mastery')
  231. ->insert([
  232. 'student_id' => $studentId,
  233. 'kp_code' => $kpCode,
  234. 'mastery_level' => $mastery,
  235. 'confidence_level' => 0.5, // 默认置信度
  236. 'created_at' => now(),
  237. 'updated_at' => now(),
  238. ]);
  239. }
  240. Log::debug('LocalAIAnalysisService: 掌握度已保存', [
  241. 'student_id' => $studentId,
  242. 'kp_code' => $kpCode,
  243. 'mastery' => $mastery,
  244. ]);
  245. } catch (\Exception $e) {
  246. // 表不存在时静默跳过
  247. Log::debug('LocalAIAnalysisService: 掌握度表不存在,跳过保存', [
  248. 'student_id' => $studentId,
  249. 'kp_code' => $kpCode,
  250. 'error' => $e->getMessage(),
  251. ]);
  252. }
  253. }
  254. /**
  255. * 获取学生掌握度
  256. *
  257. * @param string $studentId 学生ID
  258. * @param string|null $kpCode 知识点编码(可选)
  259. * @return array 掌握度数据
  260. */
  261. public function getStudentMastery(string $studentId, ?string $kpCode = null): array
  262. {
  263. try {
  264. $query = DB::table('student_knowledge_mastery')
  265. ->where('student_id', $studentId);
  266. if ($kpCode) {
  267. $query->where('kp_code', $kpCode);
  268. }
  269. $masteries = $query->get()->toArray();
  270. return [
  271. 'success' => true,
  272. 'data' => $masteries,
  273. ];
  274. } catch (\Exception $e) {
  275. // 表不存在时返回空数据
  276. Log::debug('LocalAIAnalysisService: 掌握度表不存在,返回空数据', [
  277. 'student_id' => $studentId,
  278. 'kp_code' => $kpCode,
  279. 'error' => $e->getMessage(),
  280. ]);
  281. return [
  282. 'success' => false,
  283. 'message' => '表不存在',
  284. 'data' => [],
  285. ];
  286. }
  287. }
  288. /**
  289. * 创建掌握度快照
  290. *
  291. * @param string $studentId 学生ID
  292. * @param string|null $paperId 关联试卷ID(可选)
  293. * @param string|null $answerRecordId 关联作答记录ID(可选)
  294. * @return array|null 快照数据
  295. */
  296. public function createMasterySnapshot(string $studentId, ?string $paperId = null, ?string $answerRecordId = null): ?array
  297. {
  298. try {
  299. // 获取最新掌握度数据
  300. $masteryData = $this->getStudentMastery($studentId);
  301. if (empty($masteryData['data'])) {
  302. Log::info('LocalAIAnalysisService: 没有掌握度数据,返回空快照', [
  303. 'student_id' => $studentId,
  304. ]);
  305. return [
  306. 'snapshot_id' => 'snap_' . Str::uuid()->toString(),
  307. 'student_id' => $studentId,
  308. 'paper_id' => $paperId,
  309. 'answer_record_id' => $answerRecordId,
  310. 'overall_mastery' => 0,
  311. 'weak_count' => 0,
  312. 'strong_count' => 0,
  313. 'mastery_changes' => [],
  314. ];
  315. }
  316. $snapshotId = 'snap_' . Str::uuid()->toString();
  317. $masteryItems = $masteryData['data'];
  318. $overallMastery = 0;
  319. $weakCount = 0;
  320. $strongCount = 0;
  321. foreach ($masteryItems as $item) {
  322. $level = (float) ($item->mastery_level ?? 0);
  323. $overallMastery += $level;
  324. if ($level < 0.6) {
  325. $weakCount++;
  326. } elseif ($level > 0.8) {
  327. $strongCount++;
  328. }
  329. }
  330. $overallMastery = count($masteryItems) > 0
  331. ? round($overallMastery / count($masteryItems), 4)
  332. : 0;
  333. return [
  334. 'snapshot_id' => $snapshotId,
  335. 'student_id' => $studentId,
  336. 'paper_id' => $paperId,
  337. 'answer_record_id' => $answerRecordId,
  338. 'overall_mastery' => $overallMastery,
  339. 'weak_count' => $weakCount,
  340. 'strong_count' => $strongCount,
  341. 'mastery_changes' => [],
  342. ];
  343. } catch (\Exception $e) {
  344. Log::error('LocalAIAnalysisService: 创建掌握度快照失败', [
  345. 'student_id' => $studentId,
  346. 'paper_id' => $paperId,
  347. 'error' => $e->getMessage(),
  348. ]);
  349. return null;
  350. }
  351. }
  352. }