0.0.1 • Published 1 year ago

nestjs-openai v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Features

  • Configure and inject the OpenAI API client.

Installation

yarn add nestjs-openai

Usage

Settings

OpenAIModule.register

Import the module at your module. Configure the OpenAI API client.

import { OpenAIModule } from "nestjs-openai";

@Module({
  imports: [
    OpenAIModule.register({
      apiKey: "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

OpenAIModule.registerAsync

You can also use OpenAIModule.registerAsync to configure it asynchronously. This way you can hide your api key from the code. It's recommended to use this method.

import { OpenAIModule } from "nestjs-openai";

@Module({
  imports: [
    OpenAIModule.registerAsync({
      useFactory: (config: ConfigService<EnvVars>) => ({
        apiKey: config.get("OPENAI_API_KEY"),
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Inject OpenAIService

Inject OpenAIService anywhere. Injected service is identical to OpenAI API client.

@Injectable()
export class TextCompletionService {
  constructor(private readonly openai: OpenAIService) {}

  async completion(
    messages: CreateChatCompletionRequest["messages"],
  ): Promise<string> {
    const { data } = await this.openai.createCompletion({
      model: "davinci",
      prompt: "This is a test",
    });
    return data.choices[0].text;
  }
}