This commit is contained in:
gr
2026-10-23 09:27:45 +08:00
34 changed files with 2866 additions and 225 deletions
@@ -14,6 +14,7 @@ use app\common\service\NihaixiaClinicalSkill;
use app\common\service\TcmAncientBooksReference;
use app\adminapi\service\AssistantSseTiming;
use app\adminapi\service\AiContextCompactionCache;
use app\adminapi\service\AssistantRequestControl;
use think\facade\Db;
use think\facade\Log;
@@ -347,7 +348,8 @@ class DiagnosisAiLogic extends BaseLogic
}
/**
* 在 SSE headers 发出前完成参数、权限、DataScope、病例和模型选择预检。
* 参数、权限、DataScope 和模型选择完成后可通过 on_authorized 提前开启 SSE;
* 随后的资料聚合/证据整理通过可选 progress 与取消回调协作。
* 返回值只供同一请求内的流执行使用,绝不能直接序列化给客户端。
*
* @param array<string,mixed> $adminInfo
@@ -362,7 +364,8 @@ class DiagnosisAiLogic extends BaseLogic
string $prompt,
int $adminId,
array $adminInfo,
?AssistantSseTiming $timing = null
?AssistantSseTiming $timing = null,
array $options = []
): ?array {
$prepareStartedAt = hrtime(true);
$aggregateMs = 0;
@@ -402,16 +405,6 @@ class DiagnosisAiLogic extends BaseLogic
return null;
}
$aggregateStartedAt = hrtime(true);
$context = self::buildCaseContext($diagnosis, $adminId, $adminInfo);
$aggregateMs = AssistantSseTiming::elapsedMs($aggregateStartedAt);
$sourceBytes = strlen((string) ($context['case_text'] ?? ''));
$attachmentCount = count(is_array($context['files'] ?? null) ? $context['files'] : []);
if ($context['case_lines'] === []) {
self::setError('患者纵向资料为空或聚合失败,无法使用 AI 助手');
return null;
}
$profile = self::selectAssistantProfile($task, $prompt);
$modelConfig = self::modelConfigs()[$profile] ?? [];
$model = trim((string) ($modelConfig['name'] ?? ''));
@@ -420,14 +413,40 @@ class DiagnosisAiLogic extends BaseLogic
self::setError('AI 模型服务尚未完整配置');
return null;
}
// This is the only early-start boundary: all identity, scope and task
// checks have succeeded, while no aggregation or model work has begun.
if (is_callable($options['on_authorized'] ?? null)
&& ($options['on_authorized'])(['diagnosis_id' => $diagnosisId, 'task' => $task, 'model_key' => $profile]) === false) {
self::setError('该请求标识已使用,请重新发起');
return null;
}
if (self::assistantCancelled($options['should_abort'] ?? null)) return null;
self::assistantProgress($options, ['phase' => 'preparing', 'status' => 'aggregating', 'message' => '正在聚合本次授权范围内的患者资料']);
$aggregateStartedAt = hrtime(true);
$context = self::buildCaseContext($diagnosis, $adminId, $adminInfo);
$aggregateMs = AssistantSseTiming::elapsedMs($aggregateStartedAt);
$sourceBytes = strlen((string) ($context['case_text'] ?? ''));
$attachmentCount = count(is_array($context['files'] ?? null) ? $context['files'] : []);
if (self::assistantCancelled($options['should_abort'] ?? null)) return null;
self::assistantProgress($options, ['phase' => 'preparing', 'status' => 'aggregated',
'message' => '资料已聚合,正在整理本次提交内容',
'source_summary' => $context['source_summary'] ?? [], 'attachment_count' => $attachmentCount]);
if ($context['case_lines'] === []) {
self::setError('患者纵向资料为空或聚合失败,无法使用 AI 助手');
return null;
}
$compactionAttempted = $sourceBytes > self::MAX_PROMPT_SOURCE_BYTES;
$compactionStartedAt = hrtime(true);
if (!self::fitContextForPrompt($context, $profile, $timing)) {
if (!self::fitContextForPrompt($context, $profile, $timing, $options)) {
$compactionMs = $compactionAttempted ? AssistantSseTiming::elapsedMs($compactionStartedAt) : 0;
return null;
}
$compactionMs = $compactionAttempted ? AssistantSseTiming::elapsedMs($compactionStartedAt) : 0;
if (self::assistantCancelled($options['should_abort'] ?? null)) return null;
self::assistantProgress($options, ['phase' => 'preparing', 'status' => 'ready',
'message' => '资料正文已整理,准备提交给模型',
'source_summary' => $context['source_summary'] ?? [], 'attachment_count' => $attachmentCount]);
$query = self::buildAssistantPrompt($context, $task, $prompt);
$inputs = self::buildUpstreamInputs(
@@ -455,6 +474,8 @@ class DiagnosisAiLogic extends BaseLogic
'context_scope' => (string) ($context['context_scope'] ?? 'patient_longitudinal'),
'context_version' => (string) ($context['context_version'] ?? self::ASSISTANT_PROMPT_VERSION),
'source_summary' => is_array($context['source_summary'] ?? null) ? $context['source_summary'] : [],
'source_form' => !empty($context['source_summary']['source_compacted']) ? 'evidence_summary' : 'full_context',
'evidence_cache_hit' => !empty($context['compaction_cache_hit']),
'source_diagnosis_ids' => is_array($context['source_diagnosis_ids'] ?? null)
? $context['source_diagnosis_ids']
: [],
@@ -487,7 +508,8 @@ class DiagnosisAiLogic extends BaseLogic
array $prepared,
callable $onDelta,
?callable $shouldAbort = null,
?AssistantSseTiming $timing = null
?AssistantSseTiming $timing = null,
array $options = []
): ?array {
$diagnosisId = (int) ($prepared['diagnosis_id'] ?? 0);
$profile = (string) ($prepared['profile'] ?? '');
@@ -510,6 +532,7 @@ class DiagnosisAiLogic extends BaseLogic
};
try {
if (self::assistantCancelled($shouldAbort)) return null;
try {
$result = DifyChatService::streamChat(
$profile,
@@ -518,7 +541,10 @@ class DiagnosisAiLogic extends BaseLogic
(string) ($prepared['user'] ?? ''),
$forwardDelta,
$shouldAbort,
is_array($prepared['files'] ?? null) ? $prepared['files'] : []
is_array($prepared['files'] ?? null) ? $prepared['files'] : [],
$options + ['source_summary' => $prepared['source_summary'] ?? [],
'source_form' => $prepared['source_form'] ?? 'full_context',
'evidence_cache_hit' => !empty($prepared['evidence_cache_hit'])]
);
} catch (\Throwable $e) {
if ($timing === null) {
@@ -573,7 +599,10 @@ class DiagnosisAiLogic extends BaseLogic
(string) ($prepared['query'] ?? ''),
(string) ($prepared['user'] ?? ''),
is_array($prepared['files'] ?? null) ? $prepared['files'] : [],
['timeout' => $remainingTimeout]
$options + ['timeout' => $remainingTimeout, 'should_abort' => $shouldAbort, 'blocking_compatibility' => true,
'source_summary' => $prepared['source_summary'] ?? [],
'source_form' => $prepared['source_form'] ?? 'full_context',
'evidence_cache_hit' => !empty($prepared['evidence_cache_hit'])]
);
} catch (\Throwable $e) {
if ($timing === null) {
@@ -601,6 +630,7 @@ class DiagnosisAiLogic extends BaseLogic
}
}
if (self::assistantCancelled($shouldAbort)) { $status = 'cancelled'; return null; }
$formatted = self::formatAssistantResult($prepared, $result);
$status = $formatted === null ? 'error' : 'ok';
return $formatted;
@@ -619,6 +649,35 @@ class DiagnosisAiLogic extends BaseLogic
}
}
public static function cancelAssistant(int $diagnosisId, string $requestId, int $adminId, array $adminInfo): ?array
{
if (!AssistantRequestControl::validRequestId($requestId)) {
self::setError('请求标识无效');
return null;
}
if (self::loadAuthorizedDiagnosis($diagnosisId, $adminId, $adminInfo, self::PERMISSION_ASSISTANT,
'权限不足,无法取消诊单 AI 助手') === null) return null;
try {
return (new AssistantRequestControl($adminId, $diagnosisId, $requestId))->requestCancel();
} catch (\Throwable $ignored) {
self::setError('取消请求暂未送达,请稍后重试');
return null;
}
}
private static function assistantCancelled(?callable $shouldAbort): bool
{
if ($shouldAbort === null || !$shouldAbort()) return false;
self::$assistantErrorCode = 'AI_ASSISTANT_CANCELLED';
self::setError('本次请求已取消');
return true;
}
private static function assistantProgress(array $options, array $event): void
{
if (is_callable($options['on_progress'] ?? null)) ($options['on_progress'])($event);
}
/**
* @param array<string,mixed> $prepared
* @param array<string,mixed> $result
@@ -1570,7 +1629,8 @@ PROMPT;
private static function fitContextForPrompt(
array &$context,
string $profile,
?AssistantSseTiming $timing = null
?AssistantSseTiming $timing = null,
array $options = []
): bool
{
$caseText = (string) ($context['case_text'] ?? '');
@@ -1581,9 +1641,11 @@ PROMPT;
try {
$compacted = AiContextCompactionCache::remember(
(string) ($context['compaction_cache_scope'] ?? ''), $profile, $caseText,
static fn (): array => PatientAiReportLogic::compactSourceForPrompt($profile, $caseText)
static fn (): array => PatientAiReportLogic::compactSourceForPrompt($profile, $caseText, $options),
$options['should_abort'] ?? null
);
} catch (\Throwable $e) {
if (self::assistantCancelled($options['should_abort'] ?? null)) return false;
if ($timing === null) {
Log::warning('diagnosis ai context compaction failed', [
'source_bytes' => strlen($caseText),
@@ -550,8 +550,24 @@ class PatientAiReportLogic extends BaseLogic
*
* @return array{text:string,chunk_count:int,reduction_rounds:int,source_bytes:int,compacted:bool}
*/
public static function compactSourceForPrompt(string $modelKey, string $sourceJson): array
public static function compactSourceForPrompt(string $modelKey, string $sourceJson, array $options = []): array
{
$abort = $options['should_abort'] ?? null;
$check = static function () use ($abort): void {
if (is_callable($abort) && $abort()) throw new \RuntimeException('Context operation cancelled');
};
$progress = static function (string $message, int $completed, int $total) use ($options): void {
if (is_callable($options['on_progress'] ?? null)) ($options['on_progress'])([
'phase' => 'preparing', 'status' => 'compacting', 'message' => $message,
'completed' => $completed, 'total' => $total,
]);
};
$transportOptions = array_intersect_key($options, array_flip([
'should_abort', 'on_task', 'on_stop', 'on_transfer_end', 'on_cancel_task', 'on_terminal',
]));
$transportOptions['knowledge_mode'] = 'evidence';
$upstreamUser = (string) ($options['upstream_user'] ?? 'patient-longitudinal-context');
$check();
$sourceBytes = strlen($sourceJson);
if ($sourceBytes <= self::MAX_PROMPT_CHUNK_BYTES) {
return [
@@ -567,6 +583,8 @@ class PatientAiReportLogic extends BaseLogic
$chunkCount = count($chunks);
$summaries = [];
foreach ($chunks as $index => $chunk) {
$check();
$progress('正在向模型提交资料分片并整理证据', $index, $chunkCount);
$part = DifyChatService::chat(
$modelKey,
[
@@ -576,8 +594,9 @@ class PatientAiReportLogic extends BaseLogic
'prompt_version' => self::PROMPT_VERSION,
],
self::buildChunkPrompt($chunk, $index + 1, $chunkCount),
'patient-longitudinal-context', [], ['knowledge_mode' => 'evidence']
$upstreamUser, [], $transportOptions
);
$check();
if (empty($part['ok']) || trim((string) ($part['content'] ?? '')) === '') {
throw new \RuntimeException('Patient context chunk analysis failed');
}
@@ -586,6 +605,7 @@ class PatientAiReportLogic extends BaseLogic
'total' => $chunkCount,
'summary' => self::cleanSourceText($part['content'], true),
];
$progress('资料分片证据已返回', $index + 1, $chunkCount);
}
$reductionRounds = 0;
@@ -598,6 +618,8 @@ class PatientAiReportLogic extends BaseLogic
$summaryChunks = self::splitUtf8ByBytes($summaryJson, self::MAX_PROMPT_CHUNK_BYTES);
$reduced = [];
foreach ($summaryChunks as $index => $chunk) {
$check();
$progress('正在归并第' . $reductionRounds . '轮资料证据', $index, count($summaryChunks));
$part = DifyChatService::chat(
$modelKey,
[
@@ -608,8 +630,9 @@ class PatientAiReportLogic extends BaseLogic
'prompt_version' => self::PROMPT_VERSION,
],
self::buildReductionPrompt($chunk, $index + 1, count($summaryChunks)),
'patient-longitudinal-context', [], ['knowledge_mode' => 'evidence']
$upstreamUser, [], $transportOptions
);
$check();
if (empty($part['ok']) || trim((string) ($part['content'] ?? '')) === '') {
throw new \RuntimeException('Patient context reduction failed');
}
@@ -618,6 +641,7 @@ class PatientAiReportLogic extends BaseLogic
'total' => count($summaryChunks),
'summary' => self::cleanSourceText($part['content'], true),
];
$progress('资料证据归并已返回', $index + 1, count($summaryChunks));
}
$nextJson = self::encodeJson($reduced, true);
if (strlen($nextJson) >= strlen($summaryJson) && count($reduced) >= count($summaries)) {
@@ -627,6 +651,7 @@ class PatientAiReportLogic extends BaseLogic
$summaryJson = $nextJson;
}
$check();
return [
'text' => '患者纵向完整资料(服务端已逐片读取全部来源后归并的证据摘要,覆盖 '
. $chunkCount . ' 个来源片段):' . $summaryJson,