prai
Full documentation content.
A **brand theme generator** workflow
Multi-step AI processing with **history tracking**
**Type-safe schemas** with Zod validation
**CSS output generation** from AI results
## What We'll Build
We'll create a workflow that:
1. Takes a brand name and description as input
2. Generates fitting adjectives for the brand
3. Creates a core color theme based on those adjectives
4. Expands it into a full design system theme
## Prerequisites
> [!IMPORTANT]
> Make sure you have Node.js installed and an API key from OpenAI, Groq, or Google Gemini before starting.
## Setup
First, create a new project and install dependencies:
```bash
mkdir my-prai-workflow
cd my-prai-workflow
npm init -y
npm install prai zod
npm install -D typescript @types/node
```
Create a `tsconfig.json`:
```json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
```
## Step 1: Basic Setup
Create `src/index.ts`:
```typescript showLineNumbers
import { History, Model, openai, step, consoleLogger } from 'prai'
import { z } from 'zod'
// 1. Define your inputs
const brandName = 'Acme Corp'
const brandDescription = 'Innovative software solutions company'
// 2. Create a model with your preferred provider
const model = new Model({
name: 'gpt-4.1-mini',
provider: openai({ apiKey: process.env.API_KEY })
})
// 3. Create history to track the workflow
const history = new History()
// 4. Optional: Add logging to see what's happening
consoleLogger(history)
async function main() {
console.log(`Generating theme for ${brandName}...`)
// We'll add our steps here
}
main().catch(console.error)
```
## Step 2: Generate Brand Adjectives
Add the first step to generate adjectives that describe your brand:
```typescript showLineNumbers
// Add this inside the main() function
// Step 1: Generate brand adjectives
const adjectives = await step(
`List some adjectives fitting the design of the ${brandName} brand which is a ${brandDescription}`,
z.array(z.string()).describe('List of adjectives that describe the brand'),
{ model, history }
)
console.log('Brand adjectives:', adjectives)
```
## Step 3: Create a Color Scheme
Define a reusable color schema and create a basic theme:
```typescript showLineNumbers
// Add this before the main() function
// Reusable schema for HSL colors
const colorScheme = z.object({
hue: z.number().min(0).max(360).describe('Hue in degrees (0-360)'),
saturation: z.number().min(0).max(100).describe('Saturation as percentage (0-100)'),
lightness: z.number().min(0).max(100).describe('Lightness as percentage (0-100)')
}).describe('HSL color representation')
// Add this inside main() after the adjectives step
// Step 2: Create core color theme
const coreTheme = await step(
`Based on the ${history.reference(adjectives)}, derive a fitting color theme`,
z.object({
background: colorScheme,
foreground: colorScheme,
primary: colorScheme,
secondary: colorScheme,
accent: colorScheme,
border: colorScheme,
radius: z.number().min(0).max(2).describe('Border radius in rem units')
}).describe('Core brand color theme'),
{ model, history }
)
console.log('Core theme:', coreTheme)
```
> [!NOTE]
> We use HSL color format because it's more intuitive for AI models to work with hue, saturation, and lightness values.
## Step 4: Expand to Full Theme
Create a comprehensive design system theme:
```typescript showLineNumbers
// Add this inside main() after the coreTheme step
// Step 3: Expand to full design system
const fullTheme = await step(
`Expand the ${history.reference(coreTheme)} to a complete design system theme with all necessary color variants`,
z.object({
// Base colors
background: colorScheme,
foreground: colorScheme,
// Component colors
card: colorScheme,
cardForeground: colorScheme,
popover: colorScheme,
popoverForeground: colorScheme,
// Brand colors
primary: colorScheme,
primaryForeground: colorScheme,
secondary: colorScheme,
secondaryForeground: colorScheme,
// State colors
muted: colorScheme,
mutedForeground: colorScheme,
accent: colorScheme,
accentForeground: colorScheme,
destructive: colorScheme,
destructiveForeground: colorScheme,
// UI colors
border: colorScheme,
input: colorScheme,
ring: colorScheme,
// Design tokens
radius: z.number().describe('Base border radius in rem')
}).describe('Complete design system theme'),
{ model, history }
)
console.log('Full theme generated!', fullTheme)
```
## Step 5: Format the Output
Add a utility function to convert the theme to CSS variables:
```typescript showLineNumbers
// Add this before main()
function hslToString(color: { hue: number; saturation: number; lightness: number }): string {
return `${color.hue} ${color.saturation}% ${color.lightness}%`
}
function formatThemeAsCss(theme: typeof fullTheme): string {
return `
:root {
--radius: ${theme.radius}rem;
--background: ${hslToString(theme.background)};
--foreground: ${hslToString(theme.foreground)};
--card: ${hslToString(theme.card)};
--card-foreground: ${hslToString(theme.cardForeground)};
--popover: ${hslToString(theme.popover)};
--popover-foreground: ${hslToString(theme.popoverForeground)};
--primary: ${hslToString(theme.primary)};
--primary-foreground: ${hslToString(theme.primaryForeground)};
--secondary: ${hslToString(theme.secondary)};
--secondary-foreground: ${hslToString(theme.secondaryForeground)};
--muted: ${hslToString(theme.muted)};
--muted-foreground: ${hslToString(theme.mutedForeground)};
--accent: ${hslToString(theme.accent)};
--accent-foreground: ${hslToString(theme.accentForeground)};
--destructive: ${hslToString(theme.destructive)};
--destructive-foreground: ${hslToString(theme.destructiveForeground)};
--border: ${hslToString(theme.border)};
--input: ${hslToString(theme.input)};
--ring: ${hslToString(theme.ring)};
}
`.trim()
}
// Add this at the end of main()
const cssTheme = formatThemeAsCss(fullTheme)
console.log('\nGenerated CSS theme:')
console.log(cssTheme)
```
## Step 6: Run Your Workflow
Set your API key and run the workflow:
```bash
export API_KEY="your-api-key-here"
npx tsx src/index.ts
```
## What You've Learned
Congratulations! You've built your first prai workflow. Here's what you've learned:
1. **Steps**: How to create sequential AI instructions with `step()`
2. **Schemas**: How to use [Zod](https://zod.dev/) to enforce output structure
3. **History**: How to reference previous results with `history.reference()`
4. **Models**: How to configure AI providers
5. **Logging**: How to debug workflows with `consoleLogger()`
## Next Steps
- Try different AI providers (Groq, Gemini)
- Experiment with more complex schemas
- Learn about [Special Step Types](./special-step-types.mdx) for data processing
- Learn about [Advanced Usage](./advanced-usage.mdx) patterns
- Follow [Best Practices](./best-practices.mdx) for production workflows
- Explore the [Concepts](../concepts/) documentation
]]>
**`mapStep`** - Process arrays of data with consistent prompts
**`filterStep`** - Filter arrays based on AI-powered criteria
**`combineStep`** - Merge multiple data sources intelligently
**`selectStep`** - Choose the best option from alternatives
**`allStep`** - Check if all items meet criteria
**`someStep`** - Check if any items meet criteria
**`joinStep`** - Join data with intelligent matching
**`separateStep`** - Split data into categories
**`listStep`** - Generate lists based on criteria
## Map Step
Process arrays of data with consistent prompts applied to each element.
```typescript showLineNumbers
import { mapStep } from 'prai'
const products = [
{ name: 'Laptop', category: 'Electronics', price: 999 },
{ name: 'Coffee Mug', category: 'Kitchen', price: 15 },
{ name: 'Notebook', category: 'Office', price: 5 }
]
const descriptions = await mapStep(
products,
(product) => `Write a marketing description for ${product.name} in the ${product.category} category, priced at $${product.price}`,
z.object({
description: z.string(),
keyFeatures: z.array(z.string()),
targetAudience: z.string(),
marketingTags: z.array(z.string())
}),
{ model, history }
)
console.log(descriptions)
// Array of descriptions, one for each product
```
### Map Step Options
```typescript showLineNumbers
const results = await mapStep(
data,
(item) => `Process ${item.name}`,
resultSchema,
{
model,
history,
stream: true // Optional: enable streaming
}
)
```
## Filter Step
Filter arrays based on AI-powered criteria that would be difficult to express programmatically.
```typescript showLineNumbers
import { filterStep } from 'prai'
const articles = [
{ title: 'AI in Healthcare', content: 'Machine learning is revolutionizing...' },
{ title: 'Best Coffee Recipes', content: 'Start your morning with...' },
{ title: 'Quantum Computing Basics', content: 'Quantum mechanics meets...' },
{ title: 'Cooking with Python', content: 'A cookbook for programmers...' }
]
const techArticles = await filterStep(
articles,
(article) => `Is this ${article} about technology or programming?"`,
z.boolean(),
{ model, history }
)
console.log(techArticles)
// Only articles that the AI determined were about technology
// Expected: AI in Healthcare, Quantum Computing Basics, Cooking with Python
```
### Complex Filtering
```typescript showLineNumbers
const candidates = [
{ name: 'Alice', experience: '5 years React, 3 years Node.js', education: 'CS Degree' },
{ name: 'Bob', experience: '2 years Python, ML research', education: 'PhD Physics' },
{ name: 'Carol', experience: '8 years backend, team lead', education: 'Bootcamp grad' }
]
const suitable = await filterStep(
candidates,
(candidate) => `Is this ${candidate} suitable for a senior full-stack role requiring leadership experience?`,
z.object({
suitable: z.boolean(),
reasoning: z.string()
}),
{ model, history }
)
```
## Combine Step
Intelligently merge multiple data sources or combine related information.
```typescript showLineNumbers
import { combineStep } from 'prai'
const userFeedback = [
'Great product, love the design!',
'Shipping was slow but quality is good',
'Customer service needs improvement',
'Best purchase I made this year'
]
const analyticsData = {
sessions: 1000,
bounceRate: 0.3,
avgSessionTime: 120,
conversionRate: 0.05
}
const competitorData = {
pricing: { average: 49.99, range: '29.99-79.99' },
features: ['feature1', 'feature2', 'feature3'],
marketShare: 0.15
}
const report = await combineStep(
[userFeedback, analyticsData, competitorData],
'Create a comprehensive product performance report combining user feedback, analytics, and competitive analysis',
z.object({
overallSummary: z.string(),
strengths: z.array(z.string()),
weaknesses: z.array(z.string()),
recommendations: z.array(z.object({
action: z.string(),
priority: z.enum(['high', 'medium', 'low']),
reasoning: z.string()
})),
competitivePosition: z.string()
}),
{ model, history }
)
```
## Select Step
Choose the best option from a set of alternatives based on given criteria.
```typescript showLineNumbers
import { selectStep } from 'prai'
const designOptions = [
{
name: 'Modern Minimalist',
colors: ['#000000', '#ffffff', '#f5f5f5'],
style: 'clean, minimal, lots of whitespace',
targetAudience: 'professionals, millennials'
},
{
name: 'Vibrant Creative',
colors: ['#ff6b6b', '#4ecdc4', '#45b7d1'],
style: 'colorful, energetic, playful',
targetAudience: 'creatives, young adults'
},
{
name: 'Corporate Professional',
colors: ['#2c3e50', '#3498db', '#95a5a6'],
style: 'conservative, trustworthy, formal',
targetAudience: 'enterprises, executives'
}
]
const selectedDesign = await selectStep(
designOptions,
'Select the best design for a tech startup targeting young professionals who value both innovation and professionalism',
{ model, history }
)
console.log('Selected design:', selectedDesign)
// Returns the full design object that best matches the criteria
```
### Select with Custom Scoring
```typescript showLineNumbers
const bestCandidate = await selectStep(
candidates,
'Select the best candidate for a senior developer role, considering technical skills, leadership experience, and cultural fit',
{
model,
history,
stream: false // Disable streaming for selection
}
)
```
## All Step
Check if all items in an array meet specific criteria.
```typescript showLineNumbers
import { allStep } from 'prai'
const documents = [
{ title: 'Privacy Policy', content: '...' },
{ title: 'Terms of Service', content: '...' },
{ title: 'User Guide', content: '...' }
]
const allCompliant = await allStep(
documents,
(doc) => `Is this document GDPR compliant? Check for privacy controls, data handling, and user rights. Document: ${doc.title}`,
z.object({
compliant: z.boolean(),
issues: z.array(z.string()).optional()
}),
{ model, history }
)
console.log('All documents compliant:', allCompliant)
// Returns true only if ALL documents are compliant
```
## Some Step
Check if any items in an array meet specific criteria.
```typescript showLineNumbers
import { someStep } from 'prai'
const emails = [
{ subject: 'Meeting reminder', content: 'Don\'t forget about tomorrow\'s meeting' },
{ subject: 'URGENT: Action required', content: 'Your account will be suspended...' },
{ subject: 'Newsletter', content: 'Here are this week\'s updates...' }
]
const hasUrgent = await someStep(
emails,
(email) => `Is this ${email} urgent and requiring immediate action?`,
z.boolean(),
{ model, history }
)
if (hasUrgent) {
console.log('You have urgent emails requiring attention')
}
```
## Join Step
Join or match data from different sources based on intelligent criteria.
```typescript showLineNumbers
import { joinStep } from 'prai'
const customers = [
{ id: 1, name: 'John Smith', company: 'Acme Corp' },
{ id: 2, name: 'Jane Doe', company: 'Tech Solutions' }
]
const orders = [
{ orderId: 'A123', customerInfo: 'J. Smith from Acme', amount: 500 },
{ orderId: 'B456', customerInfo: 'Jane D. - Tech Solutions Inc', amount: 750 }
]
const joined = await joinStep(
customers,
orders,
(customer, order) => `Do this ${customer} and ${order} belong to the same person?`,
z.object({
customer: z.object({
id: z.number(),
name: z.string(),
company: z.string()
}),
order: z.object({
orderId: z.string(),
customerInfo: z.string(),
amount: z.number()
}),
confidence: z.number().min(0).max(1)
}),
{ model, history }
)
```
## Separate Step
Split data into different categories based on AI analysis.
```typescript showLineNumbers
import { separateStep } from 'prai'
const mixedContent = [
{ text: 'Great product, highly recommend!' },
{ text: 'Terrible quality, waste of money' },
{ text: 'The sky is blue today' },
{ text: 'Amazing customer service' }
]
const separated = await separateStep(
mixedContent,
(item) => `Categorize this text: ${item.text}`,
z.enum(['positive_review', 'negative_review', 'neutral_comment', 'unrelated']),
{ model, history }
)
console.log(separated)
// {
// positive_review: [{ text: 'Great product...' }, { text: 'Amazing customer...' }],
// negative_review: [{ text: 'Terrible quality...' }],
// neutral_comment: [],
// unrelated: [{ text: 'The sky is blue...' }]
// }
```
## List Step
Generate lists based on criteria or context.
```typescript showLineNumbers
import { listStep } from 'prai'
const projectContext = {
type: 'e-commerce website',
target: 'small businesses',
timeline: '3 months',
budget: 'medium'
}
const tasks = await listStep(
`Generate a comprehensive task list for developing ${projectContext.type} targeting ${projectContext.target} with a ${projectContext.timeline} timeline and ${projectContext.budget} budget`,
z.object({
phase: z.string(),
task: z.string(),
estimatedHours: z.number(),
priority: z.enum(['high', 'medium', 'low']),
dependencies: z.array(z.string()).optional()
}),
{ model, history }
)
console.log(tasks)
// Returns array of task objects
```]]>
**Streaming responses** for real-time feedback
**Conditional workflows** that branch based on results
**Model fallback** mechanisms for reliability
**Testing strategies** with mock providers
## Streaming Responses
**prai** supports streaming responses for real-time feedback during long-running operations.
### Basic Streaming
```typescript {14} showLineNumbers
import { step } from 'prai'
import { z } from 'zod'
const stream = step(
'Write a detailed blog post about AI in software development',
z.object({
title: z.string(),
content: z.string(),
tags: z.array(z.string()),
}),
{
model,
history,
stream: true, // Enable streaming
},
)
// Process chunks as they arrive
for await (const chunk of stream) {
process.stdout.write(chunk)
}
// Get the final parsed result
const result = await stream.getValue()
console.log('Final result:', result)
```
### Custom Stream Processing
```typescript {8-16} showLineNumbers
// Transform stream data as it arrives
const customStream = step(
'Generate a list of programming concepts',
z.array(z.string()),
{
model,
history,
stream: async * (input: AsyncIterable) => {
let buffer = ''
for await (const chunk of input) {
buffer += chunk
// Emit progress updates
yield { type: 'progress', content: chunk, totalLength: buffer.length }
}
yield { type: 'complete', totalLength: buffer.length }
}
}
)
for await (const event of customStream) {
if (event.type === 'progress') {
console.log(`Received ${event.content.length} characters...`)
} else if (event.type === 'complete') {
console.log(`Stream complete! Total: ${event.totalLength} characters`)
}
}
```
## Testing with Mock Provider
For testing workflows, use the mock provider. See [Models - Mock Provider](../concepts/model.mdx#mock-provider) for complete documentation.
```typescript {3,12} showLineNumbers
import { mock } from 'prai'
const mockModel = new Model({
name: 'test',
provider: mock(),
})
// Mock provider returns predictable responses for testing
const testResult = await step('Test prompt', z.object({ message: z.string() }), { model: mockModel })
console.log(testResult) // { message: "mock response" }
```
## Conditional Workflows
Build workflows that branch based on previous results:
```typescript {11,17,25} showLineNumbers
const assessment = await step(
'Assess the complexity of this task',
z.object({
complexity: z.enum(['simple', 'moderate', 'complex']),
reasoning: z.string(),
}),
{ model, history },
)
let result
if (assessment.complexity === 'simple') {
result = await step('Provide a simple solution', simpleSchema, { model, history })
} else if (assessment.complexity === 'moderate') {
result = await step('Provide a detailed solution', detailedSchema, { model, history })
} else {
// Complex case - use subtasks
result = await history.subtask('Complex analysis', async (subHistory) => {
const breakdown = await step('Break down the complex task', breakdownSchema, { model, history: subHistory })
const solutions = await Promise.all(
breakdown.subtasks.map((subtask) => step(`Solve: ${subtask}`, solutionSchema, { model, history: subHistory })),
)
return step(`Combine solutions: ${subHistory.reference(solutions)}`, combinedSchema, { model, history: subHistory })
})
}
```
## Model Fallback
Implement fallback mechanisms for reliability:
```typescript {6-10} showLineNumbers
async function robustStep(prompt: string, schema: z.Schema, options: any): Promise {
const models = [
new Model({ name: '...', provider: openai({ apiKey: process.env.OPENAI_API_KEY }) }),
new Model({ name: '...', provider: groq({ apiKey: process.env.GROQ_API_KEY }) }),
new Model({ name: '...', provider: gemini({ apiKey: process.env.GEMINI_API_KEY }) }),
]
for (const model of models) {
try {
return await step(prompt, schema, { ...options, model })
} catch (error) {
console.warn(`Model ${model.options.name} failed:`, error.message)
}
}
throw new Error('All models failed')
}
```
## Dynamic Model Selection
Choose models based on task characteristics:
```typescript {2} showLineNumbers
function selectModel(taskComplexity: 'simple' | 'moderate' | 'complex') {
switch (taskComplexity) {
case 'simple':
return new Model({
name: '...',
provider: openai({ apiKey: process.env.OPENAI_API_KEY }),
})
case 'moderate':
return new Model({
name: '...',
provider: groq({ apiKey: process.env.GROQ_API_KEY }),
})
case 'complex':
return new Model({
name: '...',
provider: openai({ apiKey: process.env.OPENAI_API_KEY }),
})
}
}
const model = selectModel('complex')
const result = await step(complexPrompt, complexSchema, { model, history })
```
## Dynamic Schema Generation
Generate schemas based on runtime data:
```typescript {4} showLineNumbers
function createProductSchema(categories: string[]) {
return z.object({
name: z.string(),
category: z.enum(categories as [string, ...string[]]),
price: z.number().positive(),
description: z.string(),
})
}
const availableCategories = ['electronics', 'clothing', 'books']
const productSchema = createProductSchema(availableCategories)
const product = await step('Generate a product listing', productSchema, { model, history })
```
]]>
[!TIP]
> Providing examples helps guide the AI's output format and improves consistency across multiple runs.
Provide examples to guide the AI's output:
```typescript {10-21} showLineNumbers
const result = await step(
'Classify the sentiment of this text',
z.object({
sentiment: z.enum(['positive', 'negative', 'neutral']),
confidence: z.number()
}),
{
model,
history,
examples: [
{
input: 'I love this product!',
output: { sentiment: 'positive', confidence: 0.9 },
reason: 'Contains strong positive language'
},
{
input: 'This is okay, I guess',
output: { sentiment: 'neutral', confidence: 0.6 },
reason: 'Lukewarm, non-committal language'
}
]
}
)
```
### Streaming
Enable streaming for real-time responses:
```typescript {5,8} showLineNumbers
// Basic streaming
const stream = step(
'Write a long article about AI',
z.object({ title: z.string(), content: z.string() }),
{ model, history, stream: true }
)
for await (const chunk of stream) {
process.stdout.write(chunk)
}
const result = await stream.getValue()
```
## Schema Integration
> [!TIP]
> Use `.describe()` to more information about schema fields.
Steps use [Zod](https://zod.dev/) schemas to ensure type safety and guide AI output:
```typescript showLineNumbers
// Simple schema
const userSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().min(0).max(120)
})
// Complex nested schema
const projectSchema = z.object({
title: z.string().describe('Project title'),
description: z.string().describe('Detailed project description'),
tasks: z.array(z.object({
name: z.string(),
priority: z.enum(['low', 'medium', 'high']),
estimatedHours: z.number().positive()
})).describe('List of project tasks'),
deadline: z.string().datetime().optional()
})
const project = await step(
'Create a project plan for building a mobile app',
projectSchema,
{ model, history }
)
```
## Specialized Steps
**prai** provides specialized step functions for common patterns like processing arrays, filtering data, and combining results - see [Special Step Types](../getting-started/special-step-types.mdx).]]>
[!NOTE]
> The mock provider returns predictable responses, making it perfect for testing workflows without using actual API calls.
For testing and development:
```typescript {5} showLineNumbers
import { mock } from 'prai'
const mockModel = new Model({
name: 'test-model',
provider: mock()
})
// Returns predictable responses for testing
const result = await step(
'Test prompt',
z.object({ message: z.string() }),
{ model: mockModel }
)
// Result: { message: "mock response" }
```
]]>
**Context preservation** maintains conversation flow between AI interactions
**Reference system** allows steps to reference previous results
**Subtasks** enable parallel and isolated workflows
**Event system** provides observability and debugging capabilities
## Basic Usage
```typescript {4,14} showLineNumbers
import { History } from 'prai'
// Create a new history instance
const history = new History()
// Use history in steps
const analysis = await step(
'Analyze this market data',
analysisSchema,
{ model, history }
)
const recommendations = await step(
`Based on ${history.reference(analysis)}, provide recommendations`,
recommendationsSchema,
{ model, history }
)
```
## Reference System
The reference system allows steps to refer to previous results in a natural way:
### Basic References
```typescript {12} showLineNumbers
const userProfile = await step(
'Create a user profile',
z.object({
name: z.string(),
interests: z.array(z.string()),
experience: z.string()
}),
{ model, history }
)
const recommendations = await step(
`Given the user profile from ${history.reference(userProfile)}, suggest relevant content`,
z.array(z.object({
title: z.string(),
reason: z.string()
})),
{ model, history }
)
```
### Custom References
Add custom data to history with descriptions:
```typescript {3,9} showLineNumbers
// Add external data to history
const marketData = { revenue: 1000000, growth: 0.15, customers: 5000 }
history.add(marketData, {
description: 'Q3 market performance data',
type: 'data'
})
const analysis = await step(
`Analyze this market data: ${history.reference(marketData)}`,
analysisSchema,
{ model, history }
)
```
### Derived References
Reference data that's derived from other data:
```typescript {4-7,10} showLineNumbers
const salesData = await step('Get sales data', salesSchema, { model, history })
const processedData = processSalesData(salesData)
history.add(processedData, {
derived: { from: salesData, by: 'data processing pipeline' },
description: 'Processed sales metrics'
})
const insights = await step(
`Generate insights from ${history.reference(processedData)}`,
insightsSchema,
{ model, history }
)
```
## Multimodal Support
History supports various data types including images and audio:
### Images
```typescript {2,8} showLineNumbers
// Add image data
history.add(imageBuffer, {
type: 'image',
description: 'Product photo for analysis'
})
const analysis = await step(
`Analyze this product image: ${history.reference(imageBuffer)}. Describe the product and its features.`,
z.object({
productType: z.string(),
features: z.array(z.string()),
suggestions: z.array(z.string())
}),
{ model, history }
)
```
### Audio
```typescript {2,8} showLineNumbers
// Add audio data
history.add(audioBuffer, {
type: 'wav',
description: 'Customer feedback recording'
})
const transcription = await step(
`Transcribe and analyze this audio: ${history.reference(audioBuffer)}`,
z.object({
transcription: z.string(),
sentiment: z.enum(['positive', 'negative', 'neutral']),
keyTopics: z.array(z.string())
}),
{ model, history }
)
```
## Subtasks
> [!TIP]
> Subtasks are perfect for parallel processing and creating isolated workflows that can later be combined in the main history.
Subtasks allow you to create isolated workflows within a larger history:
```typescript {5,21,35-36} showLineNumbers
const history = new History()
// Run parallel subtasks
const [brandAnalysis, marketAnalysis] = await Promise.all([
history.subtask('Brand analysis', async (subHistory) => {
const brandData = await step(
'Analyze brand positioning',
brandSchema,
{ model, history: subHistory }
)
const brandInsights = await step(
`Generate insights from ${subHistory.reference(brandData)}`,
insightsSchema,
{ model, history: subHistory }
)
return brandInsights
}),
history.subtask('Market analysis', async (subHistory) => {
const marketData = await step(
'Analyze market conditions',
marketSchema,
{ model, history: subHistory }
)
return marketData
})
])
// Combine subtask results in main history
const strategy = await step(
`Create strategy based on:
- Brand analysis: ${history.reference(brandAnalysis)}
- Market analysis: ${history.reference(marketAnalysis)}`,
strategySchema,
{ model, history }
)
```
## State Management
### Serialization
History can be serialized and restored:
```typescript showLineNumbers
// Save history state
const historyState = history.getState()
const serialized = JSON.stringify(historyState)
// Later, restore history
const restoredHistory = new History()
restoredHistory.setState(JSON.parse(serialized))
```
## Logging
History provides an event system for observability.
```typescript showLineNumbers
// Custom event handling
history.addEventListener('step-request', (event) => {
console.log('Step started:', event.historyId)
})
history.addEventListener('step-response', (event) => {
console.log('Step completed:', event.historyId)
})
history.addEventListener('data-reference-added', (event) => {
console.log('Data added to history')
})
history.addEventListener('subtask-start', (event) => {
console.log('Subtask started:', event.subtaskHistoryId)
})
```
> [!TIP]
> Use the event system for debugging, logging, and monitoring your prai workflows in production.
### Console Logger
```typescript showLineNumbers
import { consoleLogger, History } from 'prai'
const history = new History()
// Built-in console logger
consoleLogger(history)
```
### Redis Logger
You can use the Redis logger to persist history events to a Redis stream for monitoring and debugging:
```typescript showLineNumbers
import { History } from 'prai'
import { redisLogger } from 'prai-redis'
import { createClient } from 'redis'
const history = new History()
const client = createClient({ url: process.env.REDIS_URL })
await client.connect()
await redisLogger(history, { streamName: 'stream-name', client })
```
## Cost Tracking
> [!TIP]
> Cost tracking helps you monitor and optimize AI usage costs across your workflows.
History automatically tracks the cost of all AI model calls and provides methods to retrieve total costs:
### Basic Cost Tracking
```typescript {12} showLineNumbers
import { openai, buildSimplePrice } from 'prai'
const model = new Model({
name: 'gpt-4o-mini',
provider: openai({ apiKey: process.env.OPENAI_API_KEY }),
price: buildSimplePrice(0.4, 1.6) // $0.4 per 1M input tokens, $1.6 per 1M output tokens
})
const history = new History()
// Run some steps...
const analysis = await step('Analyze this data', analysisSchema, { model, history })
const summary = await step('Summarize the analysis', summarySchema, { model, history })
// Get total cost for all steps
const totalCost = history.getCost()
console.log(`Total cost: $${totalCost}`)
```
### Cost with Subtasks
Costs from subtasks are automatically included in the main history:
```typescript {15,20} showLineNumbers
const history = new History()
// Run parallel subtasks
const [analysis1, analysis2] = await Promise.all([
history.subtask('Analysis 1', async (subHistory) => {
return await step('Analyze dataset 1', schema, { model, history: subHistory })
}),
history.subtask('Analysis 2', async (subHistory) => {
return await step('Analyze dataset 2', schema, { model, history: subHistory })
})
])
// Main history cost includes subtask costs
const totalCost = history.getCost()
console.log(`Total cost including subtasks: $${totalCost}`)
// Final step cost is also included
const final = await step('Combine analyses', finalSchema, { model, history })
console.log(`Final total cost: $${history.getCost()}`)
```
]]>