Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14936cb28a |
@@ -13,6 +13,7 @@ use app\common\model\tcm\Prescription;
|
||||
use app\common\model\tcm\PrescriptionOrder;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use think\db\Query;
|
||||
use think\facade\Cache;
|
||||
|
||||
/**
|
||||
* 处方列表
|
||||
@@ -21,51 +22,92 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
{
|
||||
use HasDataScopeFilter;
|
||||
|
||||
/** 置顶风险处方 ID 的缓存键与有效期(秒);只影响置顶顺序,行内警示仍按当前数据实时计算 */
|
||||
private const RISK_IDS_CACHE_KEY = 'tcm_prescription_lists_risk_ids';
|
||||
private const RISK_IDS_CACHE_TTL = 60;
|
||||
|
||||
/** 列表行不返回的大字段:签名图 base64 动辄数十 KB,查看/编辑都会另取详情 */
|
||||
private const LIST_OMIT_FIELDS = ['doctor_signature'];
|
||||
|
||||
/**
|
||||
* 识别「有业务订单且处方药材为空白/重复」的处方 ID(用于全局置顶排序)
|
||||
*
|
||||
* @param array<int,int|string> $candidateIds
|
||||
* 风险是处方自身的属性,与筛选条件无关:这里在全库范围计算一次并短时缓存,
|
||||
* 筛选范围的交集由 pinnedIds() 在当前查询里取。以前每次请求都先把筛选结果的
|
||||
* 全部 ID 拉出来,再逐个读药材,处方表行很宽(病历快照、签名图),整表扫描
|
||||
* 是列表慢的主因。
|
||||
*
|
||||
* @return array<int,int>
|
||||
*/
|
||||
private function collectRiskPrescriptionIds(array $candidateIds): array
|
||||
private function collectRiskPrescriptionIds(): array
|
||||
{
|
||||
$candidateIds = array_values(array_unique(array_filter(array_map('intval', $candidateIds), static function (int $id): bool {
|
||||
return $id > 0;
|
||||
})));
|
||||
if ($candidateIds === []) {
|
||||
return [];
|
||||
$cached = Cache::get(self::RISK_IDS_CACHE_KEY);
|
||||
if (is_array($cached)) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
// 仅在「存在有效业务订单」的处方里做风险判定
|
||||
$orderRxIds = PrescriptionOrder::whereIn('prescription_id', $candidateIds)
|
||||
->whereNull('delete_time')
|
||||
// 仅在「存在有效业务订单」的处方里做风险判定;订单表很小,从订单侧出发
|
||||
$orderRxIds = PrescriptionOrder::whereNull('delete_time')
|
||||
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
|
||||
->column('prescription_id');
|
||||
$orderRxIds = array_values(array_unique(array_filter(array_map('intval', $orderRxIds), static function (int $id): bool {
|
||||
return $id > 0;
|
||||
})));
|
||||
if ($orderRxIds === []) {
|
||||
|
||||
$riskIds = [];
|
||||
foreach (array_chunk($orderRxIds, 1000) as $chunk) {
|
||||
$herbsById = Prescription::whereIn('id', $chunk)
|
||||
->whereNull('delete_time')
|
||||
->column('herbs', 'id');
|
||||
foreach ($herbsById as $rid => $herbs) {
|
||||
$rid = (int) $rid;
|
||||
if ($rid > 0 && $this->isRiskHerbs($herbs)) {
|
||||
$riskIds[] = $rid;
|
||||
}
|
||||
}
|
||||
}
|
||||
$riskIds = array_values(array_unique($riskIds));
|
||||
Cache::set(self::RISK_IDS_CACHE_KEY, $riskIds, self::RISK_IDS_CACHE_TTL);
|
||||
|
||||
return $riskIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前页的处方 ID:先排当前筛选范围内的风险处方,再按 ID 倒序排其余处方。
|
||||
*
|
||||
* 拆成两段只查 ID,避免对整表做 ORDER BY CASE 的文件排序;第二段可直接沿主键倒序扫描,
|
||||
* 取够一页即停止。
|
||||
*
|
||||
* @return array<int,int>
|
||||
*/
|
||||
private function pageIds(Query $query): array
|
||||
{
|
||||
$offset = max(0, (int) $this->limitOffset);
|
||||
$length = max(0, (int) $this->limitLength);
|
||||
if ($length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = Prescription::whereIn('id', $orderRxIds)
|
||||
->whereNull('delete_time')
|
||||
->field(['id', 'herbs'])
|
||||
->select()
|
||||
->toArray();
|
||||
|
||||
$riskIds = [];
|
||||
foreach ($rows as $row) {
|
||||
$rid = (int) ($row['id'] ?? 0);
|
||||
if ($rid <= 0) {
|
||||
continue;
|
||||
}
|
||||
if ($this->isRiskHerbs($row['herbs'] ?? null)) {
|
||||
$riskIds[] = $rid;
|
||||
}
|
||||
$riskIds = $this->collectRiskPrescriptionIds();
|
||||
$pinned = [];
|
||||
if ($riskIds !== []) {
|
||||
$pinned = array_map('intval', (clone $query)->whereIn('id', $riskIds)->order('id', 'desc')->column('id'));
|
||||
}
|
||||
|
||||
return array_values(array_unique($riskIds));
|
||||
$ids = array_slice($pinned, $offset, $length);
|
||||
$remaining = $length - count($ids);
|
||||
if ($remaining > 0) {
|
||||
$rest = clone $query;
|
||||
if ($pinned !== []) {
|
||||
$rest->whereNotIn('id', $pinned);
|
||||
}
|
||||
$restIds = $rest->order('id', 'desc')
|
||||
->limit(max(0, $offset - count($pinned)), $remaining)
|
||||
->column('id');
|
||||
$ids = array_merge($ids, array_map('intval', $restIds));
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -253,22 +295,25 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
*/
|
||||
public function lists(): array
|
||||
{
|
||||
$query = $this->buildFilteredQuery();
|
||||
|
||||
// 全局置顶:有业务订单且处方药材为空白/重复
|
||||
$candidateIds = (clone $query)->column('id');
|
||||
$riskIds = $this->collectRiskPrescriptionIds(is_array($candidateIds) ? $candidateIds : []);
|
||||
|
||||
$listQuery = $query;
|
||||
if ($riskIds !== []) {
|
||||
$riskIdStr = implode(',', array_map('intval', $riskIds));
|
||||
$listQuery->orderRaw("CASE WHEN id IN ({$riskIdStr}) THEN 0 ELSE 1 END ASC");
|
||||
$pageIds = $this->pageIds($this->buildFilteredQuery());
|
||||
if ($pageIds === []) {
|
||||
return [];
|
||||
}
|
||||
$lists = $listQuery
|
||||
->order('id', 'desc')
|
||||
->limit($this->limitOffset, $this->limitLength)
|
||||
$rowsById = [];
|
||||
$rows = Prescription::whereIn('id', $pageIds)
|
||||
->withoutField(self::LIST_OMIT_FIELDS)
|
||||
->select()
|
||||
->toArray();
|
||||
foreach ($rows as $row) {
|
||||
$rowsById[(int) $row['id']] = $row;
|
||||
}
|
||||
$lists = [];
|
||||
foreach ($pageIds as $pageId) {
|
||||
if (isset($rowsById[$pageId])) {
|
||||
$lists[] = $rowsById[$pageId];
|
||||
}
|
||||
}
|
||||
|
||||
$rxIds = array_column($lists, 'id');
|
||||
$rxIds = array_map('intval', $rxIds);
|
||||
|
||||
@@ -14,6 +14,8 @@ final class PrescriptionAiGenerator
|
||||
{
|
||||
public const PROMPT_VERSION = 'manual-prescription-tcm-four-diagnoses-v7';
|
||||
private const REPORT_KEYS = ['summary', 'diagnosis', 'risk_assessment', 'treatment_advice', 'evidence_references', 'missing_information'];
|
||||
private const CANDIDATE_KEYS = ['status', 'reason', 'prescription_name', 'prescription_type', 'dose_basis', 'herbs', 'usage_instruction',
|
||||
'times_per_day', 'usage_days', 'rationale', 'risk_warnings', 'evidence_references'];
|
||||
private const RETRYABLE = ['UPSTREAM_TIMEOUT', 'UPSTREAM_BUSY', 'UPSTREAM_UNAVAILABLE', 'INCOMPLETE_RESPONSE', 'EMPTY_RESPONSE',
|
||||
'CANDIDATE_WITHHELD_BY_MODEL', 'INVALID_EVIDENCE_OUTPUT', 'INVALID_REPORT_OUTPUT'];
|
||||
/** Reserved prompt budget for one refusal re-ask plus one format repair. */
|
||||
@@ -742,10 +744,16 @@ final class PrescriptionAiGenerator
|
||||
return self::reject('candidate_shape', strlen($content));
|
||||
}
|
||||
if ($candidate['status'] !== 'available_for_review') {
|
||||
return self::keys($candidate, ['status', 'reason', 'herbs']) && $candidate['herbs'] === []
|
||||
? $value : self::reject('candidate_shape', strlen($content));
|
||||
// 模型拒绝开方时常把完整候选键一并带上(置空或附说明)。拒绝回答只认 status、reason
|
||||
// 与空 herbs,其余已知候选键不含药味,直接剥离;否则整份报告会被当成格式错误,
|
||||
// 连「携带拒绝理由追问」的环节都走不到。
|
||||
if ($candidate['herbs'] !== [] || !self::keys($candidate, self::CANDIDATE_KEYS)) {
|
||||
return self::reject('candidate_shape', strlen($content));
|
||||
}
|
||||
$value['candidate'] = ['status' => $candidate['status'], 'reason' => $candidate['reason'], 'herbs' => []];
|
||||
return $value;
|
||||
}
|
||||
if (!self::keys($candidate, ['status', 'reason', 'prescription_name', 'prescription_type', 'dose_basis', 'herbs', 'usage_instruction', 'times_per_day', 'usage_days', 'rationale', 'risk_warnings', 'evidence_references'])
|
||||
if (!self::keys($candidate, self::CANDIDATE_KEYS)
|
||||
|| !in_array($candidate['dose_basis'] ?? '', ['per_dose', 'per_day'], true) || $candidate['herbs'] === [] || count($candidate['herbs']) > 100
|
||||
|| !self::positiveNumber($candidate['times_per_day'] ?? null) || !self::positiveNumber($candidate['usage_days'] ?? null)
|
||||
|| !self::strings($candidate['risk_warnings'] ?? null) || !self::references($candidate['evidence_references'] ?? null, $knownIds) || $candidate['evidence_references'] === []) {
|
||||
|
||||
@@ -161,6 +161,29 @@ rxGeneratorExpect(!isset($refusalProgress['steps']['final']) && !isset($refusalP
|
||||
$modelWithheld = PrescriptionAiGenerator::generateWithTransport('qwen', $noncriticalContext, $alwaysWithheld, null, $withholdingConfig);
|
||||
rxGeneratorExpect($modelWithheld['ok'] && $modelWithheld['candidate']['status'] === 'withheld_for_risk',
|
||||
'configured withholding still honours model-identified safety uncertainty');
|
||||
// OpenAI 实测的拒答形态:带上全部候选键并置空。应按拒答处理并进入追问,而不是整份报告格式错误。
|
||||
$verboseRefusal = $final;
|
||||
$verboseRefusal['candidate'] = ['status' => 'insufficient_data', 'reason' => '无法确定脏腑定位。', 'prescription_name' => null,
|
||||
'prescription_type' => null, 'dose_basis' => null, 'herbs' => [], 'usage_instruction' => null, 'times_per_day' => null,
|
||||
'usage_days' => null, 'rationale' => '暂无方义。', 'risk_warnings' => ['核对合并用药。'], 'evidence_references' => ['diagnoses:1']];
|
||||
$verboseParsed = PrescriptionAiGenerator::parseFinal(rxGeneratorJson($verboseRefusal), ['diagnoses:1']);
|
||||
rxGeneratorExpect($verboseParsed !== null && $verboseParsed['candidate'] === ['status' => 'insufficient_data', 'reason' => '无法确定脏腑定位。', 'herbs' => []],
|
||||
'a refusal carrying the full candidate key set is normalised to status, reason and empty herbs');
|
||||
$smuggled = $verboseRefusal;
|
||||
$smuggled['candidate']['herbs'] = [$candidate['herbs'][0]];
|
||||
rxGeneratorExpect(PrescriptionAiGenerator::parseFinal(rxGeneratorJson($smuggled), ['diagnoses:1']) === null,
|
||||
'a refusal that still lists herbs stays invalid');
|
||||
$verboseInsistCalls = 0;
|
||||
$verboseInsist = static function ($model, $prompt, $files, $user) use ($stub, $final, $verboseRefusal, &$verboseInsistCalls): array {
|
||||
if (!str_contains($prompt, '阶段=final')) {
|
||||
return $stub($model, $prompt, $files, $user);
|
||||
}
|
||||
$verboseInsistCalls++;
|
||||
return ['ok' => true, 'content' => rxGeneratorJson(str_contains($prompt, '上一次回答没有给出候选处方') ? $final : $verboseRefusal)];
|
||||
};
|
||||
$verboseResult = PrescriptionAiGenerator::generateWithTransport('openai', $noncriticalContext, $verboseInsist);
|
||||
rxGeneratorExpect($verboseResult['ok'] && $verboseResult['candidate']['status'] === 'available_for_review' && $verboseInsistCalls === 2,
|
||||
'a verbose refusal reaches the refusal re-ask instead of burning a format repair');
|
||||
$oldPolicyContext = $context;
|
||||
$oldPolicyContext['_progress'] = $saved;
|
||||
$oldPolicyContext['_progress']['prompt_version'] = 'manual-prescription-independent-v1';
|
||||
|
||||
Reference in New Issue
Block a user