Merge branch 'master' of http://git.zhenyangtang.com.cn/ZYT/zyt
This commit is contained in:
@@ -157,8 +157,8 @@ class DifyChatService
|
||||
if ($shouldAbort !== null && $shouldAbort()) return self::error('AI_ASSISTANT_CANCELLED', '本次请求已取消');
|
||||
// The legacy compatible path cannot transmit documents. Strict callers must
|
||||
// receive an explicit gap, never a successful text-only fallback.
|
||||
if ($strictFiles && !self::strictProtocolSupportsFiles($requestSpec['protocol'], $attempt['files'])) {
|
||||
if ($requiredFiles) return self::requiredFilesFailure($options, 'REQUIRED_FILES_UNSUPPORTED', '必需资料提交失败:当前模型接口不支持原始文档等附件', $attempt['files'], $requestSpec['protocol']);
|
||||
if ($strictFiles && !self::strictProtocolSupportsFiles($requestSpec['protocol'], self::availableSourceFiles($attempt['files'], $uploadCache))) {
|
||||
if ($requiredFiles) return self::requiredFilesFailure($lastTransferOptions, 'REQUIRED_FILES_UNSUPPORTED', '必需资料提交失败:当前模型接口不支持原始文档等附件', $attempt['files'], $requestSpec['protocol']);
|
||||
return self::error('FILE_TYPE_UNSUPPORTED', '当前模型接口不支持此类原始附件');
|
||||
}
|
||||
$elapsedSeconds = (int) floor(microtime(true) - $startedAt);
|
||||
@@ -172,7 +172,7 @@ class DifyChatService
|
||||
}
|
||||
|
||||
$staged = self::prepareRequiredUpload($requestSpec, $attempt['files'], $user, $apiKey,
|
||||
$remainingTimeout, $shouldAbort, $options, $config, $uploadCache);
|
||||
$remainingTimeout, $shouldAbort, $options, $config, $uploadCache, $query);
|
||||
if (empty($staged['ok'])) return $staged;
|
||||
$requestSpec = $staged['request_spec'];
|
||||
$lastTransferOptions = $staged['options'];
|
||||
@@ -217,7 +217,7 @@ class DifyChatService
|
||||
if (!empty($formatted['ok'])) {
|
||||
$formatted['ancient_book_sources'] = $ancientBookSources;
|
||||
if ($strictFiles) {
|
||||
$formatted['transmitted_file_count'] = count($attempt['files']);
|
||||
$formatted['transmitted_file_count'] = count(self::availableSourceFiles($attempt['files'], $uploadCache));
|
||||
$formatted['attachment_transport'] = (string) ($lastSpec['protocol'] ?? '');
|
||||
}
|
||||
if ($requiredFiles) $formatted += self::finalTransferManifest($lastTransferOptions, $attempt['files'], (string) ($lastSpec['protocol'] ?? ''));
|
||||
@@ -346,8 +346,8 @@ class DifyChatService
|
||||
if ($shouldAbort !== null && $shouldAbort()) {
|
||||
return self::error('AI_ASSISTANT_CANCELLED', '本次请求已取消');
|
||||
}
|
||||
if ($strictFiles && !self::strictProtocolSupportsFiles($requestSpec['protocol'], $attempt['files'])) {
|
||||
if ($requiredFiles) return self::requiredFilesFailure($options, 'REQUIRED_FILES_UNSUPPORTED', '必需资料提交失败:当前模型接口不支持原始文档等附件', $attempt['files'], $requestSpec['protocol']);
|
||||
if ($strictFiles && !self::strictProtocolSupportsFiles($requestSpec['protocol'], self::availableSourceFiles($attempt['files'], $uploadCache))) {
|
||||
if ($requiredFiles) return self::requiredFilesFailure($lastTransferOptions, 'REQUIRED_FILES_UNSUPPORTED', '必需资料提交失败:当前模型接口不支持原始文档等附件', $attempt['files'], $requestSpec['protocol']);
|
||||
return self::error('FILE_TYPE_UNSUPPORTED', '当前模型接口不支持此类原始附件');
|
||||
}
|
||||
$elapsedSeconds = (int) floor(microtime(true) - $startedAt);
|
||||
@@ -361,7 +361,7 @@ class DifyChatService
|
||||
}
|
||||
|
||||
$staged = self::prepareRequiredUpload($requestSpec, $attempt['files'], $user, $apiKey,
|
||||
$remainingTimeout, $shouldAbort, $options, $config, $uploadCache);
|
||||
$remainingTimeout, $shouldAbort, $options, $config, $uploadCache, $query);
|
||||
if (empty($staged['ok'])) return $staged;
|
||||
$requestSpec = $staged['request_spec'];
|
||||
$lastTransferOptions = $staged['options'];
|
||||
@@ -410,7 +410,7 @@ class DifyChatService
|
||||
if (!empty($formatted['ok'])) {
|
||||
$formatted['ancient_book_sources'] = $ancientBookSources;
|
||||
if ($strictFiles) {
|
||||
$formatted['transmitted_file_count'] = count($attempt['files']);
|
||||
$formatted['transmitted_file_count'] = count(self::availableSourceFiles($attempt['files'], $uploadCache));
|
||||
$formatted['attachment_transport'] = (string) ($lastSpec['protocol'] ?? '');
|
||||
}
|
||||
if ($requiredFiles) $formatted += self::finalTransferManifest($lastTransferOptions, $attempt['files'], (string) ($lastSpec['protocol'] ?? ''));
|
||||
@@ -451,14 +451,29 @@ class DifyChatService
|
||||
&& ($body['result'] ?? '') === 'success';
|
||||
}
|
||||
|
||||
/** Stage each mandatory Dify file once; a failed upload cannot start generation. */
|
||||
/** Upload available files once; confirmed missing sources never block the clinical text. */
|
||||
private static function prepareRequiredUpload(array $spec, array $files, string $user, string $apiKey,
|
||||
int $timeout, ?callable $shouldAbort, array $options, array $config, array &$cache): array
|
||||
int $timeout, ?callable $shouldAbort, array $options, array $config, array &$cache, string $sourceQuery): array
|
||||
{
|
||||
if (empty($options['required_files']) || $files === [] || ($spec['protocol'] ?? '') !== 'dify'
|
||||
if (empty($options['required_files']) || $files === []
|
||||
|| ($config['required_attachment_transport'] ?? '') !== 'upload') {
|
||||
return ['ok' => true, 'request_spec' => $spec, 'options' => $options];
|
||||
}
|
||||
$sourceKey = 'sources:' . hash('sha256', json_encode($files));
|
||||
if (($spec['protocol'] ?? '') !== 'dify') {
|
||||
if (isset($cache[$sourceKey])) {
|
||||
$receipt = $cache[$sourceKey];
|
||||
$options['attachment_items'] = $receipt['items'];
|
||||
// Rebuild transport-only content from the original clinical query
|
||||
// and available sources; never splice URLs out of clinical text.
|
||||
$available = self::availableSourceFiles($files, $cache);
|
||||
$spec['payload']['messages'] = [['role' => 'user', 'content' => self::buildOpenAiContent(
|
||||
self::withAttachmentManifest($sourceQuery, self::nonImageFiles($available)), $available
|
||||
)]];
|
||||
$spec = self::addMissingAttachmentNotice($spec, $receipt['items']);
|
||||
}
|
||||
return ['ok' => true, 'request_spec' => $spec, 'options' => $options];
|
||||
}
|
||||
$options['attachment_transfer'] = 'uploaded_files';
|
||||
$cacheKey = hash('sha256', $spec['url'] . "\0" . $apiKey . "\0" . $user . "\0" . json_encode($files));
|
||||
if (!isset($cache[$cacheKey])) {
|
||||
@@ -484,8 +499,11 @@ class DifyChatService
|
||||
$index = (int) ($event['index'] ?? 0);
|
||||
if ($index < 1 || !isset($items[$index - 1])) return;
|
||||
$status = $event['status'] ?? '';
|
||||
if (!in_array($status, ['uploading', 'uploaded', 'failed'], true)) return;
|
||||
if (!in_array($status, ['uploading', 'uploaded', 'failed', 'skipped'], true)) return;
|
||||
$items[$index - 1]['status'] = $status;
|
||||
if ($status === 'skipped' && ($event['reason'] ?? '') === 'not_found') {
|
||||
$items[$index - 1]['reason'] = 'not_found';
|
||||
}
|
||||
$sections = self::requiredSections($options, 'prepared');
|
||||
$summary = is_array($options['source_summary'] ?? null) ? $options['source_summary'] : [];
|
||||
$summary['required_sections'] = $sections;
|
||||
@@ -496,11 +514,13 @@ class DifyChatService
|
||||
'source_form' => $options['source_form'] ?? 'full_context',
|
||||
'evidence_cache_hit' => !empty($options['evidence_cache_hit']),
|
||||
'attachment_transfer' => 'uploaded_files',
|
||||
'skipped_attachment_count' => count(array_filter($items, static fn (array $item): bool => $item['status'] === 'skipped')),
|
||||
]);
|
||||
};
|
||||
$started = microtime(true);
|
||||
$uploaded = DifyRequiredAttachmentUpload::prepare($spec['url'], $apiKey, $user, $files,
|
||||
$timeout, $shouldAbort, $uploadOptions);
|
||||
$options['attachment_items'] = $items;
|
||||
if (empty($uploaded['ok'])) {
|
||||
if (($uploaded['error_code'] ?? '') === 'AI_ASSISTANT_CANCELLED') {
|
||||
return self::error('AI_ASSISTANT_CANCELLED', '本次请求已取消', self::elapsedMilliseconds($started));
|
||||
@@ -508,15 +528,76 @@ class DifyChatService
|
||||
return self::requiredFilesFailure($options, (string) ($uploaded['error_code'] ?? 'REQUIRED_FILES_UPLOAD_FAILED'),
|
||||
(string) ($uploaded['error'] ?? '必需附件上传失败,本次未提交分析'), $files, 'dify', self::elapsedMilliseconds($started));
|
||||
}
|
||||
if (!is_array($uploaded['files'] ?? null) || count($uploaded['files']) !== count($files)) {
|
||||
$receipt = self::uploadedAttachmentReceipt($uploaded, $files);
|
||||
if ($receipt === null) {
|
||||
return self::requiredFilesFailure($options, 'REQUIRED_FILES_UPLOAD_FAILED', '必需附件上传不完整,本次未提交分析', $files);
|
||||
}
|
||||
$cache[$cacheKey] = $uploaded['files'];
|
||||
$cache[$cacheKey] = $receipt;
|
||||
$cache[$sourceKey] = $receipt;
|
||||
}
|
||||
$spec['payload']['files'] = $cache[$cacheKey];
|
||||
$options['attachment_items'] = $cache[$cacheKey]['items'];
|
||||
$spec['payload']['files'] = $cache[$cacheKey]['files'];
|
||||
$spec = self::addMissingAttachmentNotice($spec, $cache[$cacheKey]['items']);
|
||||
return ['ok' => true, 'request_spec' => $spec, 'options' => $options];
|
||||
}
|
||||
|
||||
/** Require an explicit, disjoint result for every original source; no silent omission. */
|
||||
private static function uploadedAttachmentReceipt(array $uploaded, array $files): ?array
|
||||
{
|
||||
if (!is_array($uploaded['files'] ?? null) || !array_is_list($uploaded['files'])) return null;
|
||||
$skipped = $uploaded['skipped'] ?? [];
|
||||
$indices = $uploaded['uploaded_indices'] ?? (count($uploaded['files']) === count($files)
|
||||
? ($files === [] ? [] : range(1, count($files))) : null);
|
||||
if (!is_array($skipped) || !array_is_list($skipped) || !is_array($indices)
|
||||
|| !array_is_list($indices) || count($indices) !== count($uploaded['files'])) return null;
|
||||
$items = self::attachmentItems($files, [], 'dify');
|
||||
$seen = [];
|
||||
foreach ($skipped as $skip) {
|
||||
$index = $skip['index'] ?? null;
|
||||
if (!is_int($index) || $index < 1 || $index > count($files) || isset($seen[$index])
|
||||
|| ($skip['reason'] ?? '') !== 'not_found'
|
||||
|| ($skip['kind'] ?? '') !== $files[$index - 1]['type']) return null;
|
||||
$seen[$index] = true;
|
||||
$items[$index - 1]['status'] = 'skipped';
|
||||
$items[$index - 1]['reason'] = 'not_found';
|
||||
}
|
||||
$previous = 0;
|
||||
foreach ($indices as $position => $index) {
|
||||
$wire = $uploaded['files'][$position];
|
||||
if (!is_int($index) || $index <= $previous || $index > count($files) || isset($seen[$index])
|
||||
|| ($wire['type'] ?? '') !== $files[$index - 1]['type']
|
||||
|| ($wire['transfer_method'] ?? '') !== 'local_file'
|
||||
|| !is_string($wire['upload_file_id'] ?? null) || trim($wire['upload_file_id']) === '') return null;
|
||||
$seen[$index] = true;
|
||||
$previous = $index;
|
||||
$items[$index - 1]['status'] = 'uploaded';
|
||||
}
|
||||
if (count($seen) !== count($files)) return null;
|
||||
return ['files' => $uploaded['files'], 'items' => $items, 'indices' => $indices, 'skipped' => $skipped];
|
||||
}
|
||||
|
||||
private static function availableSourceFiles(array $files, array $cache): array
|
||||
{
|
||||
$receipt = $cache['sources:' . hash('sha256', json_encode($files))] ?? null;
|
||||
return is_array($receipt) ? array_map(static fn (int $index): array => $files[$index - 1], $receipt['indices']) : $files;
|
||||
}
|
||||
|
||||
/** A trusted transport notice tells the model exactly which references were unavailable. */
|
||||
private static function addMissingAttachmentNotice(array $spec, array $items): array
|
||||
{
|
||||
$missing = array_values(array_filter($items, static fn (array $item): bool => ($item['status'] ?? '') === 'skipped'));
|
||||
if ($missing === []) return $spec;
|
||||
$notice = "\n\n【附件可用性说明】\n" . implode(';', array_map(
|
||||
static fn (array $item): string => $item['label'] . '源文件不存在,已跳过,未提供给模型', $missing))
|
||||
. '。请继续依据已提供的病例正文及其余可用附件回答,并明确资料缺口;不得声称已查看这些缺失附件。';
|
||||
if (isset($spec['payload']['query'])) {
|
||||
$spec['payload']['query'] .= $notice;
|
||||
} else {
|
||||
$spec['payload']['messages'][] = ['role' => 'user', 'content' => $notice];
|
||||
}
|
||||
return $spec;
|
||||
}
|
||||
|
||||
/** Mandatory clinical files have no lossy normalization or text-only fallback. */
|
||||
private static function requiredFiles(array $files): array
|
||||
{
|
||||
@@ -577,12 +658,11 @@ class DifyChatService
|
||||
$kind = is_array($file) && is_string($file['type'] ?? null) ? strtolower($file['type']) : 'custom';
|
||||
return ['type' => in_array($kind, ['image', 'document', 'audio', 'video', 'custom'], true) ? $kind : 'custom'];
|
||||
}, $files);
|
||||
$items = self::attachmentItems($labels, [], $protocol);
|
||||
foreach ($items as &$item) $item['status'] = 'failed';
|
||||
unset($item);
|
||||
$items = self::transferManifestItems($options, $labels, $protocol, 'failed');
|
||||
$manifest = ['required_sections' => $sections, 'source_summary' => $summary,
|
||||
'items' => $items, 'attachment_count' => count($items),
|
||||
'attachment_transfer' => $options['attachment_transfer'] ?? 'remote_url_references', 'transfer_manifest_final' => true];
|
||||
'attachment_transfer' => $options['attachment_transfer'] ?? 'remote_url_references', 'transfer_manifest_final' => true]
|
||||
+ self::attachmentOutcomeCounts($items);
|
||||
if (is_callable($options['on_progress'] ?? null)) ($options['on_progress'])([
|
||||
'phase' => 'attachments', 'status' => 'failed', 'message' => $message,
|
||||
] + $manifest);
|
||||
@@ -594,12 +674,27 @@ class DifyChatService
|
||||
$sections = self::requiredSections($options, 'submitted');
|
||||
$summary = is_array($options['source_summary'] ?? null) ? $options['source_summary'] : [];
|
||||
$summary['required_sections'] = $sections;
|
||||
$items = self::attachmentItems($files, [], $protocol);
|
||||
foreach ($items as &$item) $item['status'] = 'submitted';
|
||||
unset($item);
|
||||
$items = self::transferManifestItems($options, $files, $protocol, 'submitted');
|
||||
return ['required_sections' => $sections, 'source_summary' => $summary,
|
||||
'items' => $items, 'attachment_count' => count($files),
|
||||
'attachment_transfer' => $options['attachment_transfer'] ?? 'remote_url_references', 'transfer_manifest_final' => true];
|
||||
'attachment_transfer' => $options['attachment_transfer'] ?? 'remote_url_references', 'transfer_manifest_final' => true]
|
||||
+ self::attachmentOutcomeCounts($items);
|
||||
}
|
||||
|
||||
private static function transferManifestItems(array $options, array $files, string $protocol, string $status): array
|
||||
{
|
||||
$items = is_array($options['attachment_items'] ?? null) ? $options['attachment_items'] : self::attachmentItems($files, [], $protocol);
|
||||
foreach ($items as &$item) {
|
||||
if (!in_array($item['status'] ?? '', ['skipped', 'omitted'], true)) $item['status'] = $status;
|
||||
}
|
||||
unset($item);
|
||||
return $items;
|
||||
}
|
||||
|
||||
private static function attachmentOutcomeCounts(array $items): array
|
||||
{
|
||||
return ['submitted_attachment_count' => count(array_filter($items, static fn (array $item): bool => ($item['status'] ?? '') === 'submitted')),
|
||||
'skipped_attachment_count' => count(array_filter($items, static fn (array $item): bool => ($item['status'] ?? '') === 'skipped'))];
|
||||
}
|
||||
|
||||
/** Safe labels only; submitted means request references sent, never remote file reading. */
|
||||
@@ -1187,7 +1282,7 @@ class DifyChatService
|
||||
if (!is_callable($options['on_progress'] ?? null)) return;
|
||||
$items = $options['attachment_items'] ?? [];
|
||||
foreach ($items as &$item) {
|
||||
if ($item['status'] !== 'omitted') $item['status'] = $status;
|
||||
if (!in_array($item['status'], ['omitted', 'skipped'], true)) $item['status'] = $status;
|
||||
}
|
||||
unset($item);
|
||||
$sections = self::requiredSections($options, $status);
|
||||
@@ -1202,7 +1297,7 @@ class DifyChatService
|
||||
'evidence_cache_hit' => !empty($options['evidence_cache_hit']),
|
||||
'attachment_transfer' => $options['attachment_transfer'] ?? 'remote_url_references',
|
||||
'attachment_count' => count(array_filter($items, static fn (array $item): bool => $item['status'] !== 'omitted')),
|
||||
'items' => $items]);
|
||||
'items' => $items] + self::attachmentOutcomeCounts($items));
|
||||
if ($status === 'submitted') ($options['on_progress'])([
|
||||
'phase' => 'upstream', 'status' => 'waiting', 'message' => '资料请求已提交,正在等待模型正文',
|
||||
]);
|
||||
|
||||
Reference in New Issue
Block a user