@lobehub/chat 1.18.2 → 1.19.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.

Potentially problematic release.


This version of @lobehub/chat might be problematic. Click here for more details.

Files changed (154) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/Dockerfile +2 -0
  3. package/Dockerfile.database +2 -0
  4. package/locales/ar/chat.json +6 -0
  5. package/locales/ar/error.json +1 -0
  6. package/locales/ar/modelProvider.json +7 -0
  7. package/locales/ar/portal.json +16 -0
  8. package/locales/bg-BG/chat.json +6 -0
  9. package/locales/bg-BG/error.json +1 -0
  10. package/locales/bg-BG/modelProvider.json +7 -0
  11. package/locales/bg-BG/portal.json +16 -0
  12. package/locales/de-DE/chat.json +6 -0
  13. package/locales/de-DE/error.json +1 -0
  14. package/locales/de-DE/modelProvider.json +7 -0
  15. package/locales/de-DE/portal.json +16 -0
  16. package/locales/en-US/chat.json +6 -0
  17. package/locales/en-US/error.json +1 -0
  18. package/locales/en-US/modelProvider.json +7 -0
  19. package/locales/en-US/portal.json +16 -0
  20. package/locales/es-ES/chat.json +6 -0
  21. package/locales/es-ES/error.json +1 -0
  22. package/locales/es-ES/modelProvider.json +7 -0
  23. package/locales/es-ES/portal.json +16 -0
  24. package/locales/fr-FR/chat.json +6 -0
  25. package/locales/fr-FR/error.json +1 -0
  26. package/locales/fr-FR/modelProvider.json +7 -0
  27. package/locales/fr-FR/portal.json +16 -0
  28. package/locales/it-IT/chat.json +6 -0
  29. package/locales/it-IT/error.json +1 -0
  30. package/locales/it-IT/modelProvider.json +7 -0
  31. package/locales/it-IT/portal.json +16 -0
  32. package/locales/ja-JP/chat.json +6 -0
  33. package/locales/ja-JP/error.json +1 -0
  34. package/locales/ja-JP/modelProvider.json +7 -0
  35. package/locales/ja-JP/portal.json +16 -0
  36. package/locales/ko-KR/chat.json +6 -0
  37. package/locales/ko-KR/error.json +1 -0
  38. package/locales/ko-KR/modelProvider.json +7 -0
  39. package/locales/ko-KR/portal.json +16 -0
  40. package/locales/nl-NL/chat.json +6 -0
  41. package/locales/nl-NL/error.json +1 -0
  42. package/locales/nl-NL/modelProvider.json +7 -0
  43. package/locales/nl-NL/portal.json +16 -0
  44. package/locales/pl-PL/chat.json +6 -0
  45. package/locales/pl-PL/error.json +1 -0
  46. package/locales/pl-PL/modelProvider.json +7 -0
  47. package/locales/pl-PL/portal.json +16 -0
  48. package/locales/pt-BR/chat.json +6 -0
  49. package/locales/pt-BR/error.json +1 -0
  50. package/locales/pt-BR/modelProvider.json +7 -0
  51. package/locales/pt-BR/portal.json +16 -0
  52. package/locales/ru-RU/chat.json +6 -0
  53. package/locales/ru-RU/error.json +1 -0
  54. package/locales/ru-RU/modelProvider.json +7 -0
  55. package/locales/ru-RU/portal.json +16 -0
  56. package/locales/tr-TR/chat.json +6 -0
  57. package/locales/tr-TR/error.json +1 -0
  58. package/locales/tr-TR/modelProvider.json +7 -0
  59. package/locales/tr-TR/portal.json +16 -0
  60. package/locales/vi-VN/chat.json +6 -0
  61. package/locales/vi-VN/error.json +1 -0
  62. package/locales/vi-VN/modelProvider.json +7 -0
  63. package/locales/vi-VN/portal.json +16 -0
  64. package/locales/zh-CN/chat.json +6 -0
  65. package/locales/zh-CN/error.json +2 -1
  66. package/locales/zh-CN/modelProvider.json +7 -0
  67. package/locales/zh-CN/portal.json +17 -1
  68. package/locales/zh-TW/chat.json +6 -0
  69. package/locales/zh-TW/error.json +1 -0
  70. package/locales/zh-TW/modelProvider.json +7 -0
  71. package/locales/zh-TW/portal.json +16 -0
  72. package/package.json +4 -2
  73. package/src/app/(main)/chat/(workspace)/@portal/Artifacts/Body/Renderer/HTML.tsx +25 -0
  74. package/src/app/(main)/chat/(workspace)/@portal/Artifacts/Body/Renderer/React.tsx +30 -0
  75. package/src/app/(main)/chat/(workspace)/@portal/Artifacts/Body/Renderer/SVG.tsx +114 -0
  76. package/src/app/(main)/chat/(workspace)/@portal/Artifacts/Body/Renderer/index.tsx +25 -0
  77. package/src/app/(main)/chat/(workspace)/@portal/Artifacts/Body/index.tsx +79 -0
  78. package/src/app/(main)/chat/(workspace)/@portal/Artifacts/Header.tsx +69 -0
  79. package/src/app/(main)/chat/(workspace)/@portal/Artifacts/index.ts +10 -0
  80. package/src/app/(main)/chat/(workspace)/@portal/Artifacts/useEnable.ts +4 -0
  81. package/src/app/(main)/chat/(workspace)/@portal/FilePreview/index.ts +2 -1
  82. package/src/app/(main)/chat/(workspace)/@portal/Home/Body/{Artifacts → Plugins}/index.tsx +1 -1
  83. package/src/app/(main)/chat/(workspace)/@portal/Home/Body/index.tsx +2 -2
  84. package/src/app/(main)/chat/(workspace)/@portal/MessageDetail/index.ts +2 -1
  85. package/src/app/(main)/chat/(workspace)/@portal/Plugins/Body/ToolRender.tsx +1 -1
  86. package/src/app/(main)/chat/(workspace)/@portal/Plugins/Body/index.tsx +1 -1
  87. package/src/app/(main)/chat/(workspace)/@portal/Plugins/Footer.tsx +1 -1
  88. package/src/app/(main)/chat/(workspace)/@portal/Plugins/index.ts +2 -1
  89. package/src/app/(main)/chat/(workspace)/@portal/Plugins/useEnable.ts +1 -1
  90. package/src/app/(main)/chat/(workspace)/@portal/_layout/Desktop.tsx +2 -4
  91. package/src/app/(main)/chat/(workspace)/@portal/features/Body.tsx +27 -0
  92. package/src/app/(main)/chat/(workspace)/@portal/router.tsx +3 -1
  93. package/src/app/(main)/chat/(workspace)/@portal/type.ts +7 -0
  94. package/src/app/(main)/chat/(workspace)/_layout/Desktop/Portal.tsx +3 -2
  95. package/src/app/(main)/settings/llm/ProviderList/Github/index.tsx +53 -0
  96. package/src/app/(main)/settings/llm/ProviderList/providers.tsx +6 -1
  97. package/src/app/api/chat/agentRuntime.ts +14 -0
  98. package/src/components/SidebarHeader/index.tsx +1 -1
  99. package/src/config/llm.ts +14 -0
  100. package/src/config/modelProviders/ai21.ts +37 -0
  101. package/src/config/modelProviders/anthropic.ts +4 -0
  102. package/src/config/modelProviders/github.ts +209 -0
  103. package/src/config/modelProviders/index.ts +8 -0
  104. package/src/config/modelProviders/mistral.ts +38 -21
  105. package/src/config/modelProviders/upstage.ts +9 -9
  106. package/src/const/layoutTokens.ts +1 -1
  107. package/src/const/plugin.test.ts +80 -0
  108. package/src/const/plugin.ts +12 -0
  109. package/src/const/settings/llm.ts +10 -0
  110. package/src/features/Conversation/Error/APIKeyForm/index.tsx +4 -0
  111. package/src/features/Conversation/Messages/Tool/Inspector/index.tsx +1 -1
  112. package/src/features/Conversation/Messages/Tool/index.tsx +1 -1
  113. package/src/features/Conversation/components/ChatItem/index.tsx +24 -2
  114. package/src/features/Conversation/components/ChatItem/utils.test.ts +150 -0
  115. package/src/features/Conversation/components/ChatItem/utils.ts +28 -0
  116. package/src/features/Conversation/components/MarkdownElements/LobeArtifact/Render/Icon.tsx +96 -0
  117. package/src/features/Conversation/components/MarkdownElements/LobeArtifact/Render/index.tsx +129 -0
  118. package/src/features/Conversation/components/MarkdownElements/LobeArtifact/index.ts +10 -0
  119. package/src/features/Conversation/components/MarkdownElements/LobeArtifact/rehypePlugin.ts +74 -0
  120. package/src/features/Conversation/components/MarkdownElements/LobeThinking/Render.tsx +86 -0
  121. package/src/features/Conversation/components/MarkdownElements/LobeThinking/index.ts +12 -0
  122. package/src/features/Conversation/components/MarkdownElements/LobeThinking/rehypePlugin.test.ts +124 -0
  123. package/src/features/Conversation/components/MarkdownElements/LobeThinking/rehypePlugin.ts +51 -0
  124. package/src/features/Conversation/components/MarkdownElements/index.ts +4 -0
  125. package/src/features/Conversation/components/MarkdownElements/type.ts +7 -0
  126. package/src/libs/agent-runtime/AgentRuntime.ts +14 -0
  127. package/src/libs/agent-runtime/ai21/index.test.ts +255 -0
  128. package/src/libs/agent-runtime/ai21/index.ts +18 -0
  129. package/src/libs/agent-runtime/error.ts +2 -0
  130. package/src/libs/agent-runtime/github/index.test.ts +246 -0
  131. package/src/libs/agent-runtime/github/index.ts +15 -0
  132. package/src/libs/agent-runtime/openrouter/__snapshots__/index.test.ts.snap +2215 -28
  133. package/src/libs/agent-runtime/openrouter/fixtures/models.json +3345 -37
  134. package/src/libs/agent-runtime/openrouter/index.ts +2 -1
  135. package/src/libs/agent-runtime/types/type.ts +2 -0
  136. package/src/locales/default/chat.ts +7 -0
  137. package/src/locales/default/error.ts +3 -0
  138. package/src/locales/default/modelProvider.ts +7 -0
  139. package/src/locales/default/portal.ts +17 -1
  140. package/src/server/globalConfig/index.ts +14 -0
  141. package/src/store/chat/slices/message/selectors.ts +30 -28
  142. package/src/store/chat/slices/portal/action.ts +15 -2
  143. package/src/store/chat/slices/portal/initialState.ts +11 -0
  144. package/src/store/chat/slices/portal/selectors.test.ts +29 -7
  145. package/src/store/chat/slices/portal/selectors.ts +56 -12
  146. package/src/styles/loading.ts +28 -0
  147. package/src/tools/artifacts/index.ts +13 -0
  148. package/src/tools/artifacts/systemRole.ts +338 -0
  149. package/src/tools/index.ts +6 -0
  150. package/src/types/user/settings/keyVaults.ts +2 -0
  151. package/src/utils/clipboard.ts +53 -0
  152. /package/src/app/(main)/chat/(workspace)/@portal/Home/Body/{Artifacts → Plugins}/ArtifactList/Item/index.tsx +0 -0
  153. /package/src/app/(main)/chat/(workspace)/@portal/Home/Body/{Artifacts → Plugins}/ArtifactList/Item/style.ts +0 -0
  154. /package/src/app/(main)/chat/(workspace)/@portal/Home/Body/{Artifacts → Plugins}/ArtifactList/index.tsx +0 -0
@@ -0,0 +1,86 @@
1
+ import { Icon } from '@lobehub/ui';
2
+ import { createStyles } from 'antd-style';
3
+ import { BringToFrontIcon, ChevronDown, ChevronRight, Loader2Icon } from 'lucide-react';
4
+ import { memo, useState } from 'react';
5
+ import { useTranslation } from 'react-i18next';
6
+ import { Flexbox } from 'react-layout-kit';
7
+
8
+ import { ARTIFACT_THINKING_TAG } from '@/const/plugin';
9
+ import { useChatStore } from '@/store/chat';
10
+ import { chatSelectors } from '@/store/chat/selectors';
11
+ import { dotLoading } from '@/styles/loading';
12
+
13
+ import { MarkdownElementProps } from '../type';
14
+
15
+ /**
16
+ * Replace all line breaks in the matched `lobeArtifact` tag with an empty string
17
+ */
18
+ export const isLobeThinkingClosed = (input: string = '') => {
19
+ const openTag = `<${ARTIFACT_THINKING_TAG}>`;
20
+ const closeTag = `</${ARTIFACT_THINKING_TAG}>`;
21
+
22
+ return input.includes(openTag) && input.includes(closeTag);
23
+ };
24
+
25
+ const useStyles = createStyles(({ css, token }) => ({
26
+ container: css`
27
+ cursor: pointer;
28
+
29
+ padding-block: 8px;
30
+ padding-inline: 12px;
31
+ padding-inline-end: 12px;
32
+
33
+ color: ${token.colorText};
34
+
35
+ background: ${token.colorFillQuaternary};
36
+ border-radius: 8px;
37
+ `,
38
+ title: css`
39
+ overflow: hidden;
40
+ display: -webkit-box;
41
+ -webkit-box-orient: vertical;
42
+ -webkit-line-clamp: 1;
43
+
44
+ font-size: 12px;
45
+ text-overflow: ellipsis;
46
+ `,
47
+ }));
48
+
49
+ const Render = memo<MarkdownElementProps>(({ children, id }) => {
50
+ const { t } = useTranslation('chat');
51
+ const { styles, cx } = useStyles();
52
+
53
+ const [isGenerating] = useChatStore((s) => {
54
+ const message = chatSelectors.getMessageById(id)(s);
55
+ return [!isLobeThinkingClosed(message?.content)];
56
+ });
57
+
58
+ const [showDetail, setShowDetail] = useState(false);
59
+
60
+ const expand = showDetail || isGenerating;
61
+ return (
62
+ <Flexbox
63
+ className={styles.container}
64
+ gap={16}
65
+ onClick={() => {
66
+ setShowDetail(!showDetail);
67
+ }}
68
+ width={'100%'}
69
+ >
70
+ <Flexbox distribution={'space-between'} flex={1} horizontal>
71
+ <Flexbox gap={8} horizontal>
72
+ <Icon icon={isGenerating ? Loader2Icon : BringToFrontIcon} spin={isGenerating} />
73
+ {isGenerating ? (
74
+ <span className={cx(dotLoading)}>{t('artifact.thinking')}</span>
75
+ ) : (
76
+ t('artifact.thought')
77
+ )}
78
+ </Flexbox>
79
+ <Icon icon={expand ? ChevronDown : ChevronRight} />
80
+ </Flexbox>
81
+ {expand && children}
82
+ </Flexbox>
83
+ );
84
+ });
85
+
86
+ export default Render;
@@ -0,0 +1,12 @@
1
+ import { ARTIFACT_THINKING_TAG } from '@/const/plugin';
2
+
3
+ import Component from './Render';
4
+ import rehypePlugin from './rehypePlugin';
5
+
6
+ const AntThinkingElement = {
7
+ Component,
8
+ rehypePlugin,
9
+ tag: ARTIFACT_THINKING_TAG,
10
+ };
11
+
12
+ export default AntThinkingElement;
@@ -0,0 +1,124 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import rehypePlugin from './rehypePlugin';
4
+
5
+ describe('rehypePlugin', () => {
6
+ it('should transform <lobeThinking> tags within paragraphs', () => {
7
+ const tree = {
8
+ type: 'root',
9
+ children: [
10
+ {
11
+ type: 'element',
12
+ tagName: 'p',
13
+ children: [
14
+ { type: 'text', value: 'Before ' },
15
+ { type: 'raw', value: '<lobeThinking>' },
16
+ { type: 'text', value: 'Thinking content' },
17
+ { type: 'raw', value: '</lobeThinking>' },
18
+ { type: 'text', value: ' After' },
19
+ ],
20
+ },
21
+ ],
22
+ };
23
+
24
+ const expectedTree = {
25
+ type: 'root',
26
+ children: [
27
+ {
28
+ type: 'element',
29
+ tagName: 'lobeThinking',
30
+ properties: {},
31
+ children: [{ type: 'text', value: 'Thinking content' }],
32
+ },
33
+ ],
34
+ };
35
+
36
+ const plugin = rehypePlugin();
37
+ plugin(tree);
38
+
39
+ expect(tree).toEqual(expectedTree);
40
+ });
41
+
42
+ it('should not transform when only closing tag is present', () => {
43
+ const tree = {
44
+ type: 'root',
45
+ children: [
46
+ {
47
+ type: 'element',
48
+ tagName: 'p',
49
+ children: [
50
+ { type: 'text', value: 'Thinking content' },
51
+ { type: 'raw', value: '</lobeThinking>' },
52
+ { type: 'text', value: ' After' },
53
+ ],
54
+ },
55
+ ],
56
+ };
57
+
58
+ const originalTree = JSON.parse(JSON.stringify(tree));
59
+
60
+ const plugin = rehypePlugin();
61
+ plugin(tree);
62
+
63
+ expect(tree).toEqual(originalTree);
64
+ });
65
+
66
+ it('should handle multiple paragraphs and transformations', () => {
67
+ const tree = {
68
+ type: 'root',
69
+ children: [
70
+ {
71
+ type: 'element',
72
+ tagName: 'p',
73
+ children: [{ type: 'text', value: 'Normal paragraph' }],
74
+ },
75
+ {
76
+ type: 'element',
77
+ tagName: 'p',
78
+ children: [
79
+ { type: 'raw', value: '<lobeThinking>' },
80
+ { type: 'text', value: 'First thinking' },
81
+ { type: 'raw', value: '</lobeThinking>' },
82
+ ],
83
+ },
84
+ {
85
+ type: 'element',
86
+ tagName: 'p',
87
+ children: [
88
+ { type: 'raw', value: '<lobeThinking>' },
89
+ { type: 'text', value: 'Second thinking' },
90
+ { type: 'raw', value: '</lobeThinking>' },
91
+ ],
92
+ },
93
+ ],
94
+ };
95
+
96
+ const expectedTree = {
97
+ type: 'root',
98
+ children: [
99
+ {
100
+ type: 'element',
101
+ tagName: 'p',
102
+ children: [{ type: 'text', value: 'Normal paragraph' }],
103
+ },
104
+ {
105
+ type: 'element',
106
+ tagName: 'lobeThinking',
107
+ properties: {},
108
+ children: [{ type: 'text', value: 'First thinking' }],
109
+ },
110
+ {
111
+ type: 'element',
112
+ tagName: 'lobeThinking',
113
+ properties: {},
114
+ children: [{ type: 'text', value: 'Second thinking' }],
115
+ },
116
+ ],
117
+ };
118
+
119
+ const plugin = rehypePlugin();
120
+ plugin(tree);
121
+
122
+ expect(tree).toEqual(expectedTree);
123
+ });
124
+ });
@@ -0,0 +1,51 @@
1
+ import type { Node } from 'unist';
2
+ import { visit } from 'unist-util-visit';
3
+
4
+ import { ARTIFACT_THINKING_TAG } from '@/const/plugin';
5
+
6
+ // eslint-disable-next-line unicorn/consistent-function-scoping
7
+ const rehypePlugin = () => (tree: Node) => {
8
+ visit(tree, 'element', (node: any, index, parent) => {
9
+ if (node.type === 'element' && node.tagName === 'p') {
10
+ const children = node.children || [];
11
+ const openTagIndex = children.findIndex(
12
+ (child: any) => child.type === 'raw' && child.value === `<${ARTIFACT_THINKING_TAG}>`,
13
+ );
14
+ const closeTagIndex = children.findIndex(
15
+ (child: any) => child.type === 'raw' && child.value === `</${ARTIFACT_THINKING_TAG}>`,
16
+ );
17
+
18
+ if (openTagIndex !== -1) {
19
+ // 有闭合标签的情况
20
+ if (closeTagIndex !== -1 && closeTagIndex > openTagIndex) {
21
+ const content = children.slice(openTagIndex + 1, closeTagIndex);
22
+ const lobeThinkingNode = {
23
+ children: content,
24
+ properties: {},
25
+ tagName: ARTIFACT_THINKING_TAG,
26
+ type: 'element',
27
+ };
28
+
29
+ // Replace the entire paragraph with our new lobeThinking node
30
+ parent.children.splice(index, 1, lobeThinkingNode);
31
+ return index; // Skip processing the newly inserted node
32
+ } else {
33
+ // 无闭合标签的情况
34
+ const content = children.slice(openTagIndex + 1);
35
+ const lobeThinkingNode = {
36
+ children: content,
37
+ properties: {},
38
+ tagName: ARTIFACT_THINKING_TAG,
39
+ type: 'element',
40
+ };
41
+
42
+ // Replace the entire paragraph with our new lobeThinking node
43
+ parent.children.splice(index, 1, lobeThinkingNode);
44
+ return index; // Skip processing the newly inserted node
45
+ }
46
+ }
47
+ }
48
+ });
49
+ };
50
+
51
+ export default rehypePlugin;
@@ -0,0 +1,4 @@
1
+ import LobeArtifact from './LobeArtifact';
2
+ import LobeThinking from './LobeThinking';
3
+
4
+ export const markdownElements = [LobeArtifact, LobeThinking];
@@ -0,0 +1,7 @@
1
+ import { ReactNode } from 'react';
2
+
3
+ export interface MarkdownElementProps {
4
+ children: ReactNode;
5
+ id: string;
6
+ type: string;
7
+ }
@@ -3,6 +3,7 @@ import { ClientOptions } from 'openai';
3
3
  import type { TracePayload } from '@/const/trace';
4
4
 
5
5
  import { LobeRuntimeAI } from './BaseAI';
6
+ import { LobeAi21AI } from './ai21';
6
7
  import { LobeAi360AI } from './ai360';
7
8
  import { LobeAnthropicAI } from './anthropic';
8
9
  import { LobeAzureOpenAI } from './azureOpenai';
@@ -10,6 +11,7 @@ import { LobeBaichuanAI } from './baichuan';
10
11
  import { LobeBedrockAI, LobeBedrockAIParams } from './bedrock';
11
12
  import { LobeDeepSeekAI } from './deepseek';
12
13
  import { LobeFireworksAI } from './fireworksai';
14
+ import { LobeGithubAI } from './github';
13
15
  import { LobeGoogleAI } from './google';
14
16
  import { LobeGroq } from './groq';
15
17
  import { LobeMinimaxAI } from './minimax';
@@ -116,6 +118,7 @@ class AgentRuntime {
116
118
  static async initializeWithProviderOptions(
117
119
  provider: string,
118
120
  params: Partial<{
121
+ ai21: Partial<ClientOptions>;
119
122
  ai360: Partial<ClientOptions>;
120
123
  anthropic: Partial<ClientOptions>;
121
124
  azure: { apiVersion?: string; apikey?: string; endpoint?: string };
@@ -123,6 +126,7 @@ class AgentRuntime {
123
126
  bedrock: Partial<LobeBedrockAIParams>;
124
127
  deepseek: Partial<ClientOptions>;
125
128
  fireworksai: Partial<ClientOptions>;
129
+ github: Partial<ClientOptions>;
126
130
  google: { apiKey?: string; baseURL?: string };
127
131
  groq: Partial<ClientOptions>;
128
132
  minimax: Partial<ClientOptions>;
@@ -218,6 +222,11 @@ class AgentRuntime {
218
222
  break;
219
223
  }
220
224
 
225
+ case ModelProvider.Github: {
226
+ runtimeModel = new LobeGithubAI(params.github);
227
+ break;
228
+ }
229
+
221
230
  case ModelProvider.OpenRouter: {
222
231
  runtimeModel = new LobeOpenRouterAI(params.openrouter);
223
232
  break;
@@ -282,6 +291,11 @@ class AgentRuntime {
282
291
  runtimeModel = new LobeSparkAI(params.spark);
283
292
  break;
284
293
  }
294
+
295
+ case ModelProvider.Ai21: {
296
+ runtimeModel = new LobeAi21AI(params.ai21);
297
+ break;
298
+ }
285
299
  }
286
300
 
287
301
  return new AgentRuntime(runtimeModel);
@@ -0,0 +1,255 @@
1
+ // @vitest-environment node
2
+ import OpenAI from 'openai';
3
+ import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
+
5
+ import {
6
+ ChatStreamCallbacks,
7
+ LobeOpenAICompatibleRuntime,
8
+ ModelProvider,
9
+ } from '@/libs/agent-runtime';
10
+
11
+ import * as debugStreamModule from '../utils/debugStream';
12
+ import { LobeAi21AI } from './index';
13
+
14
+ const provider = ModelProvider.Ai21;
15
+ const defaultBaseURL = 'https://api.ai21.com/studio/v1';
16
+
17
+ const bizErrorType = 'ProviderBizError';
18
+ const invalidErrorType = 'InvalidProviderAPIKey';
19
+
20
+ // Mock the console.error to avoid polluting test output
21
+ vi.spyOn(console, 'error').mockImplementation(() => {});
22
+
23
+ let instance: LobeOpenAICompatibleRuntime;
24
+
25
+ beforeEach(() => {
26
+ instance = new LobeAi21AI({ apiKey: 'test' });
27
+
28
+ // 使用 vi.spyOn 来模拟 chat.completions.create 方法
29
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
30
+ new ReadableStream() as any,
31
+ );
32
+ });
33
+
34
+ afterEach(() => {
35
+ vi.clearAllMocks();
36
+ });
37
+
38
+ describe('LobeAi21AI', () => {
39
+ describe('init', () => {
40
+ it('should correctly initialize with an API key', async () => {
41
+ const instance = new LobeAi21AI({ apiKey: 'test_api_key' });
42
+ expect(instance).toBeInstanceOf(LobeAi21AI);
43
+ expect(instance.baseURL).toEqual(defaultBaseURL);
44
+ });
45
+ });
46
+
47
+ describe('chat', () => {
48
+ describe('Error', () => {
49
+ it('should return OpenAIBizError with an openai error response when OpenAI.APIError is thrown', async () => {
50
+ // Arrange
51
+ const apiError = new OpenAI.APIError(
52
+ 400,
53
+ {
54
+ status: 400,
55
+ error: {
56
+ message: 'Bad Request',
57
+ },
58
+ },
59
+ 'Error message',
60
+ {},
61
+ );
62
+
63
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
64
+
65
+ // Act
66
+ try {
67
+ await instance.chat({
68
+ messages: [{ content: 'Hello', role: 'user' }],
69
+ model: 'jamba-1.5-mini',
70
+ temperature: 0,
71
+ });
72
+ } catch (e) {
73
+ expect(e).toEqual({
74
+ endpoint: defaultBaseURL,
75
+ error: {
76
+ error: { message: 'Bad Request' },
77
+ status: 400,
78
+ },
79
+ errorType: bizErrorType,
80
+ provider,
81
+ });
82
+ }
83
+ });
84
+
85
+ it('should throw AgentRuntimeError with NoOpenAIAPIKey if no apiKey is provided', async () => {
86
+ try {
87
+ new LobeAi21AI({});
88
+ } catch (e) {
89
+ expect(e).toEqual({ errorType: invalidErrorType });
90
+ }
91
+ });
92
+
93
+ it('should return OpenAIBizError with the cause when OpenAI.APIError is thrown with cause', async () => {
94
+ // Arrange
95
+ const errorInfo = {
96
+ stack: 'abc',
97
+ cause: {
98
+ message: 'api is undefined',
99
+ },
100
+ };
101
+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
102
+
103
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
104
+
105
+ // Act
106
+ try {
107
+ await instance.chat({
108
+ messages: [{ content: 'Hello', role: 'user' }],
109
+ model: 'jamba-1.5-mini',
110
+ temperature: 0,
111
+ });
112
+ } catch (e) {
113
+ expect(e).toEqual({
114
+ endpoint: defaultBaseURL,
115
+ error: {
116
+ cause: { message: 'api is undefined' },
117
+ stack: 'abc',
118
+ },
119
+ errorType: bizErrorType,
120
+ provider,
121
+ });
122
+ }
123
+ });
124
+
125
+ it('should return OpenAIBizError with an cause response with desensitize Url', async () => {
126
+ // Arrange
127
+ const errorInfo = {
128
+ stack: 'abc',
129
+ cause: { message: 'api is undefined' },
130
+ };
131
+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
132
+
133
+ instance = new LobeAi21AI({
134
+ apiKey: 'test',
135
+
136
+ baseURL: 'https://api.abc.com/v1',
137
+ });
138
+
139
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
140
+
141
+ // Act
142
+ try {
143
+ await instance.chat({
144
+ messages: [{ content: 'Hello', role: 'user' }],
145
+ model: 'jamba-1.5-mini',
146
+ temperature: 0,
147
+ });
148
+ } catch (e) {
149
+ expect(e).toEqual({
150
+ endpoint: 'https://api.***.com/v1',
151
+ error: {
152
+ cause: { message: 'api is undefined' },
153
+ stack: 'abc',
154
+ },
155
+ errorType: bizErrorType,
156
+ provider,
157
+ });
158
+ }
159
+ });
160
+
161
+ it('should throw an InvalidAi21APIKey error type on 401 status code', async () => {
162
+ // Mock the API call to simulate a 401 error
163
+ const error = new Error('Unauthorized') as any;
164
+ error.status = 401;
165
+ vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
166
+
167
+ try {
168
+ await instance.chat({
169
+ messages: [{ content: 'Hello', role: 'user' }],
170
+ model: 'jamba-1.5-mini',
171
+ temperature: 0,
172
+ });
173
+ } catch (e) {
174
+ // Expect the chat method to throw an error with InvalidAi21APIKey
175
+ expect(e).toEqual({
176
+ endpoint: defaultBaseURL,
177
+ error: new Error('Unauthorized'),
178
+ errorType: invalidErrorType,
179
+ provider,
180
+ });
181
+ }
182
+ });
183
+
184
+ it('should return AgentRuntimeError for non-OpenAI errors', async () => {
185
+ // Arrange
186
+ const genericError = new Error('Generic Error');
187
+
188
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(genericError);
189
+
190
+ // Act
191
+ try {
192
+ await instance.chat({
193
+ messages: [{ content: 'Hello', role: 'user' }],
194
+ model: 'jamba-1.5-mini',
195
+ temperature: 0,
196
+ });
197
+ } catch (e) {
198
+ expect(e).toEqual({
199
+ endpoint: defaultBaseURL,
200
+ errorType: 'AgentRuntimeError',
201
+ provider,
202
+ error: {
203
+ name: genericError.name,
204
+ cause: genericError.cause,
205
+ message: genericError.message,
206
+ stack: genericError.stack,
207
+ },
208
+ });
209
+ }
210
+ });
211
+ });
212
+
213
+ describe('DEBUG', () => {
214
+ it('should call debugStream and return StreamingTextResponse when DEBUG_AI21_CHAT_COMPLETION is 1', async () => {
215
+ // Arrange
216
+ const mockProdStream = new ReadableStream() as any; // 模拟的 prod 流
217
+ const mockDebugStream = new ReadableStream({
218
+ start(controller) {
219
+ controller.enqueue('Debug stream content');
220
+ controller.close();
221
+ },
222
+ }) as any;
223
+ mockDebugStream.toReadableStream = () => mockDebugStream; // 添加 toReadableStream 方法
224
+
225
+ // 模拟 chat.completions.create 返回值,包括模拟的 tee 方法
226
+ (instance['client'].chat.completions.create as Mock).mockResolvedValue({
227
+ tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
228
+ });
229
+
230
+ // 保存原始环境变量值
231
+ const originalDebugValue = process.env.DEBUG_AI21_CHAT_COMPLETION;
232
+
233
+ // 模拟环境变量
234
+ process.env.DEBUG_AI21_CHAT_COMPLETION = '1';
235
+ vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
236
+
237
+ // 执行测试
238
+ // 运行你的测试函数,确保它会在条件满足时调用 debugStream
239
+ // 假设的测试函数调用,你可能需要根据实际情况调整
240
+ await instance.chat({
241
+ messages: [{ content: 'Hello', role: 'user' }],
242
+ model: 'jamba-1.5-mini',
243
+ stream: true,
244
+ temperature: 0,
245
+ });
246
+
247
+ // 验证 debugStream 被调用
248
+ expect(debugStreamModule.debugStream).toHaveBeenCalled();
249
+
250
+ // 恢复原始环境变量值
251
+ process.env.DEBUG_AI21_CHAT_COMPLETION = originalDebugValue;
252
+ });
253
+ });
254
+ });
255
+ });
@@ -0,0 +1,18 @@
1
+ import { ModelProvider } from '../types';
2
+ import { LobeOpenAICompatibleFactory } from '../utils/openaiCompatibleFactory';
3
+
4
+ export const LobeAi21AI = LobeOpenAICompatibleFactory({
5
+ baseURL: 'https://api.ai21.com/studio/v1',
6
+ chatCompletion: {
7
+ handlePayload: (payload) => {
8
+ return {
9
+ ...payload,
10
+ stream: !payload.tools,
11
+ } as any;
12
+ },
13
+ },
14
+ debug: {
15
+ chatCompletion: () => process.env.DEBUG_AI21_CHAT_COMPLETION === '1',
16
+ },
17
+ provider: ModelProvider.Ai21,
18
+ });
@@ -13,6 +13,8 @@ export const AgentRuntimeErrorType = {
13
13
  InvalidBedrockCredentials: 'InvalidBedrockCredentials',
14
14
  StreamChunkError: 'StreamChunkError',
15
15
 
16
+ InvalidGithubToken: 'InvalidGithubToken',
17
+
16
18
  /**
17
19
  * @deprecated
18
20
  */