AgentTraceService.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Http\Requests\V3\StoreAgentTraceRequest;
  4. use App\Models\AgentFeedback;
  5. use App\Models\AgentRun;
  6. use App\Models\AgentRunStep;
  7. use App\Models\AgentThread;
  8. use Illuminate\Support\Arr;
  9. use Illuminate\Support\Carbon;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Validation\ValidationException;
  13. /**
  14. * AI 对话的研究过程入库与清理。
  15. *
  16. * 写入方是 agent 服务(服务密钥鉴权),终端用户由它透传的 bearer 决定:
  17. * 有效的人类 token → 记到账号下;没有 / 失效 / 是模型 token → 记为游客,
  18. * 只认设备匿名 id,并记客户端 IP。token 失效也照记不拒——这批记录要用来防滥用,
  19. * 不能因为用户登录过期就丢。
  20. */
  21. class AgentTraceService
  22. {
  23. /**
  24. * 会话标题取第一句提问的前多少个字。
  25. */
  26. private const TITLE_LENGTH = 60;
  27. public function __construct(
  28. private readonly AgentAccountService $accounts,
  29. private readonly CreditService $credits,
  30. ) {}
  31. /**
  32. * 写入一次提问(幂等)。
  33. *
  34. * run_id 已存在时原样返回已有的那条(`wasRecentlyCreated` 为 false → 200),
  35. * agent 端补发同一条不会写出第二份。status=error 且没有回答时退回这次的扣费。
  36. *
  37. * @param array<string, mixed> $data {@see StoreAgentTraceRequest} 校验过的入参
  38. *
  39. * @throws ValidationException 游客没带 device_id
  40. */
  41. public function record(?string $bearerUid, array $data): AgentRun
  42. {
  43. $account = $this->accounts->resolve($bearerUid, $data['device_id'] ?? null);
  44. $startedAt = isset($data['started_at']) ? Carbon::parse($data['started_at']) : now();
  45. return DB::transaction(function () use ($data, $account, $startedAt) {
  46. // 已删除(软删)的提问也算存在:补发同一条不会重建出一份来
  47. $existing = AgentRun::withTrashed()->with('thread')->where('run_id', $data['run_id'])->first();
  48. if ($existing) {
  49. return $existing;
  50. }
  51. $thread = AgentThread::withTrashed()->createOrFirst(
  52. ['thread_id' => $data['thread_id']],
  53. [
  54. ...$account->columns(),
  55. 'title' => $this->titleOf($data['question']),
  56. 'client' => $data['client'] ?? null,
  57. 'last_run_at' => $startedAt,
  58. ],
  59. );
  60. // threadId 全局唯一:别的账号的会话不准往里写(扣费时已拦过,这里兜底)
  61. if (! $thread->isOwnedBy($account)) {
  62. abort(403, __('messages.agent_thread_forbidden'));
  63. }
  64. if ($thread->last_run_at === null || $thread->last_run_at->lt($startedAt)) {
  65. $thread->last_run_at = $startedAt;
  66. $thread->save();
  67. }
  68. // 评价先于研究过程到达时:评价了就是同意用于改进(客户端评价前已征得同意)
  69. if (! ($data['improve'] ?? true) && ! empty($data['assistant_message_id'])
  70. && AgentFeedback::ownedBy($account)->where('message_id', $data['assistant_message_id'])->exists()) {
  71. $data['improve'] = true;
  72. }
  73. // 重新生成:客户端只知道被替换那条回答的消息 id,在同一会话里换算成那一轮的 run_id。
  74. // 会话历史回放时被替换的那一轮不再返回(AgentRun::scopeVisible)
  75. if (empty($data['replaces_run_id']) && ! empty($data['replaces_message_id'])) {
  76. $data['replaces_run_id'] = AgentRun::where('agent_thread_id', $thread->id)
  77. ->where('assistant_message_id', $data['replaces_message_id'])
  78. ->value('run_id');
  79. }
  80. $run = AgentRun::withTrashed()->createOrFirst(['run_id' => $data['run_id']], [
  81. ...Arr::except($data, ['run_id', 'thread_id', 'device_id', 'client_ip', 'steps', 'replaces_message_id']),
  82. 'agent_thread_id' => $thread->id,
  83. ...$account->columns(),
  84. 'client_ip' => $account->isUser() ? null : ($data['client_ip'] ?? null),
  85. 'started_at' => $startedAt,
  86. ]);
  87. if ($run->wasRecentlyCreated) {
  88. $this->warnUnknown($run->run_id, $data);
  89. }
  90. if ($run->wasRecentlyCreated && ! empty($data['steps'])) {
  91. $run->steps()->createMany($data['steps']);
  92. }
  93. // 服务端出错、回答没生成 → 退回这次的扣费。用户自己中途取消(cancelled)照扣
  94. if ($run->wasRecentlyCreated && $run->status === 'error' && blank($run->answer)) {
  95. $this->credits->refundRun($run->run_id);
  96. }
  97. return $run->setRelation('thread', $thread);
  98. });
  99. }
  100. /**
  101. * backend 送来了 mint 还不认识的路由或步骤类型:照样入库,记一条警告提醒同步枚举
  102. * (AgentRun::ROUTES / AgentRunStep::KINDS,以及 OpenAPI 与前端)。
  103. *
  104. * @param array<string, mixed> $data
  105. */
  106. private function warnUnknown(string $runId, array $data): void
  107. {
  108. $route = $data['route'] ?? null;
  109. if ($route !== null && ! in_array($route, AgentRun::ROUTES, true)) {
  110. Log::warning('agent trace: unknown route', ['run_id' => $runId, 'route' => $route]);
  111. }
  112. $kinds = array_diff(array_unique(array_column($data['steps'] ?? [], 'kind')), AgentRunStep::KINDS);
  113. if ($kinds !== []) {
  114. Log::warning('agent trace: unknown step kinds', ['run_id' => $runId, 'kinds' => array_values($kinds)]);
  115. }
  116. }
  117. private function titleOf(string $question): string
  118. {
  119. $flat = trim((string) preg_replace('/\s+/u', ' ', $question));
  120. return mb_strlen($flat) > self::TITLE_LENGTH
  121. ? mb_substr($flat, 0, self::TITLE_LENGTH).'…'
  122. : $flat;
  123. }
  124. }