DONG-WEI-YANG
Claude Sonnet 5
chore(lint): add ESLint, fix mechanical violations, remove dead code
01fbb71
Raw History Blame Contribute Delete
11.7 kB
/**
* deviceAI.ts — Client-side Device AI Service
*
* A transparent acceleration layer: components call execute() and receive either
* a DeviceAIResult (on-device inference succeeded) or null (caller should fall
* back to the server).
*
* Two providers:
* BuiltInAI — Chrome/Edge/Opera 127+ Prompt API (window.ai / Gemini Nano)
* Wasm — Stub for future onnxruntime-web integration
*/
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type DeviceTaskType = 'soap_classify' | 'summarize' | 'correct' | 'improve_suggest'
export interface DeviceAIResult {
output: string
provider: 'builtin' | 'wasm'
confidence: number // 0–1
latencyMs: number
}
export interface DeviceAICapabilities {
builtinAI: boolean
builtinAIStatus?: 'readily' | 'after-download' | 'no'
wasm: boolean
}
// ---------------------------------------------------------------------------
// Task → provider mapping
// ---------------------------------------------------------------------------
const TASK_PROVIDERS: Record<DeviceTaskType, { builtin: boolean; wasm: boolean }> = {
soap_classify: { builtin: true, wasm: true }, // wllama implementation in #3
summarize: { builtin: true, wasm: true }, // newly enabled in #3
correct: { builtin: true, wasm: true }, // newly enabled — most valuable offline task
improve_suggest: { builtin: true, wasm: true }, // newly enabled in #3
}
// ---------------------------------------------------------------------------
// Capabilities detection (cached)
// ---------------------------------------------------------------------------
let cachedCaps: DeviceAICapabilities | null = null
export async function detectCapabilities(): Promise<DeviceAICapabilities> {
if (cachedCaps !== null) return cachedCaps
// WASM: available in all modern environments
const wasmAvailable = typeof WebAssembly !== 'undefined'
// BuiltIn AI: Chrome Prompt API — access defensively with bracket notation
let builtinAI = false
let builtinAIStatus: DeviceAICapabilities['builtinAIStatus'] = undefined
try {
const w = (typeof window !== 'undefined' ? window : undefined) as any
if (w && w['ai'] && typeof w['ai']['languageModel']?.['capabilities'] === 'function') {
const result = await w['ai']['languageModel']['capabilities']()
const available = result?.available
if (available === 'readily' || available === 'after-download') {
builtinAI = true
builtinAIStatus = available
} else if (available === 'no') {
builtinAIStatus = 'no'
}
}
} catch {
// Non-Chromium environment — silently ignore
}
cachedCaps = {
builtinAI,
builtinAIStatus,
wasm: wasmAvailable,
}
return cachedCaps
}
/** Reset the capabilities cache. Primarily used in tests. */
export function resetCapabilities(): void {
cachedCaps = null
}
// ---------------------------------------------------------------------------
// Routing helper
// ---------------------------------------------------------------------------
export function canHandle(task: DeviceTaskType, caps: DeviceAICapabilities): boolean {
const providers = TASK_PROVIDERS[task]
if (!providers) return false
if (providers.builtin && caps.builtinAI) return true
if (providers.wasm && caps.wasm) return true
return false
}
// ---------------------------------------------------------------------------
// BuiltIn AI provider
// ---------------------------------------------------------------------------
async function runBuiltIn(
task: DeviceTaskType,
input: string,
context?: string,
onLoadingStatus?: (status: string | null) => void,
): Promise<DeviceAIResult | null> {
const t0 = Date.now()
const w = (typeof window !== 'undefined' ? window : undefined) as any
if (!w?.['ai']) return null
try {
let output = ''
if (task === 'soap_classify') {
const systemPrompt = [
'You are a clinical SOAP note classifier.',
'Given the text, classify each sentence into one of: S (Subjective), O (Objective), A (Assessment), P (Plan).',
'Return a JSON array: [{"text":"...","category":"S|O|A|P"}].',
context ? `Context: ${context}` : '',
]
.filter(Boolean)
.join('\n')
const session = await w['ai']['languageModel']['create']({ systemPrompt })
output = await session.prompt(input)
session.destroy?.()
} else if (task === 'summarize') {
try {
onLoadingStatus?.('正在載入摘要模型…')
const summarizer = await w['ai']['summarizer']?.['create']?.()
onLoadingStatus?.(null)
if (summarizer) {
output = await summarizer.summarize(input)
summarizer.destroy?.()
} else {
throw new Error('summarizer not available')
}
} catch {
// Fallback to languageModel
const session = await w['ai']['languageModel']['create']({
systemPrompt: '以繁體中文簡潔摘要以下內容,不超過三句話。',
})
output = await session.prompt(input)
session.destroy?.()
}
} else if (task === 'correct') {
try {
onLoadingStatus?.('正在載入改寫模型…')
const rewriter = await w['ai']['rewriter']?.['create']?.({
tone: 'as-is',
length: 'as-is',
sharedContext: context ?? '',
})
onLoadingStatus?.(null)
if (rewriter) {
output = await rewriter.rewrite(input)
rewriter.destroy?.()
} else {
throw new Error('rewriter not available')
}
} catch {
const session = await w['ai']['languageModel']['create']({
systemPrompt: '修正以下文字的錯字和語法,保持原意,以繁體中文回答。',
})
output = await session.prompt(input)
session.destroy?.()
}
} else if (task === 'improve_suggest') {
const systemPrompt = [
'你是一位長期照顧領域的文件撰寫專家。',
'請針對以下護理紀錄提供 2–3 條具體改善建議,以繁體中文條列說明。',
context ? `背景:${context}` : '',
]
.filter(Boolean)
.join('\n')
const session = await w['ai']['languageModel']['create']({ systemPrompt })
output = await session.prompt(input)
session.destroy?.()
}
return {
output,
provider: 'builtin',
confidence: 0.85,
latencyMs: Date.now() - t0,
}
} catch (err) {
// Falling back to the server here is correct; being silent about why
// is not — this exact silent-catch shape (return null, no log) is what
// let the offline-AI feature stay completely broken for months with no
// signal in the browser console.
console.warn('[deviceAI] runBuiltIn failed, falling back to server:', err)
return null
} finally {
onLoadingStatus?.(null)
}
}
// ---------------------------------------------------------------------------
// WASM provider — wllama LLM running entirely in the browser.
// ---------------------------------------------------------------------------
async function runWasm(
task: DeviceTaskType,
input: string,
context?: string,
onLoadingStatus?: (status: string | null) => void,
): Promise<DeviceAIResult | null> {
// Gated by localStorage flag — user must opt-in via Privacy settings or modal
const enabled = typeof localStorage !== 'undefined'
&& localStorage.getItem('deviceAI.enabled') === 'true'
if (!enabled) return null
try {
onLoadingStatus?.('正在啟動離線 AI…')
const { getWllamaSession } = await import('./wllamaProvider')
const session = await getWllamaSession()
onLoadingStatus?.(null)
const t0 = Date.now()
const messages = buildMessagesForTask(task, input, context)
const output = await session.generate(messages, { maxTokens: 512, temperature: 0.1 })
return {
output: output.trim(),
provider: 'wasm',
confidence: 0.7,
latencyMs: Date.now() - t0,
}
} catch (err) {
console.warn('[deviceAI] runWasm failed, falling back to server:', err)
onLoadingStatus?.(null)
return null // caller falls back to server
}
}
function buildMessagesForTask(
task: DeviceTaskType,
input: string,
context?: string,
): Array<{ role: 'system' | 'user' | 'assistant'; content: string }> {
switch (task) {
case 'correct':
return [
{ role: 'system', content: '你是繁體中文語音轉文字校正助手。只輸出修正後的文字,不要加任何解釋。' },
{ role: 'user', content: input },
]
case 'summarize':
return [
{ role: 'system', content: '以繁體中文簡潔摘要以下內容,不超過三句話。只輸出摘要。' },
{ role: 'user', content: context ? `${context}\n\n${input}` : input },
]
case 'soap_classify':
return [
{ role: 'system', content: '你是臨床 SOAP 紀錄分類器。將每個句子分類為 S/O/A/P。輸出 JSON 陣列:[{"text":"...","category":"S|O|A|P"}]。' },
{ role: 'user', content: input },
]
case 'improve_suggest':
return [
{ role: 'system', content: '你是長照記錄品質審閱員。閱讀以下紀錄,給出 2-3 點具體改善建議。每點一行。' },
{ role: 'user', content: input },
]
}
}
// ---------------------------------------------------------------------------
// Main execute function
// ---------------------------------------------------------------------------
export async function execute(
task: DeviceTaskType,
input: string,
context?: string,
onLoadingStatus?: (status: string | null) => void,
): Promise<DeviceAIResult | null> {
const caps = await detectCapabilities()
if (!canHandle(task, caps)) return null
// Prefer BuiltInAI when available — higher quality
if (TASK_PROVIDERS[task].builtin && caps.builtinAI) {
const result = await runBuiltIn(task, input, context, onLoadingStatus)
if (result !== null) return result
}
// Fallback to WASM stub for supported tasks
if (TASK_PROVIDERS[task].wasm && caps.wasm) {
return runWasm(task, input, context)
}
return null
}
// ---------------------------------------------------------------------------
// Modal-guard helper
// ---------------------------------------------------------------------------
/**
* Whether to show the "enable offline AI" modal on a cloud-AI failure:
* true only if the user has NOT already enabled offline AI AND has NOT
* declined it this browser session.
*/
export function shouldOfferOfflineAI(): boolean {
if (typeof localStorage === 'undefined' || typeof sessionStorage === 'undefined') return false
return localStorage.getItem('deviceAI.enabled') !== 'true'
&& sessionStorage.getItem('deviceAI.declinedThisSession') !== 'true'
}
// ---------------------------------------------------------------------------
// Status label for UI display
// ---------------------------------------------------------------------------
export async function getStatusLabel(): Promise<{ level: 'full' | 'basic' | 'none'; label: string }> {
const caps = await detectCapabilities()
if (caps.builtinAI) {
return { level: 'full', label: '裝置 AI:完整模式(Gemini Nano)' }
}
if (caps.wasm) {
return { level: 'basic', label: '裝置 AI:基礎模式(WASM)' }
}
return { level: 'none', label: '裝置 AI:不可用' }
}