SystemExceptionService.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace App\Services;
  3. use App\Models\SystemException;
  4. use Illuminate\Support\Facades\Http;
  5. use Slowlyo\OwlAdmin\Services\AdminService;
  6. class SystemExceptionService extends AdminService
  7. {
  8. protected string $modelName = SystemException::class;
  9. /**
  10. * 使用 AI 分析异常
  11. */
  12. public function analyze($id)
  13. {
  14. $exception = $this->query()->findOrFail($id);
  15. // 调用免费的 AI API (这里以 ChatGPT 为例)
  16. $response = Http::post('https://api.openai.com/v1/chat/completions', [
  17. 'model' => 'gpt-3.5-turbo',
  18. 'messages' => [
  19. [
  20. 'role' => 'system',
  21. 'content' => '你是一个PHP专家,请分析这个异常并提供解决方案。'
  22. ],
  23. [
  24. 'role' => 'user',
  25. 'content' => "异常类型: {$exception->type}\n异常信息: {$exception->message}\n文件: {$exception->file}:{$exception->line}\n堆栈信息: {$exception->trace}"
  26. ]
  27. ]
  28. ], [
  29. 'Authorization' => 'Bearer ' . config('services.openai.api_key')
  30. ]);
  31. if ($response->successful()) {
  32. $solution = $response->json('choices.0.message.content');
  33. $exception->update([
  34. 'status' => 1, // 处理中
  35. 'solution' => $solution
  36. ]);
  37. return [
  38. 'status' => true,
  39. 'message' => 'AI分析完成'
  40. ];
  41. }
  42. return [
  43. 'status' => false,
  44. 'message' => 'AI分析失败: ' . $response->body()
  45. ];
  46. }
  47. /**
  48. * 批量AI分析
  49. */
  50. public function batchAnalyze()
  51. {
  52. $exceptions = $this->query()->where('status', 0)->limit(10)->get();
  53. foreach ($exceptions as $exception) {
  54. $this->analyze($exception->id);
  55. }
  56. return [
  57. 'status' => true,
  58. 'message' => '批量分析任务已提交'
  59. ];
  60. }
  61. /**
  62. * 标记为已处理
  63. */
  64. public function markHandled($id)
  65. {
  66. $this->query()->findOrFail($id)->update([
  67. 'status' => 2,
  68. 'handler' => auth()->user()->name,
  69. 'handled_at' => now()
  70. ]);
  71. return [
  72. 'status' => true,
  73. 'message' => '已标记为处理完成'
  74. ];
  75. }
  76. /**
  77. * 标记为忽略
  78. */
  79. public function ignore($id)
  80. {
  81. $this->query()->findOrFail($id)->update([
  82. 'status' => 3,
  83. 'handler' => auth()->user()->name,
  84. 'handled_at' => now()
  85. ]);
  86. return [
  87. 'status' => true,
  88. 'message' => '已标记为忽略'
  89. ];
  90. }
  91. }