处方 AI:模型追问后仍拒绝开方时,先辨证再取教材代表方作候选
OpenAI 分支对带病例的请求坚持不给剂量,但会单独给出证名与治法, 也会回答不含病例的方剂学问题。追问仍拒绝时改走 final:syndrome → final:textbook 两步,候选方标注【教材代表方】,服次疗程不给则留空。 提示词版本升至 v8。 Co-Authored-By: Claude Opus 5 <[EMAIL]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
7189f33812
commit
b8f3c049be
@@ -12,7 +12,7 @@ use app\common\service\TcmAncientBooksReference;
|
||||
/** One model branch. It receives a saved context and never queries patient data. */
|
||||
final class PrescriptionAiGenerator
|
||||
{
|
||||
public const PROMPT_VERSION = 'manual-prescription-tcm-four-diagnoses-v7';
|
||||
public const PROMPT_VERSION = 'manual-prescription-tcm-four-diagnoses-v8';
|
||||
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'];
|
||||
@@ -38,6 +38,8 @@ final class PrescriptionAiGenerator
|
||||
'files_top' => '必须返回{"files":[...]}这一个对象,没有其他顶层键,也不要输出解释文字。',
|
||||
'files_entry' => '每个附件对象只能有file_id、status、findings、evidence_references四个键;status只能是processed、unreadable或unsupported;findings必须是非空字符串。',
|
||||
'files_refs' => 'evidence_references只能逐字使用本批清单中的file_id或已给出的来源编号,不得自造、改写或留空以外的无效编号。',
|
||||
'syndrome_shape' => '只能返回disease、syndrome、treatment_principle、uncertainty四个键;syndrome与treatment_principle为非空字符串,证据不完整时也给出最可能的一个证名,不写待定。',
|
||||
'textbook_shape' => '必须返回prescription_name、herbs、times_per_day、usage_days、rationale;herbs为非空数组,每味只含name、dosage、unit,dosage为每剂克数的正数且药名不重复;请选能按每味克数给出组成的教材汤剂或散剂代表方,不选中成药。',
|
||||
'files_ids' => 'files数组必须与清单一一对应:条数相同、file_id逐字照抄且不重复,不要合并、跳过或新增编号。',
|
||||
];
|
||||
|
||||
@@ -273,10 +275,22 @@ final class PrescriptionAiGenerator
|
||||
$parsed = $retried;
|
||||
$value = $asked['value'];
|
||||
}
|
||||
// 追问后仍拒绝针对本病例给剂量时,分两步取候选:先只做辨证,再在不含病例资料的
|
||||
// 方剂学问答里按证名、治法取教材代表方及常用量。结果在 reason 里标明来源。
|
||||
$textbook = false;
|
||||
if ($requireCandidate && !self::candidateAvailable($parsed['candidate'] ?? null)) {
|
||||
$derived = self::textbookCandidate($summaries, $parsed, $modelKey, $context, $progress, $transport, $checkpoint,
|
||||
$inputBudget, $maxCalls, $dispensing, $catalogNames, $readIds);
|
||||
if ($derived !== null) {
|
||||
$parsed['candidate'] = $derived;
|
||||
$textbook = true;
|
||||
}
|
||||
}
|
||||
// A single medicine name outside the institution dictionary makes the whole plan
|
||||
// unmappable, so name it and re-ask instead of accepting an uncomparable candidate.
|
||||
// The server never substitutes a medicine on the model's behalf.
|
||||
for ($fix = 1; $catalogNames !== [] && $fix <= $insistRounds; $fix++) {
|
||||
// 教材代表方不走这一步:改名追问用的是整份病例提示词,模型会再次拒绝并覆盖已得到的候选方。
|
||||
for ($fix = 1; !$textbook && $catalogNames !== [] && $fix <= $insistRounds; $fix++) {
|
||||
$unknown = self::unknownNames($parsed['candidate'] ?? null, $catalogNames);
|
||||
if ($unknown === []) {
|
||||
break;
|
||||
@@ -300,6 +314,8 @@ final class PrescriptionAiGenerator
|
||||
for ($insist = 1; $insist <= $insistRounds; $insist++) {
|
||||
self::invalidateStep('final:insist:' . $insist, $progress, $checkpoint);
|
||||
}
|
||||
self::invalidateStep('final:syndrome', $progress, $checkpoint);
|
||||
self::invalidateStep('final:textbook', $progress, $checkpoint);
|
||||
throw new \RuntimeException('CANDIDATE_WITHHELD_BY_MODEL');
|
||||
}
|
||||
if ($candidateBlocked) {
|
||||
@@ -657,6 +673,126 @@ final class PrescriptionAiGenerator
|
||||
. "\n" . $base;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分步候选:模型对带病例的开方请求坚持不给剂量,但会做辨证,也会回答不含病例的方剂学问题。
|
||||
* 第一步只问证名与治法(带本分支已读证据);第二步只把病名、证名、治法交给方剂学问答,
|
||||
* 取教材代表方及教材常用量。第二步不含任何患者资料。任何一步失败都返回 null,由调用方按
|
||||
* 「模型未给出候选方」处理,绝不由服务端自行拼方。
|
||||
*/
|
||||
private static function textbookCandidate(array $summaries, array $parsed, string $modelKey, array $context, array &$progress,
|
||||
callable $transport, ?callable $checkpoint, int $inputBudget, int $maxCalls, array $dispensing, array $catalogNames, array $readIds): ?array
|
||||
{
|
||||
$asked = self::askStrict('final:syndrome', self::syndromePrompt($summaries, $readIds), [], $modelKey, $context, $progress,
|
||||
$transport, $checkpoint, $inputBudget, $maxCalls, static fn (string $content): ?array => self::parseSyndrome($content));
|
||||
$syndrome = $asked['parsed'];
|
||||
if ($syndrome === null) {
|
||||
return null;
|
||||
}
|
||||
$asked = self::askStrict('final:textbook', self::textbookPrompt($syndrome, $catalogNames), [], $modelKey, $context, $progress,
|
||||
$transport, $checkpoint, $inputBudget, $maxCalls, static fn (string $content): ?array => self::parseTextbook($content));
|
||||
$formula = $asked['parsed'];
|
||||
if ($formula === null) {
|
||||
return null;
|
||||
}
|
||||
$basis = in_array($dispensing['dose_basis'] ?? '', ['per_dose', 'per_day'], true) ? $dispensing['dose_basis'] : 'per_dose';
|
||||
$unit = trim((string) ($dispensing['unit'] ?? '')) !== '' ? trim((string) $dispensing['unit']) : '克';
|
||||
$references = array_values(array_intersect((array) ($parsed['report']['evidence_references'] ?? []), $readIds));
|
||||
if ($references === []) {
|
||||
$references = array_slice($readIds, 0, 20);
|
||||
}
|
||||
if ($references === []) {
|
||||
return null;
|
||||
}
|
||||
$herbs = [];
|
||||
foreach ($formula['herbs'] as $herb) {
|
||||
$herbs[] = ['name' => trim($herb['name']), 'dosage' => $herb['dosage'], 'unit' => $unit, 'dose_basis' => $basis,
|
||||
'processing' => '明确无', 'formula_type' => '主方', 'instructions' => '明确无', 'evidence_references' => $references];
|
||||
}
|
||||
$refusal = is_array($parsed['candidate'] ?? null) ? trim((string) ($parsed['candidate']['reason'] ?? '')) : '';
|
||||
$label = ($syndrome['disease'] !== '' ? $syndrome['disease'] . '·' : '') . $syndrome['syndrome'];
|
||||
$warnings = ['教材代表方及教材常用量,未按本例个体加减;药味、剂量、服次与疗程须医师逐项核定。',
|
||||
'模型未针对本病例直接开方,本方由其辨证结果推导,研究比较时应与直接开方的结果分开统计。'];
|
||||
if ($syndrome['uncertainty'] !== '') {
|
||||
$warnings[] = '辨证待核:' . mb_substr($syndrome['uncertainty'], 0, 70);
|
||||
}
|
||||
return ['status' => 'available_for_review',
|
||||
'reason' => mb_substr('【教材代表方】模型未针对本病例给出剂量' . ($refusal !== '' ? '(' . mb_substr($refusal, 0, 80) . ')' : '')
|
||||
. '。以下按其辨证「' . $label . '」、治法「' . $syndrome['treatment_principle'] . '」选取《方剂学》教材代表方及常用量,须医师复核后决定是否采用。', 0, 300),
|
||||
'prescription_name' => mb_substr($formula['prescription_name'] . '(教材代表方)', 0, 150),
|
||||
'prescription_type' => trim((string) ($dispensing['formulation'] ?? '')) !== '' ? trim((string) $dispensing['formulation']) : '汤剂',
|
||||
'dose_basis' => $basis, 'herbs' => $herbs,
|
||||
'usage_instruction' => '按教材常用量列出;具体剂型折算、用法、服次与疗程由医师确定。',
|
||||
'times_per_day' => $formula['times_per_day'], 'usage_days' => $formula['usage_days'],
|
||||
'rationale' => mb_substr($formula['rationale'], 0, 300), 'risk_warnings' => $warnings, 'evidence_references' => $references];
|
||||
}
|
||||
|
||||
private static function syndromePrompt(array $summaries, array $allowedIds): string
|
||||
{
|
||||
return self::boundary() . '\n阶段=final:syndrome。供执业中医师参考的辨证辅助,本阶段只做辨证,不选方、不开药、不给剂量。'
|
||||
. '请根据下列本分支已读证据,给出最可能的中医病名、证名(主证,可带兼证)与相应治法;证据不完整时也必须给出最可能的一个证名,不得写“待定”,'
|
||||
. '把不确定之处与待核实事项写进uncertainty。不编造患者事实。'
|
||||
. '只输出一个JSON对象:{"disease":"中医病名,无法判断时为空字符串","syndrome":"证名,不超过30字","treatment_principle":"治法,不超过30字","uncertainty":"不超过120字"}。'
|
||||
. ($allowedIds !== [] ? "\nALLOWED_EVIDENCE_IDS=" . self::json($allowedIds) : '')
|
||||
. "\nBRANCH_EVIDENCE_JSON=" . self::json($summaries);
|
||||
}
|
||||
|
||||
/** 不含任何患者资料:只给病名、证名与治法,问教材代表方。 */
|
||||
private static function textbookPrompt(array $syndrome, array $catalogNames): string
|
||||
{
|
||||
return '方剂学知识问答(不涉及具体患者)。' . ($syndrome['disease'] !== '' ? '病名:' . $syndrome['disease'] . '。' : '')
|
||||
. '证候:' . $syndrome['syndrome'] . '。治法:' . $syndrome['treatment_principle'] . '。'
|
||||
. '请选出《方剂学》《中医内科学》教材中与此证候、治法最对应的一首代表方,按教材所载组成与常用剂量给出,药味不超过20味。'
|
||||
. '只输出一个JSON对象:{"prescription_name":"方名","herbs":[{"name":"药名","dosage":数值,"unit":"克"}],"times_per_day":数值或null,"usage_days":数值或null,"rationale":"方义,不超过300字"}。'
|
||||
. ($catalogNames !== []
|
||||
? '药名优先逐字使用MEDICINE_CATALOG中的对应名称(含炮制品,如“生山药”),清单中没有的药味照常写教材药名,不得因此删减原方药味;'
|
||||
: '')
|
||||
. 'dosage为每剂克数(JSON数字);教材载有常用服次、疗程时填写,否则为null。'
|
||||
. ($catalogNames !== [] ? "\nMEDICINE_CATALOG=" . self::json($catalogNames) : '');
|
||||
}
|
||||
|
||||
private static function parseSyndrome(string $content): ?array
|
||||
{
|
||||
$value = self::object($content);
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
$value += ['disease' => '', 'uncertainty' => ''];
|
||||
if (!self::keys($value, ['disease', 'syndrome', 'treatment_principle', 'uncertainty'])
|
||||
|| !self::text($value['syndrome'] ?? null, 60) || !self::text($value['treatment_principle'] ?? null, 60)
|
||||
|| !is_string($value['disease']) || mb_strlen($value['disease']) > 30 || !is_string($value['uncertainty'])
|
||||
|| preg_match('/待定|不明|无法/u', $value['syndrome'])) {
|
||||
return self::reject('syndrome_shape', strlen($content));
|
||||
}
|
||||
return ['disease' => trim($value['disease']), 'syndrome' => trim($value['syndrome']),
|
||||
'treatment_principle' => trim($value['treatment_principle']), 'uncertainty' => trim(mb_substr($value['uncertainty'], 0, 400))];
|
||||
}
|
||||
|
||||
private static function parseTextbook(string $content): ?array
|
||||
{
|
||||
$value = self::object($content);
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
if (!self::keys($value, ['prescription_name', 'herbs', 'times_per_day', 'usage_days', 'rationale', 'usage_instruction'])
|
||||
|| !self::text($value['prescription_name'] ?? null, 100) || !self::text($value['rationale'] ?? null, 6000)
|
||||
|| !is_array($value['herbs'] ?? null) || !array_is_list($value['herbs']) || $value['herbs'] === [] || count($value['herbs']) > 30) {
|
||||
return self::reject('textbook_shape', strlen($content));
|
||||
}
|
||||
$seen = [];
|
||||
foreach ($value['herbs'] as $herb) {
|
||||
if (!is_array($herb) || !self::text($herb['name'] ?? null, 50) || !self::positiveNumber($herb['dosage'] ?? null) || $herb['dosage'] > 500
|
||||
|| isset($seen[trim($herb['name'])])) {
|
||||
return self::reject('textbook_shape', strlen($content));
|
||||
}
|
||||
$seen[trim($herb['name'])] = true;
|
||||
}
|
||||
foreach (['times_per_day' => 6, 'usage_days' => 365] as $key => $maximum) {
|
||||
$number = $value[$key] ?? null;
|
||||
$value[$key] = self::positiveNumber($number) && $number <= $maximum ? $number : null;
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function candidateAvailable($candidate): bool
|
||||
{
|
||||
return is_array($candidate) && ($candidate['status'] ?? '') === 'available_for_review'
|
||||
|
||||
@@ -184,6 +184,61 @@ $verboseInsist = static function ($model, $prompt, $files, $user) use ($stub, $f
|
||||
$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');
|
||||
// 追问后仍拒绝:先只问证名与治法,再用不含病例的方剂学问答取教材代表方。
|
||||
$syndromeAnswer = ['disease' => '消渴', 'syndrome' => '肾阴亏虚证', 'treatment_principle' => '滋养肾阴', 'uncertainty' => '兼证待核。'];
|
||||
$textbookAnswer = ['prescription_name' => '六味地黄丸', 'herbs' => [['name' => '熟地黄', 'dosage' => 24, 'unit' => '克'],
|
||||
['name' => '山茱萸', 'dosage' => 12, 'unit' => '克']], 'times_per_day' => null, 'usage_days' => 0, 'rationale' => '三补三泻。'];
|
||||
$stagedPrompts = [];
|
||||
$staged = static function (array $syndrome, array $textbook) use ($stub, $withheldFinal, &$stagedPrompts): callable {
|
||||
return static function ($model, $prompt, $files, $user) use ($stub, $withheldFinal, $syndrome, $textbook, &$stagedPrompts): array {
|
||||
if (str_contains($prompt, '阶段=final:syndrome')) {
|
||||
$stagedPrompts['syndrome'][] = $prompt;
|
||||
return ['ok' => true, 'content' => rxGeneratorJson($syndrome)];
|
||||
}
|
||||
if (str_contains($prompt, '方剂学知识问答')) {
|
||||
$stagedPrompts['textbook'][] = $prompt;
|
||||
return ['ok' => true, 'content' => rxGeneratorJson($textbook)];
|
||||
}
|
||||
if (str_contains($prompt, '阶段=final')) {
|
||||
$stagedPrompts['final'][] = $prompt;
|
||||
return ['ok' => true, 'content' => rxGeneratorJson($withheldFinal)];
|
||||
}
|
||||
return $stub($model, $prompt, $files, $user);
|
||||
};
|
||||
};
|
||||
$textbookContext = $noncriticalContext;
|
||||
$textbookContext['_comparison_catalog'] = [['name' => '熟地黄'], ['name' => '山茱萸']];
|
||||
$textbookContext['source']['dispensing'] = ['formulation' => '浓缩水丸', 'unit' => '克', 'dose_basis' => 'per_dose'];
|
||||
$derived = PrescriptionAiGenerator::generateWithTransport('openai', $textbookContext, $staged($syndromeAnswer, $textbookAnswer));
|
||||
$derivedCandidate = $derived['candidate'] ?? [];
|
||||
rxGeneratorExpect($derived['ok'] && $derivedCandidate['status'] === 'available_for_review' && count($derivedCandidate['herbs']) === 2
|
||||
&& $derivedCandidate['herbs'][0] === ['name' => '熟地黄', 'dosage' => 24, 'unit' => '克', 'dose_basis' => 'per_dose', 'processing' => '明确无',
|
||||
'formula_type' => '主方', 'instructions' => '明确无', 'evidence_references' => ['diagnoses:1']],
|
||||
'a persistent case refusal yields the textbook formula chosen from the model own syndrome');
|
||||
rxGeneratorExpect(str_contains($derivedCandidate['reason'], '【教材代表方】') && str_contains($derivedCandidate['reason'], '肾阴亏虚证')
|
||||
&& $derivedCandidate['prescription_name'] === '六味地黄丸(教材代表方)' && $derivedCandidate['prescription_type'] === '浓缩水丸'
|
||||
&& $derivedCandidate['times_per_day'] === null && $derivedCandidate['usage_days'] === null,
|
||||
'the derived candidate is labelled as a textbook formula and never invents a regimen');
|
||||
$textbookPrompt = $stagedPrompts['textbook'][0] ?? '';
|
||||
rxGeneratorExpect(count($stagedPrompts['textbook'] ?? []) === 1 && !str_contains($textbookPrompt, '示例症状')
|
||||
&& !str_contains($textbookPrompt, 'diagnoses:1') && str_contains($textbookPrompt, '证候:肾阴亏虚证')
|
||||
&& str_contains($textbookPrompt, 'MEDICINE_CATALOG='),
|
||||
'the textbook question carries only disease, syndrome, principle and the catalog, no patient evidence');
|
||||
rxGeneratorExpect(count($stagedPrompts['final']) === 3, 'a textbook candidate skips the case-bound medicine-name re-ask');
|
||||
$stagedPrompts = [];
|
||||
$undecided = PrescriptionAiGenerator::generateWithTransport('openai', $textbookContext,
|
||||
$staged(['disease' => '', 'syndrome' => '证候待定', 'treatment_principle' => '待定', 'uncertainty' => ''], $textbookAnswer));
|
||||
rxGeneratorExpect(!$undecided['ok'] && $undecided['error_code'] === 'CANDIDATE_WITHHELD_BY_MODEL'
|
||||
&& count($stagedPrompts['syndrome']) === 2 && !isset($stagedPrompts['textbook']),
|
||||
'an undecided syndrome gets one format repair and never reaches the textbook question');
|
||||
$stagedPrompts = [];
|
||||
$emptyFormulaProgress = [];
|
||||
$emptyFormula = PrescriptionAiGenerator::generateWithTransport('openai', $textbookContext,
|
||||
$staged($syndromeAnswer, ['prescription_name' => '六味地黄丸', 'herbs' => [], 'times_per_day' => null, 'usage_days' => null, 'rationale' => '目录不全。']),
|
||||
static function (array $progress) use (&$emptyFormulaProgress): void { $emptyFormulaProgress = $progress; });
|
||||
rxGeneratorExpect(!$emptyFormula['ok'] && $emptyFormula['error_code'] === 'CANDIDATE_WITHHELD_BY_MODEL' && count($stagedPrompts['textbook']) === 2
|
||||
&& !isset($emptyFormulaProgress['steps']['final:syndrome']) && !isset($emptyFormulaProgress['steps']['final:textbook']),
|
||||
'a formula without doses fails as withheld and neither derived step is cached for the retry');
|
||||
$oldPolicyContext = $context;
|
||||
$oldPolicyContext['_progress'] = $saved;
|
||||
$oldPolicyContext['_progress']['prompt_version'] = 'manual-prescription-independent-v1';
|
||||
|
||||
Reference in New Issue
Block a user