长期记忆使用示例
Unity 中四种完整的长期记忆模式——零配置持久化、身份验证身份、记忆预置和记忆重置。
最后更新于
这有帮助吗?
这有帮助吗?
using Convai.Domain.Identity;
public class AccountIdentityProvider : IEndUserIdentityProvider
{
private readonly string _accountId;
public AccountIdentityProvider(string accountId)
{
_accountId = accountId;
}
public string GetEndUserId()
{
return _accountId;
}
}using Convai.Runtime.Components;
using UnityEngine;
public class IdentityRegistrar : MonoBehaviour
{
[SerializeField] private ConvaiManager _convaiManager;
private void Awake()
{
string accountId = AuthService.CurrentUser.AccountId;
_convaiManager.SetEndUserIdentityProvider(new AccountIdentityProvider(accountId));
}
}using System.Collections.Generic;
using Convai.Domain.Identity;
public class AccountMetadataProvider : IEndUserMetadataProvider
{
private readonly string _displayName;
可选地附加一个显示名称,这样编辑器的长期记忆面板会显示可读标签,而不是原始 ID:
{
_displayName = displayName;
}
public IReadOnlyDictionary<string, object> GetEndUserMetadata()
{
public AccountMetadataProvider(string displayName)
}
}return new Dictionary<string, object> { { "name", _displayName } };
_convaiManager.SetEndUserMetadataProvider(using Convai.RestAPI;
using System.Collections.Generic;
using UnityEngine;
public class OnboardingMemorySeeder : MonoBehaviour
{
// 仅限编辑器/服务器端使用——切勿在嵌入 API 密钥的情况下发布
[ContextMenu("预置新员工记忆")]
private async void SeedEmployeeMemory()
{
string characterId = "onboarding-assistant-id";
string employeeAccountId = "emp-00421";
var certifications = new List<string>
{
"该员工已于 2025-04-10 完成消防安全一级。",
"该员工已于 2025-04-15 完成危险材料处理。",
"该员工尚未完成受限空间进入认证。"
};
using var client = new ConvaiRestClient(ConvaiSettings.Instance.ApiKey);
var response = await client.Memory.AddAsync(characterId, employeeAccountId, certifications);
Debug.Log($"已预置 {response.Memories.Count} 条记忆记录。");
}
}using Convai.RestAPI;
using UnityEngine;
public class MemoryReset : MonoBehaviour
{
[ContextMenu("清除记忆然后禁用 LTM")]
private async void PurgeAndDisable()
{
string characterId = "your-character-id";
string endUserId = "target-end-user-id";
using var client = new ConvaiRestClient(ConvaiSettings.Instance.ApiKey);
// 步骤 1:删除该用户–角色对的所有记忆
await client.Memory.DeleteAllAsync(characterId, endUserId);
Debug.Log("记忆已清除。");
// 步骤 2:为该角色禁用 LTM
await client.Characters.SetMemoryEnabledAsync(characterId, false);
Debug.Log("长期记忆已禁用。");
}
}