llm_patch.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. #!/usr/bin/env python3
  2. import sys
  3. p = "/data/ai/audio/server/src/services/llm/index.ts"
  4. src = open(p).read()
  5. old = """async function invokeWithRetry(
  6. fn: (modelId: string) => Promise<any>,
  7. modelId: string,
  8. callType: string = 'llm_chat',
  9. ): Promise<any> {
  10. const tried = new Map<string, any>();
  11. let cur = modelId;
  12. let lastErr: any = null;
  13. for (let round = 0; round < HA_RETRY_CONFIG.maxFallbackRounds; round++) {
  14. // 关键: 选下一个未 tried 的 node (而不是用 resolveProviderKey 取第一个匹配)
  15. const node = resolveNodeForModel(cur, tried);
  16. if (!node) {
  17. console.warn(`[LLM-HA] 已尝试所有 node,停止 fallback`);
  18. break;
  19. }
  20. const fp = node.provider.vendor + ':' + ((node.provider as any)._apiKey || '').slice(-12);
  21. tried.set(fp, { model: cur });
  22. let providerError: any = null;
  23. for (let attempt = 0; attempt < HA_RETRY_CONFIG.maxRetriesPerProvider; attempt++) {
  24. try {
  25. const result = await _runWithTriedNodes(new Set(tried.keys()), () => fn(cur));
  26. return result;
  27. } catch (error: any) {
  28. const em = error?.message || String(error);
  29. lastErr = error;
  30. providerError = error;
  31. if (isBusinessError(em) && !isNetworkError(em)) {
  32. console.error(`[LLM-HA] ${fp}/${cur} 业务错误,立即抛出: ${em.substring(0, 100)}`);
  33. throw error;
  34. }
  35. if (isNetworkError(em)) {
  36. console.warn(`[LLM-HA] ${fp}/${cur} 网络错误,立即切换: ${em.substring(0, 100)}`);
  37. break;
  38. }
  39. if (attempt < HA_RETRY_CONFIG.maxRetriesPerProvider - 1) {
  40. const delay = backoffWithJitter(attempt);
  41. console.log(`[LLM-HA] ${fp}/${cur} 第${attempt + 1}次失败: ${em.substring(0, 100)}, ${delay}ms后重试`);
  42. await new Promise(r => setTimeout(r, delay));
  43. }
  44. }
  45. }"""
  46. new = """// 单次 LLM 调用超时:防止某个 provider 永久 hang 而 invokeWithRetry
  47. // 永远得不到 error 来触发切换。
  48. // 设为 3 分钟,比 ChatOpenAI 内部 timeout 略大,确保正常请求有足够时间响应。
  49. const LLM_INVOKE_TIMEOUT_MS = 180_000;
  50. function invokeWithTimeout<T>(fn: () => Promise<T>, ms: number): Promise<T> {
  51. let timer: ReturnType<typeof setTimeout> | null = null;
  52. const timeoutPromise = new Promise<never>((_, reject) => {
  53. timer = setTimeout(
  54. () => reject(new Error(`Request timeout after ${ms}ms (forced by invokeWithTimeout)`)),
  55. ms,
  56. );
  57. });
  58. return Promise.race([fn(), timeoutPromise]).finally(() => {
  59. if (timer) clearTimeout(timer);
  60. }) as Promise<T>;
  61. }
  62. async function invokeWithRetry(
  63. fn: (modelId: string) => Promise<any>,
  64. modelId: string,
  65. callType: string = 'llm_chat',
  66. ): Promise<any> {
  67. const tried = new Map<string, any>();
  68. let cur = modelId;
  69. let lastErr: any = null;
  70. for (let round = 0; round < HA_RETRY_CONFIG.maxFallbackRounds; round++) {
  71. // 关键: 选下一个未 tried 的 node (而不是用 resolveProviderKey 取第一个匹配)
  72. const node = resolveNodeForModel(cur, tried);
  73. if (!node) {
  74. console.warn(`[LLM-HA] 已尝试所有 node,停止 fallback`);
  75. break;
  76. }
  77. const fp = node.provider.vendor + ':' + ((node.provider as any)._apiKey || '').slice(-12);
  78. tried.set(fp, { model: cur });
  79. let providerError: any = null;
  80. for (let attempt = 0; attempt < HA_RETRY_CONFIG.maxRetriesPerProvider; attempt++) {
  81. try {
  82. const result = await invokeWithTimeout(
  83. () => _runWithTriedNodes(new Set(tried.keys()), () => fn(cur)),
  84. LLM_INVOKE_TIMEOUT_MS,
  85. );
  86. return result;
  87. } catch (error: any) {
  88. const em = error?.message || String(error);
  89. lastErr = error;
  90. providerError = error;
  91. if (isBusinessError(em) && !isNetworkError(em)) {
  92. console.error(`[LLM-HA] ${fp}/${cur} 业务错误,立即抛出: ${em.substring(0, 100)}`);
  93. throw error;
  94. }
  95. if (isNetworkError(em)) {
  96. console.warn(`[LLM-HA] ${fp}/${cur} 网络错误,立即切换: ${em.substring(0, 100)}`);
  97. break;
  98. }
  99. if (attempt < HA_RETRY_CONFIG.maxRetriesPerProvider - 1) {
  100. const delay = backoffWithJitter(attempt);
  101. console.log(`[LLM-HA] ${fp}/${cur} 第${attempt + 1}次失败: ${em.substring(0, 100)}, ${delay}ms后重试`);
  102. await new Promise(r => setTimeout(r, delay));
  103. }
  104. }
  105. }"""
  106. if old not in src:
  107. print("ERROR: old block not found")
  108. sys.exit(1)
  109. src = src.replace(old, new, 1)
  110. open(p, 'w').write(src)
  111. print("patched llm/index.ts OK")