@lobehub/chat 1.32.0 → 1.32.2

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 1.32.2](https://github.com/lobehub/lobe-chat/compare/v1.32.1...v1.32.2)
6
+
7
+ <sup>Released on **2024-11-19**</sup>
8
+
9
+ <br/>
10
+
11
+ <details>
12
+ <summary><kbd>Improvements and Fixes</kbd></summary>
13
+
14
+ </details>
15
+
16
+ <div align="right">
17
+
18
+ [![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)
19
+
20
+ </div>
21
+
22
+ ### [Version 1.32.1](https://github.com/lobehub/lobe-chat/compare/v1.32.0...v1.32.1)
23
+
24
+ <sup>Released on **2024-11-19**</sup>
25
+
26
+ #### 🐛 Bug Fixes
27
+
28
+ - **misc**: Keyword search for chat history & sessions.
29
+
30
+ #### 💄 Styles
31
+
32
+ - **misc**: Support o1 models using streaming.
33
+
34
+ <br/>
35
+
36
+ <details>
37
+ <summary><kbd>Improvements and Fixes</kbd></summary>
38
+
39
+ #### What's fixed
40
+
41
+ - **misc**: Keyword search for chat history & sessions, closes [#4725](https://github.com/lobehub/lobe-chat/issues/4725) ([415d772](https://github.com/lobehub/lobe-chat/commit/415d772))
42
+
43
+ #### Styles
44
+
45
+ - **misc**: Support o1 models using streaming, closes [#4732](https://github.com/lobehub/lobe-chat/issues/4732) ([7e9e71a](https://github.com/lobehub/lobe-chat/commit/7e9e71a))
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 1.32.0](https://github.com/lobehub/lobe-chat/compare/v1.31.11...v1.32.0)
6
56
 
7
57
  <sup>Released on **2024-11-19**</sup>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/chat",
3
- "version": "1.32.0",
3
+ "version": "1.32.2",
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",
@@ -231,8 +231,18 @@ describe('SessionModel', () => {
231
231
 
232
232
  it('should return sessions with matching title', async () => {
233
233
  await serverDB.insert(sessions).values([
234
- { id: '1', userId, title: 'Hello World', description: 'Some description' },
235
- { id: '2', userId, title: 'Another Session', description: 'Another description' },
234
+ { id: '1', userId },
235
+ { id: '2', userId },
236
+ ]);
237
+
238
+ await serverDB.insert(agents).values([
239
+ { id: 'agent-1', userId, model: 'gpt-3.5-turbo', title: 'Hello, Agent 1' },
240
+ { id: 'agent-2', userId, model: 'gpt-4', title: 'Agent 2' },
241
+ ]);
242
+
243
+ await serverDB.insert(agentsToSessions).values([
244
+ { agentId: 'agent-1', sessionId: '1' },
245
+ { agentId: 'agent-2', sessionId: '2' },
236
246
  ]);
237
247
 
238
248
  const result = await sessionModel.queryByKeyword('hello');
@@ -241,9 +251,21 @@ describe('SessionModel', () => {
241
251
  });
242
252
 
243
253
  it('should return sessions with matching description', async () => {
254
+ // The sessions has no title and desc,
255
+ // see: https://github.com/lobehub/lobe-chat/pull/4725
244
256
  await serverDB.insert(sessions).values([
245
- { id: '1', userId, title: 'Session 1', description: 'Description with keyword' },
246
- { id: '2', userId, title: 'Session 2', description: 'Another description' },
257
+ { id: '1', userId },
258
+ { id: '2', userId },
259
+ ]);
260
+
261
+ await serverDB.insert(agents).values([
262
+ { id: 'agent-1', userId, model: 'gpt-3.5-turbo', title: 'Agent 1', description: 'Description with Keyword' },
263
+ { id: 'agent-2', userId, model: 'gpt-4', title: 'Agent 2' },
264
+ ]);
265
+
266
+ await serverDB.insert(agentsToSessions).values([
267
+ { agentId: 'agent-1', sessionId: '1' },
268
+ { agentId: 'agent-2', sessionId: '2' },
247
269
  ]);
248
270
 
249
271
  const result = await sessionModel.queryByKeyword('keyword');
@@ -253,11 +275,23 @@ describe('SessionModel', () => {
253
275
 
254
276
  it('should return sessions with matching title or description', async () => {
255
277
  await serverDB.insert(sessions).values([
278
+ { id: '1', userId },
279
+ { id: '2', userId },
280
+ { id: '3', userId },
281
+ ]);
282
+
283
+ await serverDB.insert(agents).values([
256
284
  { id: '1', userId, title: 'Title with keyword', description: 'Some description' },
257
285
  { id: '2', userId, title: 'Another Session', description: 'Description with keyword' },
258
286
  { id: '3', userId, title: 'Third Session', description: 'Third description' },
259
287
  ]);
260
288
 
289
+ await serverDB.insert(agentsToSessions).values([
290
+ { agentId: '1', sessionId: '1' },
291
+ { agentId: '2', sessionId: '2' },
292
+ { agentId: '3', sessionId: '3' },
293
+ ]);
294
+
261
295
  const result = await sessionModel.queryByKeyword('keyword');
262
296
  expect(result).toHaveLength(2);
263
297
  expect(result.map((s) => s.id)).toEqual(['1', '2']);
@@ -1,5 +1,6 @@
1
1
  import { asc, count, eq, ilike, inArray, notExists, or, sum } from 'drizzle-orm';
2
2
  import { and, desc, like } from 'drizzle-orm/expressions';
3
+ import type { PgTransaction } from 'drizzle-orm/pg-core';
3
4
 
4
5
  import { serverDBEnv } from '@/config/db';
5
6
  import { serverDB } from '@/database/server/core/db';
@@ -9,6 +10,9 @@ import {
9
10
  FileItem,
10
11
  NewFile,
11
12
  NewGlobalFile,
13
+ chunks,
14
+ embeddings,
15
+ fileChunks,
12
16
  files,
13
17
  globalFiles,
14
18
  knowledgeBaseFiles,
@@ -68,6 +72,10 @@ export class FileModel {
68
72
  const fileHash = file.fileHash!;
69
73
 
70
74
  return await serverDB.transaction(async (trx) => {
75
+ // 1. 删除相关的 chunks
76
+ await this.deleteFileChunks(trx as any, [id]);
77
+
78
+ // 2. 删除文件记录
71
79
  await trx.delete(files).where(and(eq(files.id, id), eq(files.userId, this.userId)));
72
80
 
73
81
  const result = await trx
@@ -107,6 +115,9 @@ export class FileModel {
107
115
  const hashList = fileList.map((file) => file.fileHash!);
108
116
 
109
117
  return await serverDB.transaction(async (trx) => {
118
+ // 1. 删除相关的 chunks
119
+ await this.deleteFileChunks(trx as any, ids);
120
+
110
121
  // delete the files
111
122
  await trx.delete(files).where(and(inArray(files.id, ids), eq(files.userId, this.userId)));
112
123
 
@@ -289,4 +300,30 @@ export class FileModel {
289
300
  ),
290
301
  });
291
302
  }
303
+
304
+ // 抽象出通用的删除 chunks 方法
305
+ private async deleteFileChunks(trx: PgTransaction<any>, fileIds: string[]) {
306
+ const BATCH_SIZE = 1000; // 每批处理的数量
307
+
308
+ // 1. 获取所有关联的 chunk IDs
309
+ const relatedChunks = await trx
310
+ .select({ chunkId: fileChunks.chunkId })
311
+ .from(fileChunks)
312
+ .where(inArray(fileChunks.fileId, fileIds));
313
+
314
+ const chunkIds = relatedChunks.map((c) => c.chunkId).filter(Boolean) as string[];
315
+
316
+ if (chunkIds.length === 0) return;
317
+
318
+ // 2. 分批处理删除
319
+ for (let i = 0; i < chunkIds.length; i += BATCH_SIZE) {
320
+ const batchChunkIds = chunkIds.slice(i, i + BATCH_SIZE);
321
+
322
+ await trx.delete(embeddings).where(inArray(embeddings.chunkId, batchChunkIds));
323
+
324
+ await trx.delete(chunks).where(inArray(chunks.id, batchChunkIds));
325
+ }
326
+
327
+ return chunkIds;
328
+ }
292
329
  }
@@ -61,7 +61,7 @@ export class SessionModel {
61
61
 
62
62
  const keywordLowerCase = keyword.toLowerCase();
63
63
 
64
- const data = await this.findSessions({ keyword: keywordLowerCase });
64
+ const data = await this.findSessionsByKeywords({ keyword: keywordLowerCase });
65
65
 
66
66
  return data.map((item) => this.mapSessionItem(item as any));
67
67
  }
@@ -281,15 +281,15 @@ export class SessionModel {
281
281
  pinned !== undefined ? eq(sessions.pinned, pinned) : eq(sessions.userId, this.userId),
282
282
  keyword
283
283
  ? or(
284
- like(
285
- sql`lower(${sessions.title})` as unknown as Column,
286
- `%${keyword.toLowerCase()}%`,
287
- ),
288
- like(
289
- sql`lower(${sessions.description})` as unknown as Column,
290
- `%${keyword.toLowerCase()}%`,
291
- ),
292
- )
284
+ like(
285
+ sql`lower(${sessions.title})` as unknown as Column,
286
+ `%${keyword.toLowerCase()}%`,
287
+ ),
288
+ like(
289
+ sql`lower(${sessions.description})` as unknown as Column,
290
+ `%${keyword.toLowerCase()}%`,
291
+ ),
292
+ )
293
293
  : eq(sessions.userId, this.userId),
294
294
  group ? eq(sessions.groupId, group) : isNull(sessions.groupId),
295
295
  ),
@@ -297,4 +297,37 @@ export class SessionModel {
297
297
  with: { agentsToSessions: { columns: {}, with: { agent: true } }, group: true },
298
298
  });
299
299
  }
300
+
301
+ async findSessionsByKeywords(params: {
302
+ current?: number;
303
+ keyword: string;
304
+ pageSize?: number;
305
+ }) {
306
+ const { keyword, pageSize = 9999, current = 0 } = params;
307
+ const offset = current * pageSize;
308
+ const results = await serverDB.query.agents.findMany({
309
+ limit: pageSize,
310
+ offset,
311
+ orderBy: [desc(agents.updatedAt)],
312
+ where: and(
313
+ eq(agents.userId, this.userId),
314
+ or(
315
+ like(
316
+ sql`lower(${agents.title})` as unknown as Column,
317
+ `%${keyword.toLowerCase()}%`,
318
+ ),
319
+ like(
320
+ sql`lower(${agents.description})` as unknown as Column,
321
+ `%${keyword.toLowerCase()}%`,
322
+ ),
323
+ )
324
+ ),
325
+ with: { agentsToSessions: { columns: {}, with: { session: true } } },
326
+ });
327
+ try {
328
+ // @ts-expect-error
329
+ return results.map((item) => item.agentsToSessions[0].session);
330
+ } catch {}
331
+ return []
332
+ }
300
333
  }
@@ -85,7 +85,12 @@ export class TopicModel {
85
85
  serverDB
86
86
  .select()
87
87
  .from(messages)
88
- .where(and(eq(messages.topicId, topics.id), or(matchKeyword(messages.content)))),
88
+ .where(
89
+ and(
90
+ eq(messages.topicId, topics.id),
91
+ matchKeyword(messages.content)
92
+ )
93
+ ),
89
94
  ),
90
95
  ),
91
96
  ),
@@ -10,7 +10,7 @@ export const LobeGithubAI = LobeOpenAICompatibleFactory({
10
10
  const { model } = payload;
11
11
 
12
12
  if (o1Models.has(model)) {
13
- return pruneO1Payload(payload) as any;
13
+ return { ...pruneO1Payload(payload), stream: false } as any;
14
14
  }
15
15
 
16
16
  return { ...payload, stream: payload.stream ?? true };
@@ -17,7 +17,6 @@ export const pruneO1Payload = (payload: ChatStreamPayload) => ({
17
17
  role: message.role === 'system' ? 'user' : message.role,
18
18
  })),
19
19
  presence_penalty: 0,
20
- stream: false,
21
20
  temperature: 1,
22
21
  top_p: 1,
23
22
  });
@@ -154,8 +154,6 @@ export const fileRouter = router({
154
154
  removeFile: fileProcedure.input(z.object({ id: z.string() })).mutation(async ({ input, ctx }) => {
155
155
  const file = await ctx.fileModel.delete(input.id);
156
156
 
157
- // delete the orphan chunks
158
- await ctx.chunkModel.deleteOrphanChunks();
159
157
  if (!file) return;
160
158
 
161
159
  // delele the file from remove from S3 if it is not used by other files
@@ -187,9 +185,6 @@ export const fileRouter = router({
187
185
  .mutation(async ({ input, ctx }) => {
188
186
  const needToRemoveFileList = await ctx.fileModel.deleteMany(input.ids);
189
187
 
190
- // delete the orphan chunks
191
- await ctx.chunkModel.deleteOrphanChunks();
192
-
193
188
  if (!needToRemoveFileList || needToRemoveFileList.length === 0) return;
194
189
 
195
190
  // remove from S3
@@ -42,7 +42,7 @@ const currentActiveTopicSummary = (s: ChatStoreState): ChatTopicSummary | undefi
42
42
  const isCreatingTopic = (s: ChatStoreState) => s.creatingTopic;
43
43
 
44
44
  const groupedTopicsSelector = (s: ChatStoreState): GroupedTopic[] => {
45
- const topics = currentTopics(s);
45
+ const topics = displayTopics(s);
46
46
 
47
47
  if (!topics) return [];
48
48
  const favTopics = currentFavTopics(s);