Skip to content

Commit

Permalink
Merge pull request #7 from bytemate/feat/change-api
Browse files Browse the repository at this point in the history
Add New API
  • Loading branch information
fuergaosi233 authored Jan 20, 2023
2 parents c7c1935 + 44dcf6c commit cf3c003
Show file tree
Hide file tree
Showing 6 changed files with 124 additions and 39 deletions.
15 changes: 7 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"async-retry": "^1.3.3",
"bcrypt": "5.0.1",
"cache-manager": "^5.1.4",
"chatgpt": "^3.3.12",
"chatgpt": "^3.4.2",
"class-transformer": "0.5.1",
"class-validator": "0.13.2",
"graphql": "16.5.0",
Expand Down
17 changes: 17 additions & 0 deletions prisma/migrations/20230115093723_add_session_support/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
Warnings:
- You are about to drop the column `user_id` on the `chatgpt_conversation` table. All the data in the column will be lost.
- A unique constraint covering the columns `[tenant_id,session_id]` on the table `chatgpt_conversation` will be added. If there are existing duplicate values, this will fail.
- Added the required column `session_id` to the `chatgpt_conversation` table without a default value. This is not possible if the table is not empty.
*/
-- DropIndex
DROP INDEX "chatgpt_conversation_user_id_tenant_id_key";

-- AlterTable
ALTER TABLE "chatgpt_conversation" DROP COLUMN "user_id",
ADD COLUMN "session_id" TEXT NOT NULL;

-- CreateIndex
CREATE UNIQUE INDEX "chatgpt_conversation_tenant_id_session_id_key" ON "chatgpt_conversation"("tenant_id", "session_id");
4 changes: 2 additions & 2 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ model ChatGPTConversation {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String @map("user_id")
sessionId String @map("session_id")
tenantId String @map("tenant_id")
conversationId String @map("conversation_id")
messageId String @map("message_id")
email String
@@unique([conversationId])
@@unique([userId, tenantId])
@@unique([tenantId, sessionId])
@@map("chatgpt_conversation")
}
25 changes: 24 additions & 1 deletion src/chatgpt/chatgpt.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,30 @@ export class ChatgptController {
const { message } = messageDto;
return await this.chatgptService.sendChatGPTMessage(message, {
tenantId,
userId,
sessionId: userId,
});
}
@Post('/message')
async getChatGPTMessage(
@Body() messageDto: any,
@Headers() headers: Record<string, string>
) {
const { message } = messageDto;
return await this.chatgptService.sendChatGPTMessageOnetime(message);
}
@Post('/message/:sessionId')
async getChatGPTMessageBySessionId(
@Param('sessionId') sessionId: string,
@Body() messageDto: any
) {
const { message } = messageDto;
return await this.chatgptService.sendChatGPTMessage(message, {
tenantId: TENANT_ID,
sessionId: sessionId,
});
}
@Delete('/message/:sessionId')
async deleteChatGPTMessage(@Param('sessionId') sessionId: string) {
return await this.chatgptService.resetSession(sessionId, TENANT_ID);
}
}
100 changes: 73 additions & 27 deletions src/chatgpt/chatgpt.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,59 +88,90 @@ export class ChatgptService {
const email = account[Math.floor(Math.random() * account.length)].email;
return email;
}
// Send Chatgpt Message via ChatgptPoolService
async sendChatGPTMessage(
message: string,
opts?: {
userId?: string;
sessionId?: string;
tenantId: string;
}
) {
let email: string;
const { userId, tenantId } = opts;
const onetimeRequest = !userId;
if (onetimeRequest) {
const { sessionId, tenantId } = opts;
const conversation = await this.prismaService.chatGPTConversation.findFirst(
{
where: { sessionId, tenantId },
}
);
if (!conversation) {
email = await this.getCurrentActiveChatGPT();
} else {
const conversation =
await this.prismaService.chatGPTConversation.findFirst({
where: { userId },
});
if (!conversation) {
email = await this.getCurrentActiveChatGPT();
}
email = conversation.email;
}
// Send Message
this.logger.debug(`Send message to ${email}: ${message}`);
try {
const messageResult = await this.chatgptPoolService.sendMessage(message, {
email: email,
conversationId: conversation?.conversationId,
parentMessageId: conversation?.messageId,
});
if (!messageResult) {
this.logger.error(`Send message to ${email} failed`);
return {
conversationId: null,
messageId: null,
message: null,
};
}
if (!onetimeRequest) {
// Save conversation info
await this.prismaService.chatGPTConversation.upsert({
where: { userId_tenantId: { userId, tenantId } },
create: {
userId,
email,
conversationId: messageResult.conversationId,
messageId: messageResult.messageId,
tenantId,
},
update: {
email,
},
});
// Save conversation info
await this.prismaService.chatGPTConversation.upsert({
where: { tenantId_sessionId: { sessionId, tenantId } },
create: {
sessionId,
email,
conversationId: messageResult.conversationId,
messageId: messageResult.messageId,
tenantId,
},
update: {
email,
conversationId: messageResult.conversationId,
messageId: messageResult.messageId,
},
});
return messageResult;
} catch (e) {
this.logger.error(`Send message to ${email} failed: ${e}`);
// Update Email status
this.prismaService.chatGPTAccount.update({
where: { email },
data: { status: 'Error' },
});
}
}
async sendChatGPTMessageOnetime(message: string) {
const email = await this.getCurrentActiveChatGPT();
this.logger.debug(`Send message to ${email}: ${message}`);
try {
const messageResult = await this.chatgptPoolService.sendMessage(message, {
email: email,
});
if (!messageResult) {
this.logger.error(`Send message to ${email} failed`);
return {
conversationId: null,
messageId: null,
message: null,
};
}
return messageResult;
} catch (e) {
this.logger.error(`Send message to ${email} failed: ${e}`);
// Update Email status
this.prismaService.chatGPTAccount.update({
where: { email },
data: { status: 'Down' },
data: { status: 'Error' },
});
}
}
Expand Down Expand Up @@ -200,6 +231,21 @@ export class ChatgptService {
}
this.logger.debug(`Found ${accounts.length} running accounts`);
}
async resetSession(sessionId: string, tenantId: string) {
this.logger.debug(`Reset conversation ${sessionId}`);
const conversation = await this.prismaService.chatGPTConversation.delete({
where: {
tenantId_sessionId: { sessionId, tenantId: 'default' },
},
});
if (!conversation) {
this.logger.error(`Conversation ${sessionId} not found`);
return {};
} else {
this.logger.debug(`Conversation ${sessionId} deleted`);
return conversation;
}
}
@Cron('1 * * * * *')
async startAllDownAccount() {
this.logger.debug('Start all down account');
Expand Down

0 comments on commit cf3c003

Please sign in to comment.