前提条件

开发环境

详见 面板小程序 > 搭建环境

产品名称:面板智能体

需求原型

创建智能体

准备好 智能生活 OEM App 和智能产品(可选)后,需要在 智能体平台 上创建智能体。

  1. 单击 创建 Agent 按钮,填入项目相关必选信息后,单击 确定 创建一个智能体。

  1. 依照您的需求,在 01 模型能力配置 下定制智能体的模型、记忆、工具、知识库及工作流等功能,再在 02 提示词开发 下配置提示词(Prompt),完成当前数据中心的智能体创建。

调试智能体

  1. 配置完成 Prompt 后,单击 获取调试二维码 按钮获取二维码。

  1. 调试完成后,按照您的需要分别配置不同数据中心的智能体,然后单击 发布,并配置版本号,将智能体发布至线上环境。

  1. 发布完成后,单击 上架 将智能体上架到平台账号下,用于后续产品的绑定。

  1. 完成上述步骤后返回智能体列表页面,可以看到您刚刚创建的专属智能体。

由于产品定义了面板和设备所拥有的功能点与智能体,所以在开发一个智能设备面板之前,首先需要创建一个 AI 毛绒玩具产品,定义产品有哪些功能点、携带哪些智能体,然后再在面板中一一实现这些功能点。

首先,注册登录 涂鸦开发者平台,并在平台创建产品:

  1. 在涂鸦开发者平台产品类目下,单击 创建产品

  1. 在标准类目下选择 影音穿戴 > AI 毛绒玩具

  1. 选择 智能化方式产品方案,完善产品信息,单击 创建产品

  1. 添加标准功能 页面,选择适合硬件方案维度的功能点,单击 确定

  1. 完成以上步骤后,您已经完成了产品的创建。接下来,在 01 功能定义 > 产品 AI 功能 下继续添加产品 AI 功能。

  1. 添加产品 AI 能力:单击 添加产品 AI 能力 来选择您的产品需要使用的 AI 能力,选择完成后单击 确定

  1. 选择产品 AI Agent:选择为产品配置智能体(本模板以设备端智能体为例),单击 选择智能体 进入添加智能体页面,进行设备默认智能体配置。

  1. 在智能体列表中选择要与设备绑定的默认智能体。

  1. 完成智能体绑定配置后,单击 下一步 设备交互 进入交互设置。

  1. 设备交互 页面中,选择面板模板,后续操作可参考 产品开发指南

开发者平台创建面板小程序

面板小程序的开发在 小程序开发者 平台上进行操作,首先请前往 小程序开发者平台 完成平台的注册登录。

详细操作步骤可以参考 创建面板小程序

IDE 基于模板创建项目工程

打开 IDE 创建一个基于 AI 智能体小程序模板 的面板小程序项目,需要在 Tuya MiniApp IDE 上操作。

详细操作步骤可以参考 初始化项目工程

完成以上步骤后,一个面板小程序的开发模板初始化完成。以下为工程目录的介绍:

├── src
│   ├── api // 面板所有云端 API 请求聚合文件
│   │   ├── atop.ts // ATOP 请求封装
│   │   ├── getCachedLaunchOptions.ts // 获取缓存的启动参数
│   │   ├── getCachedSystemInfo.ts // 获取缓存的系统信息
│   │   ├── index_highway.ts // 面板智能体相关 API 请求
│   │   ├── panelAgent // 面板智能体 API 模块
│   │   │   ├── apis.ts // 智能体 API 接口定义
│   │   │   ├── index.ts // 智能体 API 导出
│   │   │   ├── types.d.ts // 智能体类型定义
│   │   │   ├── universal.ts // 通用 API 方法
│   │   │   ├── utils.ts // 智能体工具方法
│   │   ├── request.ts // 请求封装工具
│   ├── components
│   │   ├── Avatar // 头像组件
│   │   ├── AvatarBar // 头像栏组件
│   │   ├── Battery // 电池电量组件
│   │   ├── BottomButton // 底部按钮组件
│   │   ├── DialogConfirm // 确认弹窗组件
│   │   ├── DialogInput // 文本输入弹窗组件
│   │   ├── DialogPicker // DP 选择弹窗组件
│   │   ├── GridBattery // 电池电量组件
│   │   ├── icon-font // svg 图标容器组件
│   │   ├── Modal // 弹窗通用组件
│   │   ├── NoData // 无数据兜底组件
│   │   ├── PickerItem // 选择按钮通用组件
│   │   ├── SearchBar // 搜索组件
│   │   ├── SubTopBar // 子页面顶部栏组件
│   │   ├── Tag // 分类标签子组件
│   │   ├── TagBar // 分类标签组件
│   │   ├── Text // 通用文本组件
│   │   ├── TopBar // 通用 TopBar 组件
│   │   ├── TouchableOpacity // 通用按钮组件
│   │   ├── WifiSignal // WiFi 信号强度组件
│   │   ├── index.ts // 组件导出文件
│   ├── constant
│   │   ├── dpCodes.ts // dpCode 常量
│   │   ├── index.ts // 存放所有的常量配置
│   ├── devices // 设备模型
│   │   ├── index.ts // 设备导出
│   │   ├── protocols // 设备协议
│   │   │   ├── index.ts // 协议导出
│   │   ├── schema.ts // 设备 Schema 定义
│   ├── hooks // hooks
│   │   ├── useAgentLanguages.ts // 智能体语言 hooks
│   │   ├── useChatEmotion.ts // 聊天情绪 hooks
│   │   ├── usePanelConfig.ts // 面板配置 hooks
│   │   ├── useSelectorWithEquality.ts // Redux selector hooks
│   │   ├── useSystemInfo.tsx // 系统信息 hooks
│   │   ├── useWakeWord.ts // 唤醒词 hooks
│   ├── i18n // 多语言
│   │   ├── index.ts // 多语言导出
│   │   ├── strings.ts // 多语言字符串定义
│   ├── image // 图片资源
│   │   ├── bg-light@3x.png // 背景图片
│   ├── pages
│   │   ├── AvatarSelect // 头像选择页面
│   │   ├── CustomAgentEdit // 智能体角色新增和编辑页面
│   │   ├── DialogHistory // 单个智能体会话历史记录页面
│   │   │   ├── DialogSingleContentNew // 会话内容组件
│   │   ├── HomeRole // 首页智能体角色页面
│   │   │   ├── BaseInfoCard // 基础信息卡片组件
│   │   │   ├── HomeTopBar // 首页顶部栏组件
│   │   │   ├── RoleMemoryEntry // 角色记忆入口组件
│   │   ├── RoleChange // 角色切换页面
│   │   │   ├── RoleItem // 角色项组件
│   │   ├── RoleMemory // 角色记忆页面
│   │   │   ├── ChatSummary // 聊天摘要组件
│   │   │   ├── MemoryFormat // 记忆格式组件
│   │   ├── VoiceSquare // 音色广场页面
│   │   │   ├── SliderValueItem // 滑块值项组件
│   │   │   ├── VoiceItem // 音色项组件
│   ├── redux // Redux
│   │   ├── index.ts // Redux 导出
│   │   ├── modules // Redux 模块
│   ├── res // 图片资源 & SVG 相关
│   │   ├── agent // 智能体相关图片
│   │   ├── iconfont // 图标字体文件
│   │   ├── signal // 信号相关图片
│   │   ├── iconsvg.ts // SVG 图标定义
│   │   ├── index.ts // 资源导出
│   ├── styles // 全局样式
│   │   ├── index.less // 全局样式入口
│   ├── types // 全局类型定义
│   │   ├── index.ts // 类型定义导出
│   ├── utils // 业务常用工具方法
│   │   ├── index.ts // 工具方法导出
│   │   ├── string.js // 字符串工具方法
│   │   ├── time.ts // 时间工具方法
│   ├── app.config.ts // 应用配置
│   ├── app.less // 应用样式
│   ├── app.tsx // 应用入口文件
│   ├── composeLayout.tsx // 处理监听子设备添加、解绑、DP 变化等
│   ├── global.config.ts // 全局配置
│   ├── global.less // 全局样式
│   ├── mixins.less // less mixins
│   ├── routes.config.ts // 配置路由
│   ├── theme.json // 主题配置
│   ├── variables.less // less variables

获取当前绑定角色

功能说明

使用 getAIAgentRoles API 方法获取当前绑定角色。

相关代码段

// 当前绑定角色请求函数
const getBindAgentRoleData = async () => {
  getBindAgentRoleLocal()
    .then((res: any) => {
      dispatch(initBindAgentRole(res));
      if (res?.bindRoleType === 1) {
        dispatch(updateRoleInfo({ roleTemplateId: res?.templateId }));
      }
      // 可以根据返回值中的bindRoleType判断当前配置的是多角色还是单角色(多角色:0-自定义角色,1-模板角色;单角色:2-单角色)
      // 多角色:当bindRoleType不等于2时
      dispatch(initSupportMultiRole(res?.bindRoleType !== 2));
      initLoading && setInitLoading(false);
      setIsUnconfigured(false);
    })
    .catch((err) => {
      console.log("getBindAgentRoleLocal::err::", err);
      setInitLoading(false);
      setIsUnconfigured(true);
    });
};

获取最近心情

功能说明

通过监听设备信息,可以获取当前角色的心情状态。

相关代码段

useEffect(() => {
  registerMQTTDeviceListener({ deviceId: getDevInfo().devId });

  const handleCallback = async ({ messageData }) => {
    try {
      const { bizType, data } = messageData;
      const { code, custom } = data;
      if (bizType === "SKILL" && code === "emo") {
        setEmojiUrl(custom?.url);

        // 刷新头部的聊天信息
        getBindAgentRoleData();
        setChatEmotion((state) => ({
          ...state,
          disableTime: true,
        }));
      }
    } catch (err) {
      console.log(err);
    }
  };

  onMqttMessageReceived(handleCallback);

  return () => {
    console.log("============================");
    unregisterMQTTDeviceListener({ deviceId: getDevInfo().devId });
    offMqttMessageReceived(handleCallback);
  };
}, []);

获取角色列表

功能说明

可以获取推荐角色列表和自定义角色列表。

相关代码段

const getCustomRoleFunc = (params: GetListParams) => {
  return new Promise((resolve, reject) => {
    getCustomRoleListLocal({})
      .then((res: VoiceRes) => {
        const { totalPage, list = [] } = res;
        // hideLoading();
        // 优化闪现暂无角色
        setTimeout(() => {
          setLoading(false);
        }, 200);
        resolve({
          total: totalPage,
          list,
        });
      })
      .catch((error) => {
        // hideLoading();
        setLoading(false);
        reject(error);
      });
  });
};

const initRoleList = () => {
  getRecommendRoleListLocal()
    .then((res) => {
      // hideLoading();
      setResList(res);
      // setLoading(false);
      // 优化闪现暂无角色
      setTimeout(() => {
        setLoading(false);
      }, 200);
    })
    .catch((error) => {
      // hideLoading();
      setLoading(false);
    });
};

切换绑定角色

功能说明

点击列表 item,切换当前角色。

相关代码段

const handleItemChecked = async (roleId: string, item: any) => {
  // TODO 切换当前绑定的角色
  // bindRoleType 0-自定义智能体角色,1-智能体角色模板,2-单角色场景默认角色
  const params = { roleId, bindRoleType: tag === "custom" ? 0 : 1 };
  postBindRoleLocal(params)
    .then(() => {
      dispatch(updateRoleInfo({ roleId }));
      // 切换完需要刷一下首页的数据
      emitter.emit("refreshDialogData", "");
      navigateBack({ delta: 1 });
    })
    .catch((error) => {
      console.log(error);
    });
};

删除自定义角色

相关代码段

const deleteAIRole = (roleId: string) => {
  showLoading({
    title: "",
  });
  deleteAIAgentRoles(roleId)
    .then(() => {
      hideLoading();
      showToast({
        title: Strings.getLang("dsc_delete_success"),
        icon: "success",
      });
      // 删除后刷新自定义列表
      initData("");
    })
    .catch((err) => {
      hideLoading();
      console.log("deleteAIAgentRoles::err::", err);
      showToast({
        title: Strings.getLang("dsc_delete_fail"),
        icon: "error",
      });
    });
  setUnbindId("-1");
  setIsShowUnbindConfirm(false);
};

页面介绍

角色新增/编辑页面主要用于修改角色信息(头像、名称,角色介绍、记忆体),以及选择音色、语种、和大模型。

获取角色模板列表/模板详情

功能说明

B 端可以预设一些模板,提供给用户选择,简化用户操作流程。

相关代码段

//获取角色模板列表
const getTemplateList = async () => {
  if (source === "createRole") {
    return;
  }
  getAIAgentRolesTemplateList()
    .then((res: any) => {
      console.log("==getTemplateList", res);
      setTemplateList(res);
      if (res?.length > 0) {
        setTemplateRoleId(res[0].roleId);
      }
    })
    .catch((err) => {
      console.log("getTemplateList::err::", err);
    });
};
//获取角色模板详情
const getTemplateListDetail = async (
  roleId: string,
  onlyReduxUpdate?: boolean
) => {
  if (CustomAgentEditForbiddenGetDetail.current) return;
  getCommonRoleDetailLocal(roleId)
    .then((res: any) => {
      console.log("==getTemplateListDetail", res);
      if (onlyReduxUpdate) {
        dispatch(initRoleDetail(res));
      } else {
        initRoleData(res);
        initRoleInfoData();
      }
    })
    .catch((err) => {
      console.log("getTemplateListDetail::err::", err, roleId);
    });
};

获取角色详情

功能说明

编辑角色时,获取当前角色详情。

相关代码段

const getAgentRoleDetail = async (
  roleId: string,
  onlyReduxUpdate?: boolean
) => {
  if (CustomAgentEditForbiddenGetDetail.current) return;
  getCustomRoleDetailLocal(roleId)
    .then((res: any) => {
      console.log("==getCustomRoleDetailLocal", res);
      if (onlyReduxUpdate) {
        dispatch(initRoleDetail(res));
      } else {
        initRoleData(res);
        initRoleInfoData();
      }
    })
    .catch((err) => {
      console.log("getCustomRoleDetailLocal::err::", err);
    });
};

创建/编辑角色

功能说明

创建/编辑角色。

相关代码段

// 创建或者编辑角色后,刷新自定义角色列表

/* 编辑角色
  * 切换列表的编辑:
  * 1.自定义角色:编辑自定义角色接口 --编辑后刷新列表✅
  * 2.推荐角色:创建模板角色接口--创建完跳转到自定义角色 tag✅
  * 从首页点进来的编辑:
  * 1.自定义角色 编辑自定义角色接口 --编辑后刷新首页✅
  * 2.推荐角色 创建模板角色接口--创建完跳转到自定义角色 tag✅
  * 创建角色
  * 1.都默认填充✅
  * 2.根据顶部的tag类型来判断 创建模板角色接口还是创建自定义角色接口✅
  */
try {
  showLoading({
    title: "",
  });
  setLoading(true);
  if (roleId) {
    params.roleId = roleId;
    params.speed = roleDetail?.speed || 33;
    params.tone = roleDetail?.tone || 33;
    console.log("roleDetail::1", roleDetail);
    await postUpdateCustomRoleLocal(params);
    setTimeout(() => {
      emitter.emit("refreshRoleList", "");
    }, 500);
  } else if (templateRoleId && source !== "createRole") {
    params.roleId = templateRoleId;
    params.speed = roleDetail?.speed || 33;
    params.tone = roleDetail?.tone || 33;
    console.log("roleDetail::2", roleDetail);
    // delete params?.roleImgUrl;
    if (needBind === "true") {
      params.needBind = true;
    }
    await postCreateRoleFromTemplateLocal(params);
    setTimeout(() => {
      emitter.emit("refreshRoleList", { toCustomTab: true });
    }, 500);
  } else if (source === "createRole") {
    params.speed = roleDetail?.speed || 33;
    params.tone = roleDetail?.tone || 33;
    console.log("roleDetail::3", roleDetail);
    await postCreateCustomRoleLocal(params);
    setTimeout(() => {
      emitter.emit("refreshRoleList", { toCustomTab: true });
    }, 500);
  }

  showToast({
    title: Strings.getLang("save_success"),
    icon: "success",
  });
  // 首页进入编辑角色后,刷新首页
  emitter.emit("refreshDialogData", "");
  navigateBack({ delta: 1 });
  setTimeout(() => {
    hideLoading();
    setLoading(false);
  }, 500);
} catch (error) {
  hideLoading();
  setLoading(false);
  if (platform === "android") {
    showToast({
      title: error?.innerError?.errorMsg,
      icon: "error",
    });
  } else if (platform === "ios") {
    showToast({
      title: iOSExtractErrorMessage(error?.innerError?.errorMsg),
      icon: "error",
    });
  }
}

获取角色头像

功能说明

B 端可以预设一些头像,提供给用户选择。

相关代码段

// 头像
const getBoundAgentsFunc = async () => {
  getAvatarListLocal()
    .then((res) => {
      console.log("getAIAvatars::", res);
      setAvatarList(res);
    })
    .catch((err) => {
      console.log("getAIAvatars::err::", err);
    });
};

useEffect(() => {
  getBoundAgentsFunc();
}, []);

获取语言语种

功能说明

获取支持的语言语种。

相关代码段

// 获取支持的语言语种
const useAgentLanguages = (id: number) => {
  const [langRangeList, setSupportLangs] = useState<Array<{ key: string; dataString: string }>>([]);

  useEffect(() => {
    const fetchSupportedLangs = async () => {
      try {
        const response = await getLanguageListLocal();
        if (response) {
          setSupportLangs(
            response?.map(item => ({
              dataString: item?.langName,
              key: item?.langCode,
            }))
          );
        }
      } catch (error) {
        console.error('Failed to fetch supported languages:', error);
      }
    };

    fetchSupportedLangs();
  }, []);

  return { langRangeList };
};

import useAgentLanguages from '@/hooks/useAgentLanguages';
const { langRangeList } = useAgentLanguages(id);

获取大模型列表

功能说明

获取大模型列表。

相关代码段

// 根据查询到的最新模型列表,判断模型如何显示
const response = await getModelListLocal();
let models = [];
if (response) {
  models = response?.map((model) => ({
    key: model.llmId,
    dataString: model.llmName,
  }));
}

页面介绍

音色管理页面主要用于切换智能体角色所携带的音色信息,主要包含系统默认音色管理。

音色广场列表

功能说明

音色广场列表主要用于展示系统默认音色列表,C 端用户可在广场内挑选适合自己的音色内容赋能给智能体角色。在筛选音色方面,模板支持分类筛选、搜索筛选功能。

相关代码段

// 音色列表请求函数
const getVoiceListFunc = (params: GetListParams) => {
  return new Promise((resolve, reject) => {
    getStandardVoiceList({
      pageNo: params.current,
      pageSize: params.pageSize,
      tag,
      agentId,
      keyWord: params.searchText,
      lang: selectedLang,
    })
      .then((res: VoiceRes) => {
        const { totalPage, list = [] } = res;
        hideLoading();
        setLoading(false);
        resolve({
          total: totalPage,
          list,
        });
      })
      .catch((error) => {
        hideLoading();
        setLoading(false);
        reject(error);
      });
  });
};
// 音色列表请求管理
const { pagination, data, run } = usePagination(
  ({ current, pageSize, searchText }) =>
    getVoiceListFunc({
      current,
      pageSize,
      searchText,
    }) as Promise<GetStandardVoice>,
  {
    manual: true,
  }
);
// 响应懒加载
useEffect(() => {
  if (data?.list) {
    pagination.current > 1
      ? dispatch(updateVoiceList([...data?.list]))
      : dispatch(initVoiceList([...data?.list]));
  }
}, [data]);

音色搜索

相关代码段

// 搜索与查询智能体列表接口请求流程相同,区别在于【searchText】字段的不同,拉取整体列表使【searchText】字段为空字符串
const { pagination, data, run } = usePagination(
  ({ current, pageSize, searchText }) =>
    getVoiceListFunc({ current, pageSize, searchText }) as Promise<GetStandardVoice>,
  {
    manual: true,
  }
);

音色切换

相关代码段

// 切换音色(编辑智能体详情)
const handleItemChecked = async (idKey: string, item: any) => {
  try {

    playVoiceAudio(item?.demoUrl);

    dispatch(
      updateRoleInfo({
        voiceId: idKey,
        voiceName: item?.voiceName,
        supportLangs: item?.supportLangs,
      })
    );
    // 创建模式时,发送这个事件,避免RoleDetail更新后引起CustomAgentEdit的getTemplateListDetail错误更新
    emitter.emit("CustomAgentEditForbiddenGetDetail", true);
    setTimeout(() => {
      dispatch(initRoleDetail({ ...roleDetail, speed: item?.speed, tone: item?.tone }));
    }, 50);

  } catch (err) {
    hideLoading();
  }
};

编辑语速

相关代码段

// 编辑智能体详情(语调、语速为智能体详情信息)
const onChangeToneOrSpeed = (sv: number, tv: number) => {
  if (!isEditMode) {
    // 创建模式时,发送这个事件,避免RoleDetail更新后引起CustomAgentEdit的getTemplateListDetail错误更新
    emitter.emit("CustomAgentEditForbiddenGetDetail", true);
    setTimeout(() => {
      dispatch(initRoleDetail({ ...roleDetail, speed: sv }));
    }, 50);
    return;
  }
  showLoading({
    title: "",
  });
  postUpdateCustomRoleLocal({
    roleId,
    [speedKey]: `${sv}`,
    // [toneKey]: `${tv}`,
  })
    .then(async (res) => {
      sv >= 0 && dispatch(initRoleDetail({ ...roleDetail, speed: sv }));
      // tv >= 0 && setToneValue(tv);
      hideLoading();
      showToast({
        title: Strings.getLang("dsc_edit_success"),
        icon: "success",
      });
    })
    .catch(() => {
      hideLoading();
      showToast({
        title: Strings.getLang("dsc_edit_fail"),
        icon: "error",
      });
    });
};

页面介绍

角色会话记录展示页主要用于展示 C 端用户与智能体角色的对话记录,当 C 端用户暂未与智能体产生对话内容时,模板将会展示空内容提示图文。

相关代码段

// 获取角色会话记录
const fetchHistoryData = useCallback(
  async (gmtEnd: number, isRefresh = false) => {
    if ((loadingUpper && !isRefresh) || (loadingLower && isRefresh)) return;

    try {
      if (isRefresh) {
        setLoadingLower(true);
      } else {
        setLoadingUpper(true);
      }

      const response = await fetchPanelAgentChatHistory({
        devId: getDevInfo().devId,
        bindRoleType: bindAgentRole?.bindRoleType,
        roleId: bindAgentRole?.roleId,
        gmtEnd,
        fetchSize: 10,
        timeAsc: false,
      });

      setRefresherTriggeredState(false);

      if (response && response.length > 0) {
        // 找到最旧的时间戳
        const oldestTime = Math.min(
          ...response.map((item) => item.gmtCreate)
        );
        oldestGmtCreate.current = oldestTime;

        // 处理数据:添加 parsedTime 字段
        const processedList = response
          .map((item) => ({
            ...item,
            parsedTime: formatTimeByTimezone(item.gmtCreate, timezoneId),
          }))
          .filter((item) => item.parsedTime !== null);

        if (isRefresh) {
          // 刷新时,累加数据到列表后面(最新的数据),按时间正序排序(最旧的在前,最新的在后)
          setHistoryList((prev) => {
            const combined = [...prev, ...processedList];
            const uniqList = _.uniqBy(combined, "requestId");
            const sortedList = uniqList.sort(
              (a, b) => a.gmtCreate - b.gmtCreate
            );
            // 更新最旧时间戳为列表中最旧的时间
            if (sortedList.length > 0) {
              oldestGmtCreate.current = sortedList[0].gmtCreate;
            }
            return sortedList;
          });
        } else {
          // 上拉加载时,追加到列表前面(更旧的数据)
          setHistoryList((prev) => {
            const combined = [...processedList, ...prev];
            const uniqList = _.uniqBy(combined, "requestId");
            return uniqList.sort((a, b) => a.gmtCreate - b.gmtCreate);
          });
        }

        // 查询到数据后,再定位
        setTimeout(() => {
          setEmptyIdState("bottomView");
        }, 500);
      } else {
        // 没有更多数据
        // if (!isRefresh) {
        //   showToast({
        //     title: "没有更多数据",
        //     icon: "none",
        //   });
        // }
      }
    } catch (error: any) {
      setRefresherTriggeredState(false);
      if (platform === "android") {
        showToast({
          title: error?.innerError?.errorMsg || error?.errorMsg,
          icon: "error",
        });
      } else if (platform === "ios") {
        showToast({
          title: error?.innerError?.errorMsg
            ? iOSExtractErrorMessage(error?.innerError?.errorMsg)
            : error?.errorMsg,
          icon: "error",
        });
      }
    } finally {
      setLoadingUpper(false);
      setLoadingLower(false);
    }
  },
  [loadingUpper, loadingLower, bindAgentRole, platform, timezoneId]
);

删除上下文

功能说明

该功能主要用于删除一组或多组角色的聊天信息。

相关代码段

// 删除上下文接口 clearAgentHistoryMessage
const handleDeleteMessage = async (requestIds?: string) => {
  try {
    showLoading({ title: "" });
    await clearAgentHistoryMessage({
      bindRoleType: bindAgentRole?.bindRoleType,
      roleId: bindAgentRole?.roleId,
      requestIds: requestIds || selectedItems?.join(","),
      clearAllHistory: false,
    });

    const newList = historyList.filter(
      (item) =>
        !selectedItems.includes(item.requestId) &&
        item.requestId !== requestIds
    );
    setHistoryList(newList);

    hideLoading();
    showToast({
      title: Strings.getLang("dsc_delete_chat_history_tip_new"),
      icon: "success",
    });
  } catch (err) {
    hideLoading();
    showToast({
      title: Strings.getLang("dsc_delete_chat_history_failed"),
      icon: "error",
    });
  }
};

页面介绍

主要用管理角色记忆相关内容,包括清除聊天记录、清除临时记忆、格式记忆、对话总结和清除全部长期记忆等功能

清除聊天记录

相关代码段

const handleClickDialog = (message: string, type: string) => {
  DialogInstance.confirm({
    selector: `#smart-dialog-edit`,
    message,
    cancelButtonText: Strings.getLang("cancel"),
    confirmButtonText: Strings.getLang("confirm"),
  })
    .then(() => {
      // 清除聊天记录
      if (type === "clear_chat_history_all") {
        clearingHistoryRecord({
          bindRoleType:
            roleMemoryEntry === "custom" ? 0 : bindAgentRole?.bindRoleType,
          roleId: roleDetail?.roleId || bindAgentRole?.roleId,
          clearAllHistory: true,
        })
          .then(() => {
            showToast({
              title: Strings.getLang("dsc_delete_chat_history_tip"),
              icon: "success",
            });
          })
          .catch(() => {
            showToast({
              title: Strings.getLang("dsc_delete_chat_history_failed"),
              icon: "error",
            });
          });
      }
      // 清除临时记忆
      if (type === "clear_context") {
        clearingContext({
          bindRoleType:
            roleMemoryEntry === "custom" ? 0 : bindAgentRole?.bindRoleType,
          roleId: roleDetail?.roleId || bindAgentRole?.roleId,
        })
          .then(() => {
            showToast({
              title: Strings.getLang("clear_context_success"),
              icon: "success",
            });
          })
          .catch(() => {
            showToast({
              title: Strings.getLang("clear_context_failed"),
              icon: "error",
            });
          });
      }
      // 清除全部长期记忆
      if (type === "clear_memory") {
        clearingMemory({
          bindRoleType:
            roleMemoryEntry === "custom" ? 0 : bindAgentRole?.bindRoleType,
          roleId: roleDetail?.roleId || bindAgentRole?.roleId,
          clearAllMemory: true,
        })
          .then(() => {
            showToast({
              title: Strings.getLang("clear_memory_success"),
              icon: "success",
            });
          })
          .catch(() => {
            showToast({
              title: Strings.getLang("clear_memory_failed"),
              icon: "error",
            });
          });
      }
    })
    .catch(() => {
      console.log("cancel");
    });
};


格式记忆

功能说明

该功能主要用于展示角色记忆和家庭共享记忆,支持删除记忆。

相关代码段

// 获取记忆
const getPanelMemoryListData = async () => {
  const params = {
    bindRoleType:
      roleMemoryEntry === "custom" ? 0 : bindAgentRole?.bindRoleType,
    roleId: roleDetail?.roleId || bindAgentRole?.roleId,
  };
  getPanelMemoryListLocal(params)
    .then((res: any) => {
      setMemoryList(res);
    })
    .catch((err) => {
      console.log("getMemorySwitchLocal::err::", err);
    });
};
// 删除记忆
const handleDeleteMemory = (memoryKey) => {
  clearingMemory({
    bindRoleType:
      roleMemoryEntry === "custom" ? 0 : bindAgentRole?.bindRoleType,
    roleId: roleDetail?.roleId || bindAgentRole?.roleId,
    memoryKeys: memoryKey,
    clearAllMemory: false,
  })
    .then(() => {
      // 删除后刷新
      getPanelMemoryListData();
    })
    .catch((error) => {
      showToast({
        title: error?.innerError?.errorMsg,
        icon: "error",
      });
    });
};

对话总结

功能说明

该功能主要用于展示并且删除对话总结。

相关代码段

// 获取对话总结
const getChatMemoryListData = async () => {
  const params = {
    bindRoleType:
      roleMemoryEntry === "custom" ? 0 : bindAgentRole?.bindRoleType,
    roleId: roleDetail?.roleId || bindAgentRole?.roleId,
  };
  getChatMemoryListLocal(params)
    .then((res: any) => {
      setSummaryList(res);
    })
    .catch((err) => {
      console.log("getMemorySwitchLocal::err::", err);
    });
};
// 删除对话总结
const handleDeleteMemory = (memoryKey) => {
  const leftMemoryList = summaryList?.filter((item) => item !== memoryKey);
  const params = {
    bindRoleType:
      roleMemoryEntry === "custom" ? 0 : bindAgentRole?.bindRoleType,
    roleId: roleDetail?.roleId || bindAgentRole?.roleId,
    summaryItems: leftMemoryList,
  };

  postUpdateChatMemoryListLocal(params).then(() => {
    // 删除后刷新
    getChatMemoryListData();
  });
};