WitIntentMatcher.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. */
  8. using System;
  9. using Meta.Conduit;
  10. using Meta.WitAi.Json;
  11. using Meta.WitAi.Data.Intents;
  12. using UnityEngine;
  13. using UnityEngine.Serialization;
  14. namespace Meta.WitAi.CallbackHandlers
  15. {
  16. // Abstract class to share confidence handling
  17. public abstract class WitIntentMatcher : WitResponseHandler
  18. {
  19. /// <summary>
  20. /// Intent name to be matched
  21. /// </summary>
  22. [Header("Intent Settings")]
  23. [SerializeField] public string intent;
  24. /// <summary>
  25. /// Confidence threshold
  26. /// </summary>
  27. [FormerlySerializedAs("confidence")]
  28. [Range(0, 1f), SerializeField] public float confidenceThreshold = .6f;
  29. // Handle simple intent validation
  30. protected override string OnValidateResponse(WitResponseNode response, bool isEarlyResponse)
  31. {
  32. // No response
  33. if (response == null)
  34. {
  35. return "No response";
  36. }
  37. // Check against all intents
  38. WitIntentData[] intents = response.GetIntents();
  39. if (intents == null || intents.Length == 0)
  40. {
  41. return "No intents found";
  42. }
  43. // Find intent
  44. WitIntentData found = null;
  45. foreach (var intentData in intents)
  46. {
  47. if (string.Equals(intent, intentData.name, StringComparison.CurrentCultureIgnoreCase))
  48. {
  49. found = intentData;
  50. break;
  51. }
  52. }
  53. if (found == null)
  54. {
  55. return $"Missing required intent '{intent}'";
  56. }
  57. // Check confidence
  58. if (found.confidence < confidenceThreshold)
  59. {
  60. return $"Required intent '{intent}' confidence too low: {found.confidence:0.000}\nRequired: {confidenceThreshold:0.000}";
  61. }
  62. return string.Empty;
  63. }
  64. protected override void OnEnable()
  65. {
  66. Manifest.WitResponseMatcherIntents.Add(intent);
  67. base.OnEnable();
  68. }
  69. protected override void OnDisable()
  70. {
  71. Manifest.WitResponseMatcherIntents.Remove(intent);
  72. base.OnDisable();
  73. }
  74. }
  75. }