@lobehub/chat 0.134.1 → 0.135.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,56 @@
2
2
 
3
3
  # Changelog
4
4
 
5
+ ### [Version 0.135.1](https://github.com/lobehub/lobe-chat/compare/v0.135.0...v0.135.1)
6
+
7
+ <sup>Released on **2024-03-14**</sup>
8
+
9
+ #### ♻ Code Refactoring
10
+
11
+ - **misc**: Refactor the db model.
12
+
13
+ <br/>
14
+
15
+ <details>
16
+ <summary><kbd>Improvements and Fixes</kbd></summary>
17
+
18
+ #### Code refactoring
19
+
20
+ - **misc**: Refactor the db model, closes [#1567](https://github.com/lobehub/lobe-chat/issues/1567) ([3d56dd6](https://github.com/lobehub/lobe-chat/commit/3d56dd6))
21
+
22
+ </details>
23
+
24
+ <div align="right">
25
+
26
+ [![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)
27
+
28
+ </div>
29
+
30
+ ## [Version 0.135.0](https://github.com/lobehub/lobe-chat/compare/v0.134.1...v0.135.0)
31
+
32
+ <sup>Released on **2024-03-14**</sup>
33
+
34
+ #### ✨ Features
35
+
36
+ - **misc**: Add claude 3 to bedrock provider.
37
+
38
+ <br/>
39
+
40
+ <details>
41
+ <summary><kbd>Improvements and Fixes</kbd></summary>
42
+
43
+ #### What's improved
44
+
45
+ - **misc**: Add claude 3 to bedrock provider, closes [#1551](https://github.com/lobehub/lobe-chat/issues/1551) ([6e1fe33](https://github.com/lobehub/lobe-chat/commit/6e1fe33))
46
+
47
+ </details>
48
+
49
+ <div align="right">
50
+
51
+ [![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)
52
+
53
+ </div>
54
+
5
55
  ### [Version 0.134.1](https://github.com/lobehub/lobe-chat/compare/v0.134.0...v0.134.1)
6
56
 
7
57
  <sup>Released on **2024-03-13**</sup>
package/README.md CHANGED
@@ -216,14 +216,14 @@ In addition, these plugins are not limited to news aggregation, but can also ext
216
216
 
217
217
  <!-- PLUGIN LIST -->
218
218
 
219
- | Recent Submits | Description |
220
- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
221
- | [Charts & Diagrams](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **pyxl** on **2024-02-05**</sup> | Mermaid Diagrams, Schemes for Presentations, Analysis, research websites, pie charts.<br/>`chart` `diagram` |
222
- | [Social Search](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **say-apps** on **2024-02-02**</sup> | The Social Search provides access to tweets, users, followers, images, media and more.<br/>`social` `twitter` `x` `search` |
223
- | [TokenInsights](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **feednews** on **2024-01-27**</sup> | Get realtime crypto price, BTC, ETH, BNB, and the latest insights.The latest coin news and airdrop opportunities.<br/>`crypto` `btc` `eth` `bnb` |
224
- | [Bilibili](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **LobeHub** on **2024-01-27**</sup> | Dive into Bilibili's vast content with features like keyword video search, replay access, interactive danmaku, trending video recommendations, and hot-search insights, all at your fingertips.<br/>`video` `bilibili` `search` |
225
-
226
- > 📊 Total plugins: [<kbd>**58**</kbd>](https://github.com/lobehub/lobe-chat-plugins)
219
+ | Recent Submits | Description |
220
+ | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
221
+ | [Calendar Assistant](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **cc** on **2024-03-13**</sup> | A plugin to manage your calendar events # will auto generate i18n in workflow<br/>`calendar` `schedule` `will-auto-generate-i-18-n-in-workflow` |
222
+ | [Charts & Diagrams](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **pyxl** on **2024-02-05**</sup> | Mermaid Diagrams, Schemes for Presentations, Analysis, research websites, pie charts.<br/>`chart` `diagram` |
223
+ | [Social Search](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **say-apps** on **2024-02-02**</sup> | The Social Search provides access to tweets, users, followers, images, media and more.<br/>`social` `twitter` `x` `search` |
224
+ | [TokenInsights](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **feednews** on **2024-01-27**</sup> | Get realtime crypto price, BTC, ETH, BNB, and the latest insights.The latest coin news and airdrop opportunities.<br/>`crypto` `btc` `eth` `bnb` |
225
+
226
+ > 📊 Total plugins: [<kbd>**59**</kbd>](https://github.com/lobehub/lobe-chat-plugins)
227
227
 
228
228
  <!-- PLUGIN LIST -->
229
229
 
package/README.zh-CN.md CHANGED
@@ -208,14 +208,14 @@ LobeChat 的插件生态系统是其核心功能的重要扩展,它极大地
208
208
 
209
209
  <!-- PLUGIN LIST -->
210
210
 
211
- | 最近新增 | 插件描述 |
212
- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
213
- | [图表和图示](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **pyxl** on **2024-02-05**</sup> | 美人鱼图表,演示文稿方案,分析,研究网站,饼图。<br/>`图表` `图示` |
214
- | [社交搜索](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **say-apps** on **2024-02-02**</sup> | 社交搜索提供访问推文、用户、关注者、图片、媒体等功能。<br/>`社交` `推特` `x` `搜索` |
215
- | [TokenInsights](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **feednews** on **2024-01-27**</sup> | 获取实时加密货币价格,BTC,ETH,BNB 和最新见解。最新的币新闻和空投机会。<br/>`加密货币` `btc` `eth` `bnb` |
216
- | [哔哩哔哩](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **LobeHub** on **2024-01-27**</sup> | 通过关键词视频搜索、回放访问、互动弹幕、热门视频推荐和热搜洞察等功能,深入体验哔哩哔哩丰富的内容,尽在您的指尖。<br/>`视频` `哔哩哔哩` `搜索` |
217
-
218
- > 📊 Total plugins: [<kbd>**58**</kbd>](https://github.com/lobehub/lobe-chat-plugins)
211
+ | 最近新增 | 插件描述 |
212
+ | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
213
+ | [日历助手](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **cc** on **2024-03-13**</sup> | 一个用于管理日历事件的插件 # 将自动生成工作流程中的 i18n<br/>`日历` `日程安排` `将自动生成工作流程中的-i-18-n` |
214
+ | [图表和图示](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **pyxl** on **2024-02-05**</sup> | 美人鱼图表,演示文稿方案,分析,研究网站,饼图。<br/>`图表` `图示` |
215
+ | [社交搜索](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **say-apps** on **2024-02-02**</sup> | 社交搜索提供访问推文、用户、关注者、图片、媒体等功能。<br/>`社交` `推特` `x` `搜索` |
216
+ | [TokenInsights](https://chat-preview.lobehub.com/settings/agent)<br/><sup>By **feednews** on **2024-01-27**</sup> | 获取实时加密货币价格,BTC,ETH,BNB 和最新见解。最新的币新闻和空投机会。<br/>`加密货币` `btc` `eth` `bnb` |
217
+
218
+ > 📊 Total plugins: [<kbd>**59**</kbd>](https://github.com/lobehub/lobe-chat-plugins)
219
219
 
220
220
  <!-- PLUGIN LIST -->
221
221
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/chat",
3
- "version": "0.134.1",
3
+ "version": "0.135.1",
4
4
  "description": "Lobe Chat - an open-source, high-performance chatbot framework that supports speech synthesis, multimodal, and extensible Function Call plugin system. Supports one-click free deployment of your private ChatGPT/LLM web application.",
5
5
  "keywords": [
6
6
  "framework",
@@ -81,7 +81,7 @@
81
81
  "@ant-design/icons": "^5",
82
82
  "@anthropic-ai/sdk": "^0.17.0",
83
83
  "@auth/core": "latest",
84
- "@aws-sdk/client-bedrock-runtime": "^3.503.1",
84
+ "@aws-sdk/client-bedrock-runtime": "^3.525.0",
85
85
  "@azure/openai": "^1.0.0-beta.11",
86
86
  "@cfworker/json-schema": "^1",
87
87
  "@google/generative-ai": "^0.2.0",
@@ -148,7 +148,7 @@
148
148
  "uuid": "^9",
149
149
  "yaml": "^2",
150
150
  "zod": "^3",
151
- "zustand": "^4.4",
151
+ "zustand": "^4.5.2",
152
152
  "zustand-utils": "^1.3.2"
153
153
  },
154
154
  "devDependencies": {
@@ -11,7 +11,7 @@ export const GET = async (req: Request) => {
11
11
 
12
12
  let res: Response;
13
13
 
14
- res = await fetch(pluginStore.getPluginIndexUrl(locale as any));
14
+ res = await fetch(pluginStore.getPluginIndexUrl(locale as any), { next: { revalidate: 3600 } });
15
15
 
16
16
  if (res.status === 404) {
17
17
  res = await fetch(pluginStore.getPluginIndexUrl(DEFAULT_LANG));
@@ -24,8 +24,7 @@ const Anthropic: ModelProviderCard = {
24
24
  description:
25
25
  'Fastest and most compact model for near-instant responsiveness. Quick and accurate targeted performance',
26
26
  displayName: 'Claude 3 Haiku',
27
- hidden: true,
28
- id: 'claude-3-haiku-20240229',
27
+ id: 'claude-3-haiku-20240307',
29
28
  maxOutput: 4096,
30
29
  tokens: 200_000,
31
30
  vision: true,
@@ -12,18 +12,34 @@ const Bedrock: ModelProviderCard = {
12
12
  },
13
13
  {
14
14
  description:
15
- 'Claude Instant 1.2 v1.2,上下文大小等于 100k,一个更快更便宜但仍然非常能干的模型,可以处理包括随意对话在内的多种任务。',
16
- displayName: 'Claude Instant 1.2',
17
- id: 'anthropic.claude-instant-v1',
18
- tokens: 100_000,
15
+ 'Anthropic 推出的 Claude 3 Sonnet 模型在智能和速度之间取得理想的平衡,尤其是在处理企业工作负载方面。该模型提供最大的效用,同时价格低于竞争产品,并且其经过精心设计,是大规模部署人工智能的可信赖、高耐久性骨干模型。 Claude 3 Sonnet 可以处理图像和返回文本输出,并且提供 200K 上下文窗口。',
16
+ displayName: 'Claude 3 Sonnet',
17
+ id: 'anthropic.claude-3-sonnet-20240229-v1:0',
18
+ tokens: 200_000,
19
+ vision: true,
20
+ },
21
+ {
22
+ description:
23
+ 'Claude 3 Haiku 是 Anthropic 最快速、最紧凑的模型,具有近乎即时的响应能力。该模型可以快速回答简单的查询和请求。客户将能够构建模仿人类交互的无缝人工智能体验。 Claude 3 Haiku 可以处理图像和返回文本输出,并且提供 200K 上下文窗口。',
24
+ displayName: 'Claude 3 Haiku',
25
+ id: 'anthropic.claude-3-haiku-20240307-v1:0',
26
+ tokens: 200_000,
27
+ vision: true,
19
28
  },
20
29
  {
21
30
  description:
22
- 'Claude 2.1 v2.1,上下文大小等于 200kClaude 2 的更新版本,特性包括双倍的上下文窗口,以及在可靠性等方面的提升。',
31
+ 'Claude 2.1 v2.1,上下文大小等于 200kClaude 2 的更新版本,采用双倍的上下文窗口,并在长文档和 RAG 上下文中提高可靠性、幻觉率和循证准确性。',
23
32
  displayName: 'Claude 2.1',
24
33
  id: 'anthropic.claude-v2:1',
25
34
  tokens: 200_000,
26
35
  },
36
+ {
37
+ description:
38
+ 'Claude Instant 1.2 v1.2,上下文大小等于 100k。一种更快速、更实惠但仍然非常强大的模型,它可以处理一系列任务,包括随意对话、文本分析、摘要和文档问题回答。',
39
+ displayName: 'Claude Instant 1.2',
40
+ id: 'anthropic.claude-instant-v1',
41
+ tokens: 100_000,
42
+ },
27
43
  {
28
44
  description: 'Llama 2 Chat 13B v1,上下文大小为 4k,Llama 2 模型的对话用例优化变体。',
29
45
  displayName: 'Llama 2 Chat 13B',
@@ -26,19 +26,8 @@ class _MessageModel extends BaseModel {
26
26
  constructor() {
27
27
  super('messages', DB_MessageSchema);
28
28
  }
29
- async create(data: CreateMessageParams) {
30
- const id = nanoid();
31
-
32
- const messageData: DB_Message = this.mapChatMessageToDBMessage(data as ChatMessage);
33
-
34
- return this._add(messageData, id);
35
- }
36
-
37
- async batchCreate(messages: ChatMessage[]) {
38
- const data: DB_Message[] = messages.map((m) => this.mapChatMessageToDBMessage(m));
39
29
 
40
- return this._batchAdd(data);
41
- }
30
+ // **************** Query *************** //
42
31
 
43
32
  async query({
44
33
  sessionId,
@@ -91,45 +80,79 @@ class _MessageModel extends BaseModel {
91
80
  return this.table.get(id);
92
81
  }
93
82
 
94
- async delete(id: string) {
95
- return this.table.delete(id);
83
+ async queryAll() {
84
+ const data: DBModel<DB_Message>[] = await this.table.orderBy('updatedAt').toArray();
85
+
86
+ return data.map((element) => this.mapToChatMessage(element));
96
87
  }
97
88
 
98
- async clearTable() {
99
- return this.table.clear();
89
+ async queryBySessionId(sessionId: string) {
90
+ return this.table.where('sessionId').equals(sessionId).toArray();
100
91
  }
101
92
 
102
- async update(id: string, data: DeepPartial<DB_Message>) {
103
- return super._update(id, data);
93
+ queryByTopicId = async (topicId: string) => {
94
+ const dbMessages = await this.table.where('topicId').equals(topicId).toArray();
95
+
96
+ return dbMessages.map((message) => this.mapToChatMessage(message));
97
+ };
98
+
99
+ async count() {
100
+ return this.table.count();
104
101
  }
105
102
 
106
- async updatePluginState(id: string, key: string, value: any) {
107
- const item = await this.findById(id);
103
+ // **************** Create *************** //
108
104
 
109
- return this.update(id, { pluginState: { ...item.pluginState, [key]: value } });
105
+ async create(data: CreateMessageParams) {
106
+ const id = nanoid();
107
+
108
+ const messageData: DB_Message = this.mapChatMessageToDBMessage(data as ChatMessage);
109
+
110
+ return this._add(messageData, id);
110
111
  }
111
112
 
112
- /**
113
- * Batch updates multiple fields of the specified messages.
114
- *
115
- * @param {string[]} messageIds - The identifiers of the messages to be updated.
116
- * @param {Partial<DB_Message>} updateFields - An object containing the fields to update and their new values.
117
- * @returns {Promise<number>} - The number of updated messages.
118
- */
119
- async batchUpdate(messageIds: string[], updateFields: Partial<DB_Message>): Promise<number> {
120
- // Retrieve the messages by their IDs
121
- const messagesToUpdate = await this.table.where(':id').anyOf(messageIds).toArray();
113
+ async batchCreate(messages: ChatMessage[]) {
114
+ const data: DB_Message[] = messages.map((m) => this.mapChatMessageToDBMessage(m));
122
115
 
123
- // Update the specified fields of each message
124
- const updatedMessages = messagesToUpdate.map((message) => ({
125
- ...message,
126
- ...updateFields,
127
- }));
116
+ return this._batchAdd(data);
117
+ }
128
118
 
129
- // Use the bulkPut method to update the messages in bulk
130
- await this.table.bulkPut(updatedMessages);
119
+ async duplicateMessages(messages: ChatMessage[]): Promise<ChatMessage[]> {
120
+ const duplicatedMessages = await this.createDuplicateMessages(messages);
121
+ // 批量添加复制后的消息到数据库
122
+ await this.batchCreate(duplicatedMessages);
123
+ return duplicatedMessages;
124
+ }
131
125
 
132
- return updatedMessages.length;
126
+ async createDuplicateMessages(messages: ChatMessage[]): Promise<ChatMessage[]> {
127
+ // 创建一个映射来存储原始消息ID和复制消息ID之间的关系
128
+ const idMapping = new Map<string, string>();
129
+
130
+ // 首先复制所有消息,并为每个复制的消息生成新的ID
131
+ const duplicatedMessages = messages.map((originalMessage) => {
132
+ const newId = nanoid();
133
+ idMapping.set(originalMessage.id, newId);
134
+
135
+ return { ...originalMessage, id: newId };
136
+ });
137
+
138
+ // 更新 parentId 为复制后的新ID
139
+ for (const duplicatedMessage of duplicatedMessages) {
140
+ if (duplicatedMessage.parentId && idMapping.has(duplicatedMessage.parentId)) {
141
+ duplicatedMessage.parentId = idMapping.get(duplicatedMessage.parentId);
142
+ }
143
+ }
144
+
145
+ return duplicatedMessages;
146
+ }
147
+
148
+ // **************** Delete *************** //
149
+
150
+ async delete(id: string) {
151
+ return this.table.delete(id);
152
+ }
153
+
154
+ async clearTable() {
155
+ return this.table.clear();
133
156
  }
134
157
 
135
158
  /**
@@ -158,55 +181,43 @@ class _MessageModel extends BaseModel {
158
181
  return this.table.bulkDelete(messageIds);
159
182
  }
160
183
 
161
- async queryAll() {
162
- const data: DBModel<DB_Message>[] = await this.table.orderBy('updatedAt').toArray();
163
-
164
- return data.map((element) => this.mapToChatMessage(element));
165
- }
166
-
167
- async count() {
168
- return this.table.count();
169
- }
184
+ // **************** Update *************** //
170
185
 
171
- async queryBySessionId(sessionId: string) {
172
- return this.table.where('sessionId').equals(sessionId).toArray();
186
+ async update(id: string, data: DeepPartial<DB_Message>) {
187
+ return this._update(id, data);
173
188
  }
174
189
 
175
- queryByTopicId = async (topicId: string) => {
176
- const dbMessages = await this.table.where('topicId').equals(topicId).toArray();
177
-
178
- return dbMessages.map((message) => this.mapToChatMessage(message));
179
- };
190
+ async updatePluginState(id: string, key: string, value: any) {
191
+ const item = await this.findById(id);
180
192
 
181
- async duplicateMessages(messages: ChatMessage[]): Promise<ChatMessage[]> {
182
- const duplicatedMessages = await this.createDuplicateMessages(messages);
183
- // 批量添加复制后的消息到数据库
184
- await this.batchCreate(duplicatedMessages);
185
- return duplicatedMessages;
193
+ return this.update(id, { pluginState: { ...item.pluginState, [key]: value } });
186
194
  }
187
195
 
188
- async createDuplicateMessages(messages: ChatMessage[]): Promise<ChatMessage[]> {
189
- // 创建一个映射来存储原始消息ID和复制消息ID之间的关系
190
- const idMapping = new Map<string, string>();
191
-
192
- // 首先复制所有消息,并为每个复制的消息生成新的ID
193
- const duplicatedMessages = messages.map((originalMessage) => {
194
- const newId = nanoid();
195
- idMapping.set(originalMessage.id, newId);
196
+ /**
197
+ * Batch updates multiple fields of the specified messages.
198
+ *
199
+ * @param {string[]} messageIds - The identifiers of the messages to be updated.
200
+ * @param {Partial<DB_Message>} updateFields - An object containing the fields to update and their new values.
201
+ * @returns {Promise<number>} - The number of updated messages.
202
+ */
203
+ async batchUpdate(messageIds: string[], updateFields: Partial<DB_Message>): Promise<number> {
204
+ // Retrieve the messages by their IDs
205
+ const messagesToUpdate = await this.table.where(':id').anyOf(messageIds).toArray();
196
206
 
197
- return { ...originalMessage, id: newId };
198
- });
207
+ // Update the specified fields of each message
208
+ const updatedMessages = messagesToUpdate.map((message) => ({
209
+ ...message,
210
+ ...updateFields,
211
+ }));
199
212
 
200
- // 更新 parentId 为复制后的新ID
201
- for (const duplicatedMessage of duplicatedMessages) {
202
- if (duplicatedMessage.parentId && idMapping.has(duplicatedMessage.parentId)) {
203
- duplicatedMessage.parentId = idMapping.get(duplicatedMessage.parentId);
204
- }
205
- }
213
+ // Use the bulkPut method to update the messages in bulk
214
+ await this.table.bulkPut(updatedMessages);
206
215
 
207
- return duplicatedMessages;
216
+ return updatedMessages.length;
208
217
  }
209
218
 
219
+ // **************** Helper *************** //
220
+
210
221
  private mapChatMessageToDBMessage(message: ChatMessage): DB_Message {
211
222
  const { extra, ...messageData } = message;
212
223
 
@@ -7,11 +7,14 @@ class _PluginModel extends BaseModel {
7
7
  constructor() {
8
8
  super('plugins', DB_PluginSchema);
9
9
  }
10
+ // **************** Query *************** //
10
11
 
11
12
  getList = async (): Promise<DB_Plugin[]> => {
12
13
  return this.table.toArray();
13
14
  };
14
15
 
16
+ // **************** Create *************** //
17
+
15
18
  create = async (plugin: DB_Plugin) => {
16
19
  const old = await this.table.get(plugin.identifier);
17
20
 
@@ -21,18 +24,20 @@ class _PluginModel extends BaseModel {
21
24
  batchCreate = async (plugins: DB_Plugin[]) => {
22
25
  return this._batchAdd(plugins);
23
26
  };
27
+ // **************** Delete *************** //
24
28
 
25
29
  delete(id: string) {
26
30
  return this.table.delete(id);
27
31
  }
32
+ clear() {
33
+ return this.table.clear();
34
+ }
35
+
36
+ // **************** Update *************** //
28
37
 
29
38
  update: (id: string, value: Partial<DB_Plugin>) => Promise<number> = async (id, value) => {
30
39
  return this.table.update(id, value);
31
40
  };
32
-
33
- clear() {
34
- return this.table.clear();
35
- }
36
41
  }
37
42
 
38
43
  export const PluginModel = new _PluginModel();
@@ -21,29 +21,7 @@ class _SessionModel extends BaseModel {
21
21
  super('sessions', DB_SessionSchema);
22
22
  }
23
23
 
24
- async create(type: 'agent' | 'group', defaultValue: Partial<LobeAgentSession>, id = uuid()) {
25
- const data = merge(DEFAULT_AGENT_LOBE_SESSION, { type, ...defaultValue });
26
- const dataDB = this.mapToDB_Session(data);
27
- return this._add(dataDB, id);
28
- }
29
-
30
- async batchCreate(sessions: LobeAgentSession[]) {
31
- const DB_Sessions = await Promise.all(
32
- sessions.map(async (s) => {
33
- if (s.group && s.group !== SessionDefaultGroup.Default) {
34
- // Check if the group exists in the SessionGroup table
35
- const groupExists = await SessionGroupModel.findById(s.group);
36
- // If the group does not exist, set it to default
37
- if (!groupExists) {
38
- s.group = SessionDefaultGroup.Default;
39
- }
40
- }
41
- return this.mapToDB_Session(s);
42
- }),
43
- );
44
-
45
- return this._batchAdd<DB_Session>(DB_Sessions, { idGenerator: uuid });
46
- }
24
+ // **************** Query *************** //
47
25
 
48
26
  async query({
49
27
  pageSize = 9999,
@@ -103,59 +81,6 @@ class _SessionModel extends BaseModel {
103
81
  return Object.fromEntries(groupItems);
104
82
  }
105
83
 
106
- async update(id: string, data: Partial<DB_Session>) {
107
- return super._update(id, data);
108
- }
109
-
110
- async updatePinned(id: string, pinned: boolean) {
111
- return this.update(id, { pinned: pinned ? 1 : 0 });
112
- }
113
-
114
- async updateConfig(id: string, data: DeepPartial<LobeAgentConfig>) {
115
- const session = await this.findById(id);
116
- if (!session) return;
117
-
118
- const config = merge(session.config, data);
119
-
120
- return this.update(id, { config });
121
- }
122
-
123
- /**
124
- * Delete a session , also delete all messages and topic associated with it.
125
- */
126
- async delete(id: string) {
127
- return this.db.transaction('rw', [this.table, this.db.topics, this.db.messages], async () => {
128
- // Delete all topics associated with the session
129
- const topics = await this.db.topics.where('sessionId').equals(id).toArray();
130
- const topicIds = topics.map((topic) => topic.id);
131
- if (topicIds.length > 0) {
132
- await this.db.topics.bulkDelete(topicIds);
133
- }
134
-
135
- // Delete all messages associated with the session
136
- const messages = await this.db.messages.where('sessionId').equals(id).toArray();
137
- const messageIds = messages.map((message) => message.id);
138
- if (messageIds.length > 0) {
139
- await this.db.messages.bulkDelete(messageIds);
140
- }
141
-
142
- // Finally, delete the session itself
143
- await this.table.delete(id);
144
- });
145
- }
146
-
147
- async clearTable() {
148
- return this.table.clear();
149
- }
150
-
151
- async findById(id: string): Promise<DBModel<DB_Session>> {
152
- return this.table.get(id);
153
- }
154
-
155
- async isEmpty() {
156
- return (await this.table.count()) === 0;
157
- }
158
-
159
84
  /**
160
85
  * Query sessions by keyword in title, description, content, or translated content
161
86
  * @param keyword The keyword to search for
@@ -225,6 +150,50 @@ class _SessionModel extends BaseModel {
225
150
  return this.mapToAgentSessions(items);
226
151
  }
227
152
 
153
+ async getPinnedSessions(): Promise<LobeSessions> {
154
+ const items: DBModel<DB_Session>[] = await this.table
155
+ .where('pinned')
156
+ .equals(1)
157
+ .reverse()
158
+ .sortBy('updatedAt');
159
+
160
+ return this.mapToAgentSessions(items);
161
+ }
162
+
163
+ async findById(id: string): Promise<DBModel<DB_Session>> {
164
+ return this.table.get(id);
165
+ }
166
+
167
+ async isEmpty() {
168
+ return (await this.table.count()) === 0;
169
+ }
170
+
171
+ // **************** Create *************** //
172
+
173
+ async create(type: 'agent' | 'group', defaultValue: Partial<LobeAgentSession>, id = uuid()) {
174
+ const data = merge(DEFAULT_AGENT_LOBE_SESSION, { type, ...defaultValue });
175
+ const dataDB = this.mapToDB_Session(data);
176
+ return this._add(dataDB, id);
177
+ }
178
+
179
+ async batchCreate(sessions: LobeAgentSession[]) {
180
+ const DB_Sessions = await Promise.all(
181
+ sessions.map(async (s) => {
182
+ if (s.group && s.group !== SessionDefaultGroup.Default) {
183
+ // Check if the group exists in the SessionGroup table
184
+ const groupExists = await SessionGroupModel.findById(s.group);
185
+ // If the group does not exist, set it to default
186
+ if (!groupExists) {
187
+ s.group = SessionDefaultGroup.Default;
188
+ }
189
+ }
190
+ return this.mapToDB_Session(s);
191
+ }),
192
+ );
193
+
194
+ return this._batchAdd<DB_Session>(DB_Sessions, { idGenerator: uuid });
195
+ }
196
+
228
197
  async duplicate(id: string, newTitle?: string) {
229
198
  const session = await this.findById(id);
230
199
  if (!session) return;
@@ -234,16 +203,57 @@ class _SessionModel extends BaseModel {
234
203
  return this._add(newSession, uuid());
235
204
  }
236
205
 
237
- async getPinnedSessions(): Promise<LobeSessions> {
238
- const items: DBModel<DB_Session>[] = await this.table
239
- .where('pinned')
240
- .equals(1)
241
- .reverse()
242
- .sortBy('updatedAt');
206
+ // **************** Delete *************** //
243
207
 
244
- return this.mapToAgentSessions(items);
208
+ /**
209
+ * Delete a session , also delete all messages and topic associated with it.
210
+ */
211
+ async delete(id: string) {
212
+ return this.db.transaction('rw', [this.table, this.db.topics, this.db.messages], async () => {
213
+ // Delete all topics associated with the session
214
+ const topics = await this.db.topics.where('sessionId').equals(id).toArray();
215
+ const topicIds = topics.map((topic) => topic.id);
216
+ if (topicIds.length > 0) {
217
+ await this.db.topics.bulkDelete(topicIds);
218
+ }
219
+
220
+ // Delete all messages associated with the session
221
+ const messages = await this.db.messages.where('sessionId').equals(id).toArray();
222
+ const messageIds = messages.map((message) => message.id);
223
+ if (messageIds.length > 0) {
224
+ await this.db.messages.bulkDelete(messageIds);
225
+ }
226
+
227
+ // Finally, delete the session itself
228
+ await this.table.delete(id);
229
+ });
230
+ }
231
+
232
+ async clearTable() {
233
+ return this.table.clear();
234
+ }
235
+
236
+ // **************** Update *************** //
237
+
238
+ async update(id: string, data: Partial<DB_Session>) {
239
+ return this._update(id, data);
240
+ }
241
+
242
+ async updatePinned(id: string, pinned: boolean) {
243
+ return this.update(id, { pinned: pinned ? 1 : 0 });
245
244
  }
246
245
 
246
+ async updateConfig(id: string, data: DeepPartial<LobeAgentConfig>) {
247
+ const session = await this.findById(id);
248
+ if (!session) return;
249
+
250
+ const config = merge(session.config, data);
251
+
252
+ return this.update(id, { config });
253
+ }
254
+
255
+ // **************** Helper *************** //
256
+
247
257
  private mapToDB_Session(session: LobeAgentSession): DBModel<DB_Session> {
248
258
  return {
249
259
  ...session,