@lobehub/chat 0.11.0 → 0.12.0

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,31 @@
2
2
 
3
3
  # Changelog
4
4
 
5
+ ## [Version 0.12.0](https://github.com/lobehub/lobe-chat/compare/v0.11.0...v0.12.0)
6
+
7
+ <sup>Released on **2023-07-23**</sup>
8
+
9
+ #### ✨ Features
10
+
11
+ - **misc**: 支持插件列表 与 基于 Serpapi 的搜索引擎插件.
12
+
13
+ <br/>
14
+
15
+ <details>
16
+ <summary><kbd>Improvements and Fixes</kbd></summary>
17
+
18
+ #### What's improved
19
+
20
+ - **misc**: 支持插件列表 与 基于 Serpapi 的搜索引擎插件, closes [#12](https://github.com/lobehub/lobe-chat/issues/12) ([d89e06f](https://github.com/lobehub/lobe-chat/commit/d89e06f))
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
+
5
30
  ## [Version 0.11.0](https://github.com/lobehub/lobe-chat/compare/v0.10.2...v0.11.0)
6
31
 
7
32
  <sup>Released on **2023-07-23**</sup>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/chat",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Lobe Chat is an open-source chatbot client using LangChain, Typescript and Next.js",
5
5
  "keywords": [
6
6
  "chatbot",
@@ -82,11 +82,13 @@
82
82
  "next": "13.4.7",
83
83
  "openai-edge": "^1",
84
84
  "polished": "^4",
85
+ "query-string": "^8",
85
86
  "react": "^18",
86
87
  "react-dom": "^18",
87
88
  "react-hotkeys-hook": "^4",
88
89
  "react-i18next": "^13",
89
90
  "react-layout-kit": "^1",
91
+ "serpapi": "^1",
90
92
  "swr": "^2",
91
93
  "ts-md5": "^1",
92
94
  "uuid": "^9",
@@ -35,6 +35,9 @@ export default {
35
35
  'newAgent': '新建助手',
36
36
  'noDescription': '暂无描述',
37
37
  'ok': '确定',
38
+ 'plugin-realtimeWeather': '实时天气预报',
39
+ 'plugin-searchEngine': '搜索引擎',
40
+ 'pluginList': '插件列表',
38
41
  'profile': '助手身份',
39
42
  'reset': '重置',
40
43
  'searchAgentPlaceholder': '搜索助手和对话...',
@@ -4,7 +4,7 @@ import { ChatCompletionFunctions, ChatCompletionRequestMessage } from 'openai-ed
4
4
 
5
5
  import { OpenAIStreamPayload } from '@/types/openai';
6
6
 
7
- import { plugins } from './plugins';
7
+ import pluginList from '../../plugins';
8
8
 
9
9
  export const runtime = 'edge';
10
10
 
@@ -18,12 +18,28 @@ const config = new Configuration({
18
18
 
19
19
  const openai = new OpenAIApi(config, isDev && OPENAI_PROXY_URL ? OPENAI_PROXY_URL : undefined);
20
20
 
21
- const functions: ChatCompletionFunctions[] = plugins.map((f) => f.schema);
22
-
23
21
  export default async function handler(req: Request) {
24
- // Extract the `messages` from the body of the request
25
- const { messages, ...params } = (await req.json()) as OpenAIStreamPayload;
22
+ const {
23
+ messages,
24
+ plugins: enabledPlugins,
25
+ ...params
26
+ } = (await req.json()) as OpenAIStreamPayload;
27
+
28
+ // ============ 1. 前置处理 functions ============ //
29
+
30
+ const filterFunctions: ChatCompletionFunctions[] = pluginList
31
+ .filter((p) => {
32
+ // 如果不存在 enabledPlugins,那么全部不启用
33
+ if (!enabledPlugins) return false;
34
+
35
+ // 如果存在 enabledPlugins,那么只启用 enabledPlugins 中的插件
36
+ return enabledPlugins.includes(p.name);
37
+ })
38
+ .map((f) => f.schema);
26
39
 
40
+ const functions = filterFunctions.length === 0 ? undefined : filterFunctions;
41
+
42
+ // ============ 2. 前置处理 messages ============ //
27
43
  const formatMessages = messages.map((m) => ({ content: m.content, role: m.role }));
28
44
 
29
45
  const response = await openai.createChatCompletion({
@@ -35,7 +51,9 @@ export default async function handler(req: Request) {
35
51
 
36
52
  const stream = OpenAIStream(response, {
37
53
  experimental_onFunctionCall: async ({ name, arguments: args }, createFunctionCallMessages) => {
38
- const func = plugins.find((f) => f.name === name);
54
+ console.log(`执行 functionCall [${name}]`, 'args:', args);
55
+
56
+ const func = pluginList.find((f) => f.name === name);
39
57
 
40
58
  if (func) {
41
59
  const result = await func.runner(args as any);
@@ -51,5 +69,6 @@ export default async function handler(req: Request) {
51
69
  }
52
70
  },
53
71
  });
72
+
54
73
  return new StreamingTextResponse(stream);
55
74
  }
@@ -0,0 +1,46 @@
1
+ import { Avatar } from '@lobehub/ui';
2
+ import { List, Switch, Tag } from 'antd';
3
+ import isEqual from 'fast-deep-equal';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { Flexbox } from 'react-layout-kit';
6
+ import { shallow } from 'zustand/shallow';
7
+
8
+ import pluginList from '@/plugins';
9
+ import { agentSelectors, useSessionStore } from '@/store/session';
10
+
11
+ const PluginList = () => {
12
+ const { t } = useTranslation('common');
13
+
14
+ const config = useSessionStore(agentSelectors.currentAgentConfigSafe, isEqual);
15
+
16
+ const [toggleAgentPlugin] = useSessionStore((s) => [s.toggleAgentPlugin], shallow);
17
+
18
+ return (
19
+ <List
20
+ bordered
21
+ dataSource={pluginList}
22
+ renderItem={(item) => (
23
+ <List.Item>
24
+ <List.Item.Meta
25
+ avatar={<Avatar avatar={item.avatar} />}
26
+ description={item.schema.description}
27
+ title={
28
+ <Flexbox align={'center'} gap={8} horizontal>
29
+ {t(`plugin-${item.name}` as any)} <Tag>{item.name}</Tag>
30
+ </Flexbox>
31
+ }
32
+ />
33
+ <Switch
34
+ checked={!config.plugins ? false : config.plugins.includes(item.name)}
35
+ onChange={() => {
36
+ toggleAgentPlugin(item.name);
37
+ }}
38
+ />
39
+ </List.Item>
40
+ )}
41
+ size={'large'}
42
+ />
43
+ );
44
+ };
45
+
46
+ export default PluginList;
@@ -9,6 +9,7 @@ import { LanguageModel } from '@/types/llm';
9
9
 
10
10
  import { FormItem } from '../FormItem';
11
11
  import { useStyles } from '../style';
12
+ import Plugin from './Plugin';
12
13
  import Prompt from './Prompt';
13
14
 
14
15
  const AgentConfig = () => {
@@ -58,8 +59,6 @@ const AgentConfig = () => {
58
59
  </FormItem>
59
60
  <Prompt />
60
61
  <Collapse
61
- activeKey={['advanceSettings']}
62
- bordered={false}
63
62
  className={styles.title}
64
63
  expandIconPosition={'end'}
65
64
  items={[
@@ -95,7 +94,19 @@ const AgentConfig = () => {
95
94
  },
96
95
  ]}
97
96
  />
98
- </Flexbox>{' '}
97
+ <Flexbox
98
+ align={'center'}
99
+ distribution={'space-between'}
100
+ horizontal
101
+ paddingBlock={12}
102
+ style={{
103
+ borderBottom: `1px solid ${theme.colorBorder}`,
104
+ }}
105
+ >
106
+ <Flexbox className={styles.profile}> {t('pluginList')}</Flexbox>
107
+ </Flexbox>
108
+ <Plugin />
109
+ </Flexbox>
99
110
  </ConfigProvider>
100
111
  );
101
112
  };
@@ -30,13 +30,5 @@ export const useStyles = createStyles(({ css, token }) => ({
30
30
  title: css`
31
31
  font-size: 16px;
32
32
  font-weight: 500;
33
-
34
- .ant-collapse-header {
35
- padding: 0 !important;
36
- }
37
-
38
- .ant-collapse-content-box {
39
- padding: 0 !important;
40
- }
41
33
  `,
42
34
  }));
@@ -0,0 +1,6 @@
1
+ import searchEngine from './searchEngine';
2
+ import getWeather from './weather';
3
+
4
+ const pluginList = [getWeather, searchEngine];
5
+
6
+ export default pluginList;
@@ -0,0 +1,27 @@
1
+ import { ChatCompletionFunctions } from 'openai-edge/types/api';
2
+
3
+ import runner from './runner';
4
+
5
+ const schema: ChatCompletionFunctions = {
6
+ description: '查询搜索引擎获取信息',
7
+ name: 'searchEngine',
8
+ parameters: {
9
+ properties: {
10
+ keywords: {
11
+ description: '关键词',
12
+ type: 'string',
13
+ },
14
+ },
15
+ required: ['keywords'],
16
+ type: 'object',
17
+ },
18
+ };
19
+
20
+ const searchEngine = {
21
+ avatar: '🔍',
22
+ name: 'searchEngine',
23
+ runner,
24
+ schema,
25
+ };
26
+
27
+ export default searchEngine;
@@ -0,0 +1,106 @@
1
+ import querystring from 'query-string';
2
+
3
+ const BASE_URL = 'https://serpapi.com/search';
4
+
5
+ const API_KEY = process.env.SERPAI_API_KEY;
6
+
7
+ export type OrganicResults = OrganicResult[];
8
+
9
+ export interface OrganicResult {
10
+ about_page_link: string;
11
+ about_page_serpapi_link: string;
12
+ about_this_result: AboutThisResult;
13
+ cached_page_link?: string;
14
+ date?: string;
15
+ displayed_link: string;
16
+ favicon?: string;
17
+ link: string;
18
+ position: number;
19
+ related_results?: RelatedResult[];
20
+ rich_snippet?: RichSnippet;
21
+ snippet: string;
22
+ snippet_highlighted_words?: string[];
23
+ source: string;
24
+ thumbnail?: string;
25
+ title: string;
26
+ }
27
+
28
+ export interface AboutThisResult {
29
+ languages: string[];
30
+ regions: string[];
31
+ source: Source;
32
+ }
33
+
34
+ export interface Source {
35
+ description: string;
36
+ icon: string;
37
+ security?: string;
38
+ source_info_link?: string;
39
+ }
40
+
41
+ export interface RelatedResult {
42
+ about_page_link: string;
43
+ about_page_serpapi_link: string;
44
+ about_this_result: AboutThisResult2;
45
+ cached_page_link: string;
46
+ date: string;
47
+ displayed_link: string;
48
+ link: string;
49
+ position: number;
50
+ snippet: string;
51
+ snippet_highlighted_words: string[];
52
+ title: string;
53
+ }
54
+
55
+ export interface AboutThisResult2 {
56
+ languages: string[];
57
+ regions: string[];
58
+ source: Source2;
59
+ }
60
+
61
+ export interface Source2 {
62
+ description: string;
63
+ icon: string;
64
+ }
65
+
66
+ export interface RichSnippet {
67
+ top: Top;
68
+ }
69
+
70
+ export interface Top {
71
+ detected_extensions: DetectedExtensions;
72
+ extensions: string[];
73
+ }
74
+
75
+ export interface DetectedExtensions {
76
+ month_ago: number;
77
+ }
78
+
79
+ const fetchResult = async (keywords: string) => {
80
+ const params = {
81
+ api_key: API_KEY,
82
+ gl: 'cn',
83
+ google_domain: 'google.com',
84
+ hl: 'zh-cn',
85
+ location: 'China',
86
+ q: keywords,
87
+ };
88
+
89
+ const query = querystring.stringify(params);
90
+
91
+ const res = await fetch(`${BASE_URL}?${query}`);
92
+
93
+ const data = await res.json();
94
+
95
+ const results = data.organic_results as OrganicResults;
96
+
97
+ return results.map((r) => ({
98
+ content: r.snippet,
99
+ date: r.date,
100
+ link: r.link,
101
+ source: r.source,
102
+ title: r.title,
103
+ }));
104
+ };
105
+
106
+ export default fetchResult;
@@ -2,7 +2,7 @@ import runner from './runner';
2
2
 
3
3
  const schema = {
4
4
  description: '获取当前天气情况',
5
- name: 'fetchWeather',
5
+ name: 'realtimeWeather',
6
6
  parameters: {
7
7
  properties: {
8
8
  city: {
@@ -15,6 +15,6 @@ const schema = {
15
15
  },
16
16
  };
17
17
 
18
- const getWeather = { name: 'fetchWeather', runner, schema };
18
+ const getWeather = { avatar: '☂️', name: 'realtimeWeather', runner, schema };
19
19
 
20
20
  export default getWeather;
@@ -1,6 +1,8 @@
1
1
  import { create } from 'zustand';
2
2
  import { PersistOptions, devtools, persist } from 'zustand/middleware';
3
3
 
4
+ import { isDev } from '@/utils/env';
5
+
4
6
  import { SessionStore, createStore } from './store';
5
7
 
6
8
  type SessionPersist = Pick<SessionStore, 'sessions'>;
@@ -23,7 +25,7 @@ const persistOptions: PersistOptions<SessionStore, SessionPersist> = {
23
25
  export const useSessionStore = create<SessionStore>()(
24
26
  persist(
25
27
  devtools(createStore, {
26
- name: LOBE_CHAT,
28
+ name: LOBE_CHAT + (isDev ? '_DEV' : ''),
27
29
  }),
28
30
  persistOptions,
29
31
  ),
@@ -1,3 +1,4 @@
1
+ import { produce } from 'immer';
1
2
  import { StateCreator } from 'zustand/vanilla';
2
3
 
3
4
  import { promptPickEmoji, promptSummaryAgentName, promptSummaryDescription } from '@/prompts/agent';
@@ -43,12 +44,13 @@ export interface AgentAction {
43
44
  * @returns 任意类型的返回值
44
45
  */
45
46
  internalUpdateAgentMeta: (id: string) => any;
47
+ toggleAgentPlugin: (pluginId: string) => void;
48
+
46
49
  /**
47
50
  * 切换配置
48
51
  * @param showPanel - 是否显示面板,默认为 true
49
52
  */
50
53
  toggleConfig: (showPanel?: boolean) => void;
51
-
52
54
  /**
53
55
  * 更新代理配置
54
56
  * @param config - 部分 LobeAgentConfig 的配置
@@ -191,6 +193,27 @@ export const createAgentSlice: StateCreator<
191
193
  };
192
194
  },
193
195
 
196
+ toggleAgentPlugin: (id: string) => {
197
+ const { activeId } = get();
198
+ const session = sessionSelectors.currentSession(get());
199
+ if (!activeId || !session) return;
200
+
201
+ const config = produce(session.config, (draft) => {
202
+ if (draft.plugins === undefined) {
203
+ draft.plugins = [id];
204
+ } else {
205
+ const plugins = draft.plugins;
206
+ if (plugins.includes(id)) {
207
+ plugins.splice(plugins.indexOf(id), 1);
208
+ } else {
209
+ plugins.push(id);
210
+ }
211
+ }
212
+ });
213
+
214
+ get().dispatchSession({ config, id: activeId, type: 'updateSessionConfig' });
215
+ },
216
+
194
217
  toggleConfig: (newValue) => {
195
218
  const showAgentSettings = typeof newValue === 'boolean' ? newValue : !get().showAgentSettings;
196
219
 
@@ -204,6 +227,7 @@ export const createAgentSlice: StateCreator<
204
227
 
205
228
  get().dispatchSession({ config, id: activeId, type: 'updateSessionConfig' });
206
229
  },
230
+
207
231
  updateAgentMeta: (meta) => {
208
232
  const { activeId } = get();
209
233
  const session = sessionSelectors.currentSession(get());
@@ -104,7 +104,8 @@ export const createChatSlice: StateCreator<
104
104
  set({ chatLoading: true });
105
105
  const config = agentSelectors.currentAgentConfigSafe(get());
106
106
 
107
- const fetcher = () => fetchChatModel({ messages, model: config.model, ...config.params });
107
+ const fetcher = () =>
108
+ fetchChatModel({ messages, model: config.model, ...config.params, plugins: config.plugins });
108
109
 
109
110
  await fetchSSE(fetcher, options);
110
111
 
@@ -1,6 +1,8 @@
1
1
  import { create } from 'zustand';
2
2
  import { type PersistOptions, devtools, persist } from 'zustand/middleware';
3
3
 
4
+ import { isDev } from '@/utils/env';
5
+
4
6
  import { type SettingsStore, createStore } from './store';
5
7
 
6
8
  export const LOBE_SETTINGS = 'LOBE_SETTINGS';
@@ -13,7 +15,7 @@ const persistOptions: PersistOptions<SettingsStore> = {
13
15
  export const useSettings = create<SettingsStore>()(
14
16
  persist(
15
17
  devtools(createStore, {
16
- name: LOBE_SETTINGS,
18
+ name: LOBE_SETTINGS + (isDev ? '_DEV' : ''),
17
19
  }),
18
20
  persistOptions,
19
21
  ),
@@ -39,6 +39,10 @@ export interface OpenAIStreamPayload {
39
39
  * @title 返回的文本数量
40
40
  */
41
41
  n?: number;
42
+ /**
43
+ * 开启的插件列表
44
+ */
45
+ plugins?: string[];
42
46
  /**
43
47
  * @title 控制生成文本中的惩罚系数,用于减少主题的变化
44
48
  * @default 0
@@ -54,6 +58,7 @@ export interface OpenAIStreamPayload {
54
58
  * @default 0.5
55
59
  */
56
60
  temperature: number;
61
+
57
62
  /**
58
63
  * @title 控制生成文本中最高概率的单个令牌
59
64
  * @default 1
@@ -39,6 +39,10 @@ export interface LobeAgentConfig {
39
39
  * 语言模型参数
40
40
  */
41
41
  params: LLMParams;
42
+ /**
43
+ * 启用的插件
44
+ */
45
+ plugins?: string[];
42
46
  /**
43
47
  * 系统角色
44
48
  */
@@ -0,0 +1 @@
1
+ export const isDev = process.env.NODE_ENV === 'development';
@@ -1,3 +0,0 @@
1
- import getWeather from './weather';
2
-
3
- export const plugins = [getWeather];