MemoryLogger.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.IO;
  3. using UnityEditor;
  4. using UnityEngine;
  5. using LLM.Editor.Data;
  6. using LLM.Editor.Helper;
  7. using LLM.Editor.Commands;
  8. using System.Collections.Generic;
  9. namespace LLM.Editor.Core
  10. {
  11. [Serializable]
  12. public class MemoryLogWrapper
  13. {
  14. public List<InteractionRecord> records;
  15. }
  16. [InitializeOnLoad]
  17. public static class MemoryLogger
  18. {
  19. private static List<InteractionRecord> _records = new();
  20. private static bool _isInitialized;
  21. private static string MemoryLogPath => Path.Combine(SessionManager.GetSessionCachePath(), "memory_log.json");
  22. private static void Initialize()
  23. {
  24. if (_isInitialized) return;
  25. LoadMemoryLog();
  26. _isInitialized = true;
  27. }
  28. public static void AddRecord(InteractionRecord record)
  29. {
  30. // We only want to log successful multi-step interactions, or single-step interactions that aren't part of a larger, failed plan.
  31. if (record.isMultiStep && record.Outcome != CommandOutcome.Success)
  32. {
  33. Debug.LogWarning($"[MemoryLogger] Skipping logging of failed multi-step interaction: {record.UserPrompt}");
  34. return;
  35. }
  36. // The embedding should already be generated and included in the record.
  37. if (record.PromptEmbedding == null || record.PromptEmbedding.Length == 0)
  38. {
  39. Debug.LogWarning($"[MemoryLogger] Record for prompt '{record.UserPrompt}' is missing its embedding. It will not be retrievable in the future.");
  40. }
  41. Initialize();
  42. _records.Add(record);
  43. SaveMemoryLog();
  44. }
  45. public static List<InteractionRecord> GetRecords()
  46. {
  47. Initialize();
  48. return _records;
  49. }
  50. private static void SaveMemoryLog()
  51. {
  52. if (!SessionManager.HasActiveSession()) return;
  53. var wrapper = new MemoryLogWrapper { records = _records };
  54. var json = wrapper.ToJson(true);
  55. File.WriteAllText(MemoryLogPath, json);
  56. }
  57. private static void LoadMemoryLog()
  58. {
  59. if (!SessionManager.HasActiveSession() || !File.Exists(MemoryLogPath))
  60. {
  61. _records = new List<InteractionRecord>();
  62. return;
  63. }
  64. var json = File.ReadAllText(MemoryLogPath);
  65. var wrapper = json.FromJson<MemoryLogWrapper>();
  66. _records = wrapper?.records ?? new List<InteractionRecord>();
  67. Debug.Log($"[MemoryLogger] Loaded {_records.Count} interaction records from memory log.");
  68. }
  69. }
  70. }