This commit is contained in:
gr
2026-10-27 16:33:30 +08:00
423 changed files with 72666 additions and 5389 deletions
@@ -7,18 +7,31 @@ namespace app\common\service;
/** Single entry point for references attached to clinical model requests. */
final class ClinicalKnowledgeReference
{
/** Case reports retain response rules without importing textbook patient-like findings. */
public static function augmentCaseQuery(string $query, bool $consultation = false): string
{
$boundary = '[TCM_CASE_SOURCE_BOUNDARY:v1]' . "\n"
. '本例事实和方药依据只能来自给定患者资料,保留否定、程度、日期与未知状态;'
. '不得用教材或古籍的常见方证补写本例症状或阴性体征。历史方药保留原时点与状态,仅作原始记录。';
$prefix = ($consultation ? TcmClinicalResponsePolicy::consultationReference()
: TcmClinicalResponsePolicy::reference()) . "\n\n" . $boundary . "\n\n";
return str_starts_with($query, $prefix) ? $query : $prefix . $query;
}
public static function augmentQuery(string $query): string
{
return TcmAncientBooksReference::augmentQuery(NihaixiaClinicalSkill::augmentQuery($query));
return TcmClinicalResponsePolicy::augmentQuery(
TcmAncientBooksReference::augmentQuery(NihaixiaClinicalSkill::augmentQuery($query))
);
}
/** @param list<array<string,mixed>> $ancientBookSources */
public static function augmentQueryWithAncientBookSources(string $query, array $ancientBookSources): string
{
return TcmAncientBooksReference::augmentQueryWithSources(
return TcmClinicalResponsePolicy::augmentQuery(TcmAncientBooksReference::augmentQueryWithSources(
NihaixiaClinicalSkill::augmentQuery($query),
$ancientBookSources
);
));
}
/** @param array<int,array<string,mixed>> $messages
@@ -26,7 +39,9 @@ final class ClinicalKnowledgeReference
*/
public static function augmentMessages(array $messages): array
{
return TcmAncientBooksReference::augmentMessages(NihaixiaClinicalSkill::augmentMessages($messages));
return TcmClinicalResponsePolicy::augmentMessages(
TcmAncientBooksReference::augmentMessages(NihaixiaClinicalSkill::augmentMessages($messages))
);
}
/** @return list<array<string,mixed>> */
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace app\common\service;
/** Request-local filter. Discarded reasoning is counted, never retained or logged. */
final class DifyReasoningTextFilter
{
private const OPEN = '<think>';
private const CLOSE = '</think>';
private string $pending = '';
private string $leading = '';
private int $depth = 0;
private int $discardedBytes = 0;
private int $tagCount = 0;
private bool $visible = false;
private bool $finished = false;
public function push(string $text): string
{
if ($this->finished) return '';
$this->pending .= $text;
$out = '';
while ($this->pending !== '') {
$offset = strpos($this->pending, '<');
if ($offset === false || $offset > 0) {
$length = $offset === false ? strlen($this->pending) : $offset;
$plain = substr($this->pending, 0, $length);
$this->pending = substr($this->pending, $length);
if ($this->depth === 0) $out .= $plain;
else $this->discardedBytes += $length;
continue;
}
$tag = null;
foreach ([self::OPEN, self::CLOSE] as $candidate) {
if (strlen($this->pending) >= strlen($candidate)
&& strncasecmp($this->pending, $candidate, strlen($candidate)) === 0) {
$tag = $candidate;
break;
}
}
if ($tag !== null) {
$this->pending = substr($this->pending, strlen($tag));
$this->discardedBytes += strlen($tag);
++$this->tagCount;
if ($tag === self::OPEN) ++$this->depth;
elseif ($this->depth > 0) --$this->depth;
continue;
}
$lower = strtolower($this->pending);
if (str_starts_with(self::OPEN, $lower) || str_starts_with(self::CLOSE, $lower)) break;
// Not a think tag: preserve ordinary markup/comparisons verbatim.
if ($this->depth === 0) $out .= '<';
else ++$this->discardedBytes;
$this->pending = substr($this->pending, 1);
}
return $this->visibleText($out);
}
public function finish(): string
{
if ($this->finished) return '';
$this->finished = true;
$unfinishedTag = in_array(strtolower($this->pending), ['<think', '</think'], true);
$tail = $this->depth === 0 && !$unfinishedTag ? $this->pending : '';
if ($this->depth > 0 || $unfinishedTag) $this->discardedBytes += strlen($this->pending);
$this->pending = '';
$out = $this->visibleText($tail);
// Whitespace without an actual answer never becomes a clinical delta.
$this->leading = '';
return $out;
}
private function visibleText(string $text): string
{
if ($this->visible) return $text;
$this->leading .= $text;
if (trim($this->leading) === '') return '';
$this->visible = true;
$out = $this->leading;
$this->leading = '';
return $out;
}
/** Safe numeric diagnostics only; no discarded text or tag buffer. */
public function counts(): array
{
return ['filtered_bytes' => $this->discardedBytes, 'think_tag_count' => $this->tagCount,
'unclosed_think_depth' => $this->depth];
}
public static function text(string $text): string
{
$filter = new self();
return $filter->push($text) . $filter->finish();
}
}
@@ -4,6 +4,8 @@ declare(strict_types=1);
namespace app\common\service;
require_once __DIR__ . '/DifyUploadedFileReuse.php';
/**
* Turn an already-authorized attachment list into Dify local_file references.
*
@@ -27,7 +29,11 @@ final class DifyRequiredAttachmentUpload
* on_upload(array{index:int,total:int,status:string,reason?:string}), resolved_hosts
* (exact hostname => nonempty public IP list). Pins take precedence over the optional
* server-owned resolve_host callable, then native DNS for unpinned hosts only.
* No file ID cache survives this call, including between different Dify users.
* File IDs remain request-local unless the server explicitly enables
* reuse_uploaded_files (default false); reuse_ttl_seconds is capped at 120.
* Reuse always follows a fresh authorized source read and is scoped by HMAC
* to credential, endpoint, user, type, MIME, upload filename and exact bytes.
* on_timing receives numeric totals only, never transport IDs or cache tokens.
* skip_missing defaults to true: only confirmed absent local files or completed
* HTTP 404/410 downloads are skipped. Other source/transport errors still fail.
* Successful files and uploaded_indices have matching order; skipped metadata
@@ -51,6 +57,9 @@ final class DifyRequiredAttachmentUpload
$skipped = [];
$index = 0;
$total = 0;
$reuseTokens = []; $published = []; $reuseHits = 0; $reuseMisses = 0;
$timing = ['source_ms' => 0, 'upload_ms' => 0, 'ocr_ms' => 0, 'reuse_wait_ms' => 0];
$tempRoot = null; $succeeded = false;
$deadline = microtime(true) + max(0, $timeout);
try {
self::check($deadline, $shouldAbort);
@@ -103,6 +112,7 @@ final class DifyRequiredAttachmentUpload
self::notify($options, $index, $total, 'uploading');
}
if (!array_key_exists($cacheKey, $cache)) {
$sourceStarted = microtime(true);
$path = @tempnam($tempRoot, 'required-');
if ($path === false) self::fail('REQUIRED_FILES_PREPARE_FAILED');
$temporary[] = $path;
@@ -125,10 +135,33 @@ final class DifyRequiredAttachmentUpload
$extension = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'application/pdf' => 'pdf',
'audio/wav' => 'wav', 'audio/mpeg' => 'mp3', 'text/plain' => 'txt'][$mime] ?? 'bin';
}
$cache[$cacheKey] = self::upload($endpoint, $apiKey, $user, $path, $mime,
'attachment-' . $index . '.' . $extension, $deadline, $shouldAbort, $options['ca_file'], $multi);
$filename = 'attachment-' . $index . '.' . $extension;
$token = null;
if (!empty($options['reuse_uploaded_files'])) {
$digest = @hash_file('sha256', $path);
if (!is_string($digest)) self::fail('REQUIRED_FILES_PREPARE_FAILED');
$token = DifyUploadedFileReuse::token($apiKey, $endpoint, $user, $item['type'], $mime, $filename, $digest);
}
$timing['source_ms'] += max(0, (int) round((microtime(true) - $sourceStarted) * 1000));
$upload = static function () use ($endpoint, $apiKey, $user, $path, $mime, $filename,
$deadline, $shouldAbort, $options, $multi, &$timing): string {
$uploadStarted = microtime(true);
try { return self::upload($endpoint, $apiKey, $user, $path, $mime, $filename,
$deadline, $shouldAbort, $options['ca_file'], $multi); }
finally { $timing['upload_ms'] += max(0, (int) round((microtime(true) - $uploadStarted) * 1000)); }
};
if ($token !== null) {
$reused = DifyUploadedFileReuse::resolve($tempRoot, $token, $options['reuse_ttl_seconds'],
$deadline, $shouldAbort, $upload);
$reuseTokens[$token] = true;
$timing['reuse_wait_ms'] += $reused['wait_ms'];
if ($reused['hit']) $reuseHits++; else $reuseMisses++;
if ($reused['generation'] !== null) $published[$token] = $reused['generation'];
$cache[$cacheKey] = $reused['id'];
} else $cache[$cacheKey] = $upload();
if ($item['type'] === 'image') $imagePaths[$cacheKey] = $path;
}
if (!$exists) $timing['source_ms'] += max(0, (int) round((microtime(true) - $sourceStarted) * 1000));
}
if ($cache[$cacheKey] === null) {
if (!$options['skip_missing']) self::fail(array_key_exists('path', $item)
@@ -146,11 +179,17 @@ final class DifyRequiredAttachmentUpload
self::check($deadline, $shouldAbort);
$textCheck = ['status' => 'disabled', 'images' => []];
if ($imageSources !== [] && !empty($options['ocr']['enabled'])) {
$textCheck = self::optionalImageText($imageSources, $tempRoot, $deadline, $shouldAbort, $options);
$ocrStarted = microtime(true);
try { $textCheck = self::optionalImageText($imageSources, $tempRoot, $deadline, $shouldAbort, $options); }
finally { $timing['ocr_ms'] += max(0, (int) round((microtime(true) - $ocrStarted) * 1000)); }
}
self::check($deadline, $shouldAbort);
return ['ok' => true, 'files' => $prepared, 'uploaded_indices' => $uploadedIndices,
$result = ['ok' => true, 'files' => $prepared, 'uploaded_indices' => $uploadedIndices,
'skipped' => $skipped, 'attachment_transport' => 'uploaded_files', 'image_text_check' => $textCheck];
if (!empty($options['reuse_uploaded_files'])) $result += ['reuse_tokens' => array_keys($reuseTokens),
'reuse_hit_count' => $reuseHits, 'reuse_miss_count' => $reuseMisses, 'timings' => $timing];
$succeeded = true;
return $result;
} catch (\Throwable $error) {
// Never expose cURL response bodies, URLs, local paths, credentials or exception text.
$code = $error instanceof \RuntimeException ? $error->getMessage() : 'REQUIRED_FILES_PREPARE_FAILED';
@@ -174,11 +213,29 @@ final class DifyRequiredAttachmentUpload
return ['ok' => false, 'error_code' => $code, 'error' => $messages[$code],
'failed_index' => $index, 'attachment_count' => $total, 'skipped' => $skipped];
} finally {
if (!$succeeded && $published !== [] && is_string($tempRoot)) {
DifyUploadedFileReuse::drop($tempRoot, array_keys($published), $published);
}
foreach ($temporary as $path) if (is_file($path)) @unlink($path);
if ($multi !== null && $multi !== false) curl_multi_close($multi);
if (is_callable($options['on_timing'] ?? null)) {
try { ($options['on_timing'])($timing); } catch (\Throwable $ignored) { /* Telemetry cannot change transport. */ }
}
}
}
/** Internal stale-file recovery. Tokens must never be included in public receipts. */
public static function invalidateReuse(array $tokens, array $options = []): void
{
try {
$options = self::options($options);
$publicRoot = realpath((string) ($options['public_root'] ?? dirname(__DIR__, 3) . '/public'));
$root = realpath((string) ($options['temp_root'] ?? dirname(__DIR__, 3) . '/runtime/dify-required-attachments'));
if ($publicRoot === false || $root === false || $root === $publicRoot || self::inside($publicRoot, $root)) return;
DifyUploadedFileReuse::drop($root, $tokens);
} catch (\Throwable $ignored) { /* A cache outage does not prevent a fresh upload. */ }
}
/** Spend only optional OCR time; the original image/model deadline is unchanged. */
private static function optionalImageText(array $images, string $root, float $deadline, ?callable $shouldAbort, array $options): array
{
@@ -221,10 +278,22 @@ final class DifyRequiredAttachmentUpload
catch (\Throwable $ignored) { $configured = []; }
}
$options = array_replace(is_array($configured) ? $configured : [], $options);
if (!array_key_exists('reuse_uploaded_files', $options)) $options['reuse_uploaded_files'] = false;
if (!is_bool($options['reuse_uploaded_files'])) self::fail('CONFIG_INVALID');
$options['reuse_ttl_seconds'] = max(1, min(120, (int) ($options['reuse_ttl_seconds'] ?? 120)));
if (!array_key_exists('skip_missing', $options)) $options['skip_missing'] = true;
if (!is_bool($options['skip_missing'])) self::fail('CONFIG_INVALID');
$caFile = $options['ca_file'] ?? '';
if (!is_string($caFile) || ($caFile !== '' && (!is_file($caFile) || !is_readable($caFile)))) self::fail('CONFIG_INVALID');
if (!is_string($caFile)) self::fail('CONFIG_INVALID');
if ($caFile !== '' && (!is_file($caFile) || !is_readable($caFile))) {
// CA 证书包是可选项:路径失效(如 .env 沿用了其他机器的路径)时退回系统证书库,
// 仍校验对端证书与主机名,不再让所有 AI 请求因此失败。
if (class_exists(\think\facade\Log::class)) {
try { \think\facade\Log::warning('dify attachment ca_file unreadable, using system CA store'); }
catch (\Throwable $ignored) {}
}
$caFile = '';
}
$options['ca_file'] = $caFile;
$options['resolved_hosts'] = self::resolvedHosts(array_key_exists('resolved_hosts', $options)
? $options['resolved_hosts'] : []);
@@ -408,7 +477,7 @@ final class DifyRequiredAttachmentUpload
} elseif (is_callable($options['resolve_host'] ?? null)) {
$addresses = ($options['resolve_host'])($host);
} else {
// Validate every returned address, then pin the actual transfer to one.
// Validate every returned address, then pin the transfer to that set.
// Native PHP DNS is synchronous; its elapsed time still consumes this deadline.
$records = @dns_get_record($host, DNS_A | DNS_AAAA);
$addresses = [];
@@ -420,7 +489,9 @@ final class DifyRequiredAttachmentUpload
self::check($deadline, $shouldAbort);
if (!is_array($addresses) || $addresses === []) self::fail('REQUIRED_FILES_DOWNLOAD_FAILED');
foreach ($addresses as $address) if (!is_string($address) || !self::publicIp($address)) self::fail('REQUIRED_FILES_SOURCE_UNTRUSTED');
$ip = $addresses[0];
// Keep every validated address available to libcurl. A stale first DNS
// pin must not hide a reachable alternate for the same verified host.
$pinnedAddresses = array_map(static fn (string $ip): string => str_contains($ip, ':') ? '[' . $ip . ']' : $ip, $addresses);
$port = (int) ($parts['port'] ?? ($parts['scheme'] === 'https' ? 443 : 80));
$output = @fopen($path, 'wb');
if ($output === false) self::fail('REQUIRED_FILES_PREPARE_FAILED');
@@ -430,7 +501,7 @@ final class DifyRequiredAttachmentUpload
$writeError = '';
try {
$curlOptions = self::curlOptions($url, $deadline, $shouldAbort, $options['ca_file']);
$curlOptions[CURLOPT_RESOLVE] = [$host . ':' . $port . ':' . (str_contains($ip, ':') ? '[' . $ip . ']' : $ip)];
$curlOptions[CURLOPT_RESOLVE] = [$host . ':' . $port . ':' . implode(',', $pinnedAddresses)];
$curlOptions[CURLOPT_HEADERFUNCTION] = static function ($handle, string $line) use ($maxBytes, &$writeError): int {
if (preg_match('/^Content-Length:\s*(\d+)/i', $line, $match) && (float) $match[1] > $maxBytes) {
$writeError = 'REQUIRED_FILES_TOO_LARGE'; return 0;
+93 -2
View File
@@ -6,13 +6,16 @@ namespace app\common\service;
/** Request-local numeric telemetry. Raw events, prompts, titles, URLs and IDs never leave it. */
final class DifyStreamTiming
{
private const EVENTS = ['workflow_started', 'workflow_finished', 'node_started', 'node_finished',
private const MAX_MILLISECONDS = 3600000;
private const MAX_COUNT = 1000000000;
private const EVENTS = ['workflow_started', 'workflow_finished', 'node_started', 'node_finished', 'node_retry',
'message', 'agent_message', 'agent_thought', 'message_end', 'error', 'ping', 'choices'];
private const TYPES = ['start', 'llm', 'knowledge-retrieval', 'tool', 'code', 'template-transform',
'if-else', 'answer', 'end', 'agent', 'http-request', 'iteration', 'question-classifier',
'variable-aggregator', 'parameter-extractor', 'list-operator', 'document-extractor'];
private \Closure $clock;
private float $started;
private int $lastElapsed = 0;
private array $metrics = [];
private array $events = [];
private array $nodes = [];
@@ -24,7 +27,77 @@ final class DifyStreamTiming
$this->started = ($this->clock)();
}
private function elapsed(): int { return max(0, (int) floor(($this->clock)() - $this->started)); }
private function elapsed(): int
{
$elapsed = ($this->clock)() - $this->started;
if (!is_finite($elapsed)) return $this->lastElapsed;
return $this->lastElapsed = max($this->lastElapsed,
(int) min(self::MAX_MILLISECONDS, max(0, floor($elapsed))));
}
private function increment(string $key): void
{
$this->metrics[$key] = min(self::MAX_COUNT, (int) ($this->metrics[$key] ?? 0) + 1);
}
/** Abort signals also include validation rejection; they do not identify user intent. */
public function interrupted(string $trigger): void
{
if (isset($this->metrics['interruption_detected_ms'])) return;
$this->metrics['interruption_detected_ms'] = $this->elapsed();
$this->metrics['interruption_trigger'] = in_array($trigger, ['abort_signal', 'callback_error', 'timeout'], true)
? $trigger : 'other';
}
/** Call only inside the callable that actually performs stop HTTP, never on lease polls. */
public function stopIoBegin(): void
{
$now = $this->elapsed();
$this->metrics['stop_io_begin_ms'] ??= $now;
$this->metrics['last_stop_io_begin_ms'] = $now;
$this->increment('stop_io_attempt_count');
}
public function stopIoEnd(bool $accepted): void
{
$now = $this->elapsed();
$this->metrics['stop_io_end_ms'] ??= $now;
$this->metrics['last_stop_io_end_ms'] = $now;
$this->increment('stop_io_completed_count');
if ($accepted) {
$this->increment('stop_io_accepted_count');
$this->stopAccepted('local_io');
}
}
/** A peer can confirm acceptance without this transport performing stop I/O. */
public function stopAccepted(string $source): void
{
if (isset($this->metrics['stop_accepted_ms'])) return;
$this->metrics['stop_accepted_ms'] = $this->elapsed();
$this->metrics['stop_accepted_source'] = in_array($source, ['local_io', 'coordinator'], true) ? $source : 'other';
}
/** The parser calls this only after its bound-task and allowed-status terminal gate. */
public function workflowTerminal(string $status): void
{
if (isset($this->metrics['workflow_terminal_ms']) || !in_array($status, ['stopped', 'succeeded', 'failed'], true)) return;
$this->metrics['workflow_terminal_ms'] = $this->elapsed();
$this->metrics['workflow_terminal_status'] = $status;
}
/** Natural EOF means the HTTP response body completed; it is not provider/GPU proof. */
public function transportReturned(string $outcome): void
{
if (isset($this->metrics['transport_return_ms'])) return;
$this->metrics['transport_return_ms'] = $this->elapsed();
$outcome = in_array($outcome, ['natural_eof', 'local_abort', 'timeout', 'transport_error', 'exception'], true)
? $outcome : 'other';
$this->metrics['transport_exit'] = $outcome;
if ($outcome === 'natural_eof') $this->metrics['natural_eof_ms'] = $this->metrics['transport_return_ms'];
}
public function transportClosed(): void { $this->metrics['transport_closed_ms'] ??= $this->elapsed(); }
public function headers(int $status): void
{
@@ -46,6 +119,20 @@ final class DifyStreamTiming
$now = $this->elapsed();
$this->events[$name] ??= ['first_ms' => $now, 'last_ms' => $now, 'count' => 0];
++$this->events[$name]['count']; $this->events[$name]['last_ms'] = $now;
if ($name === 'node_retry') {
$retry = $decoded['data']['retry_index'] ?? null;
if (is_numeric($retry) && (float) $retry >= 0 && (float) $retry <= 1000) {
$this->metrics['max_node_retry_index'] = max((int) ($this->metrics['max_node_retry_index'] ?? 0), (int) $retry);
}
}
$reasoning = $protocol === 'dify' ? ($decoded['thought'] ?? null)
: ($decoded['choices'][0]['delta']['reasoning_content'] ?? null);
if (is_string($reasoning) && $reasoning !== '') {
$this->metrics['first_reasoning_frame_ms'] ??= $now;
$this->metrics['reasoning_frame_count'] = (int) ($this->metrics['reasoning_frame_count'] ?? 0) + 1;
$this->metrics['reasoning_frame_bytes'] = min(1000000000,
(int) ($this->metrics['reasoning_frame_bytes'] ?? 0) + strlen($reasoning));
}
if (in_array($name, ['message', 'agent_message', 'choices'], true)) {
$answer = $protocol === 'dify' ? ($decoded['answer'] ?? '') : ($decoded['choices'][0]['delta']['content'] ?? '');
$visible = is_string($answer) && $answer !== '';
@@ -83,6 +170,10 @@ final class DifyStreamTiming
}
}
$usage = $name === 'message_end' ? ($decoded['metadata']['usage'] ?? []) : ($decoded['usage'] ?? []);
if (is_array($usage) && !isset($usage['reasoning_tokens'])
&& isset($usage['completion_tokens_details']['reasoning_tokens'])) {
$usage['reasoning_tokens'] = $usage['completion_tokens_details']['reasoning_tokens'];
}
foreach (['prompt_tokens', 'completion_tokens', 'total_tokens', 'reasoning_tokens'] as $key) {
$value = is_array($usage) ? ($usage[$key] ?? null) : null;
if (is_numeric($value) && is_finite((float) $value) && (float) $value >= 0) {
@@ -0,0 +1,154 @@
<?php
declare(strict_types=1);
namespace app\common\service;
/** Private, bounded transport-descriptor reuse. Never stores source bytes or OCR. */
final class DifyUploadedFileReuse
{
private const VERSION = 1;
private const SLOTS = 256;
private const MAX_RECORD_BYTES = 1024;
private const DIRECTORY = '.dify-upload-reuse-v1';
public static function token(string $apiKey, string $endpoint, string $user, string $type,
string $mime, string $filename, string $digest): string
{
return hash_hmac('sha256', serialize([self::VERSION, $endpoint, $user, $type, $mime, $filename, $digest]), $apiKey);
}
/** The caller must freshly authorize/read immutable source bytes before calling. */
public static function resolve(string $root, string $token, int $ttl, float $deadline,
?callable $abort, callable $upload): array
{
self::check($deadline, $abort);
try { $lock = self::open($root, $token); } catch (\Throwable $ignored) { $lock = null; }
$waitStarted = microtime(true);
if ($lock === null) {
$id = $upload();
self::check($deadline, $abort);
return ['id' => $id, 'hit' => false, 'wait_ms' => 0, 'generation' => null];
}
try {
$acquired = false;
while (true) {
$blocked = 0;
try { $acquired = @flock($lock, LOCK_EX | LOCK_NB, $blocked); }
catch (\Throwable $ignored) { $blocked = 0; }
if ($acquired || !$blocked) break;
self::check($deadline, $abort);
usleep(20000);
}
self::check($deadline, $abort);
$wait = max(0, (int) round((microtime(true) - $waitStarted) * 1000));
if (!$acquired) {
$id = $upload(); self::check($deadline, $abort);
return ['id' => $id, 'hit' => false, 'wait_ms' => $wait, 'generation' => null];
}
try { $record = self::read($lock, $token); } catch (\Throwable $ignored) { $record = null; }
if ($record !== null) return ['id' => $record['id'], 'hit' => true, 'wait_ms' => $wait, 'generation' => null];
$id = $upload(); // Upload exceptions are real failures, never cache fallback.
self::check($deadline, $abort);
if (!self::validId($id)) throw new \RuntimeException('REQUIRED_FILES_UPLOAD_FAILED');
$now = microtime(true);
$generation = null;
// Readers and writers hold this same stable inode's exclusive lock.
// A crash during truncate/write produces a cache miss, never a partial ID.
try {
$candidate = bin2hex(random_bytes(16));
$data = ['v' => self::VERSION, 'token' => $token, 'id' => $id, 'created' => $now,
'expires' => $now + max(1, min(120, $ttl)), 'generation' => $candidate];
if (self::write($lock, $data)) $generation = $candidate;
} catch (\Throwable $ignored) { self::clear($lock); }
try { self::check($deadline, $abort); }
catch (\Throwable $error) { self::clear($lock); throw $error; }
return ['id' => $id, 'hit' => false, 'wait_ms' => $wait, 'generation' => $generation];
} finally {
@flock($lock, LOCK_UN);
fclose($lock);
}
}
/** Drop matching records only; stable lock files are never unlinked. */
public static function drop(string $root, array $tokens, array $generations = []): void
{
foreach (array_unique(array_filter($tokens, static fn ($token): bool =>
is_string($token) && preg_match('/^[a-f0-9]{64}$/D', $token) === 1)) as $token) {
try { $lock = self::open($root, $token); } catch (\Throwable $ignored) { $lock = null; }
if ($lock === null) continue;
try {
// Invalidation must never wait on another request's active upload.
if (!@flock($lock, LOCK_EX | LOCK_NB)) continue;
$record = self::read($lock, $token, false);
if ($record !== null && (!isset($generations[$token])
|| hash_equals($generations[$token], $record['generation']))) self::clear($lock);
} catch (\Throwable $ignored) { /* Invalidation is best effort; callers bypass reuse on retry. */ }
finally { @flock($lock, LOCK_UN); fclose($lock); }
}
}
private static function open(string $root, string $token)
{
if (preg_match('/^[a-f0-9]{64}$/D', $token) !== 1 || is_link($root)) return null;
$real = realpath($root);
if ($real === false || !is_dir($real) || !is_writable($real)) return null;
$directory = $real . DIRECTORY_SEPARATOR . self::DIRECTORY;
clearstatcache(true, $directory);
if (is_link($directory)) return null;
if (!is_dir($directory) && !@mkdir($directory, 0700) && !is_dir($directory)) return null;
clearstatcache(true, $directory);
if (is_link($directory) || realpath($directory) !== $directory || !is_dir($directory)) return null;
if (!@chmod($directory, 0700)) return null;
$directoryStat = @stat($directory);
if ($directoryStat === false || (PHP_OS_FAMILY !== 'Windows' && ($directoryStat['mode'] & 077) !== 0)) return null;
$path = $directory . DIRECTORY_SEPARATOR . sprintf('%03d.cache', hexdec(substr($token, 0, 4)) % self::SLOTS);
clearstatcache(true, $path);
if (is_link($path) || (file_exists($path) && !is_file($path))) return null;
$handle = @fopen($path, 'x+b');
if ($handle === false) $handle = @fopen($path, 'r+b');
if ($handle === false) return null;
clearstatcache(true, $path);
$opened = fstat($handle); $current = @lstat($path);
if (is_link($path) || realpath($path) !== $path || $opened === false || $current === false
|| ($opened['mode'] & 0170000) !== 0100000 || ($current['mode'] & 0170000) !== 0100000
|| $opened['dev'] !== $current['dev'] || $opened['ino'] !== $current['ino']
|| $opened['nlink'] !== 1 || $current['nlink'] !== 1
|| !@chmod($path, 0600)) { fclose($handle); return null; }
return $handle;
}
private static function read($handle, string $token, bool $fresh = true): ?array
{
$size = (fstat($handle) ?: [])['size'] ?? 0;
if ($size < 1 || $size > self::MAX_RECORD_BYTES || !rewind($handle)) return null;
$raw = stream_get_contents($handle, self::MAX_RECORD_BYTES + 1);
try { $data = is_string($raw) ? json_decode($raw, true, 8, JSON_THROW_ON_ERROR) : null; }
catch (\Throwable $ignored) { return null; }
if (!is_array($data) || ($data['v'] ?? null) !== self::VERSION
|| !is_string($data['token'] ?? null) || !hash_equals($token, $data['token'])
|| !self::validId($data['id'] ?? null)
|| !is_string($data['generation'] ?? null) || preg_match('/^[a-f0-9]{32}$/D', $data['generation']) !== 1
|| !is_numeric($data['created'] ?? null) || !is_numeric($data['expires'] ?? null)) return null;
$created = (float) $data['created']; $expires = (float) $data['expires']; $now = microtime(true);
if (!is_finite($created) || !is_finite($expires) || $expires <= $created || $expires - $created > 120.001
|| ($fresh && ($now < $created - 1 || $now >= $expires))) return null;
return $data;
}
private static function write($handle, array $record): bool
{
$raw = json_encode($record, JSON_THROW_ON_ERROR);
if (strlen($raw) > self::MAX_RECORD_BYTES || !self::clear($handle)) return false;
if (@fwrite($handle, $raw) !== strlen($raw) || !@fflush($handle)) { self::clear($handle); return false; }
return true;
}
private static function clear($handle): bool { return @rewind($handle) && @ftruncate($handle, 0) && @fflush($handle); }
private static function validId($id): bool { return is_string($id) && preg_match('/^[a-zA-Z0-9_-]{1,128}$/D', $id) === 1; }
private static function check(float $deadline, ?callable $abort): void
{
if ($abort !== null && $abort()) throw new \RuntimeException('AI_ASSISTANT_CANCELLED');
if (microtime(true) >= $deadline) throw new \RuntimeException('REQUIRED_FILES_TIMEOUT');
}
}
@@ -0,0 +1,208 @@
<?php
declare(strict_types=1);
namespace app\common\service;
/**
* Private, read-only adapter for AssistantRequestControl::reconcileTerminal().
* The caller supplies an original captured identity, never a URL or credential.
* No route, retry, stop request, generation, logging or control mutation lives here.
*/
final class DifyWorkflowRunStatus
{
private const MAX_TIMEOUT_MS = 1000;
private const MAX_BODY_BYTES = 1048576;
private const STATUSES = ['scheduled', 'running', 'succeeded', 'failed', 'stopped', 'partial-succeeded', 'paused'];
/**
* Only a trusted, already authorized control may consume this private result.
* Nonterminal statuses (and partial-succeeded) do not confirm the control's
* three terminal enums. Failures contain only a static code, never a run ID.
* @return array{ok:bool,workflow_run_id?:string,status?:string,error_code?:string}
*/
public static function lookup(array $identity, int $timeoutMs): array
{
$started = hrtime(true);
if (!self::validIdentity($identity)) return self::error('RUN_STATUS_IDENTITY_INVALID');
if ($timeoutMs < 1) return self::error('RUN_STATUS_TIMEOUT');
$deadline = $started + min(self::MAX_TIMEOUT_MS, $timeoutMs) * 1000000;
try {
$config = config('prescription_ai');
} catch (\Throwable $ignored) {
return self::error('RUN_STATUS_CONFIG_UNAVAILABLE');
}
if (!is_array($config)) return self::error('RUN_STATUS_CONFIG_INVALID');
if (($config['enable'] ?? false) !== true) return self::error('RUN_STATUS_CONFIG_DISABLED');
$models = $config['models'] ?? null;
$model = is_array($models) ? ($models[$identity['profile']] ?? null) : null;
$baseUrl = $config['base_url'] ?? null;
$apiKey = is_array($model) ? ($model['api_key'] ?? null) : null;
$upload = array_key_exists('required_attachment_upload', $config) ? $config['required_attachment_upload'] : [];
$caFile = is_array($upload) ? (array_key_exists('ca_file', $upload) ? $upload['ca_file'] : '') : null;
$root = is_string($baseUrl) ? self::apiRoot($baseUrl) : null;
// 可选 CA 证书包路径失效时退回系统证书库(仍校验证书),与附件上传保持一致。
if (is_string($caFile) && $caFile !== '' && (!@is_file($caFile) || !@is_readable($caFile))) $caFile = '';
if ($root === null || !is_string($apiKey) || $apiKey === '' || strlen($apiKey) > 4096
|| preg_match('/[^\x21-\x7e]/', $apiKey) !== 0
|| !is_string($caFile) || preg_match('/[\x00-\x1f\x7f]/', $caFile) !== 0) {
return self::error('RUN_STATUS_CONFIG_INVALID');
}
unset($config, $models, $model, $upload, $baseUrl);
if (!function_exists('curl_init') && !function_exists(__NAMESPACE__ . '\\curl_init')) {
return self::error('RUN_STATUS_UNAVAILABLE');
}
$result = self::request($identity, $root, $apiKey, $caFile, $deadline);
unset($apiKey, $root, $caFile);
return hrtime(true) >= $deadline ? self::error('RUN_STATUS_TIMEOUT') : $result;
}
private static function request(array $identity, string $root, string $apiKey, string $caFile, int $deadline): array
{
$handle = null;
$body = '';
$decoded = null;
$tooLarge = false;
$expired = false;
try {
if (hrtime(true) >= $deadline) return self::error('RUN_STATUS_TIMEOUT');
$handle = @curl_init();
if ($handle === false) return self::error('RUN_STATUS_TRANSPORT_ERROR');
// Include config/setup time in the caller's original budget. Never
// round a subsecond remainder up to another second or retry it.
$remainingMs = (int) floor(($deadline - hrtime(true)) / 1000000);
if ($remainingMs < 1) return self::error('RUN_STATUS_TIMEOUT');
$protocol = str_starts_with(strtolower($root), 'https:') ? CURLPROTO_HTTPS : CURLPROTO_HTTP;
$options = [
CURLOPT_URL => $root . '/workflows/run/' . $identity['workflow_run_id'],
CURLOPT_HTTPGET => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $apiKey, 'Accept: application/json'],
CURLOPT_RETURNTRANSFER => false,
CURLOPT_HEADER => false,
CURLOPT_VERBOSE => false,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_MAXREDIRS => 0,
CURLOPT_PROXY => '',
CURLOPT_NOPROXY => '*',
CURLOPT_PROTOCOLS => $protocol,
CURLOPT_REDIR_PROTOCOLS => $protocol,
CURLOPT_NETRC => CURL_NETRC_IGNORED,
CURLOPT_UNRESTRICTED_AUTH => false,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_TIMEOUT_MS => $remainingMs,
CURLOPT_CONNECTTIMEOUT_MS => $remainingMs,
CURLOPT_NOSIGNAL => true,
CURLOPT_NOPROGRESS => false,
CURLOPT_WRITEFUNCTION => static function ($unused, string $chunk) use (&$body, &$tooLarge, &$expired, $deadline): int {
if (hrtime(true) >= $deadline) {
$expired = true;
return 0;
}
$length = strlen($chunk);
if ($length > self::MAX_BODY_BYTES - strlen($body)) {
$tooLarge = true;
$body = '';
return 0;
}
$body .= $chunk;
return $length;
},
];
if ($caFile !== '') $options[CURLOPT_CAINFO] = $caFile;
foreach (['CURLOPT_XFERINFOFUNCTION', 'CURLOPT_PROGRESSFUNCTION'] as $name) {
if (!defined($name)) continue;
$options[constant($name)] = static function (...$unused) use (&$expired, $deadline): int {
if (hrtime(true) < $deadline) return 0;
$expired = true;
return 1;
};
break;
}
if (!@curl_setopt_array($handle, $options)) return self::error('RUN_STATUS_TRANSPORT_ERROR');
unset($apiKey, $options, $root, $caFile);
if (hrtime(true) >= $deadline) return self::error('RUN_STATUS_TIMEOUT');
$executed = @curl_exec($handle);
$errno = @curl_errno($handle);
$httpCode = @curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
if ($expired || hrtime(true) >= $deadline || $errno === CURLE_OPERATION_TIMEDOUT) {
return self::error('RUN_STATUS_TIMEOUT');
}
if ($tooLarge) return self::error('RUN_STATUS_RESPONSE_TOO_LARGE');
if ($executed !== true || $errno !== 0) return self::error('RUN_STATUS_TRANSPORT_ERROR');
if ($httpCode !== 200) return self::error('RUN_STATUS_HTTP_ERROR');
try {
// This official response includes sensitive inputs/outputs. Parse
// only bounded memory, select two fields, then discard everything.
$decoded = json_decode($body, true, 64, JSON_THROW_ON_ERROR);
} catch (\Throwable $ignored) {
return self::error('RUN_STATUS_RESPONSE_INVALID');
}
$body = '';
if (hrtime(true) >= $deadline) return self::error('RUN_STATUS_TIMEOUT');
if (!is_array($decoded) || !is_string($decoded['id'] ?? null)
|| $decoded['id'] !== $identity['workflow_run_id']) {
return self::error('RUN_STATUS_IDENTITY_MISMATCH');
}
// Optional identity fields must agree if a deployment supplies them.
foreach (['task_id', 'user', 'profile', 'workflow_run_id'] as $field) {
if (array_key_exists($field, $decoded) && $decoded[$field] !== $identity[$field]) {
return self::error('RUN_STATUS_IDENTITY_MISMATCH');
}
}
if (!in_array($decoded['status'] ?? null, self::STATUSES, true)) {
return self::error('RUN_STATUS_STATUS_UNCONFIRMED');
}
return ['ok' => true, 'workflow_run_id' => $identity['workflow_run_id'], 'status' => $decoded['status']];
} catch (\Throwable $ignored) {
return self::error('RUN_STATUS_TRANSPORT_ERROR');
} finally {
$body = '';
$decoded = null;
unset($apiKey, $options, $root, $caFile);
if ($handle !== null && $handle !== false) {
try { @curl_close($handle); } catch (\Throwable $ignored) {}
}
}
}
private static function validIdentity(array $identity): bool
{
return in_array($identity['profile'] ?? null, ['qwen', 'openai'], true)
&& is_string($identity['task_id'] ?? null) && self::validId($identity['task_id'])
&& is_string($identity['workflow_run_id'] ?? null) && self::validId($identity['workflow_run_id'])
&& is_string($identity['user'] ?? null) && strlen($identity['user']) <= 128
&& preg_match('/[\x00-\x1f\x7f]/', $identity['user']) === 0
&& is_int($identity['generation'] ?? null) && $identity['generation'] > 0;
}
private static function validId(string $id): bool
{
return preg_match('/\A[A-Za-z0-9_-]{1,128}\z/', $id) === 1;
}
/** Derive one configured API root; never probe endpoints or switch protocol. */
private static function apiRoot(string $base): ?string
{
if ($base === '' || strlen($base) > 2048 || preg_match('/[\x00-\x20\x7f\\\\]/', $base) !== 0
|| filter_var($base, FILTER_VALIDATE_URL) === false) return null;
$parts = parse_url($base);
if (!is_array($parts) || !in_array(strtolower($parts['scheme'] ?? ''), ['http', 'https'], true)
|| empty($parts['host'])) return null;
foreach (['user', 'pass', 'query', 'fragment'] as $field) {
if (array_key_exists($field, $parts)) return null;
}
$path = $parts['path'] ?? '';
if (preg_match('~\A(?:/[A-Za-z0-9_-]+)*/?\z~', $path) !== 1
|| preg_match('~/chat/completions(?:/|$)~i', $path) === 1) return null;
$base = rtrim($base, '/');
if (str_ends_with($base, '/chat-messages')) $base = substr($base, 0, -strlen('/chat-messages'));
return $base;
}
private static function error(string $code): array
{
return ['ok' => false, 'error_code' => $code];
}
}
@@ -54,6 +54,9 @@ final class NihaixiaClinicalSkill
'patient-context-case-explain-nihaixia-ancient-v4',
'patient-longitudinal-report-nihaixia-ancient-v4',
'patient-longitudinal-report-required-sources-v5',
'patient-context-case-explain-tcm-four-diagnoses-v5',
'patient-longitudinal-report-tcm-four-diagnoses-v6',
'patient-longitudinal-report-tcm-four-diagnoses-v7',
], true) ? self::knowledgeSource() : null;
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace app\common\service;
/** Application-owned response rules, separate from historical reference material. */
final class TcmClinicalResponsePolicy
{
public const VERSION = 'tcm-four-diagnoses-eight-principles-v43';
public const CONSULTATION_VERSION = 'tcm-consultation-task-analysis-r37';
public static function consultationInstruction(): string
{
return '本接诊流程不采集脉象,脉象不参与本次辨证、治法或方药判断。'
. '不设脉象栏目,不补问或建议采脉,不把缺脉象列为缺口、限制或禁用方药的理由,不推断其阳性或阴性。'
. '完整原资料中的旧脉象只保留原日期和来源作历史引用,不移作本次查体或判断依据。'
. '舌象与症状病史按实际记录使用,缺项只限定依赖该项的判断,不阻断其他已有资料的分析。'
. '证候和方药是否成立取决于实际证据,不因排除脉象而自动成立。';
}
/** Selected only by the consultation server path; other products keep reference(). */
public static function consultationReference(): string
{
return '[TCM_CLINICAL_RESPONSE:' . self::CONSULTATION_VERSION . "]\n"
. self::consultationInstruction()
. '完成本次选定任务并直接给出对应分析结果:病历分析、血糖趋势、用药评估、并发症风险、问诊小结、健康建议各按自身问题作答。'
. '资料不全仍分析已知内容,逐项说明依据、可支持的结论及不确定性;缺什么说明什么,不将整个回答改成资料核对、原文摘录或通用补采清单。'
. '本次为互联网面诊,望诊以舌象为主、无脉象:须结合舌象、症状、病史与检验合理推断,明确给出倾向性结论和可执行建议,并标注为推断供医师复核,不得以资料不全为由拒答。'
. '仅在任务涉及中医辨证时按实采望闻问切及舌象→八纲→气血津液及脏腑定位→证名→治法→中药方义及禁忌组织;证据不足的证名可给有依据的鉴别方向,不能当作确诊。'
. '事实与病机分开,脏腑、证名和治法的每个限定成分分别举证,一般或正常状态本身不作病理阳性。'
. '列方须有已知依据、适用条件与禁忌,不凭病名或单症套方;新增主方方向最多一个,不输出新增剂量、频次或疗程。'
. '未记录、未采集与不详保持未知,已有否认也不能反写成未知;不臆造患者事实。'
. '西药仅既有用药及相互作用/监测,不擅停换;保留来源编号及原JSON结构,纯提取只记事实。';
}
public static function reference(): string
{
return '[TCM_CLINICAL_RESPONSE:' . self::VERSION . "]\n"
. '四诊望闻问切;舌象、脉象各单列,缺失待采集、不臆造,舌像不能推断脉象。'
. '八纲(表里寒热虚实阴阳)→气血津液及脏腑定位→证名→治法→中药方义及禁忌;不足则证候待定。'
. '四诊按实际采集方式归属,事实与病机分开;脏腑、证名和治法的每个限定成分分别举证,一般或正常状态本身不作病理阳性。'
. '关键证据不足只作鉴别;列方须有已知依据、待补证据和适用条件,不凭病名或单症套方。'
. '新增主方方向最多一个,不以合方或加味清单替代判断;不输出新增剂量、频次或疗程。'
. '未记录、未采集与不详保持未知;已有否认也不能反写成未知;禁忌缺项待核实。'
. '中药为主;西药仅既有用药及相互作用/监测,不擅停换。'
. '保留原JSON字段、来源编号;纯提取只记事实,不诊断开方。';
}
public static function augmentQuery(string $query): string
{
$prefix = self::reference() . "\n\n";
return str_starts_with($query, $prefix) ? $query : $prefix . $query;
}
/** Keep original messages and merge into the application-owned reference message. */
public static function augmentMessages(array $messages): array
{
foreach ($messages as $index => $message) {
if (($message['role'] ?? '') !== 'system') continue;
$content = $message['content'] ?? null;
if (!is_string($content)) continue;
if (str_starts_with($content, self::reference() . "\n\n")) return $messages;
if (str_starts_with($content, '[NIHAIXIA_CLINICAL_SKILL:')) {
$messages[$index]['content'] = self::augmentQuery($content);
return $messages;
}
}
array_unshift($messages, ['role' => 'system', 'content' => self::reference() . "\n\n"]);
return $messages;
}
}
@@ -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-required-candidate-nihaixia-ancient-v6';
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 RETRYABLE = ['UPSTREAM_TIMEOUT', 'UPSTREAM_BUSY', 'UPSTREAM_UNAVAILABLE', 'INCOMPLETE_RESPONSE', 'EMPTY_RESPONSE',
'CANDIDATE_WITHHELD_BY_MODEL', 'INVALID_EVIDENCE_OUTPUT', 'INVALID_REPORT_OUTPUT'];
@@ -583,36 +583,37 @@ final class PrescriptionAiGenerator
$convention = '调配约定:' . $convention . '该约定只说明本机构如何配药,不包含任何本次人工处方的药味或剂量。';
}
$policy = $requireCandidate
? '本任务用于医学研究对照:医生已另行独立完成正式处方,你的候选方只用于离线比较,不会用于取药、发药或直接给患者。'
. '因此无论资料是否完整,都必须基于已读证据独立开出一份中药候选处方,candidate状态固定为available_for_review。'
. '缺失内容不得视为正常、阴性或已读;年龄、性别、过敏史、当前用药、妊娠哺乳等未知信息按最保守假设处理,并在reason与risk_warnings逐条写明所作假设、资料缺口、禁忌核查点与待核实事项。'
. '不得返回null,不得使用insufficient_data或withheld_for_risk,不得以资料不足为由拒绝开方;同时不得编造患者事实、检查数值或用药依据,剂量取常规安全范围内可解释的取值。'
: '资料不全不等于不能给出候选方:仅缺旧资料版本、聊天同步水位、部分舌照/报告或视频转写时,应利用已有临床证据评估并尽量提出有依据的候选方;在reason与risk_warnings明确局限及待核实事项。'
. '缺失内容不得视为正常、阴性或已读。用药安全关键信息缺失、有效证据不足以支持具体药味剂量、禁忌或风险无法排除时,candidate为insufficient_data或withheld_for_risk,不能为了对比分数强行生成。';
? '医学研究对照:医生已另行独立完成正式处方,候选方仅作离线比较,不用于取药、发药或直接给患者。'
. '无论资料是否完整,须基于已读证据独立生成中药候选处方,candidate固定为available_for_review;禁止null、insufficient_data、withheld_for_risk及因资料不足拒绝开方。'
. '缺失不得视为正常、阴性或已读;年龄、性别、过敏史、当前用药、妊娠哺乳等未知信息按最保守假设处理,在reason和risk_warnings逐条注明假设、缺口、禁忌核查与待核实事项。'
. '不得编造患者事实、检查数值或用药依据;剂量取常规安全范围内可解释值。'
: '仅缺旧资料版本、聊天同步水位、部分舌照/报告或视频转写时,应评估已有临床证据并尽量提出有依据的候选方,在reason和risk_warnings注明局限及待核实事项。'
. '缺失不得视为正常、阴性或已读。用药安全关键信息缺失、证据不足以支持具体药味剂量、禁忌或风险无法排除时,candidate为insufficient_data或withheld_for_risk,不得为对比分数强行生成。';
$shape = $requireCandidate
? 'candidate必须为完整候选方案,不得为null,不得为空药味。'
? 'candidate须完整且herbs非空。'
: 'candidate可为null;不可用时为{status:"insufficient_data|withheld_for_risk",reason:"原因",herbs:[]}。';
return self::boundary() . '\n阶段=final。本次人工方已隔离。独立生成面向执业医师的中医辨证及候选用药辅助报告;不创建正式处方、签名、审核或订单。'
. '仅使用本分支已读证据,不借用其他模型结论。不凭图补造脉象,不编造患者事实、剂量单位或用药依据。'
return self::boundary() . '\n阶段=final。本次人工方已隔离。供执业医师的独立中医辨证及候选用药辅助报告;不得创建正式处方、签名、审核或订单。'
. '仅用本分支已读证据,不借用其他模型结论;不凭图补造脉象,不编造患者事实、剂量单位或用药依据。'
. $policy
. '报告、候选方及解释性内容全部使用中文,保留规范医学缩写;接口字段和来源编号必须保持原值。'
. '所有evidence_references只能逐字使用下方ALLOWED_EVIDENCE_IDS中的编号,不得引用未读到的附件编号、不得自造或改写编号;无可引用编号时该项须省略或改写为不需要引用的表述。'
. '仅返回JSON对象,顶层恰为report,candidate。report键恰为 summary,diagnosis,risk_assessment,treatment_advice,evidence_references,missing_information。'
. 'summary/diagnosis/treatment_advice为字符串;risk_assessment为[{label,level:"high|medium|low|unknown",evidence_references:[]}];其余为字符串数组且引用仅限原始来源编号。'
. '全文中文,保留规范医学缩写;接口字段、来源编号不变。'
. 'evidence_references只能逐字取自ALLOWED_EVIDENCE_IDS;禁用未读附件及自造、改写编号;无可引用编号则省略该项或改写为无需引用的表述。'
. '仅输出JSON对象,顶层恰为report,candidate;report恰含 summary,diagnosis,risk_assessment,treatment_advice,evidence_references,missing_information。'
. 'summary/diagnosis/treatment_advice为字符串;risk_assessment为[{label,level:"high|medium|low|unknown",evidence_references:[]}];其余为字符串数组,引用仅限原始来源编号。'
. 'diagnosis写四诊(舌脉单列)→八纲→气血津液/脏腑→证名;treatment_advice写治法→中药方药,缺口写missing_information。'
. $shape . $convention
. '资料足够时candidate严格为{status:"available_for_review",reason:"说明",prescription_name:"候选方名",prescription_type:"剂型",dose_basis:"per_dose|per_day",'
. 'herbs:[{name:"药名",dosage:数值,unit:"明确单位",dose_basis:"per_dose|per_day",processing:"炮制要求或明确无",formula_type:"主方|辅方",instructions:"特殊煎服要求或明确无",evidence_references:["来源编号"]}],'
. 'usage_instruction:"明确用法",times_per_day:数值,usage_days:数值,rationale:"方义",risk_warnings:["复核点"],evidence_references:["来源编号"]}。'
. '每味用量与单位、基准、主辅方、剂型、服法、服次、疗程必须有明确依据,不默认7剂/每日2次;无药材ID、签名、审核等业务字段。'
. 'candidate的键必须与上面列出的完全一致:不要增加dose_count、剂数、总量、药材ID、勾兑说明等字段,也不要漏字段;'
. 'times_per_day、usage_days与每味dosage必须是JSON数字,不能写成"2剂""7天"这类字符串;candidate与每一味的evidence_references都不能是空数组。'
. 'formula_type中的"辅方"专指与主方分开调配的另一张处方(如另包冲服、外用),不是君臣佐使中的臣药佐药;'
. '除非确实需要单独的另一张辅助处方,所有药味一律填"主方"。药名本身已经含有炮制信息时(如醋五味子、麸炒白术、生麦冬),processing填"明确无",不要重复写炮制。'
. '整份回答必须在一次输出内写完:summary、diagnosis、treatment_advice各不超过400字,rationale与candidate.reason各不超过300字,'
. 'risk_assessment、missing_information、risk_warnings每条不超过80字且总条数不超过12条,候选药味不超过20味;宁可写得精炼,也不要因为过长而被截断成不完整的JSON。'
. '各味用量单位、基准、主辅方、剂型、服法服次疗程须有据,禁默认7剂/每日2次及药材ID、签名、审核等业务字段。'
. 'candidate键须齐全且不增项(如dose_count、剂数、总量、勾兑说明)。'
. 'times_per_day、usage_days及每味dosage须为JSON数字;candidate及各味evidence_references须为非空数组。'
. '辅方仅指与主方分开调配的另一张处方,不指臣药佐药;否则各味formula_type均为主方。'
. '药名含炮制时processing填“明确无”,禁重复写炮制。'
. '一次输出完整JSON:summary、diagnosis、treatment_advice各不超过400字,rationale及candidate.reason各不超过300字;'
. 'risk_assessment、missing_information、risk_warnings每条不超过80字且总条数不超过12条,药味不超过20味。'
. ($requireCandidate
? "\nREQUIRE_CANDIDATE=true(研究对照模式:必须输出available_for_review候选方,资料缺口与假设写入reason和risk_warnings)"
: "\nCLINICAL_SAFETY_BLOCKED=" . ($clinicalSafetyBlocked ? 'true(缺少关键用药安全信息,不得给出具体候选药味剂量)' : 'false(允许依据已读资料提出供医生复核的候选方,资料缺口仍须明示并自行评估)'))
? "\nREQUIRE_CANDIDATE=true(研究对照,须按上述规则生成候选方)"
: "\nCLINICAL_SAFETY_BLOCKED=" . ($clinicalSafetyBlocked ? 'true(缺关键用药安全信息,禁止具体候选药味剂量)' : 'false(按已读证据评估候选方,明示缺口并供医生复核)'))
. ($allowedIds !== [] ? "\nALLOWED_EVIDENCE_IDS=" . self::json($allowedIds) : '')
. ($catalogNames !== [] ? "\nMEDICINE_CATALOG=" . self::json($catalogNames) : '')
. "\nCOVERAGE_JSON=" . self::json($coverage) . "\nBRANCH_EVIDENCE_JSON=" . self::json($summaries);