Skip to content

Commit 69da15f

Browse files
author
lrhh123
committed
fix: 修复回复插件
1 parent da02311 commit 69da15f

File tree

8 files changed

+108
-98
lines changed

8 files changed

+108
-98
lines changed

src/main/backend/backend.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,7 @@ class BKServer {
394394
success: false,
395395
error: error instanceof Error ? error.message : String(error),
396396
message: error instanceof Error ? error.message : String(error),
397+
consoleOutput: [],
397398
});
398399
}
399400
});

src/main/backend/controllers/configController.ts

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,23 @@ export class ConfigController {
2020
const appId = ctx.get(CTX_APP_ID);
2121
const instanceId = ctx.get(CTX_INSTANCE_ID);
2222

23-
const instanceConfig = await Config.findOne({
23+
let config;
24+
25+
config = await Config.findOne({
2426
where: { instance_id: instanceId },
2527
});
26-
if (instanceConfig) {
27-
return instanceConfig;
28-
}
2928

30-
const appConfig = await Config.findOne({
31-
where: { platform_id: appId },
32-
});
33-
if (appConfig) {
34-
return appConfig;
29+
if (!config && appId) {
30+
config = await Config.findOne({
31+
where: { platform_id: appId },
32+
});
3533
}
3634

37-
let config = await Config.findOne({
38-
where: { global: true },
39-
});
35+
if (!config) {
36+
config = await Config.findOne({
37+
where: { global: true },
38+
});
39+
}
4040

4141
if (!config) {
4242
config = await Config.create({
@@ -54,6 +54,20 @@ export class ConfigController {
5454
config.has_use_gpt = globalConfig.has_use_gpt;
5555
config.has_mouse_close = globalConfig.has_mouse_close;
5656
}
57+
58+
// 再检查 key 和 base_url 是否存在,不存在则使用全局配置
59+
if (!config.key || !config.base_url) {
60+
config.llm_type = globalConfig?.llm_type || 'chatgpt';
61+
config.model = globalConfig?.model || 'gpt-3.5-turbo';
62+
}
63+
64+
if (!config.key) {
65+
config.key = globalConfig?.key || '';
66+
}
67+
68+
if (!config.base_url) {
69+
config.base_url = globalConfig?.base_url || '';
70+
}
5771
}
5872

5973
return config;

src/main/backend/services/messageService.ts

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -152,10 +152,10 @@ export class MessageService {
152152
* 检查 LLM 是否可用
153153
*/
154154
public async checkGptHealth(cfg: LLMConfig) {
155-
const llmClient = this.createLLMClient(cfg, cfg.llmType);
156-
// 尝试使用它回复 Hi 来检查是否可用
157-
if ('chat' in llmClient) {
158-
try {
155+
try {
156+
const llmClient = this.createLLMClient(cfg, cfg.llmType);
157+
// 尝试使用它回复 Hi 来检查是否可用
158+
if ('chat' in llmClient) {
159159
// @ts-ignore
160160
const response = await llmClient.chat.completions.create({
161161
model: cfg.model,
@@ -178,13 +178,13 @@ export class MessageService {
178178
status: true,
179179
message: chunks.join(''),
180180
};
181-
} catch (error) {
182-
console.error(`Error in getLLMResponse: ${error}`);
183-
return {
184-
status: false,
185-
message: error instanceof Error ? error.message : String(error),
186-
};
187181
}
182+
} catch (error) {
183+
console.error(`Error in getLLMResponse: ${error}`);
184+
return {
185+
status: false,
186+
message: error instanceof Error ? error.message : String(error),
187+
};
188188
}
189189

190190
return {
@@ -212,8 +212,13 @@ export class MessageService {
212212

213213
let llmClient = this.llmClientMap.get(llm_name);
214214
if (!llmClient) {
215-
llmClient = this.createLLMClient(cfg, llm_name);
216-
this.llmClientMap.set(llm_name, llmClient);
215+
try {
216+
llmClient = this.createLLMClient(cfg, llm_name);
217+
this.llmClientMap.set(llm_name, llmClient);
218+
} catch (error) {
219+
console.error(`Error in getLLMResponse: ${error}`);
220+
return null;
221+
}
217222
}
218223

219224
// 检查 llmClient 是否存在 completions 方法
@@ -255,6 +260,8 @@ export class MessageService {
255260
let key;
256261
let baseUrl;
257262

263+
console.log('Creating LLM client:', llmName, cfg);
264+
258265
if ('baseUrl' in cfg) {
259266
key = cfg.key;
260267
baseUrl = cfg.baseUrl;
@@ -264,6 +271,9 @@ export class MessageService {
264271
}
265272

266273
const options = { apiKey: key, baseURL: baseUrl };
274+
if (!options.baseURL || !options.apiKey) {
275+
throw new Error('Missing required API key or base URL');
276+
}
267277

268278
if (llmName === 'ernie') {
269279
return new ErnieAI(options);

src/renderer/components/Settings/PluginSettings.tsx

Lines changed: 49 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import {
2626
updateConfig,
2727
checkPluginAvailability,
2828
} from '../../services/platform/controller';
29-
import { PluginConfig } from '../../services/platform/platform.d';
29+
import { PluginConfig, LogBody } from '../../services/platform/platform.d';
3030
import MessageModal from '../MessageModal';
3131
import { useSystemStore } from '../../stores/useSystemStore';
3232

@@ -40,6 +40,7 @@ const PluginSettings = ({
4040
// TODO: 后面需要把这个参数说明放到文档中
4141

4242
const [code, setCode] = useState<string | undefined>(PluginExampleCode);
43+
const [consoleLogs, setConsoleLogs] = useState<LogBody[]>([]);
4344
const { isOpen, onOpen, onClose } = useDisclosure();
4445
const [isOpenMessageModal, setIsOpenMessageModal] = useState(false);
4546
const cancelRef = React.useRef<any>();
@@ -152,10 +153,16 @@ const PluginSettings = ({
152153
provideCompletionItems: () => {
153154
const suggestions = [
154155
{
155-
label: 'cc.get',
156+
label: 'require',
156157
kind: monaco.languages.CompletionItemKind.Function,
157-
insertText: 'cc.get(ctx)',
158-
documentation: '从上下文中取得当前使用的配置',
158+
insertText: 'require()',
159+
documentation: '引入模块',
160+
},
161+
{
162+
label: 'console',
163+
kind: monaco.languages.CompletionItemKind.Function,
164+
insertText: 'console.log()',
165+
documentation: '打印日志',
159166
},
160167
];
161168
return { suggestions };
@@ -187,6 +194,8 @@ const PluginSettings = ({
187194
messages,
188195
});
189196

197+
setConsoleLogs(resp.consoleOutput || []);
198+
190199
if (resp.status) {
191200
toast({
192201
title: '插件测试通过',
@@ -264,56 +273,70 @@ const PluginSettings = ({
264273
>
265274
启用自定义代码
266275
</Switch>
267-
<Button
268-
onClick={handleCheckPlugin}
269-
colorScheme="green"
270-
size="sm"
271-
ml={4}
272-
>
273-
测试插件
274-
</Button>
275276
</HStack>
276277
{config.usePlugin && (
277278
<>
278-
<Box width="100%" height="400px">
279-
<Editor
280-
height="100%"
281-
defaultLanguage="javascript"
282-
value={code}
283-
onChange={setCode}
284-
beforeMount={handleEditorWillMount}
285-
theme="vs-dark"
286-
/>
287-
</Box>
288-
289279
<HStack>
290280
<Button
291281
onClick={() => {
292282
handleSaveCode();
293283
}}
284+
size="sm"
294285
colorScheme="orange"
295286
>
296287
保存代码
297288
</Button>
298289

299-
<Button onClick={handleDefaultCode} colorScheme="red">
290+
<Button onClick={handleDefaultCode} colorScheme="red" size="sm">
300291
重置代码
301292
</Button>
302293

303294
<Button
304295
onClick={() => {
305296
setIsOpenMessageModal(true);
306297
}}
298+
size="sm"
307299
colorScheme="teal"
308300
>
309301
配置测试用例
310302
</Button>
311-
312-
<Button onClick={handleExportCode} colorScheme="blue">
303+
<Button onClick={handleCheckPlugin} colorScheme="green" size="sm">
304+
测试插件
305+
</Button>
306+
<Button onClick={handleExportCode} colorScheme="blue" size="sm">
313307
导出代码
314308
</Button>
315309
</HStack>
316310

311+
<Box width="100%" height="400px">
312+
<Editor
313+
height="100%"
314+
defaultLanguage="javascript"
315+
value={code}
316+
onChange={setCode}
317+
beforeMount={handleEditorWillMount}
318+
theme="vs-dark"
319+
/>
320+
</Box>
321+
322+
<Divider />
323+
324+
{/* 展示日志 */}
325+
{consoleLogs && consoleLogs.length > 0 && (
326+
<>
327+
<Text fontSize="1xl" fontWeight="bold">
328+
插件执行日志:
329+
</Text>
330+
<Box height="200px" overflowY="auto">
331+
{consoleLogs.map((log, index) => (
332+
<Text key={index}>
333+
{log.level} {log.time} {log.message}
334+
</Text>
335+
))}
336+
</Box>
337+
</>
338+
)}
339+
317340
<AlertDialog
318341
isOpen={isOpen}
319342
leastDestructiveRef={cancelRef}

src/renderer/hooks/useBroadcastContext.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,6 @@ export const BroadcastProvider = ({ children }: { children: ReactNode }) => {
4343

4444
window.electron.ipcRenderer.on('broadcast', (msg) => {
4545
const message = msg as BroadcastMessage;
46-
console.log('Received broadcast', message);
4746
eventHandlers.forEach((handler) => handler(message));
4847
});
4948

src/renderer/services/platform/controller.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
App,
33
Instance,
44
Keyword,
5+
LogBody,
56
GenericConfig,
67
LLMConfig,
78
AccountConfig,
@@ -170,6 +171,7 @@ export async function checkPluginAvailability({
170171
status: boolean;
171172
message: string;
172173
error: string;
174+
consoleOutput: LogBody[];
173175
}>('/api/v1/base/plugin/check', {
174176
code,
175177
ctx,

src/renderer/services/platform/platform.d.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ export interface Message {
3838
type: MessageType;
3939
}
4040

41+
export interface LogBody {
42+
level: string;
43+
time: string;
44+
message: string;
45+
}
46+
4147
export interface GenericConfig {
4248
appId: string;
4349
instanceId: string;

src/renderer/utils/constants/index.ts

Lines changed: 2 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -42,53 +42,8 @@ const rp = require('reply_srv');
4242
* @returns {Reply} 插件执行结果
4343
*/
4444
async function main(ctx, messages) {
45-
const appId = ctx.get('app_id');
46-
const instanceId = ctx.get('instance_id');
47-
48-
const cfg = cc.get(ctx);
49-
50-
console.log('插件开始执行....');
51-
console.log('当前应用 ID:', appId);
52-
console.log('当前客服实例 ID:', instanceId);
53-
console.log('当前配置:', ctx, messages);
54-
55-
// 先检查是否存在用户的消息
56-
const lastUserMsg = messages
57-
.slice()
58-
.reverse()
59-
.find((msg) => msg.role === 'OTHER');
60-
61-
if (!lastUserMsg) {
62-
return {
63-
type: 'TEXT',
64-
content: cfg.default_reply, // 默认回复
65-
};
66-
}
67-
68-
// 等待随机时间
69-
await new Promise((resolve) => {
70-
const min = cfg.reply_speed;
71-
const max = cfg.reply_random_speed + cfg.reply_speed;
72-
const randomTime = min + Math.random() * (max - min);
73-
setTimeout(resolve, randomTime * 1000);
74-
});
75-
76-
// 再检查是否使用关键词匹配
77-
if (rp.isKeywordMatch) {
78-
const data = await rp.matchKeyword(ctx, lastUserMsg);
79-
if (data) return data;
80-
}
81-
82-
// 最后检查是否使用 GPT 生成回复
83-
if (rp.isUseGptReply) {
84-
const data = await rp.getLLMResponse(cfg, ctx, messages);
85-
if (data) return data;
86-
}
87-
88-
return {
89-
type: 'TEXT',
90-
content: cfg.default_reply,
91-
};
45+
const cfg = await cc.get(ctx);
46+
return await rp.getDefaultReply(cfg, ctx, messages);
9247
}`;
9348

9449
export const LLMTypeList = [

0 commit comments

Comments
 (0)