From e6e42e1af6d5c1f85ed679cf930e0d5c6fb8db5b Mon Sep 17 00:00:00 2001 From: "devansh.raj@juspay.in" Date: Mon, 8 Dec 2025 16:41:59 +0530 Subject: [PATCH] add office document processing examples --- examples/README.md | 24 + examples/office-documents/README.md | 237 ++++++++ .../office-documents/contract-analysis.ts | 325 +++++++++++ examples/office-documents/data-analysis.ts | 473 ++++++++++++++++ examples/office-documents/data/README.md | 185 +++++++ examples/office-documents/mixed-multimodal.ts | 508 ++++++++++++++++++ .../office-documents/presentation-summary.ts | 406 ++++++++++++++ 7 files changed, 2158 insertions(+) create mode 100644 examples/office-documents/README.md create mode 100644 examples/office-documents/contract-analysis.ts create mode 100644 examples/office-documents/data-analysis.ts create mode 100644 examples/office-documents/data/README.md create mode 100644 examples/office-documents/mixed-multimodal.ts create mode 100644 examples/office-documents/presentation-summary.ts diff --git a/examples/README.md b/examples/README.md index 20a3e3055..00e099376 100644 --- a/examples/README.md +++ b/examples/README.md @@ -182,8 +182,32 @@ const result = await neurolink.generate({ | External Discovery | ✅ Working | MCP server discovery examples | | CLI Usage | ✅ Ready | Command-line interface examples | | SDK Integration | ✅ Ready | TypeScript/JavaScript SDK examples | +| PDF Analysis | ✅ Ready | PDF document processing examples | +| CSV Analysis | ✅ Ready | CSV data analysis examples | +| Office Documents | ✅ Ready | DOCX, PPTX, XLSX processing examples | | External Tools | 🔧 Coming | Direct external tool execution (v1.8.0) | +## 📄 **Office Document Examples (NEW)** + +Process and analyze Microsoft Office documents with AI: + +### **Office Documents Directory** (`office-documents/`) + +- `contract-analysis.ts` - DOCX contract analysis and risk assessment +- `presentation-summary.ts` - PPTX presentation summarization +- `data-analysis.ts` - XLSX spreadsheet analysis and insights +- `mixed-multimodal.ts` - Combined document workflows + +```bash +# Run office document examples +npx tsx examples/office-documents/contract-analysis.ts +npx tsx examples/office-documents/presentation-summary.ts +npx tsx examples/office-documents/data-analysis.ts +npx tsx examples/office-documents/mixed-multimodal.ts +``` + +See [`office-documents/README.md`](office-documents/README.md) for detailed documentation. + --- **🚀 Start with `basic-usage.js` and `mcp-built-in-tools.js` to see NeuroLink in action!** diff --git a/examples/office-documents/README.md b/examples/office-documents/README.md new file mode 100644 index 000000000..059bcddd7 --- /dev/null +++ b/examples/office-documents/README.md @@ -0,0 +1,237 @@ +# 📄 Office Document Processing Examples + +This directory contains practical examples demonstrating NeuroLink's office document processing capabilities for DOCX, PPTX, and XLSX files. + +## 📋 Prerequisites + +### Required Setup + +```bash +# Install NeuroLink +npm install @juspay/neurolink + +# Set up provider credentials (choose one or more) +export GOOGLE_AI_API_KEY="AIza-your-key" # Google AI Studio +export OPENAI_API_KEY="sk-your-key" # OpenAI +export ANTHROPIC_API_KEY="sk-ant-your-key" # Anthropic Claude +export VERTEX_PROJECT="your-project" # Google Vertex AI +``` + +### Supported Providers + +Office document processing requires vision-capable providers: + +| Provider | DOCX | PPTX | XLSX | +| --------------------- | ---- | ---- | ---- | +| Google AI Studio | ✅ | ✅ | ✅ | +| OpenAI (GPT-4 Vision) | ✅ | ✅ | ✅ | +| Anthropic Claude | ✅ | ✅ | ✅ | +| Google Vertex AI | ✅ | ✅ | ✅ | +| AWS Bedrock | ✅ | ✅ | ✅ | + +## 📂 Example Files + +### Contract Analysis (`contract-analysis.ts`) + +Demonstrates DOCX document processing for legal contract analysis: + +- Extract key contract terms and clauses +- Identify parties and obligations +- Summarize contract provisions +- Highlight potential risks + +```bash +npx tsx examples/office-documents/contract-analysis.ts +``` + +### Presentation Summary (`presentation-summary.ts`) + +Demonstrates PPTX presentation processing: + +- Summarize slide content +- Extract key points and takeaways +- Identify themes and structure +- Generate meeting notes + +```bash +npx tsx examples/office-documents/presentation-summary.ts +``` + +### Data Analysis (`data-analysis.ts`) + +Demonstrates XLSX spreadsheet processing: + +- Analyze spreadsheet data +- Generate statistical summaries +- Identify trends and patterns +- Create data insights + +```bash +npx tsx examples/office-documents/data-analysis.ts +``` + +### Mixed Multimodal (`mixed-multimodal.ts`) + +Demonstrates combined office document workflows: + +- Analyze multiple document types together +- Cross-reference information across files +- Generate comprehensive reports +- Compare data from different sources + +```bash +npx tsx examples/office-documents/mixed-multimodal.ts +``` + +## 🚀 Quick Start + +### SDK Usage + +```typescript +import { NeuroLink } from "@juspay/neurolink"; + +const neurolink = new NeuroLink(); + +// Analyze a DOCX contract +const contractResult = await neurolink.generate({ + input: { + text: "Extract the key terms from this contract", + officeFiles: ["./data/sample-contract.docx"], + }, + provider: "google-ai", + maxTokens: 2000, +}); + +// Summarize a PPTX presentation +const presentationResult = await neurolink.generate({ + input: { + text: "Summarize the main points of this presentation", + officeFiles: ["./data/quarterly-report.pptx"], + }, + provider: "openai", + model: "gpt-4o", + maxTokens: 1500, +}); + +// Analyze an XLSX spreadsheet +const spreadsheetResult = await neurolink.generate({ + input: { + text: "Analyze the sales trends in this spreadsheet", + officeFiles: ["./data/sales-data.xlsx"], + }, + provider: "anthropic", + maxTokens: 1000, +}); +``` + +### CLI Usage + +```bash +# Analyze a DOCX file +npx @juspay/neurolink generate "Extract key terms from this contract" \ + --office examples/office-documents/data/sample-contract.docx \ + --provider google-ai + +# Summarize a PPTX file +npx @juspay/neurolink generate "Summarize this presentation" \ + --office examples/office-documents/data/quarterly-report.pptx \ + --provider openai + +# Analyze an XLSX file +npx @juspay/neurolink generate "What are the sales trends?" \ + --office examples/office-documents/data/sales-data.xlsx \ + --provider anthropic + +# Mixed multimodal analysis +npx @juspay/neurolink generate "Compare the contract terms with the sales data" \ + --office examples/office-documents/data/sample-contract.docx \ + --office examples/office-documents/data/sales-data.xlsx \ + --provider google-ai +``` + +## 📁 Sample Data Files + +The `data/` directory contains sample office documents for testing: + +| File | Type | Description | +| ----------------------- | ---- | ------------------------------- | +| `sample-contract.docx` | DOCX | Sample service agreement | +| `quarterly-report.pptx` | PPTX | Quarterly business presentation | +| `sales-data.xlsx` | XLSX | Sales metrics spreadsheet | + +## 🔧 Tips and Best Practices + +### Token Management + +Office documents can be large. Use these strategies: + +```typescript +// Limit response size for large documents +const result = await neurolink.generate({ + input: { + text: "Extract only the executive summary", + officeFiles: ["./large-document.docx"], + }, + maxTokens: 1000, // Limit response length +}); +``` + +### Streaming for Large Documents + +Use streaming for faster initial response: + +```typescript +const stream = await neurolink.stream({ + input: { + text: "Provide a detailed analysis of this spreadsheet", + officeFiles: ["./financial-report.xlsx"], + }, + provider: "google-ai", + maxTokens: 3000, +}); + +for await (const chunk of stream) { + process.stdout.write(chunk.content); +} +``` + +### Error Handling + +```typescript +try { + const result = await neurolink.generate({ + input: { + text: "Analyze this document", + officeFiles: ["./contract.docx"], + }, + provider: "openai", + }); + console.log(result.content); +} catch (error) { + if (error.message.includes("not supported")) { + console.log("This provider does not support office documents"); + console.log("Try: google-ai, openai, anthropic, or vertex"); + } else { + console.error("Error:", error.message); + } +} +``` + +## 📚 Related Examples + +- [`../pdf-analysis.ts`](../pdf-analysis.ts) - PDF document processing +- [`../csv-analysis.ts`](../csv-analysis.ts) - CSV data analysis +- [`../basic-usage.js`](../basic-usage.js) - Basic SDK usage + +## 🤝 Contributing + +To add new examples: + +1. Create a new TypeScript file following existing patterns +2. Add sample data files to `data/` directory +3. Update this README with the new example +4. Test with multiple providers + +--- + +**📖 Full Documentation**: [NeuroLink Docs](https://github.com/juspay/neurolink#readme) diff --git a/examples/office-documents/contract-analysis.ts b/examples/office-documents/contract-analysis.ts new file mode 100644 index 000000000..cb7a7b041 --- /dev/null +++ b/examples/office-documents/contract-analysis.ts @@ -0,0 +1,325 @@ +/** + * DOCX Contract Analysis Examples for NeuroLink + * Demonstrates contract document processing and analysis capabilities + * + * Run with: npx tsx examples/office-documents/contract-analysis.ts + * + * Prerequisites: + * - Set up provider credentials (Google AI, OpenAI, Anthropic, or Vertex AI) + * - Ensure DOCX files exist in examples/office-documents/data/ directory + * + * Note: If you encounter tool schema errors, you can disable tools: + * export NEUROLINK_DISABLE_TOOLS=true + * npx tsx examples/office-documents/contract-analysis.ts + */ + +import { NeuroLink } from "@juspay/neurolink"; + +const neurolink = new NeuroLink(); + +// Provider configuration (change as needed) +const PROVIDER = "google-ai"; // or "openai", "anthropic", "vertex" + +/** + * Example 1: Basic Contract Analysis + * Extracts key terms and parties from a contract document + */ +async function basicContractAnalysis() { + console.log("=== Example 1: Basic Contract Analysis ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Analyze this contract and extract the following information: +1. Parties involved (names and roles) +2. Contract effective date and term +3. Key obligations of each party +4. Payment terms (if any) +5. Termination conditions + +Format the response as a structured summary.`, + officeFiles: ["./examples/office-documents/data/sample-contract.docx"], + }, + provider: PROVIDER, + maxTokens: 1500, + }); + + console.log("Contract Analysis Result:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 1:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 2: Risk Assessment + * Identifies potential risks and liabilities in a contract + */ +async function riskAssessment() { + console.log("=== Example 2: Contract Risk Assessment ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Perform a risk assessment on this contract. Identify: + +1. **Potential Liabilities**: Clauses that could expose parties to liability +2. **Ambiguous Language**: Vague or unclear terms that could lead to disputes +3. **Missing Protections**: Common protections that appear to be missing +4. **Unusual Clauses**: Terms that deviate from standard contract practices +5. **Compliance Concerns**: Potential regulatory or legal compliance issues + +Rate each identified risk as: HIGH, MEDIUM, or LOW. +Provide recommendations for mitigation where applicable.`, + officeFiles: ["./examples/office-documents/data/sample-contract.docx"], + }, + provider: PROVIDER, + maxTokens: 2000, + }); + + console.log("Risk Assessment Result:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 2:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 3: Clause Extraction + * Extracts specific types of clauses from the contract + */ +async function clauseExtraction() { + console.log("=== Example 3: Clause Extraction ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Extract and summarize the following clauses from this contract (if present): + +1. **Confidentiality/NDA Clause**: Terms related to confidential information +2. **Indemnification Clause**: Who indemnifies whom and for what +3. **Limitation of Liability**: Caps or limits on damages +4. **Intellectual Property**: IP ownership and usage rights +5. **Force Majeure**: Circumstances that excuse non-performance +6. **Dispute Resolution**: How disputes will be resolved (arbitration, litigation, etc.) +7. **Governing Law**: Which jurisdiction's laws apply + +For each clause found, provide: +- A brief summary +- The section/paragraph reference (if identifiable) +- Any notable conditions or exceptions`, + officeFiles: ["./examples/office-documents/data/sample-contract.docx"], + }, + provider: PROVIDER, + maxTokens: 2500, + }); + + console.log("Extracted Clauses:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 3:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 4: Contract Summary + * Generates an executive summary of the contract + */ +async function contractSummary() { + console.log("=== Example 4: Executive Summary ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Generate an executive summary of this contract suitable for a busy executive. +The summary should: + +1. Be concise (max 300 words) +2. Highlight the most important terms +3. Call out any critical deadlines or obligations +4. Note any financial commitments +5. Flag items requiring immediate attention + +Format as bullet points for easy scanning.`, + officeFiles: ["./examples/office-documents/data/sample-contract.docx"], + }, + provider: PROVIDER, + maxTokens: 800, + }); + + console.log("Executive Summary:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 4:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 5: Contract Comparison + * Compares two contract versions (useful for amendments) + */ +async function contractComparison() { + console.log("=== Example 5: Contract Comparison ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Compare these two contract versions and identify: + +1. **Added Clauses**: New provisions in the second document +2. **Removed Clauses**: Provisions that were deleted +3. **Modified Terms**: Changes to existing provisions +4. **Financial Changes**: Any changes to monetary amounts, payment terms, or fees +5. **Timeline Changes**: Changes to dates, deadlines, or durations + +Summarize the overall impact of the changes on the contractual relationship.`, + officeFiles: [ + "./examples/office-documents/data/sample-contract.docx", + "./examples/office-documents/data/amended-contract.docx", + ], + }, + provider: PROVIDER, + maxTokens: 2000, + }); + + console.log("Comparison Result:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 5:", + error instanceof Error ? error.message : error, + ); + console.log( + "Note: This example requires two DOCX files. Ensure both files exist.", + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 6: Streaming Contract Analysis + * Uses streaming for faster response with large documents + */ +async function streamingAnalysis() { + console.log("=== Example 6: Streaming Contract Analysis ===\n"); + + try { + const stream = await neurolink.stream({ + input: { + text: `Provide a comprehensive analysis of this contract including: +- Full summary of all major provisions +- Timeline of all obligations and deadlines +- Complete list of all parties' responsibilities +- All financial terms and conditions`, + officeFiles: ["./examples/office-documents/data/sample-contract.docx"], + }, + provider: PROVIDER, + maxTokens: 3000, + }); + + console.log("Streaming Analysis:"); + for await (const chunk of stream) { + process.stdout.write(chunk.content); + } + console.log("\n\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 6:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 7: Error Handling + * Demonstrates proper error handling for unsupported providers + */ +async function errorHandlingExample() { + console.log("=== Example 7: Error Handling ===\n"); + + try { + // This may fail if the provider doesn't support office documents + const result = await neurolink.generate({ + input: { + text: "Analyze this contract", + officeFiles: ["./examples/office-documents/data/sample-contract.docx"], + }, + provider: "ollama", // Local provider - may not support office docs + maxTokens: 500, + }); + + console.log("Result:", result.content); + } catch (error) { + if ( + error instanceof Error && + error.message.includes("not currently supported") + ) { + console.log("✓ Caught expected error: Provider does not support DOCX"); + console.log("\nError message:"); + console.log(error.message); + console.log( + "\n💡 Tip: Switch to a supported provider like 'google-ai', 'openai', 'anthropic', or 'vertex'", + ); + } else { + console.log( + "Error (expected for demonstration):", + error instanceof Error ? error.message : error, + ); + } + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Main execution function + * Runs all examples in sequence + */ +async function main() { + console.log("\n" + "=".repeat(60)); + console.log(" NeuroLink DOCX Contract Analysis Examples"); + console.log(" Provider:", PROVIDER); + console.log("=".repeat(60) + "\n"); + + console.log("Note: Make sure you have set up provider credentials"); + console.log("and that DOCX files exist in examples/office-documents/data/\n"); + + console.log("Running examples...\n"); + + await basicContractAnalysis(); + await riskAssessment(); + await clauseExtraction(); + await contractSummary(); + await contractComparison(); + await streamingAnalysis(); + await errorHandlingExample(); + + console.log("All examples completed!"); +} + +// Run examples +main().catch((error) => { + console.error("Fatal error:", error); + process.exit(1); +}); diff --git a/examples/office-documents/data-analysis.ts b/examples/office-documents/data-analysis.ts new file mode 100644 index 000000000..525cb16a5 --- /dev/null +++ b/examples/office-documents/data-analysis.ts @@ -0,0 +1,473 @@ +/** + * XLSX Data Analysis Examples for NeuroLink + * Demonstrates Excel spreadsheet processing and analysis capabilities + * + * Run with: npx tsx examples/office-documents/data-analysis.ts + * + * Prerequisites: + * - Set up provider credentials (Google AI, OpenAI, Anthropic, or Vertex AI) + * - Ensure XLSX files exist in examples/office-documents/data/ directory + * + * Note: If you encounter tool schema errors, you can disable tools: + * export NEUROLINK_DISABLE_TOOLS=true + * npx tsx examples/office-documents/data-analysis.ts + */ + +import { NeuroLink } from "@juspay/neurolink"; + +const neurolink = new NeuroLink(); + +// Provider configuration (change as needed) +const PROVIDER = "google-ai"; // or "openai", "anthropic", "vertex" + +/** + * Example 1: Basic Spreadsheet Analysis + * Provides an overview of the spreadsheet content + */ +async function basicSpreadsheetAnalysis() { + console.log("=== Example 1: Basic Spreadsheet Analysis ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Analyze this Excel spreadsheet and provide: +1. Overview of the data structure (columns, rows, sheets) +2. Summary of the data types present +3. Key metrics and totals +4. General observations about the data + +Format as a structured report.`, + officeFiles: ["./examples/office-documents/data/sales-data.xlsx"], + }, + provider: PROVIDER, + maxTokens: 1500, + }); + + console.log("Spreadsheet Analysis:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 1:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 2: Statistical Summary + * Generates statistical analysis of numeric data + */ +async function statisticalSummary() { + console.log("=== Example 2: Statistical Summary ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Perform a statistical analysis on this spreadsheet: + +## Statistical Analysis + +For each numeric column, provide: +- **Count**: Number of data points +- **Sum**: Total sum +- **Average/Mean**: Arithmetic mean +- **Min/Max**: Minimum and maximum values +- **Range**: Difference between max and min + +Additionally: +- Identify any outliers (values significantly different from the mean) +- Note any patterns or correlations between columns +- Highlight any data quality issues (missing values, inconsistencies) + +Present the statistics in a table format where possible.`, + officeFiles: ["./examples/office-documents/data/sales-data.xlsx"], + }, + provider: PROVIDER, + maxTokens: 2000, + }); + + console.log("Statistical Summary:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 2:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 3: Trend Analysis + * Identifies trends and patterns in the data + */ +async function trendAnalysis() { + console.log("=== Example 3: Trend Analysis ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Analyze trends in this spreadsheet data: + +## Trend Analysis + +1. **Time-Based Trends** + - If date/time columns exist, analyze changes over time + - Identify growth or decline patterns + - Calculate period-over-period changes + +2. **Category Trends** + - Group data by categories (if applicable) + - Compare performance across categories + - Identify top and bottom performers + +3. **Correlation Analysis** + - Identify relationships between variables + - Note positive or negative correlations + - Suggest causal relationships (with caveats) + +4. **Seasonal Patterns** + - If applicable, identify seasonal variations + - Note any cyclical patterns + +5. **Growth Projections** + - Based on current trends, project future values + - Provide confidence level for projections`, + officeFiles: ["./examples/office-documents/data/sales-data.xlsx"], + }, + provider: PROVIDER, + maxTokens: 2000, + }); + + console.log("Trend Analysis:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 3:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 4: Data Quality Assessment + * Evaluates the quality and completeness of the data + */ +async function dataQualityAssessment() { + console.log("=== Example 4: Data Quality Assessment ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Perform a data quality assessment on this spreadsheet: + +## Data Quality Report + +### Completeness +- Percentage of cells with data +- Columns with missing values +- Rows with incomplete data + +### Accuracy +- Identify any obvious data entry errors +- Values that seem incorrect or out of range +- Inconsistent formatting + +### Consistency +- Naming conventions used +- Date/number format consistency +- Category standardization + +### Validity +- Data types match expected types +- Values within expected ranges +- Referential integrity (if applicable) + +### Recommendations +- Priority issues to fix +- Data cleaning suggestions +- Process improvements to prevent future issues + +Rate overall data quality: EXCELLENT / GOOD / FAIR / POOR`, + officeFiles: ["./examples/office-documents/data/sales-data.xlsx"], + }, + provider: PROVIDER, + maxTokens: 1800, + }); + + console.log("Data Quality Assessment:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 4:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 5: Business Insights + * Extracts actionable business insights from the data + */ +async function businessInsights() { + console.log("=== Example 5: Business Insights ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Generate actionable business insights from this spreadsheet: + +## Business Insights Report + +### Executive Summary +(2-3 sentence overview of key findings) + +### Top Insights + +**Insight 1**: [Title] +- Finding: [What the data shows] +- Impact: [Business implication] +- Recommendation: [Suggested action] + +**Insight 2**: [Title] +- Finding: [What the data shows] +- Impact: [Business implication] +- Recommendation: [Suggested action] + +(Continue for 5-7 key insights) + +### Risk Indicators +- [Any concerning trends or patterns] +- [Areas requiring attention] + +### Opportunities +- [Growth opportunities identified] +- [Efficiency improvements possible] + +### Recommended Actions +1. [Priority 1 action] +2. [Priority 2 action] +3. [Priority 3 action]`, + officeFiles: ["./examples/office-documents/data/sales-data.xlsx"], + }, + provider: PROVIDER, + maxTokens: 2000, + }); + + console.log("Business Insights:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 5:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 6: Comparison Analysis + * Compares data across multiple spreadsheets + */ +async function comparisonAnalysis() { + console.log("=== Example 6: Comparison Analysis ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Compare the data in these two spreadsheets: + +## Comparative Analysis + +### Data Structure Comparison +- Columns present in both vs. unique to each +- Row count differences +- Data format differences + +### Metric Comparison +| Metric | File 1 | File 2 | Difference | % Change | +|--------|--------|--------|------------|----------| +(Compare key numeric metrics) + +### Key Differences +1. [Major difference 1] +2. [Major difference 2] +3. [Major difference 3] + +### Trend Comparison +- How trends differ between datasets +- Period-over-period changes + +### Reconciliation Issues +- Data that doesn't match when it should +- Unexplained discrepancies + +### Summary +(Overall assessment of the comparison)`, + officeFiles: [ + "./examples/office-documents/data/sales-data.xlsx", + "./examples/office-documents/data/budget-data.xlsx", + ], + }, + provider: PROVIDER, + maxTokens: 2000, + }); + + console.log("Comparison Analysis:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 6:", + error instanceof Error ? error.message : error, + ); + console.log( + "Note: This example requires two XLSX files. Ensure both files exist.", + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 7: Streaming Data Analysis + * Uses streaming for faster response with large spreadsheets + */ +async function streamingDataAnalysis() { + console.log("=== Example 7: Streaming Data Analysis ===\n"); + + try { + const stream = await neurolink.stream({ + input: { + text: `Provide a comprehensive analysis of this spreadsheet including: +- Complete data summary +- All calculated metrics +- Trend analysis +- Data quality assessment +- Business recommendations`, + officeFiles: ["./examples/office-documents/data/sales-data.xlsx"], + }, + provider: PROVIDER, + maxTokens: 3000, + }); + + console.log("Streaming Analysis:"); + for await (const chunk of stream) { + process.stdout.write(chunk.content); + } + console.log("\n\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 7:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 8: Dashboard Data Extraction + * Extracts data suitable for dashboards + */ +async function dashboardDataExtraction() { + console.log("=== Example 8: Dashboard Data Extraction ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Extract key metrics from this spreadsheet for a dashboard: + +## Dashboard Metrics + +### KPI Summary +| KPI | Current Value | Previous Period | Change | +|-----|---------------|-----------------|--------| +(Extract 5-10 key performance indicators) + +### Trend Data (for charts) +\`\`\`json +{ + "timeSeries": [ + { "period": "...", "value": ... }, + ... + ] +} +\`\`\` + +### Category Breakdown (for pie charts) +\`\`\`json +{ + "categories": [ + { "name": "...", "value": ..., "percentage": ... }, + ... + ] +} +\`\`\` + +### Top/Bottom Lists +**Top 5 Performers:** +1. ... + +**Bottom 5 Performers:** +1. ... + +### Alerts & Thresholds +- Metrics exceeding thresholds +- Items requiring attention`, + officeFiles: ["./examples/office-documents/data/sales-data.xlsx"], + }, + provider: PROVIDER, + maxTokens: 2000, + }); + + console.log("Dashboard Data:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 8:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Main execution function + * Runs all examples in sequence + */ +async function main() { + console.log("\n" + "=".repeat(60)); + console.log(" NeuroLink XLSX Data Analysis Examples"); + console.log(" Provider:", PROVIDER); + console.log("=".repeat(60) + "\n"); + + console.log("Note: Make sure you have set up provider credentials"); + console.log("and that XLSX files exist in examples/office-documents/data/\n"); + + console.log("Running examples...\n"); + + await basicSpreadsheetAnalysis(); + await statisticalSummary(); + await trendAnalysis(); + await dataQualityAssessment(); + await businessInsights(); + await comparisonAnalysis(); + await streamingDataAnalysis(); + await dashboardDataExtraction(); + + console.log("All examples completed!"); +} + +// Run examples +main().catch((error) => { + console.error("Fatal error:", error); + process.exit(1); +}); diff --git a/examples/office-documents/data/README.md b/examples/office-documents/data/README.md new file mode 100644 index 000000000..b74019af4 --- /dev/null +++ b/examples/office-documents/data/README.md @@ -0,0 +1,185 @@ +# Sample Office Documents for Examples + +This directory contains sample office documents used in the NeuroLink office document processing examples. + +## Files + +### DOCX Files + +#### sample-contract.docx + +A sample service agreement contract for demonstrating contract analysis features. + +**Contents:** + +- Parties: Acme Corporation and Beta Services LLC +- Contract type: Professional Services Agreement +- Term: 12 months with auto-renewal +- Value: $120,000 annual contract +- Key clauses: Confidentiality, Indemnification, Termination + +**Use for:** + +- Contract analysis and summarization +- Risk assessment +- Clause extraction +- Legal document processing + +#### amended-contract.docx + +An amended version of the sample contract for comparison examples. + +**Contents:** + +- Same base contract with modifications +- Increased contract value to $150,000 +- Extended term to 24 months +- Added new service levels + +**Use for:** + +- Contract comparison +- Change tracking +- Version analysis + +### PPTX Files + +#### quarterly-report.pptx + +A quarterly business report presentation. + +**Contents:** + +- 12 slides covering Q3 2024 performance +- Revenue: $2.5M (15% growth) +- Key metrics and KPIs +- Strategic initiatives update +- Q4 outlook and projections + +**Use for:** + +- Presentation summarization +- Meeting notes generation +- Key insights extraction +- Executive brief creation + +#### annual-review.pptx + +An annual business review presentation. + +**Contents:** + +- 20 slides covering full year performance +- Year-over-year comparisons +- Department performance breakdown +- Budget vs. actual analysis +- Strategic priorities for next year + +**Use for:** + +- Presentation comparison (vs. quarterly) +- Long-form content analysis +- Trend identification + +### XLSX Files + +#### sales-data.xlsx + +Sales performance data spreadsheet. + +**Contents:** + +- 500 rows of transaction data +- Columns: Date, Product, Category, Quantity, Unit Price, Revenue, Region, Sales Rep +- Date range: January 2024 - September 2024 +- Categories: Electronics, Furniture, Software, Services + +**Use for:** + +- Statistical analysis +- Trend analysis +- Data quality assessment +- Business insights extraction + +#### budget-data.xlsx + +Budget and financial planning spreadsheet. + +**Contents:** + +- Monthly budget allocations +- Actual vs. planned spending +- Department breakdowns +- Variance analysis data + +**Use for:** + +- Budget comparison +- Financial reconciliation +- Spreadsheet comparison examples + +## Usage + +These files are referenced in the office document examples: + +```bash +# Contract analysis +npx tsx examples/office-documents/contract-analysis.ts + +# Presentation summary +npx tsx examples/office-documents/presentation-summary.ts + +# Data analysis +npx tsx examples/office-documents/data-analysis.ts + +# Mixed multimodal +npx tsx examples/office-documents/mixed-multimodal.ts +``` + +## CLI Examples + +```bash +# Analyze a DOCX contract +npx @juspay/neurolink generate "Extract key terms" \ + --office examples/office-documents/data/sample-contract.docx \ + --provider google-ai + +# Summarize a PPTX presentation +npx @juspay/neurolink generate "Summarize this presentation" \ + --office examples/office-documents/data/quarterly-report.pptx \ + --provider openai + +# Analyze an XLSX spreadsheet +npx @juspay/neurolink generate "Analyze sales trends" \ + --office examples/office-documents/data/sales-data.xlsx \ + --provider anthropic + +# Mixed multimodal analysis +npx @juspay/neurolink generate "Compare contract with actual sales" \ + --office examples/office-documents/data/sample-contract.docx \ + --office examples/office-documents/data/sales-data.xlsx \ + --provider google-ai +``` + +## Creating Your Own Test Files + +To create sample files for testing: + +### DOCX + +Use Microsoft Word, Google Docs, or LibreOffice Writer to create a document, then export as .docx. + +### PPTX + +Use Microsoft PowerPoint, Google Slides, or LibreOffice Impress to create a presentation, then export as .pptx. + +### XLSX + +Use Microsoft Excel, Google Sheets, or LibreOffice Calc to create a spreadsheet, then export as .xlsx. + +## Notes + +- All sample data is synthetic and for demonstration purposes only +- File sizes are kept small for quick example execution +- Real-world files may require longer processing times +- Large files may require streaming for optimal performance diff --git a/examples/office-documents/mixed-multimodal.ts b/examples/office-documents/mixed-multimodal.ts new file mode 100644 index 000000000..96a57450f --- /dev/null +++ b/examples/office-documents/mixed-multimodal.ts @@ -0,0 +1,508 @@ +/** + * Mixed Multimodal Office Documents Examples for NeuroLink + * Demonstrates combined office document workflows (DOCX + PPTX + XLSX) + * + * Run with: npx tsx examples/office-documents/mixed-multimodal.ts + * + * Prerequisites: + * - Set up provider credentials (Google AI, OpenAI, Anthropic, or Vertex AI) + * - Ensure office files exist in examples/office-documents/data/ directory + * + * Note: If you encounter tool schema errors, you can disable tools: + * export NEUROLINK_DISABLE_TOOLS=true + * npx tsx examples/office-documents/mixed-multimodal.ts + */ + +import { NeuroLink } from "@juspay/neurolink"; + +const neurolink = new NeuroLink(); + +// Provider configuration (change as needed) +const PROVIDER = "google-ai"; // or "openai", "anthropic", "vertex" + +/** + * Example 1: Contract + Spreadsheet Analysis + * Cross-references contract terms with financial data + */ +async function contractSpreadsheetAnalysis() { + console.log("=== Example 1: Contract + Spreadsheet Analysis ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Analyze the contract and spreadsheet together: + +1. **Payment Verification** + - Extract payment terms from the contract + - Compare with actual payments in the spreadsheet + - Identify any discrepancies or missing payments + +2. **Obligation Compliance** + - List contractual obligations with deadlines + - Check spreadsheet for evidence of compliance + - Flag any potential breaches + +3. **Financial Summary** + - Total contract value vs. actual spend from spreadsheet + - Remaining obligations or payments + - Variance analysis + +Provide a reconciliation report.`, + officeFiles: [ + "./examples/office-documents/data/sample-contract.docx", + "./examples/office-documents/data/sales-data.xlsx", + ], + }, + provider: PROVIDER, + maxTokens: 2500, + }); + + console.log("Contract + Spreadsheet Analysis:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 1:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 2: Presentation + Spreadsheet Validation + * Validates presentation claims against spreadsheet data + */ +async function presentationDataValidation() { + console.log("=== Example 2: Presentation + Spreadsheet Validation ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Cross-reference the presentation with the spreadsheet data: + +## Validation Report + +### Data Accuracy Check +For each metric mentioned in the presentation: +1. Find the source data in the spreadsheet +2. Verify the value matches +3. Check if calculations are correct + +### Discrepancies Found +| Presentation Claim | Spreadsheet Value | Difference | Notes | +|-------------------|-------------------|------------|-------| + +### Verified Claims +✓ [List claims that match the data] + +### Unverified Claims +? [List claims that couldn't be verified from the data] + +### Data Not in Presentation +📊 [Important data from spreadsheet not mentioned in presentation] + +### Recommendations +- Items to correct in the presentation +- Additional data points to include`, + officeFiles: [ + "./examples/office-documents/data/quarterly-report.pptx", + "./examples/office-documents/data/sales-data.xlsx", + ], + }, + provider: PROVIDER, + maxTokens: 2500, + }); + + console.log("Validation Report:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 2:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 3: Full Document Package Analysis + * Analyzes all three document types together + */ +async function fullPackageAnalysis() { + console.log("=== Example 3: Full Document Package Analysis ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Analyze this complete document package (contract, presentation, spreadsheet): + +## Comprehensive Analysis + +### Document Relationship Map +- How do these documents relate to each other? +- What is the business context they represent? + +### Key Information Summary + +**From Contract:** +- Main parties and obligations +- Financial terms +- Key dates and deadlines + +**From Presentation:** +- Main message and goals +- Key metrics presented +- Action items proposed + +**From Spreadsheet:** +- Actual performance data +- Financial figures +- Historical trends + +### Cross-Document Insights +1. [Insight from combining multiple documents] +2. [Insight from combining multiple documents] +3. [Insight from combining multiple documents] + +### Consistency Analysis +- Do the documents tell a consistent story? +- Any conflicting information? +- Areas where documents complement each other + +### Executive Summary +(5-7 sentences summarizing the complete picture)`, + officeFiles: [ + "./examples/office-documents/data/sample-contract.docx", + "./examples/office-documents/data/quarterly-report.pptx", + "./examples/office-documents/data/sales-data.xlsx", + ], + }, + provider: PROVIDER, + maxTokens: 3000, + }); + + console.log("Full Package Analysis:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 3:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 4: Due Diligence Report + * Creates a due diligence report from multiple documents + */ +async function dueDiligenceReport() { + console.log("=== Example 4: Due Diligence Report ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Generate a due diligence report based on these documents: + +# DUE DILIGENCE REPORT + +## 1. Overview +- Subject of due diligence +- Documents reviewed +- Date of analysis + +## 2. Legal Analysis (from Contract) +- Contractual structure +- Rights and obligations +- Risk factors +- Compliance status + +## 3. Business Analysis (from Presentation) +- Business model +- Market position +- Strategic direction +- Management claims + +## 4. Financial Analysis (from Spreadsheet) +- Revenue and profitability +- Key financial metrics +- Historical performance +- Financial trends + +## 5. Cross-Document Findings +- Consistencies between documents +- Discrepancies or concerns +- Information gaps + +## 6. Risk Assessment +| Risk Area | Level | Description | Mitigation | +|-----------|-------|-------------|------------| + +## 7. Recommendations +- Items requiring further investigation +- Conditions or concerns to address +- Overall assessment + +## 8. Conclusion +(Final recommendation with rationale)`, + officeFiles: [ + "./examples/office-documents/data/sample-contract.docx", + "./examples/office-documents/data/quarterly-report.pptx", + "./examples/office-documents/data/sales-data.xlsx", + ], + }, + provider: PROVIDER, + maxTokens: 3500, + }); + + console.log("Due Diligence Report:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 4:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 5: Office Documents + PDF + CSV + * Combines office documents with other file types + */ +async function mixedFileTypesAnalysis() { + console.log("=== Example 5: Office Documents + PDF + CSV ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Analyze all these documents together (office files, PDF, and CSV): + +## Multi-Format Document Analysis + +### Document Inventory +List all documents provided and their types. + +### Content Summary by Document +Summarize key information from each document. + +### Cross-Reference Analysis +- How do the different document formats relate? +- Any information overlap or contradictions? +- Unique information from each source + +### Consolidated Findings +Merge insights from all documents into a unified report: +1. Main business context +2. Key metrics and data points +3. Important dates and deadlines +4. Action items and next steps + +### Data Reconciliation +If there's numerical data across documents, check for consistency.`, + officeFiles: [ + "./examples/office-documents/data/sample-contract.docx", + "./examples/office-documents/data/sales-data.xlsx", + ], + pdfFiles: ["./examples/data/report.pdf"], + csvFiles: ["./examples/data/sales.csv"], + }, + provider: PROVIDER, + maxTokens: 3000, + }); + + console.log("Mixed File Types Analysis:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 5:", + error instanceof Error ? error.message : error, + ); + console.log( + "Note: This example requires files in multiple locations. Ensure all files exist.", + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 6: Streaming Multimodal Analysis + * Uses streaming for faster response with multiple documents + */ +async function streamingMultimodalAnalysis() { + console.log("=== Example 6: Streaming Multimodal Analysis ===\n"); + + try { + const stream = await neurolink.stream({ + input: { + text: `Provide a comprehensive analysis of all documents: +- Complete summary of each document +- Cross-document relationships +- Key findings and insights +- Recommendations and action items`, + officeFiles: [ + "./examples/office-documents/data/sample-contract.docx", + "./examples/office-documents/data/quarterly-report.pptx", + "./examples/office-documents/data/sales-data.xlsx", + ], + }, + provider: PROVIDER, + maxTokens: 4000, + }); + + console.log("Streaming Analysis:"); + for await (const chunk of stream) { + process.stdout.write(chunk.content); + } + console.log("\n\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 6:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 7: Board Meeting Package + * Prepares a board meeting summary from multiple documents + */ +async function boardMeetingPackage() { + console.log("=== Example 7: Board Meeting Package ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Prepare a board meeting summary from these documents: + +# BOARD MEETING BRIEF + +## Agenda Overview +(Based on presentation structure) + +## Key Metrics Dashboard +| Metric | Current | Previous | Trend | +|--------|---------|----------|-------| +(From spreadsheet data) + +## Legal & Contractual Matters +(From contract document) +- Active agreements +- Upcoming renewals +- Compliance status + +## Strategic Update +(From presentation) +- Key initiatives +- Progress updates +- Challenges and solutions + +## Financial Summary +(From spreadsheet) +- Revenue performance +- Cost analysis +- Projections + +## Items Requiring Board Decision +1. [Decision item from documents] +2. [Decision item from documents] + +## Appendix: Supporting Data +- Reference to specific slides/sections for detailed review`, + officeFiles: [ + "./examples/office-documents/data/sample-contract.docx", + "./examples/office-documents/data/quarterly-report.pptx", + "./examples/office-documents/data/sales-data.xlsx", + ], + }, + provider: PROVIDER, + maxTokens: 2500, + }); + + console.log("Board Meeting Package:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 7:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 8: Error Handling with Mixed Files + * Demonstrates graceful handling of errors with multiple files + */ +async function errorHandlingExample() { + console.log("=== Example 8: Error Handling with Mixed Files ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: "Analyze all provided documents", + officeFiles: [ + "./examples/office-documents/data/sample-contract.docx", + "./examples/office-documents/data/missing-file.xlsx", // This file doesn't exist + ], + }, + provider: PROVIDER, + maxTokens: 1000, + }); + + console.log("Result:", result.content); + } catch (error) { + console.log("✓ Caught expected error for missing file"); + console.log("\nError message:"); + console.log(error instanceof Error ? error.message : error); + console.log("\n💡 Tips for handling file errors:"); + console.log(" - Verify all file paths before processing"); + console.log(" - Use try/catch for graceful error handling"); + console.log( + " - Consider processing files individually for better error isolation", + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Main execution function + * Runs all examples in sequence + */ +async function main() { + console.log("\n" + "=".repeat(60)); + console.log(" NeuroLink Mixed Multimodal Office Documents Examples"); + console.log(" Provider:", PROVIDER); + console.log("=".repeat(60) + "\n"); + + console.log("Note: Make sure you have set up provider credentials"); + console.log( + "and that office files exist in examples/office-documents/data/\n", + ); + + console.log("Running examples...\n"); + + await contractSpreadsheetAnalysis(); + await presentationDataValidation(); + await fullPackageAnalysis(); + await dueDiligenceReport(); + await mixedFileTypesAnalysis(); + await streamingMultimodalAnalysis(); + await boardMeetingPackage(); + await errorHandlingExample(); + + console.log("All examples completed!"); +} + +// Run examples +main().catch((error) => { + console.error("Fatal error:", error); + process.exit(1); +}); diff --git a/examples/office-documents/presentation-summary.ts b/examples/office-documents/presentation-summary.ts new file mode 100644 index 000000000..ab2592bcf --- /dev/null +++ b/examples/office-documents/presentation-summary.ts @@ -0,0 +1,406 @@ +/** + * PPTX Presentation Summary Examples for NeuroLink + * Demonstrates PowerPoint presentation processing and summarization + * + * Run with: npx tsx examples/office-documents/presentation-summary.ts + * + * Prerequisites: + * - Set up provider credentials (Google AI, OpenAI, Anthropic, or Vertex AI) + * - Ensure PPTX files exist in examples/office-documents/data/ directory + * + * Note: If you encounter tool schema errors, you can disable tools: + * export NEUROLINK_DISABLE_TOOLS=true + * npx tsx examples/office-documents/presentation-summary.ts + */ + +import { NeuroLink } from "@juspay/neurolink"; + +const neurolink = new NeuroLink(); + +// Provider configuration (change as needed) +const PROVIDER = "google-ai"; // or "openai", "anthropic", "vertex" + +/** + * Example 1: Basic Presentation Summary + * Generates a high-level summary of the presentation + */ +async function basicPresentationSummary() { + console.log("=== Example 1: Basic Presentation Summary ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Summarize this presentation. Include: +1. Main topic and purpose +2. Key points from each slide +3. Overall message and takeaways +4. Any calls to action or next steps + +Format as a structured summary.`, + officeFiles: ["./examples/office-documents/data/quarterly-report.pptx"], + }, + provider: PROVIDER, + maxTokens: 1500, + }); + + console.log("Presentation Summary:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 1:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 2: Slide-by-Slide Analysis + * Provides detailed analysis of each slide + */ +async function slideBySlideAnalysis() { + console.log("=== Example 2: Slide-by-Slide Analysis ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Analyze this presentation slide by slide. For each slide, provide: + +**Slide Title**: (if visible) +**Content Type**: (text, chart, image, table, etc.) +**Key Message**: What is the main point of this slide? +**Data/Metrics**: Any numbers, statistics, or data points shown +**Visual Elements**: Description of charts, graphs, or images + +After all slides, provide a brief overall assessment of the presentation structure and flow.`, + officeFiles: ["./examples/office-documents/data/quarterly-report.pptx"], + }, + provider: PROVIDER, + maxTokens: 3000, + }); + + console.log("Slide Analysis:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 2:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 3: Meeting Notes Generator + * Converts presentation into meeting notes format + */ +async function meetingNotesGenerator() { + console.log("=== Example 3: Meeting Notes Generator ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Convert this presentation into meeting notes format: + +## Meeting Notes + +**Date**: [Today's date] +**Topic**: [Extract from presentation] +**Presenter**: [If identifiable] + +### Key Discussion Points +- [Bullet points of main topics covered] + +### Decisions Made +- [Any decisions or conclusions from the presentation] + +### Action Items +- [ ] [Action item 1] +- [ ] [Action item 2] +(Extract any action items or next steps from the presentation) + +### Data Highlights +- [Key metrics, statistics, or data points presented] + +### Follow-up Required +- [Items that need further discussion or clarification]`, + officeFiles: ["./examples/office-documents/data/quarterly-report.pptx"], + }, + provider: PROVIDER, + maxTokens: 2000, + }); + + console.log("Meeting Notes:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 3:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 4: Key Insights Extraction + * Extracts the most important insights and data points + */ +async function keyInsightsExtraction() { + console.log("=== Example 4: Key Insights Extraction ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Extract the top 5-10 most important insights from this presentation. + +For each insight: +1. **Insight**: Clear statement of the finding +2. **Supporting Data**: Numbers or evidence that support this insight +3. **Business Impact**: Why this matters for the business +4. **Slide Reference**: Which slide this insight comes from (if identifiable) + +Rank insights by importance to business decision-making.`, + officeFiles: ["./examples/office-documents/data/quarterly-report.pptx"], + }, + provider: PROVIDER, + maxTokens: 1500, + }); + + console.log("Key Insights:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 4:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 5: Q&A Preparation + * Generates potential Q&A for the presentation + */ +async function qaPreparation() { + console.log("=== Example 5: Q&A Preparation ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Based on this presentation, generate a Q&A preparation guide: + +## Likely Questions from the Audience + +### Strategic Questions +1. [Question about strategy or direction] + - **Suggested Answer**: [Brief answer based on presentation content] + +### Data/Metrics Questions +1. [Question about specific data points] + - **Suggested Answer**: [Reference to relevant data in presentation] + +### Implementation Questions +1. [Question about how things will be executed] + - **Suggested Answer**: [Based on action items or plans mentioned] + +### Clarification Questions +1. [Question about unclear or complex points] + - **Suggested Answer**: [Clarification based on context] + +### Potential Challenges/Pushback +1. [Skeptical question or concern] + - **How to Address**: [Strategy for handling this concern] + +Generate at least 2-3 questions per category.`, + officeFiles: ["./examples/office-documents/data/quarterly-report.pptx"], + }, + provider: PROVIDER, + maxTokens: 2500, + }); + + console.log("Q&A Preparation Guide:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 5:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 6: Streaming Presentation Analysis + * Uses streaming for faster response with large presentations + */ +async function streamingPresentationAnalysis() { + console.log("=== Example 6: Streaming Presentation Analysis ===\n"); + + try { + const stream = await neurolink.stream({ + input: { + text: `Provide a comprehensive analysis of this presentation including: +- Complete content summary +- All data and metrics mentioned +- Visual element descriptions +- Recommendations for improvement +- Assessment of overall effectiveness`, + officeFiles: ["./examples/office-documents/data/quarterly-report.pptx"], + }, + provider: PROVIDER, + maxTokens: 3000, + }); + + console.log("Streaming Analysis:"); + for await (const chunk of stream) { + process.stdout.write(chunk.content); + } + console.log("\n\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 6:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 7: Presentation Comparison + * Compares two presentations (e.g., Q1 vs Q2 reports) + */ +async function presentationComparison() { + console.log("=== Example 7: Presentation Comparison ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Compare these two presentations and analyze: + +1. **Topic Coverage**: What topics are covered in each? +2. **Data Trends**: How do the metrics compare between the two? +3. **Key Differences**: Major changes or differences in messaging +4. **Progress Assessment**: Based on the comparison, what progress has been made? +5. **Consistency**: Are the presentations consistent in format and approach? + +Provide a summary of how the story has evolved between the two presentations.`, + officeFiles: [ + "./examples/office-documents/data/quarterly-report.pptx", + "./examples/office-documents/data/annual-review.pptx", + ], + }, + provider: PROVIDER, + maxTokens: 2000, + }); + + console.log("Comparison Result:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 7:", + error instanceof Error ? error.message : error, + ); + console.log( + "Note: This example requires two PPTX files. Ensure both files exist.", + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Example 8: Executive Brief Generator + * Creates a one-page executive brief from the presentation + */ +async function executiveBriefGenerator() { + console.log("=== Example 8: Executive Brief Generator ===\n"); + + try { + const result = await neurolink.generate({ + input: { + text: `Create a one-page executive brief from this presentation: + +# EXECUTIVE BRIEF +--- + +## Summary (2-3 sentences) +[High-level overview of what the presentation covers] + +## Key Metrics +| Metric | Value | Trend | +|--------|-------|-------| +[Extract key metrics in table format] + +## Critical Findings +• [Most important finding 1] +• [Most important finding 2] +• [Most important finding 3] + +## Recommendations +1. [Top recommendation] +2. [Second recommendation] +3. [Third recommendation] + +## Next Steps +- [ ] [Immediate action 1] +- [ ] [Immediate action 2] + +--- +*Generated from presentation analysis* + +Keep the brief concise and focused on what an executive needs to know for decision-making.`, + officeFiles: ["./examples/office-documents/data/quarterly-report.pptx"], + }, + provider: PROVIDER, + maxTokens: 1000, + }); + + console.log("Executive Brief:"); + console.log(result.content); + console.log("\n" + "=".repeat(60) + "\n"); + } catch (error) { + console.error( + "Error in Example 8:", + error instanceof Error ? error.message : error, + ); + console.log("\n" + "=".repeat(60) + "\n"); + } +} + +/** + * Main execution function + * Runs all examples in sequence + */ +async function main() { + console.log("\n" + "=".repeat(60)); + console.log(" NeuroLink PPTX Presentation Summary Examples"); + console.log(" Provider:", PROVIDER); + console.log("=".repeat(60) + "\n"); + + console.log("Note: Make sure you have set up provider credentials"); + console.log("and that PPTX files exist in examples/office-documents/data/\n"); + + console.log("Running examples...\n"); + + await basicPresentationSummary(); + await slideBySlideAnalysis(); + await meetingNotesGenerator(); + await keyInsightsExtraction(); + await qaPreparation(); + await streamingPresentationAnalysis(); + await presentationComparison(); + await executiveBriefGenerator(); + + console.log("All examples completed!"); +} + +// Run examples +main().catch((error) => { + console.error("Fatal error:", error); + process.exit(1); +});