chatgpt-dto
Version:
A lightweight wrapper for OpenAI's GPT API with DTO support via class-validator and class-transformer. Designed for structured JSON output in TypeScript backends.
129 lines (84 loc) • 3.51 kB
Markdown
# 🧠 chatgpt-dto - DTO-first GPT Integration
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.
## ✨ Features
- ✅ 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
## 📦 Installation
```bash
npm install chatgpt-dto
```
## 🚀 Quick Start
```ts
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
}
```
## 🧩 API
### `getGPTProvider(options?: PluginOptions): GPTProvider`
Initializes (once) and returns a `GPTProvider` instance.
#### Options
| 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:
```ts
type GptResponse<T> = {
result: T; // typed DTO instance
usage: OpenAI.Completions.CompletionUsage;
message: OpenAI.Chat.Completions.ChatCompletionMessage;
}
```
### `gpt.chat(prompt: string, model?: string): Promise<GptResponse<string> | null>`
Standard ChatGPT interaction that returns a raw string message.
### `gpt.chatString(prompt: string, model?: string): Promise<string>`
Convenience wrapper for simple string responses.
### `gpt.JsonString<T>(prompt: string, jsonSchema: any, model?: string): Promise<T | null>`
Advanced method for validating GPT output against a manually provided JSON Schema.
## 📘 Use Case: Schema Expansion with `$ref`
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.
## 📌 Requirements
- Node.js >= 18
- OpenAI API Key
- DTOs must use `class-validator` decorators for schema generation
- `reflect-metadata` must be imported globally
```ts
import "reflect-metadata";
```
## 📄 License
MIT © unbywyd