Array Generation
Generate lists of structured objects with consistent schemas. Arrays enable creation of sequential content, batch processing, and hierarchical data structures.
Overview
Array generation allows you to:
- Generate multiple items with the same structure
- Create sequential content like chapters, sections, or episodes
- Build hierarchical data with nested arrays
- Control item count with specific instructions
- Maintain consistency across all generated items
Book Generation Example
This real-world example generates a complete book structure with chapters and pages, demonstrating nested arrays and processing order control.
- cURL
- Python
- JavaScript/Node.js
- Go
curl -X POST http://localhost:2008/objectGen \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"prompt": "Create a science fiction novel about humanity'\''s first contact with an alien civilization",
"definition": {
"type": "object",
"instruction": "Creating a fictional story given the story outline provided. This story needs to be engaging and interesting to read.",
"properties": {
"title": {
"type": "string",
"instruction": "Return the title of the book which encapsulates the story. Return the title in a maximum of 5 words."
},
"chapters": {
"type": "array",
"instruction": "Create a list of 3 chapters with detailed outlines. Each chapter will have 2 pages. Write a minimum of 100 words for each chapter outlining what will happen.",
"items": {
"type": "object",
"instruction": "Create the details of the chapter so that the story being written will feel real and lived in.",
"processingOrder": ["title", "outline", "pages"],
"properties": {
"title": {
"type": "string",
"instruction": "Create a title for the chapter which must be less than 5 words."
},
"outline": {
"type": "string",
"instruction": "Create an outline of what will occur in this chapter. Return a minimum of 100 words for this outline. This outline should cover what will occur in 2 pages."
},
"pages": {
"type": "array",
"instruction": "Create a list of 2 pages, where each page outline should be detailed enough to ensure that each one logically leads to the next, creating a satisfying narrative progression. Return a maximum of 2 items.",
"items": {
"type": "object",
"instruction": "Create the details and information for a single page within a book.",
"processingOrder": ["outline", "finalContent"],
"properties": {
"outline": {
"type": "string",
"instruction": "Create detailed overview of what content this page should include. This page outline should be detailed enough to ensure that it will logically lead to the next page. This outline should be a minimum of 250 words.",
"systemPrompt": "You are an author AI assistant. You are not a chatbot. Follow the instructions given and ensure the asked details are created."
},
"finalContent": {
"type": "string",
"instruction": "Create a vivid and immersive page for the fiction book. Focus on detailed descriptions, engaging character dialogue, and dynamic reactions to events. Return a page which has the length of around 500 words. Only return the narrative content for the page without any additional explanations.",
"narrowFocus": {
"fields": ["outline"],
"prompt": "Use the page outline to create the final narrative content. Maintain consistency with the chapter outline and writing style."
}
}
}
}
}
}
}
}
}
}
}'
import requests
url = "http://localhost:2008/objectGen"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
}
data = {
"prompt": "Create a science fiction novel about humanity's first contact with an alien civilization",
"definition": {
"type": "object",
"instruction": "Creating a fictional story given the story outline provided. This story needs to be engaging and interesting to read.",
"properties": {
"title": {
"type": "string",
"instruction": "Return the title of the book which encapsulates the story. Return the title in a maximum of 5 words."
},
"chapters": {
"type": "array",
"instruction": "Create a list of 3 chapters with detailed outlines. Each chapter will have 2 pages. Write a minimum of 100 words for each chapter outlining what will happen.",
"items": {
"type": "object",
"instruction": "Create the details of the chapter so that the story being written will feel real and lived in.",
"processingOrder": ["title", "outline", "pages"],
"properties": {
"title": {
"type": "string",
"instruction": "Create a title for the chapter which must be less than 5 words."
},
"outline": {
"type": "string",
"instruction": "Create an outline of what will occur in this chapter. Return a minimum of 100 words for this outline. This outline should cover what will occur in 2 pages."
},
"pages": {
"type": "array",
"instruction": "Create a list of 2 pages, where each page outline should be detailed enough to ensure that each one logically leads to the next, creating a satisfying narrative progression. Return a maximum of 2 items.",
"items": {
"type": "object",
"instruction": "Create the details and information for a single page within a book.",
"processingOrder": ["outline", "finalContent"],
"properties": {
"outline": {
"type": "string",
"instruction": "Create detailed overview of what content this page should include. This page outline should be detailed enough to ensure that it will logically lead to the next page. This outline should be a minimum of 250 words.",
"systemPrompt": "You are an author AI assistant. You are not a chatbot. Follow the instructions given and ensure the asked details are created."
},
"finalContent": {
"type": "string",
"instruction": "Create a vivid and immersive page for the fiction book. Focus on detailed descriptions, engaging character dialogue, and dynamic reactions to events. Return a page which has the length of around 500 words. Only return the narrative content for the page without any additional explanations.",
"narrowFocus": {
"fields": ["outline"],
"prompt": "Use the page outline to create the final narrative content. Maintain consistency with the chapter outline and writing style."
}
}
}
}
}
}
}
}
}
}
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
# Access the generated book structure
fields = result.get("data", {}).get("fields", {})
title = fields.get("title", {}).get("string_value", "")
chapters_list = fields.get("chapters", {}).get("list_value", {}).get("values", [])
print(f"Book Title: {title}\n")
print(f"Total Chapters: {len(chapters_list)}\n")
for i, chapter in enumerate(chapters_list, 1):
chapter_fields = chapter.get("struct_value", {}).get("fields", {})
chapter_title = chapter_fields.get("title", {}).get("string_value", "")
chapter_outline = chapter_fields.get("outline", {}).get("string_value", "")
pages_list = chapter_fields.get("pages", {}).get("list_value", {}).get("values", [])
print(f"Chapter {i}: {chapter_title}")
print(f"Outline: {chapter_outline[:100]}...")
print(f"Pages: {len(pages_list)}\n")
const fetch = require('node-fetch');
const url = 'http://localhost:2008/objectGen';
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
};
const data = {
prompt: "Create a science fiction novel about humanity's first contact with an alien civilization",
definition: {
type: 'object',
instruction: 'Creating a fictional story given the story outline provided. This story needs to be engaging and interesting to read.',
properties: {
title: {
type: 'string',
instruction: 'Return the title of the book which encapsulates the story. Return the title in a maximum of 5 words.'
},
chapters: {
type: 'array',
instruction: 'Create a list of 3 chapters with detailed outlines. Each chapter will have 2 pages. Write a minimum of 100 words for each chapter outlining what will happen.',
items: {
type: 'object',
instruction: 'Create the details of the chapter so that the story being written will feel real and lived in.',
processingOrder: ['title', 'outline', 'pages'],
properties: {
title: {
type: 'string',
instruction: 'Create a title for the chapter which must be less than 5 words.'
},
outline: {
type: 'string',
instruction: 'Create an outline of what will occur in this chapter. Return a minimum of 100 words for this outline. This outline should cover what will occur in 2 pages.'
},
pages: {
type: 'array',
instruction: 'Create a list of 2 pages, where each page outline should be detailed enough to ensure that each one logically leads to the next, creating a satisfying narrative progression. Return a maximum of 2 items.',
items: {
type: 'object',
instruction: 'Create the details and information for a single page within a book.',
processingOrder: ['outline', 'finalContent'],
properties: {
outline: {
type: 'string',
instruction: 'Create detailed overview of what content this page should include. This page outline should be detailed enough to ensure that it will logically lead to the next page. This outline should be a minimum of 250 words.',
systemPrompt: 'You are an author AI assistant. You are not a chatbot. Follow the instructions given and ensure the asked details are created.'
},
finalContent: {
type: 'string',
instruction: 'Create a vivid and immersive page for the fiction book. Focus on detailed descriptions, engaging character dialogue, and dynamic reactions to events. Return a page which has the length of around 500 words. Only return the narrative content for the page without any additional explanations.',
narrowFocus: {
fields: ['outline'],
prompt: 'Use the page outline to create the final narrative content. Maintain consistency with the chapter outline and writing style.'
}
}
}
}
}
}
}
}
}
}
};
fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
const fields = result.data?.fields || {};
const title = fields.title?.string_value || '';
const chapters = fields.chapters?.list_value?.values || [];
console.log(`Book Title: ${title}\n`);
console.log(`Total Chapters: ${chapters.length}\n`);
chapters.forEach((chapter, i) => {
const chapterFields = chapter.struct_value?.fields || {};
const chapterTitle = chapterFields.title?.string_value || '';
const chapterOutline = chapterFields.outline?.string_value || '';
const pages = chapterFields.pages?.list_value?.values || [];
console.log(`Chapter ${i + 1}: ${chapterTitle}`);
console.log(`Outline: ${chapterOutline.substring(0, 100)}...`);
console.log(`Pages: ${pages.length}\n`);
});
})
.catch(error => console.error('Error:', error));
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
url := "http://localhost:2008/objectGen"
// Define the book generation schema
payload := map[string]interface{}{
"prompt": "Create a science fiction novel about humanity's first contact with an alien civilization",
"definition": map[string]interface{}{
"type": "object",
"instruction": "Creating a fictional story given the story outline provided. This story needs to be engaging and interesting to read.",
"properties": map[string]interface{}{
"title": map[string]interface{}{
"type": "string",
"instruction": "Return the title of the book which encapsulates the story. Return the title in a maximum of 5 words.",
},
"chapters": map[string]interface{}{
"type": "array",
"instruction": "Create a list of 3 chapters with detailed outlines. Each chapter will have 2 pages. Write a minimum of 100 words for each chapter outlining what will happen.",
"items": map[string]interface{}{
"type": "object",
"instruction": "Create the details of the chapter so that the story being written will feel real and lived in.",
"processingOrder": []string{"title", "outline", "pages"},
"properties": map[string]interface{}{
"title": map[string]interface{}{
"type": "string",
"instruction": "Create a title for the chapter which must be less than 5 words.",
},
"outline": map[string]interface{}{
"type": "string",
"instruction": "Create an outline of what will occur in this chapter. Return a minimum of 100 words for this outline. This outline should cover what will occur in 2 pages.",
},
"pages": map[string]interface{}{
"type": "array",
"instruction": "Create a list of 2 pages, where each page outline should be detailed enough to ensure that each one logically leads to the next, creating a satisfying narrative progression. Return a maximum of 2 items.",
"items": map[string]interface{}{
"type": "object",
"instruction": "Create the details and information for a single page within a book.",
"processingOrder": []string{"outline", "finalContent"},
"properties": map[string]interface{}{
"outline": map[string]interface{}{
"type": "string",
"instruction": "Create detailed overview of what content this page should include. This page outline should be detailed enough to ensure that it will logically lead to the next page. This outline should be a minimum of 250 words.",
"systemPrompt": "You are an author AI assistant. You are not a chatbot. Follow the instructions given and ensure the asked details are created.",
},
"finalContent": map[string]interface{}{
"type": "string",
"instruction": "Create a vivid and immersive page for the fiction book. Focus on detailed descriptions, engaging character dialogue, and dynamic reactions to events. Return a page which has the length of around 500 words. Only return the narrative content for the page without any additional explanations.",
"narrowFocus": map[string]interface{}{
"fields": []string{"outline"},
"prompt": "Use the page outline to create the final narrative content. Maintain consistency with the chapter outline and writing style.",
},
},
},
},
},
},
},
},
},
},
}
// Marshal the payload to JSON
jsonData, err := json.Marshal(payload)
if err != nil {
fmt.Printf("Error marshaling JSON: %v\n", err)
return
}
// Create the request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Error creating request: %v\n", err)
return
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error sending request: %v\n", err)
return
}
defer resp.Body.Close()
// Read the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response: %v\n", err)
return
}
// Parse the response
var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil {
fmt.Printf("Error parsing response: %v\n", err)
return
}
// Navigate the response structure
data := result["data"].(map[string]interface{})
fields := data["fields"].(map[string]interface{})
// Extract title
title := fields["title"].(map[string]interface{})["string_value"].(string)
fmt.Printf("Book Title: %s\n\n", title)
// Extract chapters
chaptersData := fields["chapters"].(map[string]interface{})
listValue := chaptersData["list_value"].(map[string]interface{})
chapters := listValue["values"].([]interface{})
fmt.Printf("Total Chapters: %d\n\n", len(chapters))
// Iterate through chapters
for i, chapter := range chapters {
chapterStruct := chapter.(map[string]interface{})["struct_value"].(map[string]interface{})
chapterFields := chapterStruct["fields"].(map[string]interface{})
chapterTitle := chapterFields["title"].(map[string]interface{})["string_value"].(string)
chapterOutline := chapterFields["outline"].(map[string]interface{})["string_value"].(string)
// Extract pages
pagesData := chapterFields["pages"].(map[string]interface{})
pagesListValue := pagesData["list_value"].(map[string]interface{})
pages := pagesListValue["values"].([]interface{})
fmt.Printf("Chapter %d: %s\n", i+1, chapterTitle)
if len(chapterOutline) > 100 {
fmt.Printf("Outline: %s...\n", chapterOutline[:100])
} else {
fmt.Printf("Outline: %s\n", chapterOutline)
}
fmt.Printf("Pages: %d\n\n", len(pages))
}
// Print cost
if usdCost, ok := result["usdCost"].(float64); ok {
fmt.Printf("Cost: $%.4f\n", usdCost)
}
}
Array Definition Structure
Basic Array Configuration
{
"type": "array",
"instruction": "Create a list of N items with specific requirements",
"items": {
"type": "object",
"properties": {
// Item schema definition
}
}
}
Key Properties
| Field | Type | Description |
|---|---|---|
type | string | Must be "array" |
instruction | string | Describe what items to generate and how many |
items | object | Schema definition for each array item |
Expected Response Structure
Arrays are returned as list_value with nested structures:
{
"data": {
"fields": {
"title": {
"string_value": "First Contact Protocol"
},
"chapters": {
"list_value": {
"values": [
{
"struct_value": {
"fields": {
"title": {
"string_value": "The Signal"
},
"outline": {
"string_value": "Dr. Sarah Chen detects an anomalous radio signal..."
},
"pages": {
"list_value": {
"values": [
{
"struct_value": {
"fields": {
"outline": {
"string_value": "Introduction to Dr. Chen at the observatory..."
},
"finalContent": {
"string_value": "The observatory hummed with quiet efficiency..."
}
}
}
}
]
}
}
}
}
}
]
}
}
}
},
"usdCost": 0.15
}
Response Navigation
- Arrays:
list_value.valuescontains an array of items - Objects in arrays: Each item is a
struct_valuewithfields - Nested arrays: Can contain additional
list_valuestructures - String values: Accessed via
string_valueproperty
Advanced Features
Processing Order
Control the sequence in which fields are generated within array items:
{
"type": "array",
"items": {
"type": "object",
"processingOrder": ["title", "outline", "content"],
"properties": {
"title": { "type": "string" },
"outline": { "type": "string" },
"content": { "type": "string" }
}
}
}
This ensures each item generates its title first, then outline, then content - allowing later fields to reference earlier ones.
Narrow Focus
Use narrowFocus to have fields reference previously generated content:
{
"finalContent": {
"type": "string",
"instruction": "Write the full content",
"narrowFocus": {
"fields": ["outline"],
"prompt": "Use the outline to create the final content"
}
}
}
This explicitly passes the outline field to the generation context for finalContent.
Nested Arrays
Arrays can contain other arrays for hierarchical structures:
{
"chapters": {
"type": "array",
"items": {
"type": "object",
"properties": {
"pages": {
"type": "array",
"items": {
"type": "object",
"properties": {
"paragraphs": {
"type": "array",
"items": { "type": "string" }
}
}
}
}
}
}
}
}
Use Cases
- Content Series: Generate blog posts, chapters, or episodes
- Product Catalogs: Create consistent product descriptions
- Educational Content: Build lesson plans with multiple sections
- Test Data: Generate structured test datasets
- Documentation: Create API documentation for multiple endpoints
- Creative Writing: Build novels, scripts, or story outlines
Best Practices
- Specify Count: Clearly state how many items to generate in the instruction
- Use Processing Order: Control field generation sequence for better context
- Leverage Narrow Focus: Pass relevant context between fields
- Set Constraints: Define word counts, character limits, or formatting rules
- Nested Arrays: Keep hierarchy depth reasonable (2-3 levels max)
- System Prompts: Use different system prompts for different roles (author, editor, etc.)
- Consistency: Ensure instructions maintain consistency across all items
For large arrays (50+ items), consider generating a detailed outline first, then using it to guide the full content generation with narrowFocus.
Very large nested arrays can result in high token usage. Start with smaller counts to test your schema before scaling up.
Real-World Performance
The book generation example demonstrates:
- 3 chapters with 2 pages each = 6 total pages
- Each page generates ~750 words (250 word outline + 500 word content)
- Total output: ~4,500 words of structured, coherent narrative
- Processing time: Varies based on model and complexity
Next Steps
- See Decision Trees for quality control in arrays
- Learn about Recursive Generation for dynamic structures
- Explore Processing Order for field dependencies