UpdateWorkingContextCommand.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using UnityEngine;
  2. using LLM.Editor.Data;
  3. using LLM.Editor.Core;
  4. using LLM.Editor.Helper;
  5. using Newtonsoft.Json.Linq;
  6. using JetBrains.Annotations;
  7. namespace LLM.Editor.Commands
  8. {
  9. /// <summary>
  10. /// A command that allows the LLM to write to, update, or clear its own
  11. /// short-term memory for the current session.
  12. /// </summary>
  13. [UsedImplicitly]
  14. public class UpdateWorkingContextCommand : ICommand
  15. {
  16. [System.Serializable]
  17. private class UpdateWorkingContextParams
  18. {
  19. public JObject updates;
  20. public string[] keysToRemove;
  21. public bool clearAll;
  22. }
  23. private readonly UpdateWorkingContextParams _params;
  24. public UpdateWorkingContextCommand(string jsonParams)
  25. {
  26. _params = jsonParams?.FromJson<UpdateWorkingContextParams>();
  27. }
  28. public CommandOutcome Execute(CommandContext context)
  29. {
  30. if (_params == null)
  31. {
  32. Debug.LogError("[UpdateWorkingContextCommand] Invalid parameters.");
  33. return CommandOutcome.Error;
  34. }
  35. var workingContext = SessionManager.LoadWorkingContext();
  36. if (_params.clearAll)
  37. {
  38. workingContext = new JObject();
  39. }
  40. else
  41. {
  42. if (_params.keysToRemove != null)
  43. {
  44. foreach (var key in _params.keysToRemove)
  45. {
  46. workingContext.Remove(key);
  47. }
  48. }
  49. if (_params.updates != null)
  50. {
  51. workingContext.Merge(_params.updates, new JsonMergeSettings
  52. {
  53. MergeArrayHandling = MergeArrayHandling.Replace
  54. });
  55. }
  56. }
  57. SessionManager.SaveWorkingContext(workingContext);
  58. Debug.Log($"[UpdateWorkingContextCommand] Working context updated:\n{workingContext.ToString(Newtonsoft.Json.Formatting.Indented)}");
  59. return CommandOutcome.Success;
  60. }
  61. }
  62. }