聊天报错

This commit is contained in:
2025-09-21 19:41:49 +08:00
parent 35aa92d78a
commit 274f02b867
7 changed files with 243 additions and 221 deletions
@@ -27,6 +27,8 @@ export class ApiConfig {
private static _instance: ApiConfig; private static _instance: ApiConfig;
private config: AIConfig; private config: AIConfig;
private baseUrl: "https://generativelanguage.googleapis.com";
private constructor() { private constructor() {
this.initConfig(); this.initConfig();
} }
@@ -104,6 +106,9 @@ export class ApiConfig {
public getTimeout() { public getTimeout() {
return this.config.timeout; return this.config.timeout;
} }
public getBaseUrl() {
return this.baseUrl;
}
/** /**
* 验证配置是否有效 * 验证配置是否有效
+21 -4
View File
@@ -1,6 +1,11 @@
// 首先加载 polyfills 以确保兼容性 // 首先加载 polyfills 以确保兼容性
import "../utils/polyfills"; import "../utils/polyfills";
import { GoogleGenAI, HarmBlockThreshold, HarmCategory } from "@google/genai"; import {
Chat,
GoogleGenAI,
HarmBlockThreshold,
HarmCategory,
} from "@google/genai";
import { RoleConfigLoader } from "./RoleConfigLoader"; import { RoleConfigLoader } from "./RoleConfigLoader";
import { ChatHistoryManager } from "../manager/ChatHistoryManager"; import { ChatHistoryManager } from "../manager/ChatHistoryManager";
import { ApiConfig } from "./ApiConfigLoader"; import { ApiConfig } from "./ApiConfigLoader";
@@ -57,8 +62,16 @@ export class ChatAIService {
try { try {
this.ai = new GoogleGenAI({ this.ai = new GoogleGenAI({
apiKey: config.apiKey, apiKey: config.apiKey,
httpOptions: { timeout: ApiConfig.Instance.getTimeout() },
httpOptions: {
timeout: ApiConfig.Instance.getTimeout(),
baseUrl: ApiConfig.Instance.getBaseUrl(),
},
}); });
console.log("-------AI 启动成功-------");
console.log(this.ai);
this.ai.operations;
} catch (error) { } catch (error) {
TipsPanel.show(LanguageUtils.getText("chat_error_code_2001")); TipsPanel.show(LanguageUtils.getText("chat_error_code_2001"));
ErrorHandler.Instance.handleError( ErrorHandler.Instance.handleError(
@@ -88,7 +101,7 @@ export class ChatAIService {
* 创建或获取指定角色的聊天实例 * 创建或获取指定角色的聊天实例
* @param roleId 角色ID * @param roleId 角色ID
*/ */
async createOrGetChat(roleId: number): Promise<any> { async createOrGetChat(roleId: number): Promise<Chat> {
if (!this.chatInstances.has(roleId)) { if (!this.chatInstances.has(roleId)) {
const systemInstruction = RoleConfigLoader.getRoleInstruction(roleId); const systemInstruction = RoleConfigLoader.getRoleInstruction(roleId);
const config = ApiConfig.Instance.getAIConfig(); const config = ApiConfig.Instance.getAIConfig();
@@ -97,7 +110,7 @@ export class ChatAIService {
let savedHistory = await ChatHistoryManager.Instance.loadChatHistory( let savedHistory = await ChatHistoryManager.Instance.loadChatHistory(
roleId roleId
); );
let chat; let chat: Chat;
if (savedHistory && savedHistory.length > 0) { if (savedHistory && savedHistory.length > 0) {
chat = this.ai.chats.create({ chat = this.ai.chats.create({
model: config.model, model: config.model,
@@ -130,6 +143,7 @@ export class ChatAIService {
}, },
history: savedHistory, history: savedHistory,
}); });
console.log(chat);
console.log( console.log(
`Loaded ${savedHistory.length} history messages for role ${roleId}` `Loaded ${savedHistory.length} history messages for role ${roleId}`
); );
@@ -164,6 +178,8 @@ export class ChatAIService {
], ],
}, },
}); });
console.log(chat);
console.log(`Created new chat instance for role ${roleId}`); console.log(`Created new chat instance for role ${roleId}`);
} }
@@ -226,6 +242,7 @@ export class ChatAIService {
try { try {
const chat = await this.createOrGetChat(roleId); const chat = await this.createOrGetChat(roleId);
const response = await chat.sendMessage({ const response = await chat.sendMessage({
message: message.trim(), message: message.trim(),
}); });
@@ -124,6 +124,7 @@ export class GlobalData extends BaseData {
/** 超时时间(微秒) */ /** 超时时间(微秒) */
public getTimeout(): number { public getTimeout(): number {
//return 600000;
return this._timeout; return this._timeout;
} }
+24 -25
View File
@@ -7,6 +7,9 @@
* @version 1.0.0 * @version 1.0.0
*/ */
import LanguageUtils from "../../Main/Common/LanguageUtils";
import { TipsPanel } from "../ui/panels/TipsPanel";
export enum ErrorType { export enum ErrorType {
/** API调用错误 */ /** API调用错误 */
API_ERROR = "API_ERROR", API_ERROR = "API_ERROR",
@@ -19,7 +22,7 @@ export enum ErrorType {
/** 存储错误 */ /** 存储错误 */
STORAGE_ERROR = "STORAGE_ERROR", STORAGE_ERROR = "STORAGE_ERROR",
/** 未知错误 */ /** 未知错误 */
UNKNOWN_ERROR = "UNKNOWN_ERROR" UNKNOWN_ERROR = "UNKNOWN_ERROR",
} }
export interface ErrorInfo { export interface ErrorInfo {
@@ -67,10 +70,10 @@ export class ErrorHandler {
): void { ): void {
const errorInfo: ErrorInfo = { const errorInfo: ErrorInfo = {
type, type,
message: typeof error === 'string' ? error : error.message, message: typeof error === "string" ? error : error.message,
details, details,
timestamp: Date.now(), timestamp: Date.now(),
stack: error instanceof Error ? error.stack : undefined stack: error instanceof Error ? error.stack : undefined,
}; };
// 记录到日志 // 记录到日志
@@ -97,9 +100,14 @@ export class ErrorHandler {
const details = { const details = {
apiName, apiName,
requestData, requestData,
responseError: error responseError: error,
}; };
if (error.status == "FAILED_PRECONDITION") {
//当前用户区域不支持聊天功能
TipsPanel.show(LanguageUtils.getText("chat_error_code_2003"));
} else if (error.message.includes("Fetch is aborted")) {
TipsPanel.show(LanguageUtils.getText("chat_error_code_2004"));
} else {
this.handleError( this.handleError(
new Error(errorMessage), new Error(errorMessage),
ErrorType.API_ERROR, ErrorType.API_ERROR,
@@ -107,6 +115,7 @@ export class ErrorHandler {
true true
); );
} }
}
/** /**
* 处理验证错误 * 处理验证错误
@@ -115,7 +124,11 @@ export class ErrorHandler {
* @param {string} message - 错误消息 * @param {string} message - 错误消息
* @param {any} value - 无效值 * @param {any} value - 无效值
*/ */
public handleValidationError(field: string, message: string, value?: any): void { public handleValidationError(
field: string,
message: string,
value?: any
): void {
const errorMessage = `数据验证失败: ${field} - ${message}`; const errorMessage = `数据验证失败: ${field} - ${message}`;
const details = { field, value, validationMessage: message }; const details = { field, value, validationMessage: message };
@@ -187,22 +200,7 @@ export class ErrorHandler {
private showUserFriendlyError(errorInfo: ErrorInfo): void { private showUserFriendlyError(errorInfo: ErrorInfo): void {
let userMessage: string; let userMessage: string;
switch (errorInfo.type) { TipsPanel.show(LanguageUtils.getText("chat_error_code_2005"));
case ErrorType.API_ERROR:
userMessage = "AI服务暂时不可用,请稍后再试";
break;
case ErrorType.NETWORK_ERROR:
userMessage = "网络连接失败,请检查网络设置";
break;
case ErrorType.CONFIG_ERROR:
userMessage = "系统配置错误,请联系管理员";
break;
case ErrorType.STORAGE_ERROR:
userMessage = "数据保存失败,请重试";
break;
default:
userMessage = "发生了未知错误,请重试或联系客服";
}
// TODO: 这里应该显示UI提示,比如Toast或对话框 // TODO: 这里应该显示UI提示,比如Toast或对话框
console.log("用户提示:", userMessage); console.log("用户提示:", userMessage);
@@ -227,7 +225,7 @@ export class ErrorHandler {
* 获取特定类型的错误 * 获取特定类型的错误
*/ */
public getErrorsByType(type: ErrorType): ErrorInfo[] { public getErrorsByType(type: ErrorType): ErrorInfo[] {
return this.errorLog.filter(error => error.type === type); return this.errorLog.filter((error) => error.type === type);
} }
/** /**
@@ -235,9 +233,10 @@ export class ErrorHandler {
*/ */
public hasCriticalErrors(): boolean { public hasCriticalErrors(): boolean {
const criticalTypes = [ErrorType.API_ERROR, ErrorType.CONFIG_ERROR]; const criticalTypes = [ErrorType.API_ERROR, ErrorType.CONFIG_ERROR];
return this.errorLog.some(error => return this.errorLog.some(
(error) =>
criticalTypes.includes(error.type) && criticalTypes.includes(error.type) &&
(Date.now() - error.timestamp) < 60000 // 1分钟内的错误 Date.now() - error.timestamp < 60000 // 1分钟内的错误
); );
} }
} }
Binary file not shown.