OpenAI module for nestjs
OpenAI module for Nest based on the official openai package.
$ npm i --save @bytebitlabs/nest-openai openai
Import OpenAiModule
:
@Module({
imports: [OpenAiModule.register({
apiKey: 'Abc...',
})],
providers: [...],
})
export class AiModule {}
Inject OpenAiService
:
@Injectable()
export class AiService {
constructor(private readonly openAiService: OpenAiService) {}
}
Quite often you might want to asynchronously pass your module options instead of passing them beforehand. In such case, use registerAsync()
method, that provides a couple of various ways to deal with async data.
1. Use factory
OpenAiModule.registerAsync({
useFactory: () => ({
apiKey: 'Abc...'
})
});
Obviously, our factory behaves like every other one (might be async
and is able to inject dependencies through inject
).
OpenAiModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
apiKey: configService.get('OPENAI_API_KEY'),
}),
inject: [ConfigService],
}),
2. Use class
OpenAiModule.registerAsync({
useClass: OpenAiConfigService
});
Above construction will instantiate OpenAiConfigService
inside OpenAiModule
and will leverage it to create options object.
class OpenAiConfigService implements OpenaiOptionsFactory {
createOpenAiOptions(): OpenAiModuleOptions {
return {
apiKey: 'Abc...'
};
}
}
3. Use existing
OpenAiModule.registerAsync({
imports: [ConfigModule],
useExisting: ConfigService,
}),
It works the same as useClass
with one critical difference - OpenAiModule
will lookup imported modules to reuse already created ConfigService
, instead of instantiating it on its own.
The OpenAiService
wraps the Client
from the official openai methods. The OpenAiModule.register()
takes options
object as an argument, read more.