feat: add open router proxy
This commit is contained in:
Generated
+10
-1
@@ -42,7 +42,8 @@
|
||||
"pino-http": "^11.0.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"typeorm": "^0.3.28"
|
||||
"typeorm": "^0.3.28",
|
||||
"undici": "^6.29.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
@@ -15483,6 +15484,14 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "6.29.1",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz",
|
||||
"integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==",
|
||||
"engines": {
|
||||
"node": ">=18.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
|
||||
+2
-1
@@ -63,7 +63,8 @@
|
||||
"pino-http": "^11.0.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"typeorm": "^0.3.28"
|
||||
"typeorm": "^0.3.28",
|
||||
"undici": "^6.29.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
|
||||
+3
-2
@@ -20,7 +20,6 @@ import { TestsModule } from './modules/tests/tests.module';
|
||||
import { QuestionsModule } from './modules/questions/questions.module';
|
||||
import { SubmissionsModule } from './modules/submissions/submissions.module';
|
||||
import { ScoringModule } from './modules/scoring/scoring.module';
|
||||
import { AdminModule } from './modules/admin/admin.module';
|
||||
import { AppThrottlerGuard } from './common/guards/app-throttler.guard';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { LoggingModule } from './common/modules/logging/logging.module';
|
||||
@@ -29,6 +28,7 @@ import { ConversationModule } from './modules/conversation/conversation.module';
|
||||
import { AdminPanelModule } from './modules/admin-panel/admin-panel.module';
|
||||
import openRouterConfig from './config/open-router.config';
|
||||
import adminConfig from './config/admin.config';
|
||||
import { OpenRouterModule } from './common/modules/open-router/open-router.module';
|
||||
|
||||
const ENV = process.env.NODE_ENV;
|
||||
|
||||
@@ -107,9 +107,10 @@ const ENV = process.env.NODE_ENV;
|
||||
QuestionsModule,
|
||||
SubmissionsModule,
|
||||
ScoringModule,
|
||||
AdminModule,
|
||||
// AdminModule,
|
||||
AdminPanelModule,
|
||||
LoggingModule,
|
||||
OpenRouterModule,
|
||||
ChatbotModule,
|
||||
ConversationModule,
|
||||
],
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { OpenRouterService } from './providers/open-router.service';
|
||||
|
||||
@Module({
|
||||
providers: [OpenRouterService],
|
||||
exports: [OpenRouterService],
|
||||
})
|
||||
export class OpenRouterModule {}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Injectable, OnModuleDestroy } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class OpenRouterService implements OnModuleDestroy {
|
||||
private proxyAgent?: import('undici').ProxyAgent;
|
||||
private openRouterPromise?: Promise<
|
||||
InstanceType<(typeof import('@openrouter/sdk'))['OpenRouter']>
|
||||
>;
|
||||
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
|
||||
public getOpenRouter() {
|
||||
if (!this.openRouterPromise) {
|
||||
this.openRouterPromise = this.createOpenRouter().catch(
|
||||
(error: unknown) => {
|
||||
this.openRouterPromise = undefined;
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return this.openRouterPromise;
|
||||
}
|
||||
|
||||
private async createOpenRouter() {
|
||||
const { ProxyAgent, fetch: undiciFetch } = await import('undici');
|
||||
const { HTTPClient, OpenRouter } = await import('@openrouter/sdk');
|
||||
|
||||
const proxyUrl = this.configService.getOrThrow<string>(
|
||||
'openRouter.proxyUrl',
|
||||
);
|
||||
|
||||
const proxyUser = this.configService.getOrThrow<string>(
|
||||
'openRouter.proxyUser',
|
||||
);
|
||||
|
||||
const proxyPassword = this.configService.getOrThrow<string>(
|
||||
'openRouter.proxyPassword',
|
||||
);
|
||||
|
||||
const proxyAgent = new ProxyAgent({
|
||||
uri: proxyUrl,
|
||||
token:
|
||||
'Basic ' +
|
||||
Buffer.from(`${proxyUser}:${proxyPassword}`).toString('base64'),
|
||||
});
|
||||
|
||||
this.proxyAgent = proxyAgent;
|
||||
|
||||
try {
|
||||
const httpClient = new HTTPClient({
|
||||
fetcher: async (input, init) => {
|
||||
const response = await undiciFetch(
|
||||
input as string | URL,
|
||||
{
|
||||
...init,
|
||||
dispatcher: proxyAgent,
|
||||
} as Parameters<typeof undiciFetch>[1] & {
|
||||
dispatcher: typeof proxyAgent;
|
||||
},
|
||||
);
|
||||
|
||||
return response as unknown as Response;
|
||||
},
|
||||
});
|
||||
|
||||
return new OpenRouter({
|
||||
apiKey: this.configService.getOrThrow<string>('openRouter.apiKey'),
|
||||
httpClient,
|
||||
});
|
||||
} catch (error) {
|
||||
this.proxyAgent = undefined;
|
||||
await proxyAgent.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async onModuleDestroy(): Promise<void> {
|
||||
const agent = this.proxyAgent;
|
||||
|
||||
this.proxyAgent = undefined;
|
||||
this.openRouterPromise = undefined;
|
||||
|
||||
if (agent) {
|
||||
await agent.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,27 +4,46 @@ export default Joi.object({
|
||||
NODE_ENV: Joi.string()
|
||||
.valid('development', 'test', 'production', 'staging')
|
||||
.default('development'),
|
||||
|
||||
// Database
|
||||
DATABASE_HOST: Joi.string().required(),
|
||||
DATABASE_PORT: Joi.number().port().default(5432),
|
||||
DATABASE_USER: Joi.string().required(),
|
||||
DATABASE_PASS: Joi.string().required(),
|
||||
DATABASE_NAME: Joi.string().required(),
|
||||
DATABASE_AUTOLOAD: Joi.boolean().default('true'),
|
||||
|
||||
// JWT
|
||||
JWT_ACCESS_SECRET: Joi.string().required(),
|
||||
JWT_ACCESS_TTL: Joi.number().required(),
|
||||
JWT_REFRESH_SECRET: Joi.string().required(),
|
||||
JWT_REFRESH_TTL: Joi.number().required(),
|
||||
JWT_ISSUER: Joi.string().required(),
|
||||
JWT_AUDIENCE: Joi.string().required(),
|
||||
|
||||
// Redis
|
||||
REDIS_HOST: Joi.string().required(),
|
||||
REDIS_PORT: Joi.number().port().default(6379),
|
||||
REDIS_PASSWORD: Joi.string().required(),
|
||||
|
||||
// CORS
|
||||
CORS_ORIGINS: Joi.string().required(),
|
||||
CORS_SUBDOMAIN: Joi.string().required(),
|
||||
|
||||
// Swagger
|
||||
SWAGGER_SERVERS: Joi.string().required(),
|
||||
|
||||
// Logging
|
||||
LOG_LEVEL: Joi.string().default('info'),
|
||||
|
||||
// OpenRouter
|
||||
OPENROUTER_API_KEY: Joi.string().required(),
|
||||
OPENROUTER_MODEL: Joi.string().required(),
|
||||
OPENROUTER_PROXY_URL: Joi.string().required(),
|
||||
OPENROUTER_PROXY_USERNAME: Joi.string().required(),
|
||||
OPENROUTER_PROXY_PASSWORD: Joi.string().required(),
|
||||
|
||||
// Admin Panel (AdminJS)
|
||||
ADMIN_PANEL_ENABLED: Joi.string().valid('true', 'false').default('true'),
|
||||
// Required at runtime when the panel is enabled (validated in AdminPanelSetup)
|
||||
ADMIN_COOKIE_PASSWORD: Joi.string().allow('').default(''),
|
||||
|
||||
@@ -3,4 +3,7 @@ import { registerAs } from '@nestjs/config';
|
||||
export default registerAs('openRouter', () => ({
|
||||
apiKey: process.env.OPENROUTER_API_KEY,
|
||||
model: process.env.OPENROUTER_MODEL,
|
||||
proxyUrl: process.env.OPENROUTER_PROXY_URL,
|
||||
proxyUser: process.env.OPENROUTER_PROXY_USERNAME,
|
||||
proxyPassword: process.env.OPENROUTER_PROXY_PASSWORD,
|
||||
}));
|
||||
|
||||
@@ -23,7 +23,9 @@ export class AdminPanelSessionStore extends Store {
|
||||
private ttlSeconds(session: SessionData) {
|
||||
const maxAgeMs = session.cookie?.maxAge;
|
||||
|
||||
return typeof maxAgeMs === 'number' ? Math.floor(maxAgeMs / 1000) : undefined;
|
||||
return typeof maxAgeMs === 'number'
|
||||
? Math.floor(maxAgeMs / 1000)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
override get(
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { Response } from 'express';
|
||||
import { ChatDTO } from './dtos/chat.dto';
|
||||
import { ActiveUser } from '@/common/decorators/active-user.decorator';
|
||||
import { User } from '../users/entities/user.entity';
|
||||
import { ApiAppResponse } from '@/common/decorators/api-app-response.decorator';
|
||||
|
||||
@Controller('chatbot')
|
||||
export class ChatbotController {
|
||||
@@ -23,6 +24,16 @@ export class ChatbotController {
|
||||
|
||||
@Post('chat')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiAppResponse([
|
||||
{
|
||||
status: HttpStatus.OK,
|
||||
variants: [
|
||||
{
|
||||
model: ChatDTO,
|
||||
},
|
||||
],
|
||||
},
|
||||
])
|
||||
public async chat(@Body() chatDto: ChatDTO, @ActiveUser() user: User) {
|
||||
return this.chatbotService.chat(
|
||||
user,
|
||||
|
||||
@@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
|
||||
import { ChatbotController } from './chatbot.controller';
|
||||
import { ChatbotService } from './providers/chatbot.service';
|
||||
import { ConversationModule } from '../conversation/conversation.module';
|
||||
import { OpenRouterModule } from '@/common/modules/open-router/open-router.module';
|
||||
|
||||
@Module({
|
||||
imports: [ConversationModule],
|
||||
imports: [ConversationModule, OpenRouterModule],
|
||||
controllers: [ChatbotController],
|
||||
providers: [ChatbotService],
|
||||
})
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
import { i18nValidationMessage as t } from 'nestjs-i18n';
|
||||
|
||||
export class ChatDTO {
|
||||
@ApiProperty({
|
||||
type: 'number',
|
||||
required: false,
|
||||
example: 1,
|
||||
description: 'Id of chat conversation',
|
||||
})
|
||||
@IsInt({
|
||||
message: t('validation.wrongFieldFormat', {
|
||||
field: '$t(chatbot.fields.conversationId)',
|
||||
@@ -10,6 +17,12 @@ export class ChatDTO {
|
||||
@IsOptional()
|
||||
conversationId?: number;
|
||||
|
||||
@ApiProperty({
|
||||
type: 'string',
|
||||
required: true,
|
||||
example: 'Ask something',
|
||||
description: 'Chat message',
|
||||
})
|
||||
@IsString({
|
||||
message: t('validation.wrongFieldFormat', {
|
||||
field: '$t(chatbot.fields.message)',
|
||||
|
||||
@@ -5,6 +5,7 @@ import { User } from '@/modules/users/entities/user.entity';
|
||||
import { Conversation } from '@/modules/conversation/entities/conversation.entity';
|
||||
import { ConversationService } from '@/modules/conversation/providers/conversation.service';
|
||||
import { MessageRole } from '@/modules/conversation/enums/message-role.enum';
|
||||
import { OpenRouterService } from '@/common/modules/open-router/providers/open-router.service';
|
||||
|
||||
@Injectable()
|
||||
export class ChatbotService {
|
||||
@@ -18,16 +19,13 @@ export class ChatbotService {
|
||||
* Inject Conversation Service
|
||||
*/
|
||||
private readonly conversationService: ConversationService,
|
||||
|
||||
/**
|
||||
* Inject OpenRouter Service
|
||||
*/
|
||||
private readonly openRouterService: OpenRouterService,
|
||||
) {}
|
||||
|
||||
private async getOpenRouter() {
|
||||
const { OpenRouter } = await import('@openrouter/sdk');
|
||||
|
||||
return new OpenRouter({
|
||||
apiKey: this.configService.getOrThrow<string>('openRouter.apiKey'),
|
||||
});
|
||||
}
|
||||
|
||||
private async getConversationMessages(
|
||||
user: User,
|
||||
message: string,
|
||||
@@ -77,7 +75,7 @@ export class ChatbotService {
|
||||
conversationId,
|
||||
);
|
||||
|
||||
const openRouter = await this.getOpenRouter();
|
||||
const openRouter = await this.openRouterService.getOpenRouter();
|
||||
|
||||
const response = await openRouter.chat.send({
|
||||
chatRequest: {
|
||||
@@ -119,7 +117,7 @@ export class ChatbotService {
|
||||
conversationId,
|
||||
);
|
||||
|
||||
const openRouter = await this.getOpenRouter();
|
||||
const openRouter = await this.openRouterService.getOpenRouter();
|
||||
|
||||
const response = await openRouter.chat.send({
|
||||
chatRequest: {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { AppException } from '@/common/exceptions/app.exception';
|
||||
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
|
||||
import { User } from '@/modules/users/entities/user.entity';
|
||||
import { SUBMISSION_ANALYSIS_SYSTEM_PROMPT } from '../../constants/analysis.constants';
|
||||
import { OpenRouterService } from '@/common/modules/open-router/providers/open-router.service';
|
||||
|
||||
@Injectable()
|
||||
export class AnalyzeSubmissionProvider {
|
||||
@@ -29,6 +30,11 @@ export class AnalyzeSubmissionProvider {
|
||||
* Inject Config Service
|
||||
*/
|
||||
private readonly configService: ConfigService,
|
||||
|
||||
/**
|
||||
* Inject OpenRouter Service
|
||||
*/
|
||||
private readonly openRouterService: OpenRouterService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -162,18 +168,10 @@ export class AnalyzeSubmissionProvider {
|
||||
return 'بیپاسخ';
|
||||
}
|
||||
|
||||
private async getOpenRouter() {
|
||||
const { OpenRouter } = await import('@openrouter/sdk');
|
||||
|
||||
return new OpenRouter({
|
||||
apiKey: this.configService.getOrThrow<string>('openRouter.apiKey'),
|
||||
});
|
||||
}
|
||||
|
||||
private async *streamAnalysis(
|
||||
questionnaire: string,
|
||||
): AsyncGenerator<string, void, unknown> {
|
||||
const openRouter = await this.getOpenRouter();
|
||||
const openRouter = await this.openRouterService.getOpenRouter();
|
||||
|
||||
const response = await openRouter.chat.send({
|
||||
chatRequest: {
|
||||
|
||||
@@ -19,6 +19,7 @@ import { HistoryGuestProvider } from './providers/history/history-guest.provider
|
||||
import { SubmissionHistoryProvider } from './providers/history/submission-history.provider';
|
||||
import { UserSubmissionListingProvider } from './providers/listing/user-submission-listing.provider';
|
||||
import { AnalyzeSubmissionProvider } from './providers/analyze/analyze-submission.provider';
|
||||
import { OpenRouterModule } from '@/common/modules/open-router/open-router.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -27,6 +28,7 @@ import { AnalyzeSubmissionProvider } from './providers/analyze/analyze-submissio
|
||||
QuestionsModule,
|
||||
RedisModule,
|
||||
ScoringModule,
|
||||
OpenRouterModule,
|
||||
],
|
||||
controllers: [SubmissionsController],
|
||||
providers: [
|
||||
|
||||
Reference in New Issue
Block a user