Просмотр исходного кода

Merge branch 'master' of http://git.izouma.com/xiongzhu/chat-api

wangqifan 2 лет назад
Родитель
Сommit
423df12359

+ 3 - 0
src/chat-role/entities/chat-role.entity.ts

@@ -14,6 +14,9 @@ export class ChatRole {
     @Column()
     describe: string
 
+    @Column()
+    condition: string
+
     @Column()
     pic: String
 

+ 3 - 2
src/chat/chat.module.ts

@@ -11,6 +11,7 @@ import { SysConfigModule } from '../sys-config/sys-config.module'
 @Module({
     imports: [TypeOrmModule.forFeature([ChatHistory, TokenUsage]), MembershipModule, HttpModule, SysConfigModule],
     providers: [ChatService],
-    controllers: [ChatController]
+    controllers: [ChatController],
+    exports: [ChatService]
 })
-export class ChatModule {}
+export class ChatModule { }

+ 40 - 41
src/chat/chat.service.ts

@@ -1,5 +1,5 @@
 import { ForbiddenException, Injectable, InternalServerErrorException, Logger } from '@nestjs/common'
-import { Observable } from 'rxjs'
+import { Observable, interval } from 'rxjs'
 import { ChatGPTAPI, ChatMessage } from '../chatapi'
 import type { RequestProps } from './types'
 import { chatReplyProcess } from './chatgpt'
@@ -27,7 +27,7 @@ export class ChatService {
         private readonly membershipService: MembershipService,
         private readonly httpService: HttpService,
         private readonly sysConfigService: SysConfigService
-    ) {}
+    ) { }
 
     public chat(req, res): Observable<any> {
         res.setHeader('Content-Type', 'application/octet-stream')
@@ -50,7 +50,7 @@ export class ChatService {
                 temperature,
                 top_p
             })
-                .then(() => {})
+                .then(() => { })
                 .catch((error) => {
                     observer.error(error)
                 })
@@ -128,44 +128,43 @@ export class ChatService {
         }
     }
 
-    async sendMessage() {
-        const message = '请你发一条此时此刻的动态文案';
+    public async sendMessage(prompt: string, message: string,): Promise<string> {
         try {
-          const result = await chatReplyProcess({
-            message: message,
-            process: (chat: ChatMessage) => {},
-          });
-          const chatMessage = result.data as ChatMessage;
-          this.chatHistoryRepository.save(
-            new ChatHistory({
-              messageId: chatMessage.parentMessageId,
-              parentMessageId: null,
-              userId: 0,
-              message: message,
-              role: 'system',
-              token: chatMessage.detail.usage.prompt_tokens,
-              time: new Date(),
-            }),
-          );
-          this.chatHistoryRepository.save(
-            new ChatHistory({
-              messageId: chatMessage.id,
-              parentMessageId: chatMessage.parentMessageId,
-              userId: 0,
-              message: chatMessage.text,
-              role: 'assistant',
-              token: chatMessage.detail.usage.completion_tokens,
-              time: new Date(),
-            }),
-          );
-          Logger.log(`机器人回答:${chatMessage.text}`, 'SendMessage');
-        } catch (error) {
-          Logger.error(error, 'SendMessage');
-        } 
-      }
-    
-      
+            const result = await chatReplyProcess({
+                message: prompt,
+                systemMessage: message,
+                process: (chat: ChatMessage) => { },
+            });
+            const chatMessage = result.data as ChatMessage;
+            this.chatHistoryRepository.save(
+                new ChatHistory({
+                    messageId: chatMessage.parentMessageId,
+                    parentMessageId: null,
+                    userId: 0,
+                    message: message,
+                    role: 'system',
+                    token: chatMessage.detail.usage.prompt_tokens,
+                    time: new Date(),
+                }),
+            );
+            this.chatHistoryRepository.save(
+                new ChatHistory({
+                    messageId: chatMessage.id,
+                    parentMessageId: chatMessage.parentMessageId,
+                    userId: 0,
+                    message: chatMessage.text,
+                    role: 'assistant',
+                    token: chatMessage.detail.usage.completion_tokens,
+                    time: new Date(),
+                }),
+            );
 
+            Logger.log(`机器人回答:${chatMessage.text}`, 'SendMessage');
+            return chatMessage.text
+        } catch (error) {
+            Logger.error(error, 'SendMessage');
+        }
+    }
 
     public async chatProxy(req) {
         const url = `${process.env.AZURE_OPENAI_ENDPOINT}/openai/deployments/${process.env.AZURE_OPENAI_DEPLOYMENT}/chat/completions?api-version=${process.env.AZURE_OPENAI_VERSION}`
@@ -203,8 +202,8 @@ export class ChatService {
                         this.tiktokenAndSave(
                             req.user.id,
                             req.body.messages.map((message) => `${message.role}:\n${message.content}`).join('\n\n') +
-                                '\n\nassistant:\n' +
-                                text
+                            '\n\nassistant:\n' +
+                            text
                         )
                         return subscriber.complete()
                     }

+ 3 - 3
src/moments/dto/moments.dto.ts

@@ -1,8 +1,8 @@
-import { IsString } from 'class-validator'
+import { IsNumber, IsString } from 'class-validator'
 
 export class MomentsDto {
-    @IsString()
-    name: string
+    @IsNumber()
+    userId: number
 
     @IsString()
     content: string

+ 4 - 1
src/moments/moments.module.ts

@@ -7,9 +7,12 @@ import { ChatRoleModule } from '../chat-role/chat-role.module'
 import { LikesModule } from 'src/likes/likes.module'
 import { ChatRole } from 'src/chat-role/entities/chat-role.entity'
 import { Likes } from 'src/likes/entities/likes.entity'
+import { ChatModule } from 'src/chat/chat.module'
+import { MaskModule } from 'src/mask/mask.module'
+import { Mask } from 'src/mask/entities/mask.entity'
 
 @Module({
-    imports: [TypeOrmModule.forFeature([Moments, ChatRole, Likes]), ChatRoleModule, LikesModule],
+    imports: [TypeOrmModule.forFeature([Moments, ChatRole, Likes, Mask]), ChatRoleModule, LikesModule, ChatModule, MaskModule],
     controllers: [MomentsController],
     providers: [MomentsService],
     exports: [MomentsService]

+ 26 - 3
src/moments/moments.service.ts

@@ -10,14 +10,16 @@ import {
 import { In, Repository, UpdateResult } from 'typeorm'
 import { InjectRepository } from '@nestjs/typeorm'
 import { Moments } from './entities/moments.entity'
-
 import { paginate, Pagination } from 'nestjs-typeorm-paginate'
 import { PageRequest } from '../common/dto/page-request'
 import { ChatRoleService } from '../chat-role/chat-role.service'
 import { LikesService } from 'src/likes/likes.service'
 import { ChatRole } from 'src/chat-role/entities/chat-role.entity'
 import { Likes } from 'src/likes/entities/likes.entity'
-import { el } from 'date-fns/locale'
+import { setInterval } from 'timers';
+import { ChatService } from 'src/chat/chat.service'
+import { Mask } from 'src/mask/entities/mask.entity'
+import { MomentsDto } from './dto/moments.dto'
 
 @Injectable()
 export class MomentsService {
@@ -28,9 +30,16 @@ export class MomentsService {
         private readonly chatRoleRepository: Repository<ChatRole>,
         @InjectRepository(Likes)
         private readonly likesRepository: Repository<Likes>,
+        @InjectRepository(Mask)
+        private readonly maskRepository: Repository<Mask>,
         private readonly chatRoleService: ChatRoleService,
+        private readonly chatService: ChatService,
         private readonly likesService: LikesService
-    ) { }
+    ) {
+        setInterval(() => {
+            this.automaticallySendMoments();
+        }, 24 * 60 * 60 * 1000);
+    }
 
     async findAll(req: PageRequest<Moments>, userId: number): Promise<Pagination<Moments>> {
         const page = await paginate<Moments>(this.momentsRepository, req.page, req.search)
@@ -95,4 +104,18 @@ export class MomentsService {
         }
     }
 
+    public async automaticallySendMoments() {
+        const message = "请你以类似于朋友圈的放肆发一条此时此刻的动态"
+        const chatRoleList = await this.chatRoleRepository.createQueryBuilder().getMany()
+
+        chatRoleList.forEach(async role => {
+            const text = await this.chatService.sendMessage(role.condition, message)
+            const momentsDto = new MomentsDto
+            momentsDto.content = text
+            momentsDto.userId = role.id
+            await this.momentsRepository.save(momentsDto)
+        })
+
+    }
+
 }