diff --git a/Assets/_Project/Resources/LLMConfig.asset b/Assets/_Project/Resources/LLMConfig.asset index 645b1d3d..3a49cca0 100644 --- a/Assets/_Project/Resources/LLMConfig.asset +++ b/Assets/_Project/Resources/LLMConfig.asset @@ -15,6 +15,8 @@ MonoBehaviour: _endpoint: https://api.deepseek.com/v1/chat/completions _apiKey: sk-2c23ffc2bce6490f8a85678da3dd950d _model: deepseek-v4-pro + _fallbackModels: + - deepseek-v4-flash _angelSystemTemplate: "\u4F60\u662F\u4E00\u4F4D\u5929\u4F7F (Angel) \u2014\u2014 \u6E29\u67D4\u3001\u5305\u5BB9\u3001\u613F\u610F\u6307\u51FA\u5E0C\u671B\u3002\n\u5F53\u524D\u7684\u4F60\uFF1A{personality}\n\u7528\u4E2D\u6587\u7ED9\u51FA\u5854\u7F57\u89E3\u8BFB\uFF0C\u4E0D\u8D85\u8FC7 100 \u4E2A\u6C49\u5B57\u3002" diff --git a/Assets/_Project/Scenes/WorldMap/WorldMap_Main.unity b/Assets/_Project/Scenes/WorldMap/WorldMap_Main.unity index b5855959..765cf3d9 100644 --- a/Assets/_Project/Scenes/WorldMap/WorldMap_Main.unity +++ b/Assets/_Project/Scenes/WorldMap/WorldMap_Main.unity @@ -14976,7 +14976,7 @@ Transform: m_GameObject: {fileID: 138913199} serializedVersion: 2 m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: 27.760061, y: -2.942834, z: -0.25} + m_LocalPosition: {x: -44.75, y: -2.942834, z: -0.25} m_LocalScale: {x: 0.22, y: 0.22, z: 0.22} m_ConstrainProportionsScale: 0 m_Children: [] @@ -74945,81 +74945,6 @@ RectTransform: m_AnchoredPosition: {x: 0, y: 0} m_SizeDelta: {x: 20, y: 5} m_Pivot: {x: 0.5, y: 0.5} ---- !u!1 &625096670 -GameObject: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - serializedVersion: 6 - m_Component: - - component: {fileID: 625096673} - - component: {fileID: 625096672} - - component: {fileID: 625096671} - m_Layer: 5 - m_Name: Page_Intro - m_TagString: Untagged - m_Icon: {fileID: 0} - m_NavMeshLayer: 0 - m_StaticEditorFlags: 0 - m_IsActive: 0 ---- !u!114 &625096671 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 625096670} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} - m_Name: - m_EditorClassIdentifier: - m_Material: {fileID: 0} - m_Color: {r: 1, g: 1, b: 1, a: 1} - m_RaycastTarget: 0 - m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0} - m_Maskable: 1 - m_OnCullStateChanged: - m_PersistentCalls: - m_Calls: [] - m_Sprite: {fileID: 21300000, guid: 41bf3937f73ed3c4a8bda649666e7e6f, type: 3} - m_Type: 0 - m_PreserveAspect: 1 - m_FillCenter: 1 - m_FillMethod: 4 - m_FillAmount: 1 - m_FillClockwise: 1 - m_FillOrigin: 0 - m_UseSpriteMesh: 0 - m_PixelsPerUnitMultiplier: 1 ---- !u!222 &625096672 -CanvasRenderer: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 625096670} - m_CullTransparentMesh: 1 ---- !u!224 &625096673 -RectTransform: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 625096670} - m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: 0, y: 0, z: 0} - m_LocalScale: {x: 1, y: 1, z: 1} - m_ConstrainProportionsScale: 0 - m_Children: [] - m_Father: {fileID: 916898188} - m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_AnchorMin: {x: 0.5, y: 0.5} - m_AnchorMax: {x: 0.5, y: 0.5} - m_AnchoredPosition: {x: 0, y: 0} - m_SizeDelta: {x: 1720, y: 970} - m_Pivot: {x: 0.5, y: 0.5} --- !u!1 &625495091 GameObject: m_ObjectHideFlags: 0 @@ -111539,11 +111464,9 @@ MonoBehaviour: m_Name: m_EditorClassIdentifier: _previewImage: {fileID: 0} - _previewTarget: {fileID: 625096670} - _previewKey: outdoor-intro + _previewTarget: {fileID: 886367749} + _previewKey: outdoor-1 _variants: - - Key: outdoor-1 - Target: {fileID: 886367749} - Key: outdoor-2 Target: {fileID: 896074888} - Key: outdoor-3 @@ -111572,7 +111495,6 @@ RectTransform: - {fileID: 1436077564} - {fileID: 896074891} - {fileID: 886367752} - - {fileID: 625096673} - {fileID: 1823067439} - {fileID: 1482816828} - {fileID: 1259785875} @@ -115614,7 +115536,7 @@ Transform: m_GameObject: {fileID: 955552920} serializedVersion: 2 m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: 25.06006, y: -2.942834, z: -0.25} + m_LocalPosition: {x: -47.45, y: -2.942834, z: -0.25} m_LocalScale: {x: 0.22, y: 0.22, z: 0.22} m_ConstrainProportionsScale: 0 m_Children: [] @@ -203121,7 +203043,7 @@ Transform: m_GameObject: {fileID: 1732304706} serializedVersion: 2 m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} - m_LocalPosition: {x: 26.41006, y: -2.942834, z: -0.25} + m_LocalPosition: {x: -46.1, y: -2.942834, z: -0.25} m_LocalScale: {x: 0.22, y: 0.22, z: 0.22} m_ConstrainProportionsScale: 0 m_Children: [] diff --git a/Assets/_Project/Scripts/Editor/SceneBootstrap/WorldMapOutdoorTutorialAuthoring.cs b/Assets/_Project/Scripts/Editor/SceneBootstrap/WorldMapOutdoorTutorialAuthoring.cs index c384cf7b..878ee3b9 100644 --- a/Assets/_Project/Scripts/Editor/SceneBootstrap/WorldMapOutdoorTutorialAuthoring.cs +++ b/Assets/_Project/Scripts/Editor/SceneBootstrap/WorldMapOutdoorTutorialAuthoring.cs @@ -45,7 +45,7 @@ public static void Patch() ConfigureFullscreen(panel); SceneAuthoredImageVariantView pageView = GetOrAdd(panel); - GameObject introPage = EnsurePage(panel.transform, "Page_Intro", OutdoorArtRoot + "/intro.png", uiLayer); + RemoveChild(panel.transform, "Page_Intro"); GameObject[] pages = new GameObject[6]; for (int i = 0; i < pages.Length; i++) { @@ -56,7 +56,7 @@ public static void Patch() uiLayer); } - ConfigurePageView(pageView, introPage, pages); + ConfigurePageView(pageView, pages); Button previousButton = EnsureImageButton( panel.transform, @@ -97,12 +97,11 @@ public static void Patch() EditorUtility.SetDirty(pageView); EditorSceneManager.MarkSceneDirty(scene); EditorSceneManager.SaveScene(scene); - Debug.Log("[WorldMapOutdoorTutorialAuthoring] Outdoor tutorial authored with seven pages and placeholder entry."); + Debug.Log("[WorldMapOutdoorTutorialAuthoring] Outdoor tutorial authored with six pages and placeholder entry."); } private static void ConfigurePageView( SceneAuthoredImageVariantView pageView, - GameObject introPage, GameObject[] pages) { SerializedObject serialized = new SerializedObject(pageView); @@ -111,22 +110,22 @@ private static void ConfigurePageView( SerializedProperty? previewTarget = serialized.FindProperty("_previewTarget"); if (previewTarget != null) { - previewTarget.objectReferenceValue = introPage; + previewTarget.objectReferenceValue = pages.Length > 0 ? pages[0] : null; } SerializedProperty? previewKey = serialized.FindProperty("_previewKey"); if (previewKey != null) { - previewKey.stringValue = "outdoor-intro"; + previewKey.stringValue = pages.Length > 0 ? "outdoor-1" : string.Empty; } SerializedProperty? variants = serialized.FindProperty("_variants"); if (variants != null) { - variants.arraySize = pages.Length; - for (int i = 0; i < pages.Length; i++) + variants.arraySize = Mathf.Max(0, pages.Length - 1); + for (int i = 1; i < pages.Length; i++) { - SerializedProperty element = variants.GetArrayElementAtIndex(i); + SerializedProperty element = variants.GetArrayElementAtIndex(i - 1); element.FindPropertyRelative("Key").stringValue = $"outdoor-{i + 1}"; element.FindPropertyRelative("Target").objectReferenceValue = pages[i]; } @@ -232,6 +231,15 @@ private static GameObject EnsureChild(Transform parent, string name, int layer) return created; } + private static void RemoveChild(Transform parent, string name) + { + Transform? existing = parent.Find(name); + if (existing != null) + { + Undo.DestroyObjectImmediate(existing.gameObject); + } + } + private static void ConfigureFullscreen(GameObject target) { SetRect( diff --git a/Assets/_Project/Scripts/Modules/AI/EmotionGardenAiProvider.cs b/Assets/_Project/Scripts/Modules/AI/EmotionGardenAiProvider.cs index 655b24d0..d65d6ace 100644 --- a/Assets/_Project/Scripts/Modules/AI/EmotionGardenAiProvider.cs +++ b/Assets/_Project/Scripts/Modules/AI/EmotionGardenAiProvider.cs @@ -44,7 +44,12 @@ public EmotionGardenAiProvider(LLMConfigSO config) return null; } - Debug.Log($"[AI] request-entry role={role} feature=Emotion inputEmpty={inputEmpty} service={GetType().Name} registered=true sent=false"); + string[] modelCandidates = _config.ModelCandidates; + if (modelCandidates.Length == 0) + { + LogFallback(role, "NoModelCandidates"); + return null; + } string systemPrompt = BuildSystemPrompt(normalizedOwner); string userPrompt = BuildUserPrompt( @@ -55,46 +60,57 @@ public EmotionGardenAiProvider(LLMConfigSO config) flowerName, flowerDescription); - try + Debug.Log($"[AI] request-entry role={role} feature=Emotion inputEmpty={inputEmpty} service={GetType().Name} registered=true models={string.Join(",", modelCandidates)}"); + + string lastFailure = string.Empty; + for (int modelIndex = 0; modelIndex < modelCandidates.Length; modelIndex++) { - using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - float timeoutSeconds = _config.TimeoutSeconds > 0f ? _config.TimeoutSeconds : 10f; - timeoutCts.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds)); + string model = modelCandidates[modelIndex]; + try + { + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + float timeoutSeconds = _config.TimeoutSeconds > 0f ? _config.TimeoutSeconds : 10f; + timeoutCts.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds)); - string responseContent = await SendRequestAsync(role, systemPrompt, userPrompt, timeoutCts.Token); - Debug.Log($"[AI] raw-response role={role} feature=Emotion content={SanitizeForLog(responseContent)}"); + string responseContent = await SendRequestAsync(role, model, systemPrompt, userPrompt, timeoutCts.Token); + Debug.Log($"[AI] raw-response role={role} feature=Emotion model={model} content={SanitizeForLog(responseContent)}"); - EmotionGardenAiResult result = ParseResponse(responseContent); - if (!EmotionGardenAiValidation.IsCompleteResult(result, out string validationReason)) + EmotionGardenAiResult result = ParseResponse(responseContent); + if (!EmotionGardenAiValidation.IsCompleteResult(result, out string validationReason)) + { + lastFailure = $"InvalidResult:{validationReason}"; + LogModelFailure(role, model, modelIndex, modelCandidates.Length, lastFailure); + continue; + } + + result.EmotionType = EmotionFlowerCatalog.NormalizeEmotionType(result.EmotionType); + result.EmotionKeywords = EmotionGardenAiValidation.NormalizeKeywords(result.EmotionKeywords); + result.FlowerDescription = EmotionGardenAiValidation.NormalizeText(result.FlowerDescription, 120); + result.FlowerLanguage = EmotionGardenAiValidation.NormalizeText(result.FlowerLanguage, 160); + result.Summary = EmotionGardenAiValidation.NormalizeText(result.Summary, 60); + result.AngelNote = EmotionGardenAiValidation.NormalizeText(result.AngelNote, 80); + result.DevilNote = EmotionGardenAiValidation.NormalizeText(result.DevilNote, 80); + result.ResultSource = EmotionGardenResultSources.Ai; + result.IsFallback = false; + + Debug.Log($"{EmotionGardenResultSources.Ai} role={role} feature=Emotion model={model} result=Accepted emotion={result.EmotionType}"); + return result; + } + catch (OperationCanceledException) { - LogFallback(role, $"InvalidResult:{validationReason}"); - return null; + if (cancellationToken.IsCancellationRequested) throw; + lastFailure = "Timeout"; + LogModelFailure(role, model, modelIndex, modelCandidates.Length, lastFailure); + } + catch (Exception ex) + { + lastFailure = $"{ex.GetType().Name}:{SanitizeForLog(ex.Message, 240)}"; + LogModelFailure(role, model, modelIndex, modelCandidates.Length, lastFailure); } - - result.EmotionType = EmotionFlowerCatalog.NormalizeEmotionType(result.EmotionType); - result.EmotionKeywords = EmotionGardenAiValidation.NormalizeKeywords(result.EmotionKeywords); - result.FlowerDescription = EmotionGardenAiValidation.NormalizeText(result.FlowerDescription, 120); - result.FlowerLanguage = EmotionGardenAiValidation.NormalizeText(result.FlowerLanguage, 160); - result.Summary = EmotionGardenAiValidation.NormalizeText(result.Summary, 60); - result.AngelNote = EmotionGardenAiValidation.NormalizeText(result.AngelNote, 80); - result.DevilNote = EmotionGardenAiValidation.NormalizeText(result.DevilNote, 80); - result.ResultSource = EmotionGardenResultSources.Ai; - result.IsFallback = false; - - Debug.Log($"{EmotionGardenResultSources.Ai} role={role} feature=Emotion result=Accepted emotion={result.EmotionType}"); - return result; - } - catch (OperationCanceledException) - { - if (cancellationToken.IsCancellationRequested) throw; - LogFallback(role, "Timeout"); - return null; - } - catch (Exception ex) - { - LogFallback(role, $"{ex.GetType().Name}:{SanitizeForLog(ex.Message, 240)}"); - return null; } + + LogFallback(role, $"AllModelsFailed:{lastFailure}"); + return null; } private static string BuildSystemPrompt(string owner) @@ -111,7 +127,9 @@ private static string BuildSystemPrompt(string owner) "必须优先根据玩家输入判断,不能无理由返回平静;例如生气/愤怒优先选愤怒,开心/快乐优先选喜悦,悲伤/难过优先选悲伤,明确平静才选平静。" + "EmotionKeywords 返回 2 到 5 个简短中文关键词。" + "Summary 必须是 30 到 60 个中文字符;AngelNote 和 DevilNote 必须分别是 40 到 80 个中文字符。" + - "FlowerDescription 和 FlowerLanguage 使用具体、自然的中文。"; + "FlowerDescription 必须紧扣玩家输入,至少使用其中一个具体事件、细节、情绪、人物关系或愿望,并把它映射到花朵的形态、气质或象征上。" + + "禁止只写花瓣、露珠、阳光等与输入无关的通用外观描写,禁止套用脱离玩家输入也成立的固定句式,也不要逐字复述整句输入。" + + "若玩家输入为空,只能使用不编造经历的泛化表达。FlowerLanguage 也要使用具体、自然的中文,并可适度承接玩家输入。"; } private static string BuildUserPrompt( @@ -135,13 +153,14 @@ private static string BuildUserPrompt( private async Task SendRequestAsync( string role, + string model, string systemPrompt, string userPrompt, CancellationToken cancellationToken) { var body = new LlmRequest { - model = _config.Model, + model = model, messages = new[] { new LlmMessage { role = "system", content = systemPrompt }, @@ -161,7 +180,7 @@ private async Task SendRequestAsync( request.SetRequestHeader("Authorization", $"Bearer {_config.ApiKey}"); var operation = request.SendWebRequest(); - Debug.Log($"[AI] request-sent role={role} feature=Emotion method=POST endpoint={_config.Endpoint} model={_config.Model}"); + Debug.Log($"[AI] request-sent role={role} feature=Emotion method=POST endpoint={_config.Endpoint} model={model}"); while (!operation.isDone) { if (cancellationToken.IsCancellationRequested) @@ -292,6 +311,12 @@ private void LogFallback(string role, string reason) Debug.LogWarning($"{EmotionGardenResultSources.Fallback} role={role} feature=Emotion reason={SanitizeForLog(reason, 240)}"); } + private void LogModelFailure(string role, string model, int modelIndex, int modelCount, string reason) + { + bool hasNextModel = modelIndex + 1 < modelCount; + Debug.LogWarning($"[AI] model-failed role={role} feature=Emotion model={model} attempt={modelIndex + 1}/{modelCount} hasNext={hasNextModel} reason={SanitizeForLog(reason, 240)}"); + } + private static string ResolveLogRole(string owner) { return EmotionFlowerCatalog.NormalizeOwner(owner) == EmotionFlowerCatalog.OwnerDemon diff --git a/Assets/_Project/Scripts/Modules/HubUI/Panels/WeeklyGardenPanelStub.cs b/Assets/_Project/Scripts/Modules/HubUI/Panels/WeeklyGardenPanelStub.cs index 5eae9818..a8a75e54 100644 --- a/Assets/_Project/Scripts/Modules/HubUI/Panels/WeeklyGardenPanelStub.cs +++ b/Assets/_Project/Scripts/Modules/HubUI/Panels/WeeklyGardenPanelStub.cs @@ -36,6 +36,7 @@ public sealed class WeeklyGardenPanelStub : StubPanelBase [SerializeField] private SceneAuthoredImageVariantView? _detailGrowthView; [SerializeField] private TMP_Text? _detailDateText; [SerializeField] private TMP_Text? _detailEmotionText; + // 场景字段名沿用既有序列化引用;该文本现在展示 AI 返回的花朵简介。 [SerializeField] private TMP_Text? _detailFlowerLanguageText; // 这些引用保留给 Scene/Inspector 和 authoring 使用;运行时不写入 Image.sprite。 @@ -274,20 +275,20 @@ private void RefreshDetailBar(EmotionFlowerData?[] flowers) string keywordText = data.EmotionKeywords != null && data.EmotionKeywords.Length > 0 ? string.Join("、", data.EmotionKeywords) : emotionName; - string languageText = string.IsNullOrWhiteSpace(data.FlowerLanguage) - ? $"{flowerName}的花语暂未生成" - : data.FlowerLanguage.Trim(); + string descriptionText = string.IsNullOrWhiteSpace(data.FlowerDescription) + ? $"{flowerName}的简介暂未生成" + : data.FlowerDescription.Trim(); SetDetailText( FormatFlowerDate(data.DateIso), $"{emotionName}\n关键词:{keywordText}", - $"{flowerName}\n{languageText}\n{stateText}"); + $"{flowerName}\n简介:{descriptionText}\n{stateText}"); } - private void SetDetailText(string date, string emotion, string flowerLanguage) + private void SetDetailText(string date, string emotion, string flowerDescription) { if (_detailDateText != null) _detailDateText.text = date; if (_detailEmotionText != null) _detailEmotionText.text = emotion; - if (_detailFlowerLanguageText != null) _detailFlowerLanguageText.text = flowerLanguage; + if (_detailFlowerLanguageText != null) _detailFlowerLanguageText.text = flowerDescription; } private int ResolveDisplayDayIndex() diff --git a/Assets/_Project/Scripts/Modules/Pet/Chat/PetChatService.cs b/Assets/_Project/Scripts/Modules/Pet/Chat/PetChatService.cs index ee0b6c51..c301adfd 100644 --- a/Assets/_Project/Scripts/Modules/Pet/Chat/PetChatService.cs +++ b/Assets/_Project/Scripts/Modules/Pet/Chat/PetChatService.cs @@ -132,32 +132,54 @@ public async Task SendMessageAsync( return (GetFallback(petId), true); } - try + string[] modelCandidates = _config.ModelCandidates; + if (modelCandidates.Length == 0) { - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(TimeSpan.FromSeconds(_timeoutSeconds)); - - Debug.Log($"[PetChat] Sending LLM request for {petId}..."); - string response = await SendLLMRequestAsync(systemPrompt, userPrompt, cts.Token); - Debug.Log($"[PetChat] LLM response for {petId}: {(string.IsNullOrWhiteSpace(response) ? "" : response[..Math.Min(response.Length, 50)])}..."); - string cleaned = CleanResponse(response); - if (string.IsNullOrWhiteSpace(cleaned)) - { - Debug.LogWarning($"[PetChat] Empty/cleaned response for {petId}, using fallback"); - return (GetFallback(petId), true); - } - return (cleaned, false); - } - catch (OperationCanceledException) - { - if (cancellationToken.IsCancellationRequested) throw; + LogFallback(petId, "NoModelCandidates"); return (GetFallback(petId), true); } - catch (Exception ex) + + Debug.Log($"[AI] request-entry role={petId} feature=PetChat service={GetType().Name} registered=true models={string.Join(",", modelCandidates)}"); + string lastFailure = string.Empty; + for (int modelIndex = 0; modelIndex < modelCandidates.Length; modelIndex++) { - Debug.LogWarning($"[PetChat] LLM request failed for {petId}: {ex.Message}"); - return (GetFallback(petId), true); + string model = modelCandidates[modelIndex]; + try + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cts.CancelAfter(TimeSpan.FromSeconds(_timeoutSeconds)); + + string response = await SendLLMRequestAsync(systemPrompt, userPrompt, model, cts.Token); + string preview = string.IsNullOrWhiteSpace(response) + ? "" + : response[..Math.Min(response.Length, 50)]; + Debug.Log($"[AI] raw-response role={petId} feature=PetChat model={model} content={SanitizeForLog(preview)}"); + string cleaned = CleanResponse(response); + if (string.IsNullOrWhiteSpace(cleaned)) + { + lastFailure = "EmptyResponse"; + LogModelFailure(petId, model, modelIndex, modelCandidates.Length, lastFailure); + continue; + } + + Debug.Log($"[AI] result-accepted role={petId} feature=PetChat model={model}"); + return (cleaned, false); + } + catch (OperationCanceledException) + { + if (cancellationToken.IsCancellationRequested) throw; + lastFailure = "Timeout"; + LogModelFailure(petId, model, modelIndex, modelCandidates.Length, lastFailure); + } + catch (Exception ex) + { + lastFailure = $"{ex.GetType().Name}:{SanitizeForLog(ex.Message, 240)}"; + LogModelFailure(petId, model, modelIndex, modelCandidates.Length, lastFailure); + } } + + LogFallback(petId, $"AllModelsFailed:{lastFailure}"); + return (GetFallback(petId), true); } private string BuildSystemPrompt(PetId petId) @@ -240,11 +262,11 @@ private static string BuildUserPrompt(string userMessage, string? otherPetReply, } private async Task SendLLMRequestAsync( - string systemPrompt, string userPrompt, CancellationToken cancellationToken) + string systemPrompt, string userPrompt, string model, CancellationToken cancellationToken) { var body = new LLMRequest { - model = _config.Model, + model = model, messages = new[] { new LLMMessage { role = "system", content = systemPrompt }, @@ -262,6 +284,7 @@ private async Task SendLLMRequestAsync( req.SetRequestHeader("Authorization", $"Bearer {_config.ApiKey}"); var operation = req.SendWebRequest(); + Debug.Log($"[AI] request-sent role=PetChat feature=PetChat method=POST endpoint={_config.Endpoint} model={model}"); while (!operation.isDone) { if (cancellationToken.IsCancellationRequested) @@ -287,6 +310,31 @@ private async Task SendLLMRequestAsync( return response.choices[0].message?.content ?? string.Empty; } + private void LogModelFailure(PetId petId, string model, int modelIndex, int modelCount, string reason) + { + bool hasNextModel = modelIndex + 1 < modelCount; + Debug.LogWarning($"[AI] model-failed role={petId} feature=PetChat model={model} attempt={modelIndex + 1}/{modelCount} hasNext={hasNextModel} reason={SanitizeForLog(reason, 240)}"); + } + + private void LogFallback(PetId petId, string reason) + { + Debug.LogWarning($"[Fallback] role={petId} feature=PetChat reason={SanitizeForLog(reason, 240)}"); + } + + private string SanitizeForLog(string value, int maxLength = 240) + { + string sanitized = value ?? string.Empty; + if (!string.IsNullOrWhiteSpace(_config.ApiKey)) + { + sanitized = sanitized.Replace(_config.ApiKey, "[REDACTED]"); + } + + sanitized = sanitized.Replace("\r", "\\r").Replace("\n", "\\n"); + return sanitized.Length <= maxLength + ? sanitized + : sanitized.Substring(0, Math.Max(1, maxLength - 3)) + "..."; + } + private static string GetFallback(PetId petId) { var pool = petId == PetId.Angel ? AngelFallbacks : DevilFallbacks; diff --git a/Assets/_Project/Scripts/Modules/Tarot/DirectLLMBackend.cs b/Assets/_Project/Scripts/Modules/Tarot/DirectLLMBackend.cs index 28d404ea..ec7821b7 100644 --- a/Assets/_Project/Scripts/Modules/Tarot/DirectLLMBackend.cs +++ b/Assets/_Project/Scripts/Modules/Tarot/DirectLLMBackend.cs @@ -33,35 +33,53 @@ public async Task RequestAsync( { if (!_config.IsConfigured) { + LogFallback($"role={petId} feature=TarotReading", "ConfigMissing"); return LocalFallback.Build(draw, petId, orientation); } string systemPrompt = BuildSystemPrompt(petId); string userPrompt = BuildUserPrompt(draw, petId); - string responseText; - try + string[] modelCandidates = _config.ModelCandidates; + if (modelCandidates.Length == 0) { - responseText = await SendRequestAsync(systemPrompt, userPrompt, cancellationToken) - .ConfigureAwait(false); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) - { - Debug.LogWarning($"[DirectLLM] Request failed: {ex.Message}"); + LogFallback($"role={petId} feature=TarotReading", "NoModelCandidates"); return LocalFallback.Build(draw, petId, orientation); } - if (string.IsNullOrWhiteSpace(responseText)) + string lastFailure = string.Empty; + for (int modelIndex = 0; modelIndex < modelCandidates.Length; modelIndex++) { - Debug.LogWarning("[DirectLLM] API returned empty content, falling back"); - return LocalFallback.Build(draw, petId, orientation); + string model = modelCandidates[modelIndex]; + try + { + string responseText = await SendRequestAsync("Tarot", systemPrompt, userPrompt, model, cancellationToken) + .ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(responseText)) + { + lastFailure = "EmptyResponse"; + LogModelFailure($"role={petId} feature=TarotReading", model, modelIndex, modelCandidates.Length, lastFailure); + continue; + } + + Debug.Log($"[AI] result-accepted role={petId} feature=TarotReading model={model}"); + return new TarotReading(petId, orientation, responseText, isFromGateway: true); + } + catch (OperationCanceledException) + { + if (cancellationToken.IsCancellationRequested) throw; + lastFailure = "Timeout"; + LogModelFailure($"role={petId} feature=TarotReading", model, modelIndex, modelCandidates.Length, lastFailure); + } + catch (Exception ex) + { + lastFailure = $"{ex.GetType().Name}:{SanitizeForLog(ex.Message, 240)}"; + LogModelFailure($"role={petId} feature=TarotReading", model, modelIndex, modelCandidates.Length, lastFailure); + } } - return new TarotReading(petId, orientation, responseText, isFromGateway: true); + LogFallback($"role={petId} feature=TarotReading", $"AllModelsFailed:{lastFailure}"); + return LocalFallback.Build(draw, petId, orientation); } public async Task RequestSummaryAsync( @@ -70,6 +88,7 @@ public async Task RequestSummaryAsync( { if (!_config.IsConfigured) { + LogFallback("role=Tarot feature=TarotSummary", "ConfigMissing"); return TarotSummaryResult.Default(); } @@ -79,23 +98,47 @@ public async Task RequestSummaryAsync( .Replace("{futureCard}", $"{future.Card.DisplayNameZh} ({future.Card.DisplayNameEn})") .Replace("{question}", question ?? "未指定"); - string responseText; - try + string[] modelCandidates = _config.ModelCandidates; + if (modelCandidates.Length == 0) { - responseText = await SendRequestAsync(systemPrompt, "请返回 JSON。", cancellationToken) - .ConfigureAwait(false); - } - catch (OperationCanceledException) - { - throw; + LogFallback("role=Tarot feature=TarotSummary", "NoModelCandidates"); + return TarotSummaryResult.Default(); } - catch (Exception ex) + + string lastFailure = string.Empty; + for (int modelIndex = 0; modelIndex < modelCandidates.Length; modelIndex++) { - Debug.LogWarning($"[DirectLLM] Summary request failed: {ex.Message}"); - return TarotSummaryResult.Default(); + string model = modelCandidates[modelIndex]; + try + { + string responseText = await SendRequestAsync("Tarot", systemPrompt, "请返回 JSON。", model, cancellationToken) + .ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(responseText)) + { + lastFailure = "EmptyResponse"; + LogModelFailure("role=Tarot feature=TarotSummary", model, modelIndex, modelCandidates.Length, lastFailure); + continue; + } + + TarotSummaryResult result = TarotSummaryResult.FromJson(responseText); + Debug.Log($"[AI] result-accepted role=Tarot feature=TarotSummary model={model}"); + return result; + } + catch (OperationCanceledException) + { + if (cancellationToken.IsCancellationRequested) throw; + lastFailure = "Timeout"; + LogModelFailure("role=Tarot feature=TarotSummary", model, modelIndex, modelCandidates.Length, lastFailure); + } + catch (Exception ex) + { + lastFailure = $"{ex.GetType().Name}:{SanitizeForLog(ex.Message, 240)}"; + LogModelFailure("role=Tarot feature=TarotSummary", model, modelIndex, modelCandidates.Length, lastFailure); + } } - return TarotSummaryResult.FromJson(responseText); + LogFallback("role=Tarot feature=TarotSummary", $"AllModelsFailed:{lastFailure}"); + return TarotSummaryResult.Default(); } private string BuildSystemPrompt(PetId petId) @@ -119,12 +162,12 @@ private string BuildUserPrompt(TarotDrawResult draw, PetId petId) .Replace("{keywords}", string.Join("、", draw.Card.GetKeywords(draw.Orientation))); } - private async Task SendRequestAsync(string systemPrompt, string userPrompt, - CancellationToken cancellationToken) + private async Task SendRequestAsync(string role, string systemPrompt, string userPrompt, + string model, CancellationToken cancellationToken) { var body = new LLMRequest { - model = _config.Model, + model = model, messages = new[] { new LLMMessage { role = "system", content = systemPrompt }, @@ -142,6 +185,7 @@ private async Task SendRequestAsync(string systemPrompt, string userProm req.SetRequestHeader("Authorization", $"Bearer {_config.ApiKey}"); var operation = req.SendWebRequest(); + Debug.Log($"[AI] request-sent role={role} feature=Tarot method=POST endpoint={_config.Endpoint} model={model}"); while (!operation.isDone) { if (cancellationToken.IsCancellationRequested) @@ -167,6 +211,31 @@ private async Task SendRequestAsync(string systemPrompt, string userProm return response.choices[0].message?.content ?? string.Empty; } + private void LogModelFailure(string roleAndFeature, string model, int modelIndex, int modelCount, string reason) + { + bool hasNextModel = modelIndex + 1 < modelCount; + Debug.LogWarning($"[AI] model-failed {roleAndFeature} model={model} attempt={modelIndex + 1}/{modelCount} hasNext={hasNextModel} reason={SanitizeForLog(reason, 240)}"); + } + + private void LogFallback(string roleAndFeature, string reason) + { + Debug.LogWarning($"[Fallback] {roleAndFeature} reason={SanitizeForLog(reason, 240)}"); + } + + private string SanitizeForLog(string value, int maxLength = 240) + { + string sanitized = value ?? string.Empty; + if (!string.IsNullOrWhiteSpace(_config.ApiKey)) + { + sanitized = sanitized.Replace(_config.ApiKey, "[REDACTED]"); + } + + sanitized = sanitized.Replace("\r", "\\r").Replace("\n", "\\n"); + return sanitized.Length <= maxLength + ? sanitized + : sanitized.Substring(0, Math.Max(1, maxLength - 3)) + "..."; + } + private string ResolvePersonality(PetId petId) { if (_personalityResolver != null) diff --git a/Assets/_Project/Scripts/Modules/Tarot/LLMConfigSO.cs b/Assets/_Project/Scripts/Modules/Tarot/LLMConfigSO.cs index 7c0d5935..f3c0f92b 100644 --- a/Assets/_Project/Scripts/Modules/Tarot/LLMConfigSO.cs +++ b/Assets/_Project/Scripts/Modules/Tarot/LLMConfigSO.cs @@ -1,4 +1,5 @@ #nullable enable +using System.Collections.Generic; using UnityEngine; namespace GeminiLab.Modules.Tarot @@ -16,9 +17,12 @@ public sealed class LLMConfigSO : ScriptableObject [Tooltip("API Key")] [SerializeField] private string _apiKey = string.Empty; - [Tooltip("模型名,如 gpt-4o / claude-sonnet-4-6")] + [Tooltip("首选模型名,如 deepseek-v4-pro")] [SerializeField] private string _model = "gpt-4o"; + [Tooltip("首选模型无有效返回时按顺序尝试的备用模型列表")] + [SerializeField] private string[] _fallbackModels = { "deepseek-v4-flash" }; + [Tooltip("天使 System prompt。占位符: {personality}")] [TextArea(5, 20)] [SerializeField] private string _angelSystemTemplate = @@ -63,6 +67,23 @@ public sealed class LLMConfigSO : ScriptableObject public string Endpoint => _endpoint; public string ApiKey => _apiKey; public string Model => _model; + public string[] ModelCandidates + { + get + { + var candidates = new List(); + AddModelCandidate(candidates, _model); + if (_fallbackModels != null) + { + foreach (string fallbackModel in _fallbackModels) + { + AddModelCandidate(candidates, fallbackModel); + } + } + + return candidates.ToArray(); + } + } public string AngelSystemTemplate => _angelSystemTemplate; public string DevilSystemTemplate => _devilSystemTemplate; public string UserMessageTemplate => _userMessageTemplate; @@ -70,5 +91,16 @@ public sealed class LLMConfigSO : ScriptableObject public float TimeoutSeconds => _timeoutSeconds; public bool IsConfigured => !string.IsNullOrWhiteSpace(_endpoint) && !string.IsNullOrWhiteSpace(_apiKey); + + private static void AddModelCandidate(List candidates, string? model) + { + if (string.IsNullOrWhiteSpace(model)) return; + + string normalized = model.Trim(); + if (!candidates.Contains(normalized)) + { + candidates.Add(normalized); + } + } } -} \ No newline at end of file +} diff --git a/Assets/_Project/Settings/Tarot/LLMConfig.asset b/Assets/_Project/Settings/Tarot/LLMConfig.asset index 766cc5d0..fc6030f2 100644 --- a/Assets/_Project/Settings/Tarot/LLMConfig.asset +++ b/Assets/_Project/Settings/Tarot/LLMConfig.asset @@ -15,6 +15,8 @@ MonoBehaviour: _endpoint: https://api.deepseek.com/v1/chat/completions _apiKey: sk-2c23ffc2bce6490f8a85678da3dd950d _model: deepseek-v4-pro + _fallbackModels: + - deepseek-v4-flash _angelSystemTemplate: "\u4F60\u662F\u4E00\u4F4D\u5929\u4F7F (Angel) \u2014\u2014 \u6E29\u67D4\u3001\u5305\u5BB9\u3001\u613F\u610F\u6307\u51FA\u5E0C\u671B\u3002\n\u5F53\u524D\u7684\u4F60\uFF1A{personality}\n\u7528\u4E2D\u6587\u7ED9\u51FA\u5854\u7F57\u89E3\u8BFB\uFF0C\u4E0D\u8D85\u8FC7 200 \u4E2A\u6C49\u5B57\u3002" diff --git a/docs/ai-memory/gemini-lab-memory-main.md b/docs/ai-memory/gemini-lab-memory-main.md index cb84b4ea..79ddfc37 100644 --- a/docs/ai-memory/gemini-lab-memory-main.md +++ b/docs/ai-memory/gemini-lab-memory-main.md @@ -794,7 +794,7 @@ WorldMap 苹果树点击后由 `AppleTreeDropController` 播放快速晃动并 ### 2026-09-06 WorldMap 室外新手指引 -- `WorldMap_Main.unity` 的 `Canvas/Panel_OutdoorTutorial` 已保存七个页面节点:`Page_Intro` 与 `Page_Outdoor1`~`Page_Outdoor6`,图片来自 `Assets/_Project/Art/新手引导/outdoor/`。 +- 初始版本的 `WorldMap_Main.unity` 曾在 `Canvas/Panel_OutdoorTutorial` 保存七个页面节点;2026-09-13 调整后当前为 `Page_Outdoor1`~`Page_Outdoor6` 六个页面,图片来自 `Assets/_Project/Art/新手引导/outdoor/`。 - 面板保存 `left.png`、`right.png`、`outdoor/close.png` 三个按钮资源,并提供 `Btn_OutdoorTutorial` 占位入口。入口当前只负责打开第一页,后续可在 Inspector 中替换按钮 Sprite 或绑定正式入口。 - `SceneAuthoredImageVariantView` 负责运行时切换已作者化页面,上一页/下一页在首尾边界停止;运行时不创建 GameObject、不加载路径资源,也不写入最终 Sprite。 - `WorldMapOutdoorTutorialAuthoring` 是定向作者化工具(菜单 `Tools/Gemini-Lab/WorldMap/Author Outdoor Tutorial`),只维护自己的节点,不重建或清空 WorldMap 场景。当前没有绑定邮箱、标牌或首次进入等正式业务触发条件。 @@ -838,3 +838,8 @@ WorldMap 苹果树点击后由 `AppleTreeDropController` 播放快速晃动并 - 在保留天空派生范围、正弦往返和端点折返方式不变的前提下,`WorldMapAmbientAnimationController` 的 `_cloudMoveSpeed` 从 `0.12` 降为 `0.06`,即当前移动速度减半。 - 本次不改云层移动范围、折返方式、天空/云层视觉资源或其他 WorldMap 系统;Play 结果仍需人工确认。 + +### 2026-09-13 WorldMap 室外新手指引首页调整 + +- `Canvas/Panel_OutdoorTutorial` 当前保存六个页面节点:`Page_Outdoor1`~`Page_Outdoor6`;`Page_Outdoor1` 作为首页,原 `Page_Intro` 已从场景和分页引用中移除。 +- 原始 `Assets/_Project/Art/新手引导/outdoor/intro.png` 及其 `.meta` 保留在仓库中,但不再由室外新手指引展示或挂载。 diff --git a/docs/ai-memory/gemini-lab-memory-rules-and-history.md b/docs/ai-memory/gemini-lab-memory-rules-and-history.md index fc2fa1ea..5ff487d8 100644 --- a/docs/ai-memory/gemini-lab-memory-rules-and-history.md +++ b/docs/ai-memory/gemini-lab-memory-rules-and-history.md @@ -368,6 +368,11 @@ Updated: 2026-08-21 ### 2026-09-06 WorldMap 室外新手指引更新 -- 新手指引采用 Scene 作者化七页结构,页面顺序固定为 `intro`、`outdoor1`~`outdoor6`;翻页按钮为点击按钮,不使用拖拽。 +- 初始版本的新手指引采用 Scene 作者化七页结构,页面顺序为 `intro`、`outdoor1`~`outdoor6`;2026-09-13 调整后当前顺序为 `outdoor1`~`outdoor6`。翻页按钮为点击按钮,不使用拖拽。 - 当前只提供可替换的占位入口按钮,未擅自接入邮箱、标牌、首次进入或其他业务触发。正式入口确定后只需替换该按钮的 UnityEvent 绑定。 - 图片资源保留为非空序列化 Sprite 引用,运行时只切换页面显隐;Scene 与 Play 的视觉节点保持同一套来源。 + +### 2026-09-13 WorldMap 室外新手指引首页调整 + +- 删除室外新手指引首页 `Page_Intro` 的展示对象和分页引用,页面顺序调整为 `outdoor1`~`outdoor6`,`outdoor1` 现在是第一页。 +- `intro.png` 原始资源不删除,仅不再挂载到 `Panel_OutdoorTutorial`;其他页面、按钮和 Scene/Play 作者化规则不变。 diff --git a/docs/ai-memory/gemini-lab-project-file-guide.md b/docs/ai-memory/gemini-lab-project-file-guide.md index 6238be87..d0cd495a 100644 --- a/docs/ai-memory/gemini-lab-project-file-guide.md +++ b/docs/ai-memory/gemini-lab-project-file-guide.md @@ -655,7 +655,7 @@ Updated: 2026-08-22 - 场景:`Assets/_Project/Scenes/WorldMap/WorldMap_Main.unity`,节点位于 `Canvas/Panel_OutdoorTutorial`。 - 作者化脚本:`Assets/_Project/Scripts/Editor/SceneBootstrap/WorldMapOutdoorTutorialAuthoring.cs`,菜单为 `Tools/Gemini-Lab/WorldMap/Author Outdoor Tutorial`。脚本只增量维护新手指引子树。 -- 页面资源:`Assets/_Project/Art/新手引导/outdoor/intro.png`、`outdoor1.png`~`outdoor6.png`;按钮资源:`Assets/_Project/Art/新手引导/left.png`、`right.png`、`outdoor/close.png`。 +- 页面资源:当前挂载并展示 `Assets/_Project/Art/新手引导/outdoor/outdoor1.png`~`outdoor6.png`,首页为 `outdoor1.png`;原 `outdoor/intro.png` 及其 `.meta` 保留但不再挂载。按钮资源:`Assets/_Project/Art/新手引导/left.png`、`right.png`、`outdoor/close.png`。 - 运行时分页组件:`Assets/_Project/Scripts/Modules/HubUI/Panels/SceneAuthoredImageVariantView.cs`,只操作 Scene 中的页面节点和按钮事件。 ### WorldMap 室外点击路由(2026-09-07) diff --git a/docs/ai-memory/memory-index.paths.txt b/docs/ai-memory/memory-index.paths.txt index a4c346fa..a4337818 100644 --- a/docs/ai-memory/memory-index.paths.txt +++ b/docs/ai-memory/memory-index.paths.txt @@ -275,8 +275,8 @@ Assets/_Project/Scripts/Modules/HubUI/Panels/WeeklyGardenPanelStub.cs (关键词 Assets/_Project/Tests/EditMode/EmotionGardenAiTests.cs Assets/_Project/Scripts/Editor/SceneBootstrap/WorldMapOutdoorTutorialAuthoring.cs (WorldMap 室外新手指引 Scene 作者化与占位入口) Assets/_Project/Scripts/Modules/HubUI/Panels/SceneAuthoredImageVariantView.cs (Scene 作者化页面显隐与翻页) -Assets/_Project/Scenes/WorldMap/WorldMap_Main.unity (Panel_OutdoorTutorial 七页新手指引) -Assets/_Project/Art/新手引导/outdoor/ (intro、outdoor1-6、close 页面资源) +Assets/_Project/Scenes/WorldMap/WorldMap_Main.unity (Panel_OutdoorTutorial 六页新手指引,首页为 outdoor1) +Assets/_Project/Art/新手引导/outdoor/ (outdoor1-6、close 页面资源;intro.png 保留但不再挂载) Assets/_Project/Art/新手引导/left.png (新手指引上一页按钮) Assets/_Project/Art/新手引导/right.png (新手指引下一页按钮) Assets/_Project/Art/WorldMap/weather/WorldMapClouds_Alpha.png (天气云层派生透明 Sprite) diff --git a/docs/manual-validation-checklist.md b/docs/manual-validation-checklist.md index ac3fa49d..47086104 100644 --- a/docs/manual-validation-checklist.md +++ b/docs/manual-validation-checklist.md @@ -966,11 +966,11 @@ Updated: 2026-08-22 | 检查项 | 结果 | 备注 | | :--- | :--- | :--- | -| 点击 `Btn_OutdoorTutorial` 后显示 `intro` 页面 | 待 Play 验证 | 当前为可替换占位入口 | -| 点击下一页按 `intro`→`outdoor1`~`outdoor6` 顺序切换 | 待 Play 验证 | 首页/末页保持边界,不循环 | +| 点击 `Btn_OutdoorTutorial` 后显示 `outdoor1` 页面 | 待 Play 验证 | 当前为可替换占位入口 | +| 点击下一页按 `outdoor1`→`outdoor2`~`outdoor6` 顺序切换 | 待 Play 验证 | 首页/末页保持边界,不循环 | | 点击上一页按相反顺序切换,首末页不越界 | 待 Play 验证 | 使用点击按钮事件 | | 点击 `close.png` 关闭面板 | 待 Play 验证 | 面板关闭后入口仍可用 | -| Scene 中七页 Sprite 引用与 Play 显示一致 | 待人工验证 | 页面和布局均已保存到 `WorldMap_Main.unity` | +| Scene 中六页 Sprite 引用与 Play 显示一致 | 待人工验证 | 页面和布局均已保存到 `WorldMap_Main.unity`,首页为 `outdoor1` | ## B37. WorldMap 第一阶段室外点击交互(2026-09-07) | 检查项 | 结果 | 备注 | diff --git a/docs/project-structure-overview.md b/docs/project-structure-overview.md index 78808848..df42483a 100644 --- a/docs/project-structure-overview.md +++ b/docs/project-structure-overview.md @@ -496,7 +496,7 @@ SO 分类规划已写明,而且当前已经开始落地实际 `.asset` 文件 ## WorldMap 室外新手指引(2026-09-06) -- `Canvas/Panel_OutdoorTutorial` 保存七张可替换的教程页面,以及上一页、下一页、关闭按钮;面板默认关闭。 +- `Canvas/Panel_OutdoorTutorial` 保存六张可替换的教程页面 `Page_Outdoor1`~`Page_Outdoor6`,首页为 `Page_Outdoor1`,以及上一页、下一页、关闭按钮;面板默认关闭。原 `intro.png` 资源保留但不再挂载。 - `Canvas/Btn_OutdoorTutorial` 是当前的占位入口,后续可直接替换其 Sprite 或 UnityEvent,不需要改动分页代码。 - 所有图片引用和 RectTransform 都保存在 Scene;`SceneAuthoredImageVariantView` 运行时只做页面显隐与首尾边界控制,符合 Scene/Play 视觉一致约束。 ### 2026-09-07 WorldMap 室外点击交互