A lightweight wrapper around the OpenAI GPT API with first-class support for DTO-based JSON output validation using class-validator
and class-transformer
. Ideal for TypeScript-based server applications (e.g., NestJS, routing-controllers
) that require structured and type-safe responses from ChatGPT.
- ✅ Seamless integration with
class-validator
&class-transformer
- 🧩 Converts DTOs to JSON Schema using
class-validator-jsonschema
- 🧠 Utilizes OpenAI's JSON Schema output format (
response_format: json_schema
) - 🔄 Automatically parses and validates GPT responses into typed DTO instances
- ⚙️ Minimal setup, with lazy singleton provider initialization
- 🪄 Supports
$ref
schema expansion for complex/nested DTOs
npm install chatgpt-dto
import { getGPTProvider } from "chatgpt-dto";
import { IsString, IsEmail } from "class-validator";
import { Expose } from "class-transformer";
class UserDTO {
@IsString()
@Expose()
name: string;
@IsEmail()
@Expose()
email: string;
}
async function run() {
const gpt = getGPTProvider({
apiKey: "your-openai-api-key", // Required
model: "gpt-4o-mini", // Optional (default: gpt-4o-mini)
});
const response = await gpt.jsonDTO("Generate a random user", UserDTO);
console.log(response?.result); // typed UserDTO instance
}
Initializes (once) and returns a GPTProvider
instance.
Option | Type | Required | Description |
---|---|---|---|
apiKey |
string |
✅ | Your OpenAI API key |
model |
string |
❌ | Model name (default: gpt-4o-mini ) |
gpt.jsonDTO<T>(prompt: string, dtoClass: new () => T, model?: string): Promise<GptResponse<T> | null>
Sends a prompt and expects a structured JSON response that matches the given DTO class.
- Automatically generates JSON Schema from the DTO
- Expands
$ref
properties for compatibility with OpenAI
Returns:
type GptResponse<T> = {
result: T; // typed DTO instance
usage: OpenAI.Completions.CompletionUsage;
message: OpenAI.Chat.Completions.ChatCompletionMessage;
}
Standard ChatGPT interaction that returns a raw string message.
Convenience wrapper for simple string responses.
Advanced method for validating GPT output against a manually provided JSON Schema.
This plugin automatically expands $ref
references in generated schemas. That means you can safely use nested DTOs, and the schema sent to OpenAI will be fully inlined and self-contained.
- Node.js >= 18
- OpenAI API Key
- DTOs must use
class-validator
decorators for schema generation -
reflect-metadata
must be imported globally
import "reflect-metadata";
MIT © unbywyd