igengx
This commit is contained in:
@@ -5,10 +5,11 @@ declare(strict_types=1);
|
||||
namespace app\common\service;
|
||||
|
||||
/**
|
||||
* Screenshot-only Dify transport. Reuses the configured assistant app, but never
|
||||
* Screenshot-only model transport. Reuses the configured assistant app, but never
|
||||
* enters clinical augmentation, OCR, history or protocol fallback. A rejected
|
||||
* answer may be regenerated once from the same image within the total deadline.
|
||||
* The private PHP upload is sent directly to Dify; no public storage is involved.
|
||||
* Dify receives the private PHP upload directly; 豆包 (火山方舟) receives the same
|
||||
* bytes inline as a data URI. No public storage is involved.
|
||||
*/
|
||||
final class DifyTongueScreenshotService
|
||||
{
|
||||
@@ -28,6 +29,24 @@ PROMPT;
|
||||
$settings = self::settings($config, $model);
|
||||
if (!function_exists('curl_init')) throw new \DomainException('截图分析服务暂不可用');
|
||||
$deadline = microtime(true) + self::TIMEOUT_SECONDS;
|
||||
$ask = $settings['protocol'] === 'openai'
|
||||
? self::openAiAsker($image, $settings, $deadline)
|
||||
: self::difyAsker($image, $settings, $deadline);
|
||||
$answer = $ask(TongueScreenshotAnalysis::prompt());
|
||||
try {
|
||||
$analysis = TongueScreenshotAnalysis::parse($answer);
|
||||
} catch (\DomainException $error) {
|
||||
if ($deadline - microtime(true) < self::MIN_CORRECTION_SECONDS) throw $error;
|
||||
// Only parser rejection permits one correction. Never replay the
|
||||
// rejected answer, reset the budget, upload again or change models.
|
||||
$analysis = TongueScreenshotAnalysis::parse($ask(TongueScreenshotAnalysis::prompt() . "\n" . self::CORRECTION_PROMPT));
|
||||
}
|
||||
return ['analysis' => $analysis, 'model' => $model, 'model_label' => $settings['label']];
|
||||
}
|
||||
|
||||
/** Dify: upload the private image once, then every question references that same file. */
|
||||
private static function difyAsker(TongueScreenshotImage $image, array $settings, float $deadline): \Closure
|
||||
{
|
||||
// No patient, diagnosis, admin ID, filename or historical conversation is sent.
|
||||
$user = 'tongue-screenshot-' . bin2hex(random_bytes(16));
|
||||
$upload = self::post($settings['base'] . '/files/upload', $settings, [
|
||||
@@ -40,29 +59,43 @@ PROMPT;
|
||||
}
|
||||
// An upload failure can never become a text-only success. Both possible
|
||||
// model calls use this same private image and anonymous request-local user.
|
||||
$payload = [
|
||||
'inputs' => (object) [],
|
||||
'query' => TongueScreenshotAnalysis::prompt(),
|
||||
'response_mode' => 'blocking',
|
||||
'user' => $user,
|
||||
'auto_generate_name' => false,
|
||||
'files' => [['type' => 'image', 'transfer_method' => 'local_file', 'upload_file_id' => $upload['id']]],
|
||||
];
|
||||
$response = self::post($settings['base'] . '/chat-messages', $settings,
|
||||
json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), $deadline);
|
||||
$answer = self::answer($response);
|
||||
try {
|
||||
$analysis = TongueScreenshotAnalysis::parse($answer);
|
||||
} catch (\DomainException $error) {
|
||||
if ($deadline - microtime(true) < self::MIN_CORRECTION_SECONDS) throw $error;
|
||||
// Only parser rejection permits one correction. Never replay the
|
||||
// rejected answer, reset the budget, upload again or change models.
|
||||
$payload['query'] = TongueScreenshotAnalysis::prompt() . "\n" . self::CORRECTION_PROMPT;
|
||||
$response = self::post($settings['base'] . '/chat-messages', $settings,
|
||||
return static function (string $query) use ($settings, $deadline, $user, $upload): string {
|
||||
$payload = [
|
||||
'inputs' => (object) [],
|
||||
'query' => $query,
|
||||
'response_mode' => 'blocking',
|
||||
'user' => $user,
|
||||
'auto_generate_name' => false,
|
||||
'files' => [['type' => 'image', 'transfer_method' => 'local_file', 'upload_file_id' => $upload['id']]],
|
||||
];
|
||||
return self::answer(self::post($settings['base'] . '/chat-messages', $settings,
|
||||
json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), $deadline));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenAI 兼容接口(豆包直连火山方舟):截图以 base64 data URI 内联,
|
||||
* 不产生任何公开地址;同样不发送患者、诊单或账号标识。
|
||||
*/
|
||||
private static function openAiAsker(TongueScreenshotImage $image, array $settings, float $deadline): \Closure
|
||||
{
|
||||
$bytes = @file_get_contents($image->path());
|
||||
if (!is_string($bytes) || $bytes === '') throw new \DomainException('截图无法读取,请重新截图');
|
||||
$dataUri = 'data:image/jpeg;base64,' . base64_encode($bytes);
|
||||
unset($bytes);
|
||||
return static function (string $query) use ($settings, $deadline, $dataUri): string {
|
||||
$payload = [
|
||||
'model' => $settings['model'],
|
||||
'messages' => [['role' => 'user', 'content' => [
|
||||
['type' => 'text', 'text' => $query],
|
||||
['type' => 'image_url', 'image_url' => ['url' => $dataUri]],
|
||||
]]],
|
||||
] + $settings['payload_options'];
|
||||
$response = self::post($settings['base'], $settings,
|
||||
json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), $deadline);
|
||||
$analysis = TongueScreenshotAnalysis::parse(self::answer($response));
|
||||
}
|
||||
return ['analysis' => $analysis, 'model' => $model, 'model_label' => $settings['label']];
|
||||
$content = $response['choices'][0]['message']['content'] ?? null;
|
||||
return self::answer(['answer' => $content]);
|
||||
};
|
||||
}
|
||||
|
||||
private static function answer(array $response): string
|
||||
@@ -75,11 +108,14 @@ PROMPT;
|
||||
|
||||
private static function settings(array $config, string $model): array
|
||||
{
|
||||
if (!in_array($model, ['qwen', 'openai'], true)) throw new \DomainException('截图分析模型无效');
|
||||
if (!in_array($model, ['qwen', 'openai', 'doubao'], true)) throw new \DomainException('截图分析模型无效');
|
||||
if (empty($config['enable'])) throw new \DomainException('AI 截图分析功能未启用');
|
||||
// The selected profile owns both the image upload and chat. No cross-model fallback.
|
||||
$profile = $config['models'][$model] ?? [];
|
||||
$base = rtrim(trim((string) ($config['base_url'] ?? '')), '/');
|
||||
// A profile with its own address (豆包 → 火山方舟) speaks OpenAI-compatible chat/completions.
|
||||
$ownBase = rtrim(trim((string) ($profile['base_url'] ?? '')), '/');
|
||||
$openAi = $ownBase !== '';
|
||||
$base = $openAi ? $ownBase : rtrim(trim((string) ($config['base_url'] ?? '')), '/');
|
||||
$key = trim((string) ($profile['api_key'] ?? ''));
|
||||
$parts = parse_url($base);
|
||||
if (!is_array($parts) || !in_array(strtolower($parts['scheme'] ?? ''), ['https', 'http'], true)
|
||||
@@ -87,20 +123,30 @@ PROMPT;
|
||||
|| isset($parts['query']) || isset($parts['fragment'])
|
||||
|| preg_match('/[\x00-\x20\x7f]/', $base) || $key === ''
|
||||
|| preg_match('/[\x00-\x1f\x7f]/', (string) ($profile['api_key'] ?? ''))
|
||||
|| str_ends_with(strtolower($parts['path'] ?? ''), '/chat/completions')) {
|
||||
|| str_ends_with(strtolower($parts['path'] ?? ''), '/chat/completions') !== $openAi
|
||||
|| ($openAi && trim((string) ($profile['name'] ?? '')) === '')) {
|
||||
throw new \DomainException('截图分析服务配置不完整');
|
||||
}
|
||||
if (str_ends_with($base, '/chat-messages')) $base = substr($base, 0, -strlen('/chat-messages'));
|
||||
elseif (!str_ends_with($base, '/v1')) $base .= '/v1';
|
||||
$caFile = (string) ($config['required_attachment_upload']['ca_file'] ?? '');
|
||||
// Ark's chat/completions address is used as-is; only Dify bases are normalized.
|
||||
if (!$openAi) {
|
||||
if (str_ends_with($base, '/chat-messages')) $base = substr($base, 0, -strlen('/chat-messages'));
|
||||
elseif (!str_ends_with($base, '/v1')) $base .= '/v1';
|
||||
}
|
||||
// The optional attachment CA bundle trusts the private Dify/attachment hosts;
|
||||
// the public Ark endpoint always validates against the system trust store.
|
||||
$caFile = $openAi ? '' : (string) ($config['required_attachment_upload']['ca_file'] ?? '');
|
||||
if ($caFile !== '' && (!is_file($caFile) || !is_readable($caFile))) {
|
||||
// Match the established attachment transport on other hosts: an
|
||||
// optional stale CA path falls back to the system trust store.
|
||||
// CURLOPT_SSL_VERIFYPEER/VERIFYHOST remain enabled below.
|
||||
$caFile = '';
|
||||
}
|
||||
$label = $model === 'qwen' ? '千问' : 'GPT';
|
||||
return ['base' => $base, 'key' => $key, 'ca_file' => $caFile, 'label' => $label];
|
||||
$label = ['qwen' => '千问', 'openai' => 'GPT', 'doubao' => '豆包'][$model];
|
||||
$thinking = (string) ($profile['thinking'] ?? '');
|
||||
return ['base' => $base, 'key' => $key, 'ca_file' => $caFile, 'label' => $label,
|
||||
'protocol' => $openAi ? 'openai' : 'dify', 'model' => trim((string) ($profile['name'] ?? '')),
|
||||
'payload_options' => in_array($thinking, ['enabled', 'disabled', 'auto'], true)
|
||||
? ['thinking' => ['type' => $thinking]] : []];
|
||||
}
|
||||
|
||||
/** Exactly one bounded POST; redirects and ambient proxies must not receive credentials/images. */
|
||||
|
||||
Reference in New Issue
Block a user