Skip to content

Commit 39aaf29

Browse files
committed
refactor: enhance OpenAI controller and service for better credential management
This commit refactors the OpenAIController and OpenAIService to improve credential handling and error management. Key changes include: - Added checks to prevent duplicate API keys and names during bot creation. - Updated the getModels method to accept an optional credential ID for more flexible credential usage. - Enhanced error handling with specific BadRequestException messages for better clarity. - Removed unused methods and streamlined the speech-to-text functionality to utilize instance-specific settings. These improvements enhance the maintainability and usability of the OpenAI integration.
1 parent 22e99f7 commit 39aaf29

File tree

3 files changed

+109
-220
lines changed

3 files changed

+109
-220
lines changed

src/api/integrations/chatbot/openai/controllers/openai.controller.ts

Lines changed: 58 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ export class OpenaiController extends BaseChatbotController<OpenaiBot, OpenaiDto
117117
}
118118
}
119119

120-
// Bots
120+
// Override createBot to handle OpenAI-specific credential logic
121121
public async createBot(instance: InstanceDto, data: OpenaiDto) {
122122
if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled');
123123

@@ -206,58 +206,6 @@ export class OpenaiController extends BaseChatbotController<OpenaiBot, OpenaiDto
206206
return super.createBot(instance, data);
207207
}
208208

209-
public async findBot(instance: InstanceDto) {
210-
if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled');
211-
212-
const instanceId = await this.prismaRepository.instance
213-
.findFirst({
214-
where: {
215-
name: instance.instanceName,
216-
},
217-
})
218-
.then((instance) => instance.id);
219-
220-
const bots = await this.botRepository.findMany({
221-
where: {
222-
instanceId: instanceId,
223-
},
224-
});
225-
226-
if (!bots.length) {
227-
return null;
228-
}
229-
230-
return bots;
231-
}
232-
233-
public async fetchBot(instance: InstanceDto, botId: string) {
234-
if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled');
235-
236-
const instanceId = await this.prismaRepository.instance
237-
.findFirst({
238-
where: {
239-
name: instance.instanceName,
240-
},
241-
})
242-
.then((instance) => instance.id);
243-
244-
const bot = await this.botRepository.findFirst({
245-
where: {
246-
id: botId,
247-
},
248-
});
249-
250-
if (!bot) {
251-
throw new Error('Openai Bot not found');
252-
}
253-
254-
if (bot.instanceId !== instanceId) {
255-
throw new Error('Openai Bot not found');
256-
}
257-
258-
return bot;
259-
}
260-
261209
// Process OpenAI-specific bot logic
262210
protected async processBot(
263211
instance: any,
@@ -284,8 +232,31 @@ export class OpenaiController extends BaseChatbotController<OpenaiBot, OpenaiDto
284232
})
285233
.then((instance) => instance.id);
286234

287-
if (!data.apiKey) throw new Error('API Key is required');
288-
if (!data.name) throw new Error('Name is required');
235+
if (!data.apiKey) throw new BadRequestException('API Key is required');
236+
if (!data.name) throw new BadRequestException('Name is required');
237+
238+
// Check if API key already exists
239+
const existingApiKey = await this.credsRepository.findFirst({
240+
where: {
241+
apiKey: data.apiKey,
242+
},
243+
});
244+
245+
if (existingApiKey) {
246+
throw new BadRequestException('This API key is already registered. Please use a different API key.');
247+
}
248+
249+
// Check if name already exists for this instance
250+
const existingName = await this.credsRepository.findFirst({
251+
where: {
252+
name: data.name,
253+
instanceId: instanceId,
254+
},
255+
});
256+
257+
if (existingName) {
258+
throw new BadRequestException('This credential name is already in use. Please choose a different name.');
259+
}
289260

290261
try {
291262
const creds = await this.credsRepository.create({
@@ -449,7 +420,7 @@ export class OpenaiController extends BaseChatbotController<OpenaiBot, OpenaiDto
449420
}
450421

451422
// Models - OpenAI specific functionality
452-
public async getModels(instance: InstanceDto) {
423+
public async getModels(instance: InstanceDto, openaiCredsId?: string) {
453424
if (!this.integrationEnabled) throw new BadRequestException('Openai is disabled');
454425

455426
const instanceId = await this.prismaRepository.instance
@@ -462,21 +433,40 @@ export class OpenaiController extends BaseChatbotController<OpenaiBot, OpenaiDto
462433

463434
if (!instanceId) throw new Error('Instance not found');
464435

465-
const defaultSettings = await this.settingsRepository.findFirst({
466-
where: {
467-
instanceId: instanceId,
468-
},
469-
include: {
470-
OpenaiCreds: true,
471-
},
472-
});
436+
let apiKey: string;
437+
438+
if (openaiCredsId) {
439+
// Use specific credential ID if provided
440+
const creds = await this.credsRepository.findFirst({
441+
where: {
442+
id: openaiCredsId,
443+
instanceId: instanceId, // Ensure the credential belongs to this instance
444+
},
445+
});
473446

474-
if (!defaultSettings) throw new Error('Settings not found');
447+
if (!creds) throw new Error('OpenAI credentials not found for the provided ID');
475448

476-
if (!defaultSettings.OpenaiCreds)
477-
throw new Error('OpenAI credentials not found. Please create credentials and associate them with the settings.');
449+
apiKey = creds.apiKey;
450+
} else {
451+
// Use default credentials from settings if no ID provided
452+
const defaultSettings = await this.settingsRepository.findFirst({
453+
where: {
454+
instanceId: instanceId,
455+
},
456+
include: {
457+
OpenaiCreds: true,
458+
},
459+
});
460+
461+
if (!defaultSettings) throw new Error('Settings not found');
478462

479-
const { apiKey } = defaultSettings.OpenaiCreds;
463+
if (!defaultSettings.OpenaiCreds)
464+
throw new Error(
465+
'OpenAI credentials not found. Please create credentials and associate them with the settings.',
466+
);
467+
468+
apiKey = defaultSettings.OpenaiCreds.apiKey;
469+
}
480470

481471
try {
482472
this.client = new OpenAI({ apiKey });

src/api/integrations/chatbot/openai/routes/openai.router.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ export class OpenaiRouter extends RouterBroker {
153153
request: req,
154154
schema: instanceSchema,
155155
ClassRef: InstanceDto,
156-
execute: (instance) => openaiController.getModels(instance),
156+
execute: (instance) => openaiController.getModels(instance, req.query.openaiCredsId as string),
157157
});
158158

159159
res.status(HttpStatus.OK).json(response);

0 commit comments

Comments
 (0)