Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions data/completed_orders.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
order_id,customer_name,product,quantity,price,order_date,status
1001,John Smith,Laptop,1,999.99,2024-01-15,completed
1002,Jane Doe,Mouse,2,24.99,2024-01-16,completed
1004,Alice Brown,Monitor,2,299.99,2024-01-17,completed
1007,Frank Miller,USB Hub,2,19.99,2024-01-19,completed
1009,Henry Chen,External SSD,1,149.99,2024-01-20,completed
124 changes: 124 additions & 0 deletions data/order_summary.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
{
"totalOrders": 10,
"totalRevenue": 2254.84,
"averageOrderValue": 225.48,
"statusBreakdown": {
"completed": 5,
"processing": 3,
"shipped": 2
},
"topProducts": [
{
"product": "Headphones",
"totalQuantity": 3
},
{
"product": "Mouse",
"totalQuantity": 2
},
{
"product": "Monitor",
"totalQuantity": 2
},
{
"product": "USB Hub",
"totalQuantity": 2
},
{
"product": "Wireless Charger",
"totalQuantity": 2
}
],
"orderDetails": [
{
"order_id": "1001",
"customer_name": "John Smith",
"product": "Laptop",
"quantity": "1",
"price": "999.99",
"order_date": "2024-01-15",
"status": "completed"
},
{
"order_id": "1002",
"customer_name": "Jane Doe",
"product": "Mouse",
"quantity": "2",
"price": "24.99",
"order_date": "2024-01-16",
"status": "completed"
},
{
"order_id": "1003",
"customer_name": "Bob Johnson",
"product": "Keyboard",
"quantity": "1",
"price": "79.99",
"order_date": "2024-01-17",
"status": "processing"
},
{
"order_id": "1004",
"customer_name": "Alice Brown",
"product": "Monitor",
"quantity": "2",
"price": "299.99",
"order_date": "2024-01-17",
"status": "completed"
},
{
"order_id": "1005",
"customer_name": "Charlie Wilson",
"product": "Headphones",
"quantity": "3",
"price": "49.99",
"order_date": "2024-01-18",
"status": "shipped"
},
{
"order_id": "1006",
"customer_name": "Emma Davis",
"product": "Webcam",
"quantity": "1",
"price": "89.99",
"order_date": "2024-01-19",
"status": "processing"
},
{
"order_id": "1007",
"customer_name": "Frank Miller",
"product": "USB Hub",
"quantity": "2",
"price": "19.99",
"order_date": "2024-01-19",
"status": "completed"
},
{
"order_id": "1008",
"customer_name": "Grace Lee",
"product": "Desk Lamp",
"quantity": "1",
"price": "34.99",
"order_date": "2024-01-20",
"status": "shipped"
},
{
"order_id": "1009",
"customer_name": "Henry Chen",
"product": "External SSD",
"quantity": "1",
"price": "149.99",
"order_date": "2024-01-20",
"status": "completed"
},
{
"order_id": "1010",
"customer_name": "Isabel Garcia",
"product": "Wireless Charger",
"quantity": "2",
"price": "29.99",
"order_date": "2024-01-21",
"status": "processing"
}
]
}
11 changes: 11 additions & 0 deletions data/orders.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
order_id,customer_name,product,quantity,price,order_date,status
1001,John Smith,Laptop,1,999.99,2024-01-15,completed
1002,Jane Doe,Mouse,2,24.99,2024-01-16,completed
1003,Bob Johnson,Keyboard,1,79.99,2024-01-17,processing
1004,Alice Brown,Monitor,2,299.99,2024-01-17,completed
1005,Charlie Wilson,Headphones,3,49.99,2024-01-18,shipped
1006,Emma Davis,Webcam,1,89.99,2024-01-19,processing
1007,Frank Miller,USB Hub,2,19.99,2024-01-19,completed
1008,Grace Lee,Desk Lamp,1,34.99,2024-01-20,shipped
1009,Henry Chen,External SSD,1,149.99,2024-01-20,completed
1010,Isabel Garcia,Wireless Charger,2,29.99,2024-01-21,processing
11 changes: 11 additions & 0 deletions data/report.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"generatedAt": "2025-09-09T17:40:24.911Z",
"summary": {
"orders": 10,
"revenue": 2254.84,
"topProduct": {
"product": "Headphones",
"totalQuantity": 3
}
}
}
177 changes: 177 additions & 0 deletions examples/file_io.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/**
* File I/O Tool Example
* Demonstrates reading CSV files and writing JSON files using the core File I/O tool
*/

import { fileIOTool, readCSVFile, writeJSONFile } from '../src/tools/fileIOTool.js';
import * as path from 'path';

interface OrderSummary {
totalOrders: number;
totalRevenue: number;
averageOrderValue: number;
statusBreakdown: Record<string, number>;
topProducts: Array<{ product: string; totalQuantity: number }>;
orderDetails: any[];
}

async function demonstrateFileIO() {
console.log('=== File I/O Tool Demonstration ===\n');

try {
// 1. Read CSV file using the tool directly
console.log('1. Reading CSV file using fileIOTool...');
const csvPath = path.join(process.cwd(), 'data', 'orders.csv');

const readResult = await fileIOTool.execute({
action: 'read',
filepath: csvPath,
format: 'csv'
}, {} as any); // Context would be provided by the agent framework

// Check if result is a ToolResult
let orders: any[];
if (typeof readResult === 'string') {
throw new Error('Unexpected string result');
} else if (readResult.status === 'success') {
orders = readResult.data.data as any[];
} else {
throw new Error(readResult.message || 'Failed to read CSV');
}
console.log(`✓ Successfully read ${orders.length} orders from CSV\n`);

// Display first few orders
console.log('First 3 orders:');
orders.slice(0, 3).forEach(order => {
console.log(` Order #${order.order_id}: ${order.customer_name} - ${order.product} (${order.status})`);
});
console.log();

// 2. Process the data
console.log('2. Processing order data...');

// Calculate summary statistics
const totalRevenue = orders.reduce((sum, order) => {
return sum + (parseFloat(order.price) * parseInt(order.quantity));
}, 0);

const statusBreakdown: Record<string, number> = {};
orders.forEach(order => {
statusBreakdown[order.status] = (statusBreakdown[order.status] || 0) + 1;
});

// Find top products by quantity
const productQuantities: Record<string, number> = {};
orders.forEach(order => {
const qty = parseInt(order.quantity);
productQuantities[order.product] = (productQuantities[order.product] || 0) + qty;
});

const topProducts = Object.entries(productQuantities)
.map(([product, totalQuantity]) => ({ product, totalQuantity }))
.sort((a, b) => b.totalQuantity - a.totalQuantity)
.slice(0, 5);

const summary: OrderSummary = {
totalOrders: orders.length,
totalRevenue: Math.round(totalRevenue * 100) / 100,
averageOrderValue: Math.round((totalRevenue / orders.length) * 100) / 100,
statusBreakdown,
topProducts,
orderDetails: orders
};

console.log('✓ Data processing complete\n');
console.log('Summary:');
console.log(` Total Orders: ${summary.totalOrders}`);
console.log(` Total Revenue: $${summary.totalRevenue}`);
console.log(` Average Order Value: $${summary.averageOrderValue}`);
console.log(` Status Breakdown:`, summary.statusBreakdown);
console.log();

// 3. Write JSON file using the tool
console.log('3. Writing summary to JSON file...');
const jsonPath = path.join(process.cwd(), 'data', 'order_summary.json');

const writeResult = await fileIOTool.execute({
action: 'write',
filepath: jsonPath,
content: summary,
format: 'json'
}, {} as any);

if (typeof writeResult !== 'string' && writeResult.status !== 'success') {
throw new Error(writeResult.message || 'Failed to write JSON');
}

console.log(`✓ Successfully wrote summary to ${jsonPath}\n`);

// 4. Demonstrate convenience functions
console.log('4. Using convenience functions...');

// Read CSV using convenience function
const ordersAlt = await readCSVFile(csvPath);
console.log(`✓ readCSVFile: Read ${ordersAlt.length} orders`);

// Write JSON using convenience function
const reportPath = path.join(process.cwd(), 'data', 'report.json');
await writeJSONFile(reportPath, {
generatedAt: new Date().toISOString(),
summary: {
orders: summary.totalOrders,
revenue: summary.totalRevenue
}
});
console.log(`✓ writeJSONFile: Created report at ${reportPath}\n`);

// 5. Read the written JSON file to verify
console.log('5. Verifying written JSON file...');
const verifyResult = await fileIOTool.execute({
action: 'read',
filepath: jsonPath,
format: 'json'
}, {} as any);

if (typeof verifyResult !== 'string' && verifyResult.status === 'success') {
const verifiedData = verifyResult.data.data as OrderSummary;
console.log(`✓ Verified JSON file contains ${verifiedData.totalOrders} orders`);
console.log(`✓ Revenue matches: $${verifiedData.totalRevenue}\n`);
}

// 6. Demonstrate CSV writing
console.log('6. Writing filtered data to new CSV...');
const completedOrders = orders.filter(order => order.status === 'completed');

const csvWriteResult = await fileIOTool.execute({
action: 'write',
filepath: path.join(process.cwd(), 'data', 'completed_orders.csv'),
content: completedOrders,
format: 'csv'
}, {} as any);

if (typeof csvWriteResult !== 'string' && csvWriteResult.status !== 'success') {
throw new Error(csvWriteResult.message || 'Failed to write CSV');
}

console.log(`✓ Wrote ${completedOrders.length} completed orders to new CSV file\n`);

console.log('=== File I/O Tool Demonstration Complete ===');
console.log('\nThe fileIOTool provides:');
console.log(' • Core Tool<A, Ctx> interface compatible with JAF framework');
console.log(' • Read/write support for text, JSON, and CSV files');
console.log(' • Automatic format detection based on file extension');
console.log(' • CSV parsing with configurable delimiter and headers');
console.log(' • Type-safe parameters using Zod schemas');
console.log(' • Proper error handling with ToolResult types');
console.log(' • Convenience functions for common operations');

} catch (error) {
console.error('Error during file I/O demonstration:', error);
process.exit(1);
}
}

// Run the demonstration
if (import.meta.url === `file://${process.argv[1]}`) {
demonstrateFileIO().catch(console.error);
}
Loading
Loading