* publish 0.2.10 (#2797) 新功能: - 优化 PDF 文件的 OCR,过滤无意义的小图片 by @liunux4odoo #2525 - 支持 Gemini 在线模型 by @yhfgyyf #2630 - 支持 GLM4 在线模型 by @zRzRzRzRzRzRzR - elasticsearch更新https连接 by @xldistance #2390 - 增强对PPT、DOC知识库文件的OCR识别 by @596192804 #2013 - 更新 Agent 对话功能 by @zRzRzRzRzRzRzR - 每次创建对象时从连接池获取连接,避免每次执行方法时都新建连接 by @Lijia0 #2480 - 实现 ChatOpenAI 判断token有没有超过模型的context上下文长度 by @glide-the - 更新运行数据库报错和项目里程碑 by @zRzRzRzRzRzRzR #2659 - 更新配置文件/文档/依赖 by @imClumsyPanda @zRzRzRzRzRzRzR - 添加日文版 readme by @eltociear #2787 修复: - langchain 更新后,PGVector 向量库连接错误 by @HALIndex #2591 - Minimax's model worker 错误 by @xyhshen - ES库无法向量检索.添加mappings创建向量索引 by MSZheng20 #2688 * Update README.md * Add files via upload * Update README.md * 修复PDF旋转的BUG * Support Chroma * perf delete unused import * 忽略测试代码 * 更新文件 * API前端丢失问题解决 * 更新了chromadb的打印的符号 * autodl代号错误 * Update README.md * Update README.md * Update README.md * 修复milvus相关bug * 支持星火3.5模型 * 修复es 知识库查询bug (#2848) * 修复es 知识库查询bug (#2848) * 更新zhipuai请求方式 * 增加对 .htm 扩展名的显式支持 * 更新readme * Docker镜像制作与K8S YAML部署操作说明 (#2892) * Dev (#2280) * 修复Azure 不设置Max token的bug * 重写agent 1. 修改Agent实现方式,支持多参数,仅剩 ChatGLM3-6b和 OpenAI GPT4 支持,剩余模型将在暂时缺席Agent功能 2. 删除agent_chat 集成到llm_chat中 3. 重写大部分工具,适应新Agent * 更新架构 * 删除web_chat,自动融合 * 移除所有聊天,都变成Agent控制 * 更新配置文件 * 更新配置模板和提示词 * 更改参数选择bug * 修复模型选择的bug * 更新一些内容 * 更新多模态 语音 视觉的内容 1. 更新本地模型语音 视觉多模态功能并设置了对应工具 * 支持多模态Grounding 1. 美化了chat的代码 2. 支持视觉工具输出Grounding任务 3. 完善工具调用的流程 * 支持XPU,修改了glm3部分agent * 添加 qwen agent * 对其ChatGLM3-6B与Qwen-14B * fix callback handler * 更新Agent工具返回 * fix: LLMChain no output when no tools selected * 跟新了langchain 0.1.x需要的依赖和修改的代码 * 更新chatGLM3 langchain0.1.x Agent写法 * 按照 langchain 0.1 重写 qwen agent * 修复 callback 无效的问题 * 添加文生图工具 * webui 支持文生图 * 集成openai plugins插件 * 删除fastchat的配置 * 增加openai插件 * 集成openai plugins插件 * 更新模型执行列表和今晚修改的内容 * 集成openai_plugins/imitater插件 * 集成openai_plugins/imitater插件 * 集成openai_plugins/imitater插件 * 减少错误的显示 * 标准配置 * vllm参数配置 * 增加智谱插件 * 删除本地fschat配置 * 删除本地fschat配置,pydantic升级到2 * 删除本地fschat workers * openai-plugins-list.json * 升级agent,pydantic升级到2 * fix model_config是系统关键词问题 * embeddings模块集成openai plugins插件,使用统一api调用 * loom模型服务update_store更新逻辑 * 集成LOOM在线embedding业务 * 本地知识库搜索字段修改 * 知识库在线api接入点配置在线api接入点配置更新逻辑 * Update model_config.py.example * 修改模型配置方式,所有模型以 openai 兼容框架的形式接入,chatchat 自身不再加载模型。 改变 Embeddings 模型改为使用框架 API,不再手动加载,删除自定义 Embeddings Keyword 代码 修改依赖文件,移除 torch transformers 等重依赖 暂时移出对 loom 的集成 后续: 1、优化目录结构 2、检查合并中有无被覆盖的 0.2.10 内容 * move document_loaders & text_splitter under server * make torch & transformers optional import pydantic Model & Field from langchain.pydantic_v1 instead of pydantic.v1 * - pydantic 限定为 v1,并统一项目中所有 pydantic 导入路径,为以后升级 v2 做准备 - 重构 api.py: - 按模块划分为不同的 router - 添加 openai 兼容的转发接口,项目默认使用该接口以实现模型负载均衡 - 添加 /tools 接口,可以获取/调用编写的 agent tools - 移除所有 EmbeddingFuncAdapter,统一改用 get_Embeddings - 待办: - /chat/chat 接口改为 openai 兼容 - 添加 /chat/kb_chat 接口,openai 兼容 - 改变 ntlk/knowledge_base/logs 等数据目录位置 * 移除 llama-index 依赖;修复 /v1/models 错误 * 原因:windows下启动失败提示补充python-multipart包 (#3184) 改动:requirements添加python-multipart==0.0.9 版本:0.0.9 Requires: Python >=3.8 Co-authored-by: XuCai <liangxc@akulaku.com> * 添加 xinference 本地模型和自定义模型配置 UI: streamlit run model_loaders/xinference_manager.py * update xinference manager ui * fix merge conflict * model_config 中补充 oneapi 默认在线模型;/v1/models 接口支持 oneapi 平台,统一返回模型列表 * 重写 calculate 工具 * 调整根目录结构,kb/logs/media/nltk_data 移动到专用数据目录(可配置,默认 data)。注意知识库文件要做相应移动 * update kb_config.py.example * 优化 ES 知识库 - 开发者 - get_OpenAIClient 的 local_wrap 默认值改为 False,避免 API 服务未启动导致其它功能受阻(如Embeddings) - 修改 ES 知识库服务: - 检索策略改为 ApproxRetrievalStrategy - 设置 timeout 为 60, 避免文档过多导致 ConnecitonTimeout Error - 修改 LocalAIEmbeddings,使用多线程进行 embed_texts,效果不明显,瓶颈可能主要在提供 Embedding 的服务器上 * 修复glm3 agent被注释的agent会话文本结构解析代码 看起来输出的文本占位符如下,目前解析代码是有问题的 Thought <|assistant|> Action\r ```python tool_call(action_input) ```<|observation|> * make qwen agent work with langchain>=0.1 (#3228) * make xinference model manager support xinference 0.9.x * 使用多进程提高导入知识库的速度 (#3276) * xinference的代码 先传 我后面来改 * Delete server/xinference directory * Create khazic * diiii diii * Revert "xinference的代码" * fix markdown header split (#1825) (#3324) * dify model_providers configuration This module provides the interface for invoking and authenticating various models, and offers Dify a unified information and credentials form rule for model providers. * fix merge conflict: langchain Embeddings not imported in server.utils * 添加 react 编写的新版 WEBUI (#3417) * feat:提交前端代码 * feat:提交logo样式切换 * feat:替换avatar、部分位置icon、chatchat相关说明、git链接、Wiki链接、关于、设置、反馈与建议等功能,关闭lobehub自检更新功能 * fix:移除多余代码 --------- Co-authored-by: liunux4odoo <41217877+liunux4odoo@users.noreply.github.com> * model_providers bootstrap * model_providers bootstrap * update to pydantic v2 (#3486) * 使用poetry管理项目 * 使用poetry管理项目 * dev分支解决pydantic版本冲突问题,增加ollama配置,支持ollama会话和向量接口 (#3508) * dev分支解决pydantic版本冲突问题,增加ollama配置,支持ollama会话和向量接口 1、因dev版本的pydantic升级到了v2版本,由于在class History(BaseModel)中使用了from server.pydantic_v1,而fastapi的引用已变为pydantic的v2版本,所以fastapi用v2版本去校验用v1版本定义的对象,当会话历史histtory不为空的时候,会报错:TypeError: BaseModel.validate() takes 2 positional arguments but 3 were given。经测试,解方法为在class History(BaseModel)中也使用v2版本即可; 2、配置文件参照其它平台配置,增加了ollama平台相关配置,会话模型用户可根据实际情况自行添加,向量模型目前支持nomic-embed-text(必须升级ollama到0.1.29以上)。 3、因ollama官方只在会话部分对openai api做了兼容,向量api暂未适配,好在langchain官方库支持OllamaEmbeddings,因而在get_Embeddings方法中添加了相关支持代码。 * 修复 pydantic 升级到 v2 后 DocumentWithVsID 和 /v1/embeddings 兼容性问题 --------- Co-authored-by: srszzw <srszzw@163.com> Co-authored-by: liunux4odoo <liunux@qq.com> * 对python的要求降级到py38 * fix bugs; make poetry using tsinghua mirror of pypi * update gitignore; remove unignored files * update wiki sub module * 20240326 * 20240326 * qqqq * 删除历史文件 * 移动项目模块 * update .gitignore; fix model version error in api_schemas * 封装ModelManager * - 重写 tool 部分: (#3553) - 简化 tool 的定义方式 - 所有 tool 和 tool_config 支持热加载 - 修复:json_schema_extra warning * 使用yaml加载用户配置适配器 * 格式化代码 * 格式化 * 优化工具定义;添加 openai 兼容的统一 chat 接口 (#3570) - 修复: - Qwen Agent 的 OutputParser 不再抛出异常,遇到非 COT 文本直接返回 - CallbackHandler 正确处理工具调用信息 - 重写 tool 定义方式: - 添加 regist_tool 简化 tool 定义: - 可以指定一个用户友好的名称 - 自动将函数的 __doc__ 作为 tool.description - 支持用 Field 定义参数,不再需要额外定义 ModelSchema - 添加 BaseToolOutput 封装 tool 返回结果,以便同时获取原始值、给LLM的字符串值 - 支持工具热加载(有待测试) - 增加 openai 兼容的统一 chat 接口,通过 tools/tool_choice/extra_body 不同参数组合支持: - Agent 对话 - 指定工具调用(如知识库RAG) - LLM 对话 - 根据后端功能更新 webui * 修复:search_local_knowledge_base 工具返回值错误;/tools 路由错误;webui 中“正在思考”一直显示 (#3571) * 添加 openai 兼容的 files 接口 (#3573) * 使用BootstrapWebBuilder适配RESTFulOpenAIBootstrapBaseWeb加载 * 格式化和代码检查说明 * 模型列表适配 * make format * chat_completions接口报文适配 * make format * xinference 插件示例 * 一些默认参数 * exec path fix * 解决ollama部署的qwen,执行agent,返回的json格式不正确问题。 * provider_configuration.py 查询所有的平台信息,包含计费策略和配置schema_validators(参数必填信息校验规则) /workspaces/current/model-providers 查询平台模型分类的详细默认信息,包含了模型类型,模型参数,模型状态 workspaces/current/models/model-types/{model_type} * 开发手册 * 兼容model_providers,集成webui及API中平台配置的初始化 (#3625) * provider_configuration init of MODEL_PLATFORMS * 开发手册 * 兼容model_providers,集成webui及API中平台配置的初始化 * Dev model providers (#3628) * gemini 初始化参数问题 * gemini 同步工具调用 * embedding convert endpoint * 修复 --api -w命令 * /v1/models 接口返回值由 List[Model] 改为 {'data': List[Model]},兼容最新版 xinference * 3.8兼容 (#3769) * 增加使用说明 * 3.8兼容性配置 * fix * formater * 不同平台兼容测试用例 * embedding兼容 * 增加日志信息 * pip源仓库设置,一些版本问题,启动说明 配置说明 (#3854) * 仓库设置,一些版本问题 * pip源仓库设置,一些版本问题,启动说明 * 配置说明 * 泛型标记错误 (#3855) * 仓库设置,一些版本问题 * pip源仓库设置,一些版本问题,启动说明 * 配置说明 * 发布的依赖信息 * 泛型标记错误 * 泛型标记错误 * CICD github action build publish pypi、Release Tag (#3886) * 测试用例 * CICD 流程 * CICD 流程 * CICD 流程 * 一些agent数据处理的问题,model_runtime模块的说明文档 (#3943) * 一些agent数据出来的问题 * Changes: - Translated and updated the Model Runtime documentation to reflect the latest changes and features. - Clarified the decoupling benefits of the Model Runtime module from the Chatchat service. - Removed outdated information regarding the model configuration storage module. - Detailed the retained functionalities post-removal of the Dify configuration page. - Provided a comprehensive overview of the Model Runtime's three-layered structure. - Included the status of the `fetch-from-remote` feature and its non-implementation in Dify. - Added instructions for custom service provider model capabilities. * - 新功能 (#3944) - streamlit 更新到 1.34,webui 支持 Dialog 操作 - streamlit-chatbox 更新到 1.1.12,更好的多会话支持 - 开发者 - 在 API 中增加项目图片路由(/img/{file_name}),方便前端使用 * 修改包名 * 修改包信息 * ollama配置解析问题 * 用户配置动态加载 (#3951) * version = "0.3.0.20240506" * version = "0.3.0.20240506" * version = "0.3.0.20240506" * version = "0.3.0.20240506" * 启动说明 * 一些bug * 修复了一些配置重载的bug * 配置的加载行为修改 * 配置的加载行为修改 * agent代码优化 * ollama 代码升级,使用openai协议 * 支持deepseek客户端 * contributing (#4043) * 添加了贡献说明 docs/contributing,包含了一些代码仓库说明和开发规范,以及在model_providers下面编写了一些单元测试的示例 * 关于providers的配置说明 * python3.8兼容 * python3.8兼容 * ollama兼容 * ollama兼容 * 一些兼容 pydantic<3,>=1.9.0 的代码, * 一些兼容 pydantic<3,>=1.9.0 model_config 的代码, * make format * test * 更新版本 * get_img_base64 * get_img_base64 * get_img_base64 * get_img_base64 * get_img_base64 * 统一模型类型编码 * 向量处理问题 * 优化目录结构 (#4058) * 优化目录结构 * 修改一些测试问题 --------- Co-authored-by: glide-the <2533736852@qq.com> * repositories * 调整日志 * 调整日志zdf * 增加可选依赖extras * feat:Added some documentation. (#4085) * feat:Added some documentation. * feat:Added some documentation. * feat:Added some documentation. --------- Co-authored-by: yuehuazhang <yuehuazhang@tencent.com> * fix code.md typos * fix chatchat-server/pyproject.toml typos * feat:README (#4118) Co-authored-by: yuehuazhang <yuehuazhang@tencent.com> * 初始化数据库集成model_providers * 关闭守护进程 * 1、修改知识库列表接口,返回全量属性字段,同时修改受影响的相关代码。 (#4119) 2、run_in_process_pool改为run_in_thread_pool,解决兼容性问题。 3、poetry配置文件修复。 * 动态更新Prompt中的知识库描述信息,使大模型更容易判断使用哪个知识库。 (#4121) * 1、修改知识库列表接口,返回全量属性字段,同时修改受影响的相关代码。 2、run_in_process_pool改为run_in_thread_pool,解决兼容性问题。 3、poetry配置文件修复。 * 1、动态更新Prompt中的知识库描述信息,使大模型更容易判断使用哪个知识库。 * fix: 补充 xinference 配置信息 (#4123) * feat:README * feat:补充 xinference 平台 llm 和 embedding 模型配置. --------- Co-authored-by: yuehuazhang <yuehuazhang@tencent.com> * 知识库工具的下拉列表改为动态获取,不必重启服务。 (#4126) * 1、知识库工具的下拉列表改为动态获取,不必重启服务。 * update README and imgs * update README and imgs * update README and imgs * update README and imgs * 修改安装说明描述问题 * make formater * 更新版本"0.3.0.20240606 * Update code.md * 优化知识库相关功能 (#4153) - 新功能 - pypi 包新增 chatchat-kb 命令脚本,对应 init_database.py 功能 - 开发者 - _model_config.py 中默认包含 xinference 配置项 - 所有涉及向量库的操作,前置检查当前 Embed 模型是否可用 - /knowledge_base/create_knowledge_base 接口增加 kb_info 参数 - /knowledge_base/list_files 接口返回所有数据库字段,而非文件名称列表 - 修正 xinference 模型管理脚本 * 消除警告 * 一些依赖问题 * 增加text2sql工具,支持特定表、智能判定表,支持对表名进行额外说明 (#4154) * 1、增加text2sql工具,支持特定表、智能判定表,支持对表名进行额外说明 * 支持SQLAlchemy大部分数据库、新增read-only模式,提高安全性、增加text2sql使用建议 (#4155) * 1、修改text2sql连接配置,支持SQLAlchemy大部分数据库; 2、新增read-only模式,若有数据库写保护需求,会从大模型判断、SQLAlchemy拦截器两个层面进行写拦截,提高安全性; 3、增加text2sql使用建议; * dotenv * dotenv 配置 * 用户工作空间操作 (#4156) 工作空间的配置预设,提供ConfigBasic建造方法产生实例。 该类的实例对象用于存储工作空间的配置信息,如工作空间的路径等 工作空间的配置信息存储在用户的家目录下的.config/chatchat/workspace/workspace_config.json文件中。 注意:不存在则读取默认 提供了操作入口 指令` chatchat-config` 工作空间配置 options: ``` -h, --help show this help message and exit -v {true,false}, --verbose {true,false} 是否开启详细日志 -d DATA, --data DATA 数据存放路径 -f FORMAT, --format FORMAT 日志格式 --clear 清除配置 ``` * 配置路径问题 * fix faiss_cache bug * Feature(File RAG): add file_rag in chatchat-server, add ensemble retriever and vectorstore retriever. * Feature(File RAG): add file_rag in chatchat-server, add ensemble retriever and vectorstore retriever. * fix xinference manager bug * Fix(File RAG): use jieba instead of cutword * Fix(File RAG): update kb_doc_api.py * 工作空间的配置预设,提供ConfigBasic建造 实例。 (#4158) - ConfigWorkSpace接口说明 ```text ConfigWorkSpace是一个配置工作空间的抽象类,提供基础的配置信息存储和读取功能。 提供ConfigFactory建造方法产生实例。 该类的实例对象用于存储工作空间的配置信息,如工作空间的路径等 工作空间的配置信息存储在用户的家目录下的.chatchat/workspace/workspace_config.json文件中。 注意:不存在则读取默认 ``` * 编写配置说明 * 编写配置说明 --------- Co-authored-by: liunux4odoo <41217877+liunux4odoo@users.noreply.github.com> Co-authored-by: glide-the <2533736852@qq.com> Co-authored-by: tonysong <tonysong@digitalgd.com.cn> Co-authored-by: songpb <songpb@gmail.com> Co-authored-by: showmecodett <showmecodett@gmail.com> Co-authored-by: zR <2448370773@qq.com> Co-authored-by: zqt <1178747941@qq.com> Co-authored-by: zqt996 <67185303+zqt996@users.noreply.github.com> Co-authored-by: fengyaojie <fengyaojie@xdf.cn> Co-authored-by: Hans WAN <hanswan@tom.com> Co-authored-by: thinklover <thinklover@gmail.com> Co-authored-by: liunux4odoo <liunux@qq.com> Co-authored-by: xucailiang <74602715+xucailiang@users.noreply.github.com> Co-authored-by: XuCai <liangxc@akulaku.com> Co-authored-by: dignfei <913015993@qq.com> Co-authored-by: Leb <khazzz1c@gmail.com> Co-authored-by: Sumkor <sumkor@foxmail.com> Co-authored-by: panhong <381500590@qq.com> Co-authored-by: srszzw <741992282@qq.com> Co-authored-by: srszzw <srszzw@163.com> Co-authored-by: yuehua-s <41819795+yuehua-s@users.noreply.github.com> Co-authored-by: yuehuazhang <yuehuazhang@tencent.com>
28 KiB
Complete Guide to LobeChat Feature Development
This document aims to guide developers on how to develop a complete feature requirement in LobeChat.
We will use the implementation of sessionGroup as an example: ✨ feat: add session group manager, and explain the complete implementation process through the following six main sections:
- Data Model / Database Definition
- Service Implementation / Model Implementation
- Frontend Data Flow Store Implementation
- UI Implementation and Action Binding
- Data Migration
- Data Import and Export
1. Database Section
To implement the Session Group feature, it is necessary to define the relevant data model and indexes at the database level.
Define a new sessionGroup table in 3 steps:
1. Establish Data Model Schema
Define the data model of DB_SessionGroup in src/database/schema/sessionGroup.ts:
import { z } from 'zod';
export const DB_SessionGroupSchema = z.object({
name: z.string(),
sort: z.number().optional(),
});
export type DB_SessionGroup = z.infer<typeof DB_SessionGroupSchema>;
2. Create Database Indexes
Since a new table needs to be added, an index needs to be added to the database schema for the sessionGroup table.
Add dbSchemaV4 in src/database/core/schema.ts:
// ... previous implementations
// ************************************** //
// ******* Version 3 - 2023-12-06 ******* //
// ************************************** //
// - Added `plugin` table
export const dbSchemaV3 = {
...dbSchemaV2,
plugins:
'&identifier, type, manifest.type, manifest.meta.title, manifest.meta.description, manifest.meta.author, createdAt, updatedAt',
};
+ // ************************************** //
+ // ******* Version 4 - 2024-01-21 ******* //
+ // ************************************** //
+ // - Added `sessionGroup` table
+ export const dbSchemaV4 = {
+ ...dbSchemaV3,
+ sessionGroups: '&id, name, sort, createdAt, updatedAt',
+ sessions: '&id, type, group, pinned, meta.title, meta.description, meta.tags, createdAt, updatedAt',
};
[!Note]
In addition to
sessionGroups, the definition ofsessionshas also been modified here due to data migration. However, as this section only focuses on schema definition and does not delve into the implementation of data migration, please refer to section five for details.
[!Important]
If you are unfamiliar with the need to create indexes here and the syntax of schema definition, you may need to familiarize yourself with the basics of Dexie.js. You can refer to the 📘 Local Database section for relevant information.
3. Add the sessionGroups Table to the Local DB
Extend the local database class to include the new sessionGroups table:
import { dbSchemaV1, dbSchemaV2, dbSchemaV3, dbSchemaV4 } from './schemas';
interface LobeDBSchemaMap {
files: DB_File;
messages: DB_Message;
plugins: DB_Plugin;
+ sessionGroups: DB_SessionGroup;
sessions: DB_Session;
topics: DB_Topic;
}
// Define a local DB
export class LocalDB extends Dexie {
public files: LobeDBTable<'files'>;
public sessions: LobeDBTable<'sessions'>;
public messages: LobeDBTable<'messages'>;
public topics: LobeDBTable<'topics'>;
public plugins: LobeDBTable<'plugins'>;
+ public sessionGroups: LobeDBTable<'sessionGroups'>;
constructor() {
super(LOBE_CHAT_LOCAL_DB_NAME);
this.version(1).stores(dbSchemaV1);
this.version(2).stores(dbSchemaV2);
this.version(3).stores(dbSchemaV3);
+ this.version(4).stores(dbSchemaV4);
this.files = this.table('files');
this.sessions = this.table('sessions');
this.messages = this.table('messages');
this.topics = this.table('topics');
this.plugins = this.table('plugins');
+ this.sessionGroups = this.table('sessionGroups');
}
}
As a result, you can now view the sessionGroups table in the LOBE_CHAT_DB in Application -> Storage -> IndexedDB.
2. Model and Service Section
Define Model
When building the LobeChat application, the Model is responsible for interacting with the database. It defines how to read, insert, update, and delete data from the database, as well as defining specific business logic.
In src/database/model/sessionGroup.ts, the SessionGroupModel is defined as follows:
import { BaseModel } from '@/database/core';
import { DB_SessionGroup, DB_SessionGroupSchema } from '@/database/schemas/sessionGroup';
import { nanoid } from '@/utils/uuid';
class _SessionGroupModel extends BaseModel {
constructor() {
super('sessions', DB_SessionGroupSchema);
}
async create(name: string, sort?: number, id = nanoid()) {
return this._add({ name, sort }, id);
}
// ... Implementation of other CRUD methods
}
export const SessionGroupModel = new _SessionGroupModel();
Service Implementation
In LobeChat, the Service layer is mainly responsible for communicating with the backend service, encapsulating business logic, and providing data to other layers in the frontend. SessionService is a service class specifically handling business logic related to sessions. It encapsulates operations such as creating sessions, querying sessions, and updating sessions.
To maintain code maintainability and extensibility, we place the logic related to session grouping in the SessionService. This helps to keep the business logic of the session domain cohesive. When business requirements increase or change, it becomes easier to modify and extend within this domain.
SessionService implements session group-related request logic by calling methods from SessionGroupModel. The following is the implementation of Session Group-related request logic in sessionService:
class SessionService {
// ... Omitted session business logic
// ************************************** //
// *********** SessionGroup *********** //
// ************************************** //
async createSessionGroup(name: string, sort?: number) {
const item = await SessionGroupModel.create(name, sort);
if (!item) {
throw new Error('session group create Error');
}
return item.id;
}
// ... Other SessionGroup related implementations
}
3. Store Action Section
In the LobeChat application, the Store module is used to manage the frontend state of the application. The Actions within it are functions that trigger state updates, usually by calling methods in the service layer to perform actual data processing operations and then updating the state in the Store. We use zustand as the underlying dependency for the Store module. For a detailed practical introduction to state management, you can refer to 📘 Best Practices for State Management.
sessionGroup CRUD
CRUD operations for session groups are the core behaviors for managing session group data. In src/store/session/slice/sessionGroup, we will implement the state logic related to session groups, including adding, deleting, updating session groups, and their sorting.
The following are the methods of the SessionGroupAction interface that need to be implemented in the action.ts file:
export interface SessionGroupAction {
// Add session group
addSessionGroup: (name: string) => Promise<string>;
// Remove session group
removeSessionGroup: (id: string) => Promise<void>;
// Update session group ID for a session
updateSessionGroupId: (sessionId: string, groupId: string) => Promise<void>;
// Update session group name
updateSessionGroupName: (id: string, name: string) => Promise<void>;
// Update session group sorting
updateSessionGroupSort: (items: SessionGroupItem[]) => Promise<void>;
}
Taking the addSessionGroup method as an example, we first call the createSessionGroup method of sessionService to create a new session group, and then use the refreshSessions method to refresh the sessions state:
export const createSessionGroupSlice: StateCreator<
SessionStore,
[['zustand/devtools', never]],
[],
SessionGroupAction
> = (set, get) => ({
// Implement the logic for adding a session group
addSessionGroup: async (name) => {
// Call the createSessionGroup method in the service layer and pass in the session group name
const id = await sessionService.createSessionGroup(name);
// Call the get method to get the current Store state and execute the refreshSessions method to refresh the session data
await get().refreshSessions();
// Return the ID of the newly created session group
return id;
},
// ... Other action implementations
});
With the above implementation, we can ensure that after adding a new session group, the application's state will be updated in a timely manner, and the relevant components will receive the latest state and re-render. This approach improves the predictability and maintainability of the data flow, while also simplifying communication between components.
Sessions Group Logic Refactoring
This requirement involves upgrading the Sessions feature to transform it from a single list to three different groups: pinnedSessions (pinned list), customSessionGroups (custom groups), and defaultSessions (default list).
To handle these groups, we need to refactor the implementation logic of useFetchSessions. Here are the key changes:
- Use the
sessionService.getSessionsWithGroupmethod to call the backend API and retrieve the grouped session data. - Save the retrieved data into three different state fields:
pinnedSessions,customSessionGroups, anddefaultSessions.
useFetchSessions Method
This method is defined in createSessionSlice as follows:
export const createSessionSlice: StateCreator<
SessionStore,
[['zustand/devtools', never]],
[],
SessionAction
> = (set, get) => ({
// ... other methods
useFetchSessions: () =>
useSWR<ChatSessionList>(FETCH_SESSIONS_KEY, sessionService.getSessionsWithGroup, {
onSuccess: (data) => {
set(
{
customSessionGroups: data.customGroup,
defaultSessions: data.default,
isSessionsFirstFetchFinished: true,
pinnedSessions: data.pinned,
sessions: data.all,
},
false,
n('useFetchSessions/onSuccess', data),
);
},
}),
});
After successfully retrieving the data, we use the set method to update the customSessionGroups, defaultSessions, pinnedSessions, and sessions states. This ensures that the states are synchronized with the latest session data.
sessionService.getSessionsWithGroup Method
The sessionService.getSessionsWithGroup method is responsible for calling the backend API SessionModel.queryWithGroups().
class SessionService {
// ... other SessionGroup related implementations
async getSessionsWithGroup(): Promise<ChatSessionList> {
return SessionModel.queryWithGroups();
}
}
SessionModel.queryWithGroups Method
This method is the core method called by sessionService.getSessionsWithGroup, and it is responsible for querying and organizing session data. The code is as follows:
class _SessionModel extends BaseModel {
// ... other methods
/**
* Query session data and categorize sessions based on groups.
* @returns {Promise<ChatSessionList>} An object containing all sessions and categorized session lists.
*/
async queryWithGroups(): Promise<ChatSessionList> {
// Query session group data
const groups = await SessionGroupModel.query();
// Query custom session groups based on session group IDs
const customGroups = await this.queryByGroupIds(groups.map((item) => item.id));
// Query default session list
const defaultItems = await this.querySessionsByGroupId(SessionDefaultGroup.Default);
// Query pinned sessions
const pinnedItems = await this.getPinnedSessions();
// Query all sessions
const all = await this.query();
// Combine and return all sessions and their group information
return {
all, // Array containing all sessions
customGroup: groups.map((group) => ({ ...group, children: customGroups[group.id] })), // Custom groups
default: defaultItems, // Default session list
pinned: pinnedItems, // Pinned session list
};
}
}
The queryWithGroups method first queries all session groups, then based on the IDs of these groups, it queries custom session groups, as well as default and pinned sessions. Finally, it returns an object containing all sessions and categorized session lists.
Adjusting sessions selectors
Due to changes in the logic of grouping within sessions, we need to adjust the logic of the sessions selectors to ensure they can correctly handle the new data structure.
Original selectors:
// Default group
const defaultSessions = (s: SessionStore): LobeSessions => s.sessions;
// Pinned group
const pinnedSessionList = (s: SessionStore) =>
defaultSessions(s).filter((s) => s.group === SessionGroupDefaultKeys.Pinned);
// Unpinned group
const unpinnedSessionList = (s: SessionStore) =>
defaultSessions(s).filter((s) => s.group === SessionGroupDefaultKeys.Default);
Revised:
const defaultSessions = (s: SessionStore): LobeSessions => s.defaultSessions;
const pinnedSessions = (s: SessionStore): LobeSessions => s.pinnedSessions;
const customSessionGroups = (s: SessionStore): CustomSessionGroup[] => s.customSessionGroups;
Since all data retrieval in the UI is implemented using syntax like useSessionStore(sessionSelectors.defaultSessions), we only need to modify the selector implementation of defaultSessions to complete the data structure change. The data retrieval code in the UI layer does not need to be changed at all, which can greatly reduce the cost and risk of refactoring.
![Important]
If you are not familiar with the concept and functionality of selectors, you can refer to the section 📘 Data Storage and Retrieval Module for relevant information.
IV. UI Section
Bind Store Action in the UI component to implement interactive logic, for example CreateGroupModal:
const CreateGroupModal = () => {
// ... Other logic
const [updateSessionGroup, addCustomGroup] = useSessionStore((s) => [
s.updateSessionGroupId,
s.addSessionGroup,
]);
return (
<Modal
onOk={async () => {
// ... Other logic
const groupId = await addCustomGroup(name);
await updateSessionGroup(sessionId, groupId);
}}
>
{/* ... */}
</Modal>
);
};
5. Data Migration
In the process of software development, data migration is an inevitable issue, especially when the existing data structure cannot meet the new business requirements. For this iteration of SessionGroup, we need to handle the migration of the group field in the session, which is a typical data migration case.
Issues with the Old Data Structure
In the old data structure, the group field was used to mark whether the session was "pinned" or belonged to a "default" group. However, when support for multiple session groups is needed, the original data structure becomes inflexible.
For example:
before pin: group = abc
after pin: group = pinned
after unpin: group = default
From the above example, it can be seen that once a session is unpinned from the "pinned" state, the group field cannot be restored to its original abc value. This is because we do not have a separate field to maintain the pinned state. Therefore, we have introduced a new field pinned to indicate whether the session is pinned, while the group field will be used solely to identify the session group.
Migration Strategy
The core logic of this migration is as follows:
- When the user's
groupfield ispinned, set theirpinnedfield totrue, and set the group todefault.
However, data migration in LobeChat typically involves two parts: configuration file migration and database migration. Therefore, the above logic will need to be implemented separately in these two areas.
Configuration File Migration
For configuration file migration, we recommend performing it before database migration, as configuration file migration is usually easier to test and validate. LobeChat's file migration configuration is located in the src/migrations/index.ts file, which defines the various versions of configuration file migration and their corresponding migration scripts.
// Current latest version number
- export const CURRENT_CONFIG_VERSION = 2;
+ export const CURRENT_CONFIG_VERSION = 3;
// Historical version upgrade module
const ConfigMigrations = [
+ /**
+ * 2024.01.22
+ * from `group = pinned` to `pinned:true`
+ */
+ MigrationV2ToV3,
/**
* 2023.11.27
* Migrate from single key database to dexie-based relational structure
*/
MigrationV1ToV2,
/**
* 2023.07.11
* just the first version, Nothing to do
*/
MigrationV0ToV1,
];
The logic for this configuration file migration is defined in src/migrations/FromV2ToV3/index.ts, simplified as follows:
export class MigrationV2ToV3 implements Migration {
// Specify the version from which to upgrade
version = 2;
migrate(data: MigrationData<V2ConfigState>): MigrationData<V3ConfigState> {
const { sessions } = data.state;
return {
...data,
state: {
...data.state,
sessions: sessions.map((s) => this.migrateSession(s)),
},
};
}
migrateSession = (session: V2Session): V3Session => {
return {
...session,
group: 'default',
pinned: session.group === 'pinned',
};
};
}
It can be seen that the migration implementation is very simple. However, it is important to ensure the correctness of the migration, so corresponding test cases need to be written in src/migrations/FromV2ToV3/migrations.test.ts:
import { MigrationData, VersionController } from '@/migrations/VersionController';
import { MigrationV1ToV2 } from '../FromV1ToV2';
import inputV1Data from '../FromV1ToV2/fixtures/input-v1-session.json';
import inputV2Data from './fixtures/input-v2-session.json';
import outputV3DataFromV1 from './fixtures/output-v3-from-v1.json';
import outputV3Data from './fixtures/output-v3.json';
import { MigrationV2ToV3 } from './index';
describe('MigrationV2ToV3', () => {
let migrations;
let versionController: VersionController<any>;
beforeEach(() => {
migrations = [MigrationV2ToV3];
versionController = new VersionController(migrations, 3);
});
it('should migrate data correctly through multiple versions', () => {
const data: MigrationData = inputV2Data;
const migratedData = versionController.migrate(data);
expect(migratedData.version).toEqual(outputV3Data.version);
expect(migratedData.state.sessions).toEqual(outputV3Data.state.sessions);
expect(migratedData.state.topics).toEqual(outputV3Data.state.topics);
expect(migratedData.state.messages).toEqual(outputV3Data.state.messages);
});
it('should work correct from v1 to v3', () => {
const data: MigrationData = inputV1Data;
versionController = new VersionController([MigrationV2ToV3, MigrationV1ToV2], 3);
const migratedData = versionController.migrate(data);
expect(migratedData.version).toEqual(outputV3DataFromV1.version);
expect(migratedData.state.sessions).toEqual(outputV3DataFromV1.state.sessions);
expect(migratedData.state.topics).toEqual(outputV3DataFromV1.state.topics);
expect(migratedData.state.messages).toEqual(outputV3DataFromV1.state.messages);
});
});
Unit tests require the use of fixtures to fix the test data. The test cases include verification logic for two parts: 1) the correctness of a single migration (v2 -> v3) and 2) the correctness of a complete migration (v1 -> v3).
[!Important]
The version number in the configuration file may not match the database version number, as database version updates do not always involve changes to the data structure (such as adding tables or fields), while configuration file version updates usually involve data migration.
#### Database Migration
Database migration needs to be implemented in the `LocalDB` class, which is defined in the `src/database/core/db.ts` file. The migration process involves adding a new `pinned` field for each record in the `sessions` table and resetting the `group` field:
```diff
export class LocalDB extends Dexie {
public files: LobeDBTable<'files'>;
public sessions: LobeDBTable<'sessions'>;
public messages: LobeDBTable<'messages'>;
public topics: LobeDBTable<'topics'>;
public plugins: LobeDBTable<'plugins'>;
public sessionGroups: LobeDBTable<'sessionGroups'>;
constructor() {
super(LOBE_CHAT_LOCAL_DB_NAME);
this.version(1).stores(dbSchemaV1);
this.version(2).stores(dbSchemaV2);
this.version(3).stores(dbSchemaV3);
this.version(4)
.stores(dbSchemaV4)
+ .upgrade((trans) => this.upgradeToV4(trans));
this.files = this.table('files');
this.sessions = this.table('sessions');
this.messages = this.table('messages');
this.topics = this.table('topics');
this.plugins = this.table('plugins');
this.sessionGroups = this.table('sessionGroups');
}
+ /**
+ * 2024.01.22
+ *
+ * DB V3 to V4
+ * from `group = pinned` to `pinned:true`
+ */
+ upgradeToV4 = async (trans: Transaction) => {
+ const sessions = trans.table('sessions');
+ await sessions.toCollection().modify((session) => {
+ // translate boolean to number
+ session.pinned = session.group === 'pinned' ? 1 : 0;
session.group = 'default';
});
+ };
}
This is our data migration strategy. When performing the migration, it is essential to ensure the correctness of the migration script and validate the migration results through thorough testing.
VI. Data Import and Export
In LobeChat, the data import and export feature is designed to ensure that users can migrate their data between different devices. This includes session, topic, message, and settings data. In the implementation of the Session Group feature, we also need to handle data import and export to ensure that the complete exported data can be restored exactly the same on other devices.
The core implementation of data import and export is in the ConfigService in src/service/config.ts, with key methods as follows:
| Method Name | Description |
|---|---|
importConfigState |
Import configuration data |
exportAgents |
Export all agent data |
exportSessions |
Export all session data |
exportSingleSession |
Export single session data |
exportSingleAgent |
Export single agent data |
exportSettings |
Export settings data |
exportAll |
Export all data |
Data Export
In LobeChat, when a user chooses to export data, the current session, topic, message, and settings data are packaged into a JSON file and provided for download. The standard structure of this JSON file is as follows:
{
"exportType": "sessions",
"state": {
"sessions": [],
"topics": [],
"messages": []
},
"version": 3
}
Where:
exportType: Identifies the type of data being exported, currently includingsessions,agent,settings, andall.state: Stores the actual data, with different data types for differentexportType.version: Indicates the data version.
In the implementation of the Session Group feature, we need to add sessionGroups data to the state field. This way, when users export data, their Session Group data will also be included.
For example, when exporting sessions, the relevant implementation code modification is as follows:
class ConfigService {
// ... Other code omitted
exportSessions = async () => {
const sessions = await sessionService.getSessions();
+ const sessionGroups = await sessionService.getSessionGroups();
const messages = await messageService.getAllMessages();
const topics = await topicService.getAllTopics();
- const config = createConfigFile('sessions', { messages, sessions, topics });
+ const config = createConfigFile('sessions', { messages, sessionGroups, sessions, topics });
exportConfigFile(config, 'sessions');
};
}
Data Import
The data import functionality is implemented through ConfigService.importConfigState. When users choose to import data, they need to provide a JSON file that conforms to the above structure specification. The importConfigState method accepts the data of the configuration file and imports it into the application.
In the implementation of the Session Group feature, we need to handle the sessionGroups data during the data import process. This way, when users import data, their Session Group data will also be imported correctly.
The following is the modified code for the import implementation in importConfigState:
class ConfigService {
// ... Other code omitted
+ importSessionGroups = async (sessionGroups: SessionGroupItem[]) => {
+ return sessionService.batchCreateSessionGroups(sessionGroups);
+ };
importConfigState = async (config: ConfigFile): Promise<ImportResults | undefined> => {
switch (config.exportType) {
case 'settings': {
await this.importSettings(config.state.settings);
break;
}
case 'agents': {
+ const sessionGroups = await this.importSessionGroups(config.state.sessionGroups);
const data = await this.importSessions(config.state.sessions);
return {
+ sessionGroups: this.mapImportResult(sessionGroups),
sessions: this.mapImportResult(data),
};
}
case 'all': {
await this.importSettings(config.state.settings);
+ const sessionGroups = await this.importSessionGroups(config.state.sessionGroups);
const [sessions, messages, topics] = await Promise.all([
this.importSessions(config.state.sessions),
this.importMessages(config.state.messages),
this.importTopics(config.state.topics),
]);
return {
messages: this.mapImportResult(messages),
+ sessionGroups: this.mapImportResult(sessionGroups),
sessions: this.mapImportResult(sessions),
topics: this.mapImportResult(topics),
};
}
case 'sessions': {
+ const sessionGroups = await this.importSessionGroups(config.state.sessionGroups);
const [sessions, messages, topics] = await Promise.all([
this.importSessions(config.state.sessions),
this.importMessages(config.state.messages),
this.importTopics(config.state.topics),
]);
return {
messages: this.mapImportResult(messages),
+ sessionGroups: this.mapImportResult(sessionGroups),
sessions: this.mapImportResult(sessions),
topics: this.mapImportResult(topics),
};
}
}
};
}
One key point of the above modification is to import sessionGroup first, because if sessions are imported first and the corresponding SessionGroup Id is not found in the current database, the group of this session will default to be modified to the default value. This will prevent the correct association of the sessionGroup's ID with the session.
This is the implementation of the LobeChat Session Group feature in the data import and export process. This approach ensures that users' Session Group data is correctly handled during the import and export process.
Summary
The above is the complete implementation process of the LobeChat Session Group feature. Developers can refer to this document for the development and testing of related functionalities.