New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

@revenium/google

Package Overview
Dependencies
Maintainers
4
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

@revenium/google

Transparent TypeScript middleware for automatic Revenium usage tracking with Google AI (Gemini)

latest
Source
npmnpm
Version
1.0.12
Version published
Maintainers
4
Created
Source

Revenium Middleware for Google AI (Node.js)

npm version Node Versions Documentation License: MIT

Automatically track and meter your Google AI API usage with Revenium. This middleware provides seamless integration with Google AI v1 (deprecated) and Google AI v2 (latest), requiring minimal code changes.

Features

  • Dual SDK Support: Google v1 (legacy) and v2 (latest) in one package
  • Complete Metering: Track tokens, costs, and performance metrics
  • Custom Metadata: Add business context to your AI usage
  • Streaming Support: Real-time streaming with analytics
  • Vector Embeddings: Full embedding support (v2 only)
  • Type Safe: Full TypeScript support with comprehensive types
  • Analytics: Detailed usage analytics and reporting
  • Migration Ready: Easy migration from v1 to v2

SDK Comparison:

FeatureGoogle v1Google v2
StatusDeprecated (EOL: Nov 2025)Latest
ChatYesYes
StreamingYesYes
EmbeddingsNoYes
AuthenticationAPI KeyAPI Key
Use CaseLegacy projectsNew projects

Supported Models

Important: The model parameter is required when calling any controller method. You must specify the model explicitly in your code.

This middleware supports all models available in Google AI Studio. The middleware does not maintain a hardcoded list of models, ensuring compatibility with new models as Google releases them.

For the latest available models, see:

Example usage:

// Without metadata (clean, simple)
const result = await controller.createChat(
  ["Your prompt here"],
  "gemini-2.0-flash-001"  // required model parameter
);

// With metadata (optional)
const metadata = {
  subscriberId: "user-123",
  subscriberEmail: "user@example.com",
  organizationId: "org-456",
  productId: "product-789"
};

const resultWithMetadata = await controller.createChat(
  ["Your prompt here"],
  "gemini-2.0-flash-001",
  metadata  // optional metadata parameter
);

Getting Started

Quick Start

npm install @revenium/google

Note: The middleware automatically loads your .env file when imported. You don't need to install or configure dotenv separately.

For complete setup instructions and usage examples, see the examples linked throughout this guide.

Step-by-Step Guide

The following guide walks you through setting up Revenium middleware in your project:

Step 1: Install the Package

npm install @revenium/google

Note: The middleware automatically loads your .env file when imported. You don't need to install or configure dotenv separately.

Step 2: Get Your API Keys

Revenium API Key:

  • Go to Revenium Dashboard
  • Sign up or log in
  • Navigate to API Keys section
  • Copy your API key (starts with hak_)

Google AI API Key:

  • Go to Google AI Studio
  • Sign in with your Google account
  • Click "Create API Key"
  • Copy your API key

Step 3: Setup Environment Variables

Create a .env file in your project root:

# Create .env file
echo. > .env  # On Windows (CMD TERMINAL)
touch .env  # On Mac/Linux (CMD TERMINAL)
# OR
#PowerShell
New-Item -Path .env -ItemType File

Copy and paste the following into .env:

# Google AI Configuration
GOOGLE_API_KEY=your_google_ai_api_key_here

# Revenium Configuration
REVENIUM_METERING_API_KEY=your_revenium_api_key_here

# Optional: For development/testing (defaults to https://api.revenium.ai)
# REVENIUM_METERING_BASE_URL=https://api.revenium.ai

# Optional: Enable debug logging
REVENIUM_LOG_LEVEL=INFO

Step 4: Implement in Your Code

Create test-google.js with basic usage:

import { GoogleV2Controller } from "@revenium/google";

const controller = new GoogleV2Controller();
const result = await controller.createChat(
  ["What is artificial intelligence?"],
  "gemini-2.0-flash-001"
);

For a complete working example, see: Google V2 Basic Example

Note: Need the legacy v1 SDK? See the Legacy Support section below.

Use the examples as reference for implementing the middleware in your project. See the examples linked above for complete implementation including:

  • How to initialize the controller
  • Making API calls with automatic metering
  • Handling streaming responses
  • Adding custom metadata to track business context

Step 5: Update package.json (Optional)

Add test scripts and module type to your package.json:

{
  "name": "my-google-ai-project",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test-google": "node test-google.js"
  },
  "dependencies": {
    "@revenium/google": "^1.0.0"
  }
}

Important: If you get a "Cannot use import statement outside a module" error, make sure your package.json includes "type": "module" as shown above.

Next Steps

For more advanced usage including streaming, embeddings, and custom metadata, see the complete examples:

Running Examples from Cloned Repository

If you've cloned this repository from GitHub and want to run the included examples to see how the middleware works (without modifying the middleware source code):

Setup

# Clone the repository
git clone https://github.com/revenium/revenium-middleware-google-node.git
cd revenium-middleware-google-node

# Install dependencies
npm install

# Build the packages
npm run build

# Configure environment variables
cp .env.example .env
# Edit .env with your API keys

Run Examples

Using npm scripts:

# Google AI v2 examples (recommended)
npm run example:google:v2:basic      # Basic chat completion
npm run example:google:v2:streaming  # Streaming response
npm run example:google:v2:embedding  # Text embeddings

# Google AI v1 examples (legacy)
npm run example:google:v1:basic      # Basic chat
npm run example:google:v1:streaming  # Streaming
npm run example:google:v1:chat       # Multi-turn conversation

Or use npx tsx directly:

npx tsx packages/google/examples/v2/basic.ts
npx tsx packages/google/examples/v2/streaming.ts
npx tsx packages/google/examples/v2/embedding.ts

For detailed information about each example, see the examples directory.

Want to Modify the Middleware Code?

If you're planning to modify the examples or experiment with the code, the setup above is sufficient. However, if you want to modify the middleware source code itself (files in packages/google/src/), you'll need to understand the development workflow.

See Local Development and Contributing below for the complete development guide.

Already have a project? Just install and replace imports:

Step 1. Install the Package

npm install @revenium/google

Step 2. Add Environment Variables

Add to your existing .env file:

GOOGLE_API_KEY=your_google_ai_api_key_here
REVENIUM_METERING_API_KEY=your_revenium_api_key_here

# Optional: For development/testing (defaults to https://api.revenium.ai)
# REVENIUM_METERING_BASE_URL=https://api.revenium.ai

# Optional: Enable debug logging
REVENIUM_LOG_LEVEL=INFO

Step 3. Replace Your Imports

Before:

import { GoogleGenerativeAI } from "@google/generative-ai";

After:

// Google v2 (Recommended)
import { GoogleV2Controller } from "@revenium/google";

// OR Google v1 (Legacy - deprecated)
import { GoogleV1Controller } from "@revenium/google";

Step 4. Update Your Code

Basic usage pattern:

import { GoogleV2Controller } from "@revenium/google";

const controller = new GoogleV2Controller();
const result = await controller.createChat(
  ["Your prompt here"],
  "gemini-2.0-flash-001"  // required model parameter
);

For complete working examples, see:

Advanced Usage

Streaming Responses

Basic streaming pattern:

const result = await controller.createStreaming(
  ["Your prompt here"],
  "gemini-2.0-flash-001"
);

for await (const chunk of result.stream) {
  // Process streaming chunks
}

For complete streaming examples with performance tracking and metadata, see:

Text Embeddings

Note: Embeddings are only available in Google v2. Google v1 does not support embeddings.

Basic embedding pattern:

const result = await controller.createEmbedding(
  "Text to embed",
  "text-embedding-004"
);

For complete embedding examples with metadata and batch processing, see:

Custom Metadata Tracking

Add business context to your AI usage. See the Revenium Metering API Reference for complete header options.

Metadata Fields

The usageMetadata parameter supports the following fields for detailed tracking:

FieldDescriptionUse Case
traceIdSession/conversation tracking identifierDistributed tracing, debugging
taskTypeAI task categorizationCost analysis by workload type
subscriberIdUser identifierBilling, rate limiting
subscriberEmailUser email addressSupport, compliance
subscriberCredentialNameAuth credential nameTrack API keys
subscriberCredentialAuth credential valueSecurity auditing
organizationIdOrganization IDMulti-tenant cost allocation
subscriptionIdSubscription plan IDPlan limit tracking
productIdProduct/feature IDFeature cost attribution
agentAI agent identifierDistinguish workflows
responseQualityScoreQuality rating 0.0-1.0Performance analysis
modelSourceRouting layer (e.g., DIRECT, GOOGLE)Integration analytics
systemFingerprintProvider-issued model fingerprintDebugging and attribution
temperatureSampling temperature appliedCompare response creativity
errorReasonUpstream error messageError monitoring
mediationLatencyGateway latency in msDiagnose mediation overhead

Note: The Google middleware accepts these fields in a flat structure. Internally, subscriber fields are transformed to a nested structure (subscriber.id, subscriber.email, subscriber.credential.name, subscriber.credential.value) before being sent to the Revenium API.

Usage Example

Basic pattern with metadata:

const customMetadata = {
  subscriberId: "user-123",
  subscriberEmail: "user@example.com",
  organizationId: "org-456",
  productId: "chat-app"
};

const result = await controller.createChat(
  ["Your prompt here"],
  "gemini-2.0-flash-001",  // required model parameter
  customMetadata  // optional metadata parameter
);

For complete metadata examples with all available fields, see:

What Gets Tracked

  • Token Usage: Input and output tokens for accurate billing
  • Request Duration: Total time for each API call
  • Model Information: Which model was used
  • Operation Type: Chat completion, embedding, streaming
  • Error Tracking: Failed requests and error details
  • Streaming Metrics: Time to first token for streaming responses

Supported Models

Important: The model parameter is required when calling any controller method. You must specify the model explicitly in your code.

This middleware supports all models available in Google AI Studio. The middleware does not maintain a hardcoded list of models, ensuring compatibility with new models as Google releases them.

For the latest available models, see:

Common models used in examples:

  • Chat/Streaming (v1 & v2): gemini-2.0-flash-001, gemini-1.5-pro, gemini-1.5-flash
  • Embeddings (v2 only): text-embedding-004

Note: Google v1 SDK does not support embeddings. Use v2 for embedding operations.

Example usage:

// Basic pattern - model is required
const result = await controller.createChat(
  ["Your prompt here"],
  "gemini-2.0-flash-001"  // required model parameter
);

For complete examples with different models and use cases, see:

Note: Google v1 SDK does not support embeddings due to API limitations.

Configuration Options

Environment Variables

Required:

Optional:

  • REVENIUM_METERING_BASE_URL - Revenium API base URL (defaults to https://api.revenium.ai, only needed for development/testing)
  • REVENIUM_LOG_LEVEL - Log level: DEBUG, INFO, WARN, ERROR (defaults to INFO)

Manual Configuration

Controllers read configuration from environment variables:

export GOOGLE_API_KEY="your-api-key"
export REVENIUM_METERING_API_KEY="your-revenium-key"

# Optional: Only for development/testing
# export REVENIUM_METERING_BASE_URL="https://api.revenium.ai"

Then instantiate the controller:

import { GoogleV2Controller } from "@revenium/google";

const controller = new GoogleV2Controller();
const response = await controller.createChat(
  ["Hello world"],
  "gemini-2.0-flash-001"
);

For complete configuration examples, see:

Troubleshooting

Common Issues

"Missing API Key" Error

export GOOGLE_API_KEY="your-actual-api-key"
echo $GOOGLE_API_KEY  # Verify it's set

"Requests not being tracked"

export REVENIUM_METERING_API_KEY="your-actual-revenium-key"
export REVENIUM_LOG_LEVEL="DEBUG"  # Enable debug logging

Module Import Errors

{
  "type": "module"
}

Requirements

  • Node.js 18+
  • Google AI API key
  • Revenium API key

Documentation

For detailed documentation, visit docs.revenium.io

Contributing

See CONTRIBUTING.md

Code of Conduct

See CODE_OF_CONDUCT.md

Security

See SECURITY.md

Legacy Support (Google V1)

The Google AI v1 SDK (@google/generative-ai) is deprecated and will reach end-of-life in November 2025. We recommend migrating to v2 (@google/genai).

Using Google V1 (Legacy)

If you need to use the legacy v1 SDK:

import { GoogleV1Controller } from "@revenium/google";

const controller = new GoogleV1Controller();
const result = await controller.createChat(
  ["What is artificial intelligence?"],
  "gemini-2.0-flash-001"
);

Legacy examples:

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For issues, feature requests, or contributions:

Local Development and Contributing

Are you planning to modify the middleware source code? (Not just run examples)

If you want to:

  • Fix bugs in the middleware
  • Add new features to @revenium/google
  • Contribute to the project
  • Test changes to the middleware before publishing

Then follow the complete development workflow in DEVELOPMENT.md, which covers:

What DEVELOPMENT.md Includes:

  • Development Workflow - Step-by-step process for making changes
  • Build System - Understanding the monorepo and TypeScript compilation
  • Testing Local Changes - How to test your modifications properly
  • When to Rebuild - Understanding when npm run build is needed
  • Publishing Checklist - Steps to publish new versions
  • Architecture Notes - Understanding the codebase structure
  • Contributing Guidelines - How to contribute to the project

Key Difference:

  • Running Examples (above): You can modify example files and run them directly with npx tsx - no rebuild needed
  • Modifying Middleware (DEVELOPMENT.md): If you modify source files in packages/google/src/, you must run npm run build before testing

Quick Start for Contributors:

# 1. Make changes to source code
vim packages/google/src/v2/googleV2.service.ts

# 2. Rebuild the package
npm run build

# 3. Test your changes
npm run example:google:v2:basic

# 4. See DEVELOPMENT.md for complete workflow

Built by Revenium

Keywords

google

FAQs

Package last updated on 10 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts