@lobehub/chat 0.111.3 → 0.111.5

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.
Files changed (53) hide show
  1. package/.i18nrc.js +7 -5
  2. package/CHANGELOG.md +50 -0
  3. package/README.md +2 -2
  4. package/README.zh-CN.md +3 -3
  5. package/docs/Deployment/Analytics.md +20 -0
  6. package/docs/{Analytics.zh-CN.md → Deployment/Analytics.zh-CN.md} +5 -0
  7. package/docs/{Docker-Deployment.md → Deployment/Docker-Deployment.md} +7 -0
  8. package/docs/{Docker-Deployment.zh-CN.md → Deployment/Docker-Deployment.zh-CN.md} +7 -0
  9. package/docs/{Environment-Variable.md → Deployment/Environment-Variable.md} +1 -1
  10. package/docs/{Environment-Variable.zh-CN.md → Deployment/Environment-Variable.zh-CN.md} +1 -1
  11. package/docs/Development/Architecture.md +47 -0
  12. package/docs/{Development-Guide → Development}/Architecture.zh-CN.md +11 -1
  13. package/docs/Development/Chat-API.md +136 -0
  14. package/docs/{Development-Guide → Development}/Chat-API.zh-CN.md +10 -1
  15. package/docs/Development/Data-Store-Selectors.md +68 -0
  16. package/docs/{Development-Guide/Data-Store/Selectors.zh-CN.md → Development/Data-Store-Selectors.zh-CN.md} +1 -1
  17. package/docs/Development/Feature-Development.md +126 -0
  18. package/docs/{Development-Guide → Development}/Feature-Development.zh-CN.md +9 -1
  19. package/docs/Development/Folder-Structure.md +40 -0
  20. package/docs/Development/Resources.md +19 -0
  21. package/docs/Development/Steup-Development.md +69 -0
  22. package/docs/{Development-Guide → Development}/Steup-Development.zh-CN.md +8 -1
  23. package/docs/Development/Test.md +87 -0
  24. package/docs/{Development-Guide → Development}/Test.zh-CN.md +9 -1
  25. package/docs/Development/index.md +43 -0
  26. package/docs/{Development-Guide → Development}/index.zh-CN.md +6 -1
  27. package/docs/Home.md +32 -19
  28. package/docs/_Sidebar.md +29 -19
  29. package/locales/en_US/chat.json +1 -1
  30. package/package.json +8 -1
  31. package/scripts/docsWorkflow/const.ts +14 -0
  32. package/scripts/docsWorkflow/index.ts +73 -0
  33. package/scripts/docsWorkflow/toc.ts +60 -0
  34. package/scripts/docsWorkflow/utils.ts +38 -0
  35. package/src/chains/__tests__/summaryTitle.test.ts +2 -2
  36. package/src/chains/summaryTitle.ts +3 -4
  37. package/src/const/modelTokens.ts +3 -1
  38. package/src/store/global/selectors/__snapshots__/settings.test.ts.snap +16 -0
  39. package/src/types/llm.ts +2 -0
  40. /package/docs/{Deploy-with-Azure-OpenAI.md → Deployment/Deploy-with-Azure-OpenAI.md} +0 -0
  41. /package/docs/{Deploy-with-Azure-OpenAI.zh-CN.md → Deployment/Deploy-with-Azure-OpenAI.zh-CN.md} +0 -0
  42. /package/docs/{Upstream-Sync.md → Deployment/Upstream-Sync.md} +0 -0
  43. /package/docs/{Upstream-Sync.zh-CN.md → Deployment/Upstream-Sync.zh-CN.md} +0 -0
  44. /package/docs/{Development-Guide → Development}/Folder-Structure.zh-CN.md +0 -0
  45. /package/docs/{Development-Guide → Development}/Resources.zh-CN.md +0 -0
  46. /package/docs/{Lighthouse.md → Others/Lighthouse.md} +0 -0
  47. /package/docs/{Lighthouse.zh-CN.md → Others/Lighthouse.zh-CN.md} +0 -0
  48. /package/docs/{Plugin-Development.md → Plugins/Plugin-Development.md} +0 -0
  49. /package/docs/{Plugin-Development.zh-CN.md → Plugins/Plugin-Development.zh-CN.md} +0 -0
  50. /package/docs/{Usage-Agents.md → Usage/Usage-Agents.md} +0 -0
  51. /package/docs/{Usage-Agents.zh-CN.md → Usage/Usage-Agents.zh-CN.md} +0 -0
  52. /package/docs/{Usage-Topics.md → Usage/Usage-Topics.md} +0 -0
  53. /package/docs/{Usage-Topics.zh-CN.md → Usage/Usage-Topics.zh-CN.md} +0 -0
package/.i18nrc.js CHANGED
@@ -12,11 +12,13 @@ module.exports = defineConfig({
12
12
  jsonMode: true,
13
13
  },
14
14
  markdown: {
15
- entry: ['./README.md'],
16
- outputLocales: ['zh_CN'],
17
- outputExtensions: (locale) => {
18
- if (locale === 'en_US') return '.md';
19
- return `.${locale.replace('_', '-')}.md`;
15
+ entry: ['./README.zh-CN.md', './docs/**/*.zh-CN.md'],
16
+ entryLocale: 'zh-CN',
17
+ entryExtension: '.zh-CN.md',
18
+ outputLocales: ['en-US'],
19
+ outputExtensions: (locale, { getDefaultExtension }) => {
20
+ if (locale === 'en-US') return '.md';
21
+ return getDefaultExtension(locale);
20
22
  },
21
23
  },
22
24
  });
package/CHANGELOG.md CHANGED
@@ -2,6 +2,56 @@
2
2
 
3
3
  # Changelog
4
4
 
5
+ ### [Version 0.111.5](https://github.com/lobehub/lobe-chat/compare/v0.111.4...v0.111.5)
6
+
7
+ <sup>Released on **2023-12-14**</sup>
8
+
9
+ #### 🐛 Bug Fixes
10
+
11
+ - **misc**: Wrong locale language in en_US.
12
+
13
+ <br/>
14
+
15
+ <details>
16
+ <summary><kbd>Improvements and Fixes</kbd></summary>
17
+
18
+ #### What's fixed
19
+
20
+ - **misc**: Wrong locale language in en_US, closes [#660](https://github.com/lobehub/lobe-chat/issues/660) ([e1c31ee](https://github.com/lobehub/lobe-chat/commit/e1c31ee))
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.111.4](https://github.com/lobehub/lobe-chat/compare/v0.111.3...v0.111.4)
31
+
32
+ <sup>Released on **2023-12-14**</sup>
33
+
34
+ #### 🐛 Bug Fixes
35
+
36
+ - **misc**: Revert "🐛 fix: clean up gpt-3.5 model".
37
+
38
+ <br/>
39
+
40
+ <details>
41
+ <summary><kbd>Improvements and Fixes</kbd></summary>
42
+
43
+ #### What's fixed
44
+
45
+ - **misc**: Revert "🐛 fix: clean up gpt-3.5 model", closes [#653](https://github.com/lobehub/lobe-chat/issues/653) ([b8b14fc](https://github.com/lobehub/lobe-chat/commit/b8b14fc))
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.111.3](https://github.com/lobehub/lobe-chat/compare/v0.111.2...v0.111.3)
6
56
 
7
57
  <sup>Released on **2023-12-14**</sup>
package/README.md CHANGED
@@ -206,12 +206,12 @@ Our marketplace is not just a showcase platform but also a collaborative space.
206
206
 
207
207
  | Recent Submits | Description |
208
208
  | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
209
+ | [Stable Diffusion Prompts Crafter](https://chat-preview.lobehub.com/market?agent=stable-diffusion)<br/><sup>By **[ShinChven](https://github.com/ShinChven)** on **2023-12-14**</sup> | This GPT helps create precise prompts for Stable Diffusion. You will get descriptions, prompts, and negative prompts. prompts and negative prompts are in plain text code blocks for easy copy.<br/>`stable-diffusion` |
209
210
  | [Dream Analyst](https://chat-preview.lobehub.com/market?agent=dream-psychoanalyst)<br/><sup>By **[ghyghoo8](https://github.com/ghyghoo8)** on **2023-12-13**</sup> | Input a dream and I will help you analyze it.<br/>`dream` `master` `think` |
210
211
  | [Payroll Game](https://chat-preview.lobehub.com/market?agent=payroll-game)<br/><sup>By **[ghyghoo8](https://github.com/ghyghoo8)** on **2023-12-13**</sup> | In this salary negotiation game, you'll be facing the notorious 'Iron Rooster,' a boss known for being tight-fisted. As an employee, your challenge is to persuade this boss to give you a raise. However, no matter how reasonable your arguments are, the 'Iron Rooster' always finds a way to reject them. Get ready with your arguments for a clever and humorous showdown!<br/>`game` `boss` `payroll` |
211
212
  | [Python Coder Gradio](https://chat-preview.lobehub.com/market?agent=gradio-coding)<br/><sup>By **[Igroshka](https://github.com/Igroshka)** on **2023-12-12**</sup> | Python programmer experienced with Gradio for Hugging Face.<br/>`programming` `assistant` `python` |
212
- | [English Translation Expert](https://chat-preview.lobehub.com/market?agent=translate-eng-expert)<br/><sup>By **[caolixiang](https://github.com/caolixiang)** on **2023-12-12**</sup> | Perfect Translation<br/>`translate` `expert` `english` |
213
213
 
214
- > 📊 Total agents: [<kbd>**63**</kbd> ](https://github.com/lobehub/lobe-chat-agents)
214
+ > 📊 Total agents: [<kbd>**64**</kbd> ](https://github.com/lobehub/lobe-chat-agents)
215
215
 
216
216
  <!-- AGENT LIST -->
217
217
 
package/README.zh-CN.md CHANGED
@@ -92,7 +92,7 @@ LobeChat 是开源的高性能聊天机器人框架,支持语音合成、多
92
92
 
93
93
  ![](https://github-production-user-asset-6210df.s3.amazonaws.com/17870709/284072129-382bdf30-e3d6-4411-b5a0-249710b8ba08.png)
94
94
 
95
- LobeChat 已经支持 OpenAI 最新的 [`gpt-4-vsion`](https://platform.openai.com/docs/guides/vision) 支持视觉识别的模型,这是一个具备视觉识别能力的多模态智能。
95
+ LobeChat 已经支持 OpenAI 最新的 [`gpt-4-vision`](https://platform.openai.com/docs/guides/vision) 支持视觉识别的模型,这是一个具备视觉识别能力的多模态智能。
96
96
  用户可以轻松上传图片或者拖拽图片到对话框中,助手将能够识别图片内容,并在此基础上进行智能对话,构建更智能、更多元化的聊天场景。
97
97
 
98
98
  这一特性打开了新的互动方式,使得交流不再局限于文字,而是可以涵盖丰富的视觉元素。无论是日常使用中的图片分享,还是在特定行业内的图像解读,助手都能提供出色的对话体验。
@@ -183,12 +183,12 @@ LobeChat 的插件生态系统是其核心功能的重要扩展,它极大地
183
183
 
184
184
  | 最近新增 | 助手说明 |
185
185
  | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
186
+ | [稳定扩散促使手艺者](https://chat-preview.lobehub.com/market?agent=stable-diffusion)<br/><sup>By **[ShinChven](https://github.com/ShinChven)** on **2023-12-14**</sup> | 这个 GPT 帮助创建稳定扩散的精确提示。您将获得描述、提示和负面提示。提示和负面提示以纯文本代码块的形式呈现,便于复制。<br/>`stable-diffusion` |
186
187
  | [梦境分析师](https://chat-preview.lobehub.com/market?agent=dream-psychoanalyst)<br/><sup>By **[ghyghoo8](https://github.com/ghyghoo8)** on **2023-12-13**</sup> | 输入一段梦境,帮你分析分析<br/>`dream` `master` `think` |
187
188
  | [工资谈判游戏](https://chat-preview.lobehub.com/market?agent=payroll-game)<br/><sup>By **[ghyghoo8](https://github.com/ghyghoo8)** on **2023-12-13**</sup> | 在这个工资谈判游戏中,你将面对臭名昭著的 “铁公鸡” 老板,他以吝啬著称。作为员工,你的挑战是说服这位老板给你加薪。然而,无论你的论点多么合理,“铁公鸡” 总能找到拒绝它们的理由。准备好你的论点,迎接一场聪明幽默的对决吧!<br/>`游戏` `老板` `工资` |
188
189
  | [Python Gradio 代码师](https://chat-preview.lobehub.com/market?agent=gradio-coding)<br/><sup>By **[Igroshka](https://github.com/Igroshka)** on **2023-12-12**</sup> | 具有与 Hugging Face 合作的 Gradio 经验的 Python 程序员。<br/>`编程` `助手` `python` |
189
- | [英文翻译专家](https://chat-preview.lobehub.com/market?agent=translate-eng-expert)<br/><sup>By **[caolixiang](https://github.com/caolixiang)** on **2023-12-12**</sup> | 完美翻译<br/>`translate` `expert` `english` |
190
190
 
191
- > 📊 Total agents: [<kbd>**63**</kbd> ](https://github.com/lobehub/lobe-chat-agents)
191
+ > 📊 Total agents: [<kbd>**64**</kbd> ](https://github.com/lobehub/lobe-chat-agents)
192
192
 
193
193
  <!-- AGENT LIST -->
194
194
 
@@ -0,0 +1,20 @@
1
+ # Data Statistics
2
+
3
+ To better analyze the usage of LobeChat users, we have integrated several free/open-source data statistics services in LobeChat for collecting user usage data, which you can enable as needed.
4
+
5
+ #### TOC
6
+
7
+ - [Vercel Analytics](#vercel-analytics)
8
+ - [🚧 Posthog](#-posthog)
9
+
10
+ ## Vercel Analytics
11
+
12
+ [Vercel Analytics](https://vercel.com/analytics) is a data analysis service launched by Vercel, which can help you collect website visit information, including traffic, sources, and devices used for access.
13
+
14
+ We have integrated Vercel Analytics into the code, and you can enable it by setting the environment variable `NEXT_PUBLIC_ANALYTICS_VERCEL=1`, and then open the Analytics tab in the Vercel deployment project to view your application's visit information.
15
+
16
+ Vercel Analytics provides 2500 free Web Analytics Events per month (which can be understood as PV), which is generally sufficient for personal deployment and self-use products.
17
+
18
+ If you need detailed instructions on using Vercel Analytics, please refer to [Vercel Web Analytics Quick Start](https://vercel.com/docs/analytics/quickstart).
19
+
20
+ ## 🚧 Posthog
@@ -2,6 +2,11 @@
2
2
 
3
3
  为更好地帮助分析 LobeChat 的用户使用情况,我们在 LobeChat 中集成了若干免费 / 开源的数据统计服务,用于收集用户的使用情况,你可以按需开启。
4
4
 
5
+ #### TOC
6
+
7
+ - [Vercel Analytics](#vercel-analytics)
8
+ - [🚧 Posthog](#-posthog)
9
+
5
10
  ## Vercel Analytics
6
11
 
7
12
  [Vercel Analytics](https://vercel.com/analytics) 是 Vercel 推出的一款数据分析服务,它可以帮助你收集网站的访问情况,包括访问量、访问来源、访问设备等等。
@@ -6,6 +6,13 @@
6
6
 
7
7
  We provide [Docker Images][docker-release-link] for you to deploy LobeChat service on your private device.
8
8
 
9
+ #### TOC
10
+
11
+ - [Install Docker container environment](#install-docker-container-environment)
12
+ - [Deploy container image](#deploy-container-image)
13
+ - [`A` Command deployment (recommended)](#a-command-deployment-recommended)
14
+ - [`B` Docker Compose](#b-docker-compose)
15
+
9
16
  ## Install Docker container environment
10
17
 
11
18
  If already installed, skip this step.
@@ -6,6 +6,13 @@
6
6
 
7
7
  我们提供了 [Docker 镜像][docker-release-link],供你在自己的私有设备上部署 LobeChat 服务
8
8
 
9
+ #### TOC
10
+
11
+ - [安装 Docker 容器环境](#安装-docker-容器环境)
12
+ - [部署容器镜像](#部署容器镜像)
13
+ - [`A` 指令部署(推荐)](#a-指令部署推荐)
14
+ - [`B` Docker Compose](#b-docker-compose)
15
+
9
16
  ## 安装 Docker 容器环境
10
17
 
11
18
  如果已安装,请跳过此步
@@ -60,7 +60,7 @@ The above example adds `qwen-7b-chat` and `glm-6b` to the model list, removes `g
60
60
 
61
61
  ## Azure OpenAI
62
62
 
63
- If you need to use Azure OpenAI to provide model services, you can refer to the [Deploy with Azure OpenAI](./Deploy-with-Azure-OpenAI.zh-CN.md) section for detailed steps. Here are the environment variables related to Azure OpenAI.
63
+ If you need to use Azure OpenAI to provide model services, you can refer to the [Deploy with Azure OpenAI](Deploy-with-Azure-OpenAI.zh-CN.md) section for detailed steps. Here are the environment variables related to Azure OpenAI.
64
64
 
65
65
  ### `USE_AZURE_OPENAI`
66
66
 
@@ -60,7 +60,7 @@ LobeChat 在部署时提供了一些额外的配置项,使用环境变量进
60
60
 
61
61
  ## Azure OpenAI
62
62
 
63
- 如果你需要使用 Azure OpenAI 来提供模型服务,可以查阅 [使用 Azure OpenAI 部署](./Deploy-with-Azure-OpenAI.zh-CN.md) 章节查看详细步骤,这里将列举和 Azure OpenAI 相关的环境变量。
63
+ 如果你需要使用 Azure OpenAI 来提供模型服务,可以查阅 [使用 Azure OpenAI 部署](Deploy-with-Azure-OpenAI.zh-CN.md) 章节查看详细步骤,这里将列举和 Azure OpenAI 相关的环境变量。
64
64
 
65
65
  ### `USE_AZURE_OPENAI`
66
66
 
@@ -0,0 +1,47 @@
1
+ # Architecture Design
2
+
3
+ LobeChat is an AI conversation application built on the Next.js framework, aiming to provide an AI productivity platform that enables users to interact with AI through natural language. The following is an overview of the architecture design of LobeChat:
4
+
5
+ #### TOC
6
+
7
+ - [Application Architecture Overview](#application-architecture-overview)
8
+ - [Frontend Architecture](#frontend-architecture)
9
+ - [Edge Runtime API](#edge-runtime-api)
10
+ - [Agents Market](#agents-market)
11
+ - [Plugin Market](#plugin-market)
12
+ - [Security and Performance Optimization](#security-and-performance-optimization)
13
+ - [Development and Deployment Process](#development-and-deployment-process)
14
+
15
+ ## Application Architecture Overview
16
+
17
+ The overall architecture of LobeChat consists of the frontend, EdgeRuntime API, Agents Market, Plugin Market, and independent plugins. These components collaborate to provide a complete AI experience.
18
+
19
+ ## Frontend Architecture
20
+
21
+ The frontend of LobeChat adopts the Next.js framework, leveraging its powerful server-side rendering (SSR) capability and routing functionality. The frontend utilizes a stack of technologies, including the antd component library, lobe-ui AIGC component library, zustand state management, swr request library, i18next internationalization library, and more. These technologies collectively support the functionality and features of LobeChat.
22
+
23
+ The components in the frontend architecture include app, components, config, const, features, helpers, hooks, layout, locales, migrations, prompts, services, store, styles, types, and utils. Each component has specific responsibilities and collaborates with others to achieve different functionalities.
24
+
25
+ ## Edge Runtime API
26
+
27
+ The Edge Runtime API is one of the core components of LobeChat, responsible for handling the core logic of AI conversations. It provides interaction interfaces with the AI engine, including natural language processing, intent recognition, and response generation. The EdgeRuntime API communicates with the frontend, receiving user input and returning corresponding responses.
28
+
29
+ ## Agents Market
30
+
31
+ The Agents Market is a crucial part of LobeChat, providing various AI agents for different scenarios to handle specific tasks and domains. The Agents Market also offers functionality for discovering and uploading agents, allowing users to find agents created by others and easily share their own agents in the market.
32
+
33
+ ## Plugin Market
34
+
35
+ The Plugin Market is another key component of LobeChat, offering various plugins to extend the functionality and features of LobeChat. Plugins can be independent functional modules or integrated with agents from the Agents Market. During conversations, the assistant automatically identifies user input, recognizes suitable plugins, and passes them to the corresponding plugins for processing and returns the results.
36
+
37
+ ## Security and Performance Optimization
38
+
39
+ LobeChat's security strategy includes authentication and permission management. Users need to authenticate before using LobeChat, and operations are restricted based on the user's permissions.
40
+
41
+ To optimize performance, LobeChat utilizes Next.js SSR functionality to achieve fast page loading and response times. Additionally, a series of performance optimization measures are implemented, including code splitting, caching, and resource compression.
42
+
43
+ ## Development and Deployment Process
44
+
45
+ LobeChat's development process includes version control, testing, continuous integration, and continuous deployment. The development team uses version control systems for code management and conducts unit and integration testing to ensure code quality. Continuous integration and deployment processes ensure rapid delivery and deployment of code.
46
+
47
+ The above is a brief introduction to the architecture design of LobeChat, detailing the responsibilities and collaboration of each component, as well as the impact of design decisions on application functionality and performance.
@@ -1,7 +1,17 @@
1
- ## 架构设计
1
+ # 架构设计
2
2
 
3
3
  LobeChat 是一个基于 Next.js 框架构建的 AI 会话应用,旨在提供一个 AI 生产力平台,使用户能够与 AI 进行自然语言交互。以下是 LobeChat 的架构设计介稿:
4
4
 
5
+ #### TOC
6
+
7
+ - [应用架构概览](#应用架构概览)
8
+ - [前端架构](#前端架构)
9
+ - [Edge Runtime API](#edge-runtime-api)
10
+ - [Agents 市场](#agents-市场)
11
+ - [插件市场](#插件市场)
12
+ - [安全性和性能优化](#安全性和性能优化)
13
+ - [开发和部署流程](#开发和部署流程)
14
+
5
15
  ## 应用架构概览
6
16
 
7
17
  LobeChat 的整体架构由前端、EdgeRuntime API、Agents 市场、插件市场和独立插件组成。这些组件相互协作,以提供完整的 AI 体验。
@@ -0,0 +1,136 @@
1
+ # Conversation API Implementation Logic
2
+
3
+ The implementation of LobeChat's large model AI mainly relies on OpenAI's API, including the core conversation API on the backend and the integrated API on the frontend. Next, we will introduce the implementation approach and code for the backend and frontend separately.
4
+
5
+ #### TOC
6
+
7
+ - [Backend Implementation](#backend-implementation)
8
+ - [Core Conversation API](#core-conversation-api)
9
+ - [Conversation Result Processing](#conversation-result-processing)
10
+ - [Frontend Implementation](#frontend-implementation)
11
+ - [Frontend Integration](#frontend-integration)
12
+ - [Using Streaming to Get Results](#using-streaming-to-get-results)
13
+
14
+ ## Backend Implementation
15
+
16
+ The following code removes authentication, error handling, and other logic, retaining only the core functionality logic.
17
+
18
+ ### Core Conversation API
19
+
20
+ In the file `src/app/api/openai/chat/handler.ts`, we define a `POST` method, which first parses the payload data from the request (i.e., the conversation content sent by the client), and then retrieves the authorization information from the request. Then, we create an `openai` object and call the `createChatCompletion` method, which is responsible for sending the conversation request to OpenAI and returning the result.
21
+
22
+ ```ts
23
+ export const POST = async (req: Request) => {
24
+ const payload = await req.json();
25
+
26
+ const { apiKey, endpoint } = getOpenAIAuthFromRequest(req);
27
+
28
+ const openai = createOpenai(apiKey, endpoint);
29
+
30
+ return createChatCompletion({ openai, payload });
31
+ };
32
+ ```
33
+
34
+ ### Conversation Result Processing
35
+
36
+ In the file `src/app/api/openai/chat/createChatCompletion.ts`, we define the `createChatCompletion` method, which first preprocesses the payload data, then calls OpenAI's `chat.completions.create` method to send the request, and uses the `OpenAIStream` from the [Vercel AI SDK](https://sdk.vercel.ai/docs) to convert the returned result into a streaming response.
37
+
38
+ ```ts
39
+ import { OpenAIStream, StreamingTextResponse } from 'ai';
40
+
41
+ export const createChatCompletion = async ({ payload, openai }: CreateChatCompletionOptions) => {
42
+ const { messages, ...params } = payload;
43
+
44
+ const formatMessages = messages.map((m) => ({
45
+ content: m.content,
46
+ name: m.name,
47
+ role: m.role,
48
+ }));
49
+
50
+ const response = await openai.chat.completions.create(
51
+ {
52
+ messages: formatMessages,
53
+ ...params,
54
+ stream: true,
55
+ },
56
+ { headers: { Accept: '*/*' } },
57
+ );
58
+ const stream = OpenAIStream(response);
59
+ return new StreamingTextResponse(stream);
60
+ };
61
+ ```
62
+
63
+ ## Frontend Implementation
64
+
65
+ ### Frontend Integration
66
+
67
+ In the `src/services/chatModel.ts` file, we define the `fetchChatModel` method, which first preprocesses the payload data, then sends a POST request to the `/chat` endpoint on the backend, and returns the request result.
68
+
69
+ ```ts
70
+ export const fetchChatModel = (
71
+ { plugins: enabledPlugins, ...params }: Partial<OpenAIStreamPayload>,
72
+ options?: FetchChatModelOptions,
73
+ ) => {
74
+ const payload = merge(
75
+ {
76
+ model: initialLobeAgentConfig.model,
77
+ stream: true,
78
+ ...initialLobeAgentConfig.params,
79
+ },
80
+ params,
81
+ );
82
+
83
+ const filterFunctions: ChatCompletionFunctions[] = pluginSelectors.enabledSchema(enabledPlugins)(
84
+ usePluginStore.getState(),
85
+ );
86
+
87
+ const functions = filterFunctions.length === 0 ? undefined : filterFunctions;
88
+
89
+ return fetch(OPENAI_URLS.chat, {
90
+ body: JSON.stringify({ ...payload, functions }),
91
+ headers: createHeaderWithOpenAI({ 'Content-Type': 'application/json' }),
92
+ method: 'POST',
93
+ signal: options?.signal,
94
+ });
95
+ };
96
+ ```
97
+
98
+ ### Using Streaming to Get Results
99
+
100
+ In the `src/utils/fetch.ts` file, we define the `fetchSSE` method, which uses a streaming approach to retrieve data. When a new data chunk is read, it calls the `onMessageHandle` callback function to process the data chunk, achieving a typewriter-like output effect.
101
+
102
+ ```ts
103
+ export const fetchSSE = async (fetchFn: () => Promise<Response>, options: FetchSSEOptions = {}) => {
104
+ const response = await fetchFn();
105
+
106
+ if (!response.ok) {
107
+ const chatMessageError = await getMessageError(response);
108
+
109
+ options.onErrorHandle?.(chatMessageError);
110
+ return;
111
+ }
112
+
113
+ const returnRes = response.clone();
114
+
115
+ const data = response.body;
116
+
117
+ if (!data) return;
118
+
119
+ const reader = data.getReader();
120
+ const decoder = new TextDecoder();
121
+
122
+ let done = false;
123
+
124
+ while (!done) {
125
+ const { value, done: doneReading } = await reader.read();
126
+ done = doneReading;
127
+ const chunkValue = decoder.decode(value);
128
+
129
+ options.onMessageHandle?.(chunkValue);
130
+ }
131
+
132
+ return returnRes;
133
+ };
134
+ ```
135
+
136
+ The above is the core implementation of the LobeChat session API. With an understanding of these core codes, further expansion and optimization of LobeChat's AI functionality can be achieved.
@@ -1,7 +1,16 @@
1
- # LobeChat 会话 API 实现逻辑
1
+ # 会话 API 实现逻辑
2
2
 
3
3
  LobeChat 的大模型 AI 实现主要依赖于 OpenAI 的 API,包括后端的核心会话 API 和前端的集成 API。接下来,我们将分别介绍后端和前端的实现思路和代码。
4
4
 
5
+ #### TOC
6
+
7
+ - [后端实现](#后端实现)
8
+ - [核心会话 API](#核心会话-api)
9
+ - [会话结果处理](#会话结果处理)
10
+ - [前端实现](#前端实现)
11
+ - [前端集成](#前端集成)
12
+ - [使用流式获取结果](#使用流式获取结果)
13
+
5
14
  ## 后端实现
6
15
 
7
16
  以下代码中移除了鉴权、错误处理等逻辑,仅保留了核心的主要功能逻辑。
@@ -0,0 +1,68 @@
1
+ # Data Store Selector
2
+
3
+ Selectors are data retrieval modules under the LobeChat data flow development framework. Their role is to extract data from the store using specific business logic for consumption by components.
4
+
5
+ Taking `src/store/plugin/selectors.ts` as an example:
6
+
7
+ This TypeScript code snippet defines an object named `pluginSelectors`, which contains a series of selector functions used to retrieve data from the plugin storage state. Selectors are functions that extract and derive data from a Redux store (or similar state management library). This specific example is for managing the state related to the frontend application's plugin system.
8
+
9
+ Here are some key points to note:
10
+
11
+ - `enabledSchema`: A function that returns an array of `ChatCompletionFunctions` filtered based on the enabled plugin list `enabledPlugins`. It appends the plugin identifier as a prefix to the API names to ensure uniqueness and uses the `uniqBy` function from the Lodash library to remove duplicates.
12
+ - `onlinePluginStore`: Returns the current online plugin list.
13
+ - `pluginList`: Returns the list of plugins, including custom plugins and standard plugins.
14
+ - `getPluginMetaById`: Returns the plugin metadata based on the plugin ID.
15
+ - `getDevPluginById`: Returns information about the custom plugins in development.
16
+ - `getPluginManifestById`: Returns the plugin manifest based on the plugin ID.
17
+ - `getPluginSettingsById`: Returns the plugin settings based on the plugin ID.
18
+ - `getPluginManifestLoadingStatus`: Returns the loading status of the plugin manifest (loading, success, or error) based on the plugin ID.
19
+ - `isCustomPlugin`: Checks if the plugin with the given ID is a custom plugin.
20
+ - `displayPluginList`: Returns a processed plugin list, including author, avatar, creation time, description, homepage URL, identifier, and title.
21
+ - `hasPluginUI`: Determines if the plugin has UI components based on the plugin ID.
22
+
23
+ Selectors are highly modular and maintainable. By encapsulating complex state selection logic in separate functions, they make the code more concise and intuitive when accessing state data in other parts of the application. Additionally, by using TypeScript, each function can have clear input and output types, which helps improve code reliability and development efficiency.
24
+
25
+ Taking the `displayPluginList` method as an example, its code is as follows:
26
+
27
+ ```ts
28
+ const pluginList = (s: PluginStoreState) => [...s.pluginList, ...s.customPluginList];
29
+
30
+ const displayPluginList = (s: PluginStoreState) =>
31
+ pluginList(s).map((p) => ({
32
+ author: p.author,
33
+ avatar: p.meta?.avatar,
34
+ createAt: p.createAt,
35
+ desc: pluginHelpers.getPluginDesc(p.meta),
36
+ homepage: p.homepage,
37
+ identifier: p.identifier,
38
+ title: pluginHelpers.getPluginTitle(p.meta),
39
+ }));
40
+ ```
41
+
42
+ - `pluginList` method: Used to retrieve the list of all plugins from the plugin state storage `PluginStoreState`. It creates a new plugin list by combining two arrays: `pluginList` and `customPluginList`.
43
+ - `displayPluginList` method: Calls the `pluginList` method to retrieve the merged plugin list and transforms the `title` and `desc` into text displayed on the UI.
44
+
45
+ In components, the final consumed data can be directly obtained by importing:
46
+
47
+ ```tsx | pure
48
+ import { usePluginStore } from '@/store/plugin';
49
+ import { pluginSelectors } from '@/store/plugin/selectors';
50
+
51
+ const Render = ({ plugins }) => {
52
+ const list = usePluginStore(pluginSelectors.displayPluginList);
53
+
54
+ return <> ... </>;
55
+ };
56
+ ```
57
+
58
+ The benefits of implementing this approach are:
59
+
60
+ 1. **Decoupling and reusability**: By separating selectors from components, we can reuse these selectors across multiple components without rewriting data retrieval logic. This reduces duplicate code, improves development efficiency, and makes the codebase cleaner and easier to maintain.
61
+ 2. **Performance optimization**: Selectors can be used to compute derived data, avoiding redundant calculations in each component. When the state changes, only the selectors dependent on that part of the state will recalculate, reducing unnecessary rendering and computation.
62
+ 3. **Ease of testing**: Selectors are pure functions, relying only on the passed parameters. This means they can be tested in an isolated environment without the need to simulate the entire store or component tree.
63
+ 4. **Type safety**: As LobeChat uses TypeScript, each selector has explicit input and output type definitions. This provides developers with the advantage of auto-completion and compile-time checks, reducing runtime errors.
64
+ 5. **Maintainability**: Selectors centralize the logic for reading state, making it more intuitive to track state changes and management. If the state structure changes, only the relevant selectors need to be updated, rather than searching and replacing in multiple places throughout the codebase.
65
+ 6. **Composability**: Selectors can be composed with other selectors to create more complex selection logic. This pattern allows developers to build a hierarchy of selectors, making state selection more flexible and powerful.
66
+ 7. **Simplified component logic**: Components do not need to know the structure of the state or how to retrieve and compute the required data. Components only need to call selectors to obtain the data needed for rendering, simplifying and clarifying component logic.
67
+
68
+ With this design, LobeChat developers can focus more on building the user interface and business logic without worrying about the details of data retrieval and processing. This pattern also provides better adaptability and scalability for potential future changes in state structure.
@@ -1,4 +1,4 @@
1
- ## Selector
1
+ # 数据存储取数模块
2
2
 
3
3
  selectors 是 LobeChat 数据流研发框架下的取数模块,它的作用是从 store 中以特定特务逻辑取出数据,供组件消费使用。
4
4
 
@@ -0,0 +1,126 @@
1
+ # How to Develop a New Feature
2
+
3
+ LobeChat is built on the Next.js framework and uses TypeScript as the primary development language. When developing a new feature, we need to follow a certain development process to ensure the quality and stability of the code. The general process can be divided into the following five steps:
4
+
5
+ 1. Routing: Define routes (`src/app`).
6
+ 2. Data Structure: Define data structures (`src/types`).
7
+ 3. Business Logic Implementation: Zustand store (`src/store`).
8
+ 4. Page Display: Write static components/pages (`src/app/<new-page>/features/<new-feature>.tsx`).
9
+ 5. Function Binding: Bind the store with page triggers (`const [state, function] = useNewStore(s => [s.state, s.function])`).
10
+
11
+ Taking the "Chat Messages" feature as an example, here are the brief steps to implement this feature:
12
+
13
+ #### TOC
14
+
15
+ - [1. Define Routes](#1-define-routes)
16
+ - [2. Define Data Structure](#2-define-data-structure)
17
+ - [3. Create Zustand Store](#3-create-zustand-store)
18
+ - [4. Create Page and Components](#4-create-page-and-components)
19
+ - [5. Function Binding](#5-function-binding)
20
+
21
+ ## 1. Define Routes
22
+
23
+ In the `src/app` directory, we need to define a new route to host the "Chat Messages" page. Generally, we would create a new folder under `src/app`, for example, `chat`, and create a `page.tsx` file within this folder to export a React component as the main body of the page.
24
+
25
+ ```tsx
26
+ // src/app/chat/page.tsx
27
+ import ChatPage from './features/chat';
28
+
29
+ export default ChatPage;
30
+ ```
31
+
32
+ ## 2. Define Data Structure
33
+
34
+ In the `src/types` directory, we need to define the data structure for "Chat Messages". For example, we create a `chat.ts` file and define the `ChatMessage` type within it:
35
+
36
+ ```ts
37
+ // src/types/chat.ts
38
+
39
+ export type ChatMessage = {
40
+ id: string;
41
+ content: string;
42
+ timestamp: number;
43
+ sender: 'user' | 'bot';
44
+ };
45
+ ```
46
+
47
+ ## 3. Create Zustand Store
48
+
49
+ In the `src/store` directory, we need to create a new Zustand Store to manage the state of "Chat Messages". For example, we create a `chatStore.ts` file and define a Zustand Store within it:
50
+
51
+ ```ts
52
+ // src/store/chatStore.ts
53
+ import create from 'zustand';
54
+
55
+ type ChatState = {
56
+ messages: ChatMessage[];
57
+ addMessage: (message: ChatMessage) => void;
58
+ };
59
+
60
+ export const useChatStore = create<ChatState>((set) => ({
61
+ messages: [],
62
+ addMessage: (message) => set((state) => ({ messages: [...state.messages, message] })),
63
+ }));
64
+ ```
65
+
66
+ ## 4. Create Page and Components
67
+
68
+ In `src/app/<new-page>/features/<new-feature>.tsx`, we need to create a new page or component to display "Chat Messages". In this file, we can use the Zustand Store created earlier and Ant Design components to build the UI:
69
+
70
+ ```jsx
71
+ // src/features/chat/index.tsx
72
+ import { List, Typography } from 'antd';
73
+ import { useChatStore } from 'src/store/chatStore';
74
+
75
+ const ChatPage = () => {
76
+ const messages = useChatStore((state) => state.messages);
77
+
78
+ return (
79
+ <List
80
+ dataSource={messages}
81
+ renderItem={(message) => (
82
+ <List.Item>
83
+ <Typography.Text>{message.content}</Typography.Text>
84
+ </List.Item>
85
+ )}
86
+ />
87
+ );
88
+ };
89
+
90
+ export default ChatPage;
91
+ ```
92
+
93
+ ## 5. Function Binding
94
+
95
+ In a page or component, we need to bind the Zustand Store's state and methods to the UI. In the example above, we have already bound the `messages` state to the `dataSource` property of the list. Now, we also need a method to add new messages. We can define this method in the Zustand Store and then use it in the page or component:
96
+
97
+ ```jsx
98
+ import { Button } from 'antd';
99
+
100
+ const ChatPage = () => {
101
+ const messages = useChatStore((state) => state.messages);
102
+ const addMessage = useChatStore((state) => state.addMessage);
103
+
104
+ const handleSend = () => {
105
+ addMessage({ id: '1', content: 'Hello, world!', timestamp: Date.now(), sender: 'user' });
106
+ };
107
+
108
+ return (
109
+ <>
110
+ <List
111
+ dataSource={messages}
112
+ renderItem={(message) => (
113
+ <List.Item>
114
+ <Typography.Text>{message.content}</Typography.Text>
115
+ </List.Item>
116
+ )}
117
+ />
118
+ <Button onClick={handleSend}>Send</Button>
119
+ </>
120
+ );
121
+ };
122
+
123
+ export default ChatPage;
124
+ ```
125
+
126
+ The above is the step to implement the "chat message" feature in LobeChat. Of course, in the actual development of LobeChat, the business requirements and scenarios faced in real situations are far more complex than the above demo. Please develop according to the actual situation.