Hive SDK

Complete reference for the Hive SDK module architecture and integration patterns

Published: 1/15/2025

Hive SDK Module

The Hive SDK is a TypeScript/JavaScript library that allows you to send logs from your applications to Forge Hive for monitoring, debugging, and quality assessment. This module provides a complete observability solution that integrates seamlessly with your applications.

Module Architecture

The Hive SDK is designed with simplicity and reliability in mind:

  • Silent Mode Operation: Works gracefully even when credentials are missing
  • Type Safety: Full TypeScript support with comprehensive type definitions
  • Error Handling: Robust error handling with detailed error types
  • Debug Support: Built-in debugging capabilities using the debug package

Integration Patterns

Using with Forge Tasks

The Hive SDK works seamlessly with Forge tasks. Here's how to integrate logging into a task:

import { createTask } from '@forgehive/task'
import { createHiveLogClient } from '@forgehive/hive-sdk'
import { Schema } from '@forgehive/schema'

const hiveLogger = createHiveLogClient('Stock Analysis System')

const schema = new Schema({
  ticker: Schema.string()
})

const boundaries = {
  fetchStockPrice: async (ticker: string) => {
    const response = await fetch(`https://api.stocks.com/price/${ticker}`)
    return await response.json()
  }
}

export const getStockPrice = createTask(
  schema,
  boundaries,
  async function ({ ticker }, { fetchStockPrice }) {
    const startTime = Date.now()

    try {
      const priceData = await fetchStockPrice(ticker)
      const processingTime = Date.now() - startTime

      const result = {
        ticker,
        price: priceData.price,
        currency: priceData.currency,
        timestamp: new Date().toISOString()
      }

      // Send success log to Hive
      await hiveLogger.sendLog('stock-price-lookup', {
        input: { ticker },
        output: result,
        boundaries: {
          fetchStockPrice: [{
            input: ticker,
            output: priceData,
            error: null
          }]
        },
        metadata: { processingTime }
      })

      return result
    } catch (error) {
      // Send error log to Hive
      await hiveLogger.sendLog('stock-price-lookup', {
        input: { ticker },
        output: null,
        error: {
          message: error.message,
          type: error.constructor.name
        },
        boundaries: {
          fetchStockPrice: [{
            input: ticker,
            output: null,
            error: error.message
          }]
        }
      })

      throw error
    }
  }
)

Silent Mode Operation

The Hive SDK is designed to work gracefully even when credentials are missing. This allows you to develop and test locally without requiring Hive credentials:

// This works even without credentials
const hiveLogger = createHiveLogClient('My App')

// sendLog will return 'silent' instead of failing
const status = await hiveLogger.sendLog('my-task', { data: 'test' })

if (status === 'silent') {
  console.log('Hive logging disabled - running locally')
}

// Other methods will throw errors without credentials
if (hiveLogger.isActive()) {
  await hiveLogger.getLog('task', 'uuid')
  await hiveLogger.setQuality('task', 'uuid', quality)
}

Debugging and Troubleshooting

Enable Debug Logging

The SDK uses the debug package for internal logging. Enable it to see detailed SDK behavior:

DEBUG=hive-sdk node your-app.js

Common Issues

1. Credentials not found

  • Ensure your environment variables are set correctly
  • Check that HIVE_API_KEY, HIVE_API_SECRET, and HIVE_HOST are all defined

2. Network errors

  • Verify your HIVE_HOST URL is correct and accessible
  • Check firewall and network connectivity

3. API errors

  • Use isApiError() to check for API-specific errors
  • Enable debug logging to see detailed error messages

Complete Example

Here's a comprehensive example showing all SDK features:

import { createHiveLogClient, isApiError, Quality } from '@forgehive/hive-sdk'

async function main() {
  // Initialize the client
  const hiveLogger = createHiveLogClient('Knowledge Management System')

  // Check if client is properly configured
  if (!hiveLogger.isActive()) {
    console.log('Running in silent mode - logs will not be sent')
  }

  // Send a log entry
  const logData = {
    input: {
      query: 'artificial intelligence research',
      filters: { year: 2024, category: 'ML' }
    },
    output: {
      results: ['paper1.pdf', 'paper2.pdf'],
      count: 2,
      relevanceScore: 0.95
    },
    boundaries: {
      elasticsearch: [{
        input: { query: 'AI research', filters: '...' },
        output: { hits: 150, took: '12ms' },
        error: null
      }],
      database: [{
        input: 'SELECT * FROM papers WHERE category = ?',
        output: [{ id: 1, title: '...' }],
        error: null
      }]
    }
  }

  const status = await hiveLogger.sendLog('paper-search', logData)
  console.log('Log send status:', status)

  // Only proceed if we have credentials
  if (hiveLogger.isActive()) {
    try {
      // Retrieve a log (you'd normally get the UUID from the log response)
      const retrievedLog = await hiveLogger.getLog('paper-search', 'some-uuid')

      if (retrievedLog && !isApiError(retrievedLog)) {
        console.log('Retrieved log:', retrievedLog.logItem)

        // Set quality assessment
        const quality: Quality = {
          score: 9.2,
          reason: 'Excellent search accuracy with fast response time',
          suggestions: 'Consider adding semantic search for better relevance'
        }

        const qualitySet = await hiveLogger.setQuality('paper-search', retrievedLog.uuid, quality)
        console.log('Quality assessment saved:', qualitySet)
      }
    } catch (error) {
      console.error('Error accessing logs:', error.message)
    }
  }
}

main().catch(console.error)

The Hive SDK provides a simple but powerful way to add observability to your applications. By sending structured logs with input, output, and boundary information, you can monitor your application's behavior, debug issues, and assess the quality of your system's performance over time.