This documentation provides an in-depth overview of the generateStructuredJSON module, which validates and converts raw invoice-related data into a structured JSON format using predefined schemas.
Client Documentation Server Documentation
- Introduction
- Dependencies
- Environment Variables
- Schemas
- Function: generateStructuredJSON
- How to Use
- Error Handling
- Sample Input and Output
generateStructuredJSON is a utility function designed to process raw invoice data into a well-structured JSON format using Zod schemas for validation. It ensures missing or inconsistent fields are handled gracefully by filling defaults and reporting errors where applicable.
- Node.js Modules:
@ai-sdk/openai: Used to interact with OpenAI for structured data generation.ai: Provides AI capabilities for object generation.zod: Schema validation library.dotenv: Manages environment variables.
Install the dependencies:
npm install @ai-sdk/openai ai zod dotenvThe following environment variable must be configured:
OPENAI_API_KEY: Your OpenAI API key. Ensure it is set in a.envfile in the project root.
Example .env file:
OPENAI_API_KEY=your-api-key-here
SECRET_KEY=your-secret-key
Defines the structure of a product in an invoice.
| Field | Type | Description |
|---|---|---|
productId |
string |
A unique identifier for the product. |
productName |
string |
The name of the product (e.g., "Laptop"). |
quantity |
number |
Quantity purchased (defaults to 1 if missing). |
unitPrice |
number |
Price per unit (defaults to "actual price" if missing). |
totalPrice |
number |
Total price without applying tax or discount. |
tax |
string |
Tax applied (e.g., "15%"). Defaults to "0%" if missing. |
priceAfterTax |
number |
Price after applying tax. |
discount |
string |
Optional discount applied (e.g., "10%"). Defaults to "0%" if missing. |
priceAfterDiscount |
number |
Optional final price after applying discount. Defaults to priceAfterTax if not provided. |
Defines the structure of customer details.
| Field | Type | Description |
|---|---|---|
customerId |
string |
A unique identifier for the customer. |
customerName |
string |
Full name of the customer (defaults to "N/A" if missing). |
totalPurchaseAmount |
number |
Total amount spent by the customer (defaults to 0 if missing). |
customerPhone |
string |
Optional phone number (defaults to "N/A" if missing). |
customerEmail |
string |
Optional email address (defaults to "N/A" if missing). |
customerAddress |
string |
Optional address (defaults to "N/A" if missing). |
Defines the structure of an invoice.
| Field | Type | Description |
|---|---|---|
invoiceNumber |
string |
Unique identifier for the invoice. |
products |
array |
Array of ProductSchema objects. |
date |
string |
Invoice creation date in YYYY-MM-DD format. |
customer |
CustomerSchema |
Customer details. |
amountBeforeTax |
number |
Total amount before applying tax. |
qty |
number |
Total quantity of products purchased. |
tax |
string |
Tax rate applied (e.g., "15%"). |
amountAfterTax |
number |
Total amount after applying tax. |
The FullSchema combines all schemas to validate the entire structured JSON.
| Field | Type | Description |
|---|---|---|
products |
array |
List of all products, validated against ProductSchema. |
customers |
array |
List of all customers, validated against CustomerSchema. |
invoices |
array |
List of all invoices, validated against InvoiceSchema. |
error |
string (optional) |
Error message if data validation fails. |
data: Raw data to be processed.
- A structured JSON object conforming to
FullSchema.
- Log Input Data: Logs raw data for debugging.
- Process Data: Uses the
aipackage to interact with OpenAI, validating and generating structured JSON based on schemas. - Handle Errors: Gracefully handles errors and provides descriptive error messages.
- Import and configure the function:
const generateStructuredJSON = require("./path-to-your-file");
// Example raw data
const rawData = {
// Raw data to be processed
};
generateStructuredJSON(rawData).then((result) => {
console.log("Structured JSON:", result);
});- Ensure your environment is properly configured with the required API key.
- If the data validation fails, the function will return an error message in the following format:
{
"error": "Unable to process data. Check logs for details."
}{
"products": [
{
"productId": "123ABC",
"productName": "Laptop",
"quantity": 2,
"unitPrice": 50000,
"totalPrice": 100000,
"tax": "18%",
"priceAfterTax": 118000
}
],
"customers": [
{
"customerId": "CUST001",
"customerName": "John Doe",
"totalPurchaseAmount": 118000
}
],
"invoices": [
{
"invoiceNumber": "INV001",
"products": [
{
"productId": "123ABC",
"productName": "Laptop",
"quantity": 2,
"unitPrice": 50000,
"totalPrice": 100000,
"tax": "18%",
"priceAfterTax": 118000
}
],
"date": "2024-11-20",
"customer": {
"customerId": "CUST001",
"customerName": "John Doe",
"totalPurchaseAmount": 118000
},
"amountBeforeTax": 100000,
"qty": 2,
"tax": "18%",
"amountAfterTax": 118000
}
]
}{
"products": [...],
"customers": [...],
"invoices": [...],
"error": null
}