Skip to content

Examples

Practical examples for using Verdikta Common in real-world scenarios.

Basic Usage Examples

Simple Case Processing

const { parseManifest, createClient } = require('@verdikta/common');

async function processSimpleCase() {
  // Method 1: Direct parsing (for local files)
  const result = await parseManifest('./case-archive');

  console.log('Query:', result.prompt);
  console.log('Models:', result.models);
  console.log('Outcomes:', result.outcomes);
}

// Method 2: Using configured client
async function processWithClient() {
  const client = createClient({
    ipfs: { timeout: 60000 },
    logging: { level: 'info' }
  });

  const { manifestParser, archiveService } = client;

  // Fetch from IPFS and parse
  const archive = await archiveService.getArchive('QmCaseArchiveCID');
  const extractPath = await archiveService.extractArchive(archive, './temp');
  const manifest = await manifestParser.parse(extractPath);

  return manifest;
}

IPFS Integration

const { createClient } = require('@verdikta/common');

async function ipfsExample() {
  const client = createClient({
    ipfs: {
      pinningKey: process.env.PINATA_API_KEY,
      timeout: 45000
    }
  });

  const { ipfsClient } = client;

  // Fetch content
  const content = await ipfsClient.fetchFromIPFS('QmContentCID');

  // Upload new content
  const uploadResult = await ipfsClient.uploadToIPFS(
    JSON.stringify({ data: 'example' }),
    'example.json'
  );

  console.log('Uploaded to:', uploadResult.IpfsHash);
}

Multi-CID Scenarios

Two-Party Dispute

const { createClient } = require('@verdikta/common');

async function twoPartyDispute() {
  const client = createClient();
  const { manifestParser, archiveService } = client;

  // CIDs for plaintiff and defendant archives
  const plaintiffCID = 'QmPlaintiffArchive';
  const defendantCID = 'QmDefendantArchive';

  // Fetch and extract both archives
  const plaintiffArchive = await archiveService.getArchive(plaintiffCID);
  const defendantArchive = await archiveService.getArchive(defendantCID);

  const plaintiffPath = await archiveService.extractArchive(plaintiffArchive, './temp/plaintiff');
  const defendantPath = await archiveService.extractArchive(defendantArchive, './temp/defendant');

  // Parse multiple manifests
  const extractedPaths = [plaintiffPath, defendantPath];
  const cidOrder = ['plaintiffComplaint', 'defendantRebuttal'];

  const result = await manifestParser.parseMultipleManifests(extractedPaths, cidOrder);

  console.log('Combined query:', result.prompt);
  console.log('All references:', result.references);
}

Complex Multi-Party Case

async function complexMultiPartyCase() {
  const client = createClient({
    logging: { level: 'debug' }
  });

  const { manifestParser, archiveService } = client;

  // Multiple parties with evidence
  const cids = [
    'QmPrimaryComplaint',
    'QmFirstRebuttal', 
    'QmSecondRebuttal',
    'QmExpertWitness'
  ];

  const cidOrder = ['primary', 'rebuttal1', 'rebuttal2', 'expert'];
  const extractedPaths = [];

  // Process all archives
  for (let i = 0; i < cids.length; i++) {
    const archive = await archiveService.getArchive(cids[i]);
    const extractPath = await archiveService.extractArchive(archive, `./temp/${cidOrder[i]}`);
    extractedPaths.push(extractPath);
  }

  // Parse with combined context
  const result = await manifestParser.parseMultipleManifests(extractedPaths, cidOrder);

  // Add real-time data
  const finalQuery = await manifestParser.constructCombinedQuery(
    result.primaryManifest,
    result.bCIDManifests,
    'Current market conditions as of ' + new Date().toISOString()
  );

  return finalQuery;
}

Validation Examples

Manifest Validation

const { validator, ValidationError } = require('@verdikta/common');

async function validateManifestExample() {
  const manifestData = {
    version: "1.0",
    primary: {
      filename: "primary_query.json"
    },
    juryParameters: {
      NUMBER_OF_OUTCOMES: 2,
      AI_NODES: [
        {
          AI_MODEL: "gpt-4o",
          AI_PROVIDER: "OpenAI",
          NO_COUNTS: 1,
          WEIGHT: 0.5
        }
      ],
      ITERATIONS: 1
    }
  };

  try {
    await validator.validateManifest(manifestData);
    console.log('✅ Manifest is valid');
  } catch (error) {
    if (error instanceof ValidationError) {
      console.error('❌ Validation failed:', error.details);
    }
  }
}

Request Validation

async function validateRequestExample() {
  const requestData = {
    query: "Should party A receive compensation?",
    references: ["contract.pdf", "evidence.jpg"],
    outcomes: ["Yes, full compensation", "No compensation"]
  };

  try {
    await validator.validateRequest(requestData);
    console.log('✅ Request is valid');
  } catch (error) {
    console.error('❌ Request validation failed:', error.message);
  }
}

Error Handling Patterns

Comprehensive Error Handling

const { 
  parseManifest, 
  ValidationError, 
  IPFSError, 
  ArchiveError 
} = require('@verdikta/common');

async function robustProcessing(archivePath) {
  try {
    const result = await parseManifest(archivePath);
    return result;
  } catch (error) {
    switch (error.constructor) {
      case ValidationError:
        console.error('Validation failed:', error.details);
        // Handle validation errors - maybe retry with corrected data
        break;

      case IPFSError:
        console.error('IPFS operation failed:', error.message);
        // Handle IPFS errors - maybe retry or use backup gateway
        break;

      case ArchiveError:
        console.error('Archive processing failed:', error.message);
        // Handle archive errors - maybe try different extraction method
        break;

      default:
        console.error('Unexpected error:', error.message);
        // Handle unknown errors
        throw error;
    }
  }
}

Retry Logic

async function withRetry(operation, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await operation();
    } catch (error) {
      if (attempt === maxRetries) {
        throw error;
      }

      console.log(`Attempt ${attempt} failed, retrying...`);
      await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
    }
  }
}

// Usage
const result = await withRetry(async () => {
  return await parseManifest('./problematic-archive');
});

Custom Configuration Examples

Production Configuration

const { createClient } = require('@verdikta/common');

const productionClient = createClient({
  ipfs: {
    gateway: 'https://cloudflare-ipfs.com',
    pinningService: 'https://api.pinata.cloud',
    pinningKey: process.env.PINATA_API_KEY,
    timeout: 60000,
    retryOptions: {
      retries: 10,
      factor: 2,
      minTimeout: 2000,
      maxTimeout: 30000,
      randomize: true
    }
  },
  logging: {
    level: 'warn',
    console: false,
    file: true,
    filename: '/var/log/verdikta-common.log'
  },
  temp: {
    dir: '/tmp/verdikta-processing'
  }
});

Development Configuration

const developmentClient = createClient({
  ipfs: {
    gateway: 'http://localhost:8080',
    timeout: 10000
  },
  logging: {
    level: 'debug',
    console: true,
    file: false
  },
  temp: {
    dir: './dev-temp'
  }
});

Testing Examples

Unit Testing with Jest

const { parseManifest, createClient } = require('@verdikta/common');
const path = require('path');

describe('Verdikta Common', () => {
  test('should parse basic manifest', async () => {
    const testArchive = path.join(__dirname, 'fixtures', 'basic-case');
    const result = await parseManifest(testArchive);

    expect(result.prompt).toBeDefined();
    expect(result.models).toHaveLength(1);
    expect(result.outcomes).toHaveLength(2);
  });

  test('should handle IPFS errors gracefully', async () => {
    const client = createClient({
      ipfs: { gateway: 'http://invalid-gateway' }
    });

    await expect(
      client.ipfsClient.fetchFromIPFS('QmInvalidCID')
    ).rejects.toThrow();
  });
});

Integration Testing

describe('Integration Tests', () => {
  test('should process multi-CID case end-to-end', async () => {
    const client = createClient();
    const { manifestParser, archiveService } = client;

    // Use test CIDs or local fixtures
    const testCIDs = ['QmTestCID1', 'QmTestCID2'];
    const extractedPaths = [];

    for (const cid of testCIDs) {
      const archive = await archiveService.getArchive(cid);
      const extractPath = await archiveService.extractArchive(archive, `./temp/${cid}`);
      extractedPaths.push(extractPath);
    }

    const result = await manifestParser.parseMultipleManifests(
      extractedPaths, 
      ['primary', 'rebuttal']
    );

    expect(result.prompt).toContain('primary');
    expect(result.prompt).toContain('rebuttal');
  });
});

Performance Optimization

Caching Example

const { createClient } = require('@verdikta/common');
const NodeCache = require('node-cache');

class CachedVerdiktaClient {
  constructor() {
    this.cache = new NodeCache({ stdTTL: 600 }); // 10 minute cache
    this.client = createClient();
  }

  async getCachedArchive(cid) {
    const cacheKey = `archive:${cid}`;
    let archive = this.cache.get(cacheKey);

    if (!archive) {
      archive = await this.client.archiveService.getArchive(cid);
      this.cache.set(cacheKey, archive);
    }

    return archive;
  }
}

Parallel Processing

async function parallelMultiCIDProcessing(cids) {
  const client = createClient();
  const { archiveService, manifestParser } = client;

  // Fetch all archives in parallel
  const archivePromises = cids.map(cid => archiveService.getArchive(cid));
  const archives = await Promise.all(archivePromises);

  // Extract all archives in parallel
  const extractPromises = archives.map((archive, index) => 
    archiveService.extractArchive(archive, `./temp/${index}`)
  );
  const extractedPaths = await Promise.all(extractPromises);

  // Parse manifests
  const cidOrder = cids.map((_, index) => `archive${index}`);
  return await manifestParser.parseMultipleManifests(extractedPaths, cidOrder);
}

These examples cover the most common use cases for Verdikta Common. For more specific scenarios, check the API Reference or review the source code examples in the repository.