
Company News
Socket Named Top Sales Organization by RepVue
Socket won two 2026 Reppy Awards from RepVue, ranking in the top 5% of all sales orgs. AE Alexandra Lister shares what it's like to grow a sales career here.
@revenium/google-genai
Advanced tools
Transparent TypeScript middleware for automatic Revenium usage tracking with Google AI (Gemini)
Automatically track and meter your Google AI API usage with Revenium. This middleware provides seamless integration with Google AI (Gemini), requiring minimal code changes.
npm install @revenium/google-genai
For complete setup instructions and usage examples, see the examples linked throughout this guide.
The following guide walks you through setting up Revenium middleware in your project:
npm install @revenium/google-genai
Revenium API Key:
hak_)Google AI API Key:
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
Note: A template .env.example file is included in this package at node_modules/@revenium/google-genai/examples/.env.example with all required variables and helpful comments.
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
Create test-google.js with basic usage:
import { GoogleGenAIController } from "@revenium/google-genai";
const controller = new GoogleGenAIController();
const result = await controller.createChat(
["What is artificial intelligence?"],
"gemini-2.0-flash-001",
);
For a complete working example, see: Google AI Basic Example
Use the examples as reference for implementing the middleware in your project. See the examples linked above for complete implementation including:
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-genai": "^0.1.1"
}
}
Important: If you get a "Cannot use import statement outside a module" error, make sure your package.json includes "type": "module" as shown above.
For more advanced usage including streaming, embeddings, and custom metadata, see the complete examples:
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):
# 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
Using npm scripts:
# Google AI examples
npm run example:genai:basic # Basic chat completion
npm run example:genai:streaming # Streaming response
npm run example:genai:embedding # Text embeddings
Or use npx tsx directly:
npx tsx packages/google-genai/examples/basic.ts
npx tsx packages/google-genai/examples/streaming.ts
npx tsx packages/google-genai/examples/embedding.ts
For detailed information about each example, see the examples directory.
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-genai/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:
npm install @revenium/google-genai
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
Before:
import { GoogleGenerativeAI } from "@google/generative-ai";
After:
import { GoogleGenAIController } from "@revenium/google-genai";
Basic usage pattern:
import { GoogleGenAIController } from "@revenium/google-genai";
const controller = new GoogleGenAIController();
const result = await controller.createChat(
["Your prompt here"],
"gemini-2.0-flash-001", // required model parameter
);
For complete working examples, see:
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:
Basic embedding pattern:
const result = await controller.createEmbedding(
"Text to embed",
"text-embedding-004",
);
For complete embedding examples with metadata and batch processing, see:
Add business context to your AI usage. See the Revenium Metering API Reference for complete header options.
The usageMetadata parameter supports the following fields for detailed tracking:
| Field | Description | Use Case |
|---|---|---|
traceId | Session/conversation tracking identifier | Distributed tracing, debugging |
taskType | AI task categorization | Cost analysis by workload type |
subscriberId | User identifier | Billing, rate limiting |
subscriberEmail | User email address | Support, compliance |
subscriberCredentialName | Auth credential name | Track API keys |
subscriberCredential | Auth credential value | Security auditing |
organizationId | Organization ID | Multi-tenant cost allocation |
subscriptionId | Subscription plan ID | Plan limit tracking |
productId | Product/feature ID | Feature cost attribution |
agent | AI agent identifier | Distinguish workflows |
responseQualityScore | Quality rating 0.0-1.0 | Performance analysis |
modelSource | Routing layer (e.g., DIRECT, GOOGLE) | Integration analytics |
systemFingerprint | Provider-issued model fingerprint | Debugging and attribution |
temperature | Sampling temperature applied | Compare response creativity |
errorReason | Upstream error message | Error monitoring |
mediationLatency | Gateway latency in ms | Diagnose 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.
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:
The middleware automatically captures trace visualization fields for distributed tracing and analytics:
| Field | Type | Description | Environment Variable |
|---|---|---|---|
environment | string | Deployment environment (production, staging, development) | REVENIUM_ENVIRONMENT, NODE_ENV |
operationType | string | Operation classification (CHAT, EMBED, etc.) - automatically detected | N/A (auto-detected) |
operationSubtype | string | Additional detail (function_call, etc.) - automatically detected | N/A (auto-detected) |
retryNumber | number | Retry attempt number (0 for first attempt, 1+ for retries) | REVENIUM_RETRY_NUMBER |
parentTransactionId | string | Parent transaction reference for distributed tracing | REVENIUM_PARENT_TRANSACTION_ID |
transactionName | string | Human-friendly operation label | REVENIUM_TRANSACTION_NAME |
region | string | Cloud region (us-east-1, etc.) - auto-detected from AWS/Azure/GCP | AWS_REGION, REVENIUM_REGION |
credentialAlias | string | Human-readable credential name | REVENIUM_CREDENTIAL_ALIAS |
traceType | string | Categorical identifier (alphanumeric, hyphens, underscores only, max 128 chars) | REVENIUM_TRACE_TYPE |
traceName | string | Human-readable label for trace instances (max 256 chars) | REVENIUM_TRACE_NAME |
All trace visualization fields are optional. The middleware will automatically detect and populate these fields when possible.
REVENIUM_ENVIRONMENT=production
REVENIUM_REGION=us-east-1
REVENIUM_CREDENTIAL_ALIAS=Google AI Production Key
REVENIUM_TRACE_TYPE=customer_support
REVENIUM_TRACE_NAME=Support Ticket #12345
REVENIUM_PARENT_TRANSACTION_ID=parent-txn-123
REVENIUM_TRANSACTION_NAME=Answer Customer Question
REVENIUM_RETRY_NUMBER=0
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
);
For complete examples with different models and use cases, see:
Required:
GOOGLE_API_KEY - Your Google AI API key from Google AI StudioREVENIUM_METERING_API_KEY - Your Revenium API key from Revenium DashboardOptional:
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)REVENIUM_PRINT_SUMMARY - Print cost/metrics summary to console after each request: true, false, "human", or "json" (defaults to false)REVENIUM_TEAM_ID - Your Revenium team ID (required for cost metrics in summary output)REVENIUM_CAPTURE_PROMPTS - Capture prompts and responses for analysis: true or false (defaults to false)The middleware can capture prompts and responses for analysis and debugging. This feature is disabled by default for privacy and performance.
Enable via environment variable:
REVENIUM_CAPTURE_PROMPTS=true
Override the global setting for individual requests:
import { GoogleGenAIController } from "@revenium/google-genai";
const controller = new GoogleGenAIController();
const result = await controller.createChat(
["What is artificial intelligence?"],
"gemini-2.0-flash-001",
{
capturePrompts: true,
},
);
All captured prompts are automatically sanitized to remove sensitive credentials including:
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 { GoogleGenAIController } from "@revenium/google-genai";
const controller = new GoogleGenAIController();
const response = await controller.createChat(
["Hello world"],
"gemini-2.0-flash-001",
);
For complete configuration examples, see:
"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"
}
For detailed documentation, visit docs.revenium.io
See CONTRIBUTING.md
See SECURITY.md
This project is licensed under the MIT License - see the LICENSE file for details.
For issues, feature requests, or contributions:
Are you planning to modify the middleware source code? (Not just run examples)
If you want to:
Then follow the complete development workflow in DEVELOPMENT.md, which covers:
npm run build is needednpx tsx - no rebuild neededpackages/google-genai/src/, you must run npm run build before testingQuick Start for Contributors:
# 1. Make changes to source code
vim packages/google-genai/src/googleGenAI.service.ts
# 2. Rebuild the package
npm run build
# 3. Test your changes
npm run example:genai:getting-started
# 4. See DEVELOPMENT.md for complete workflow
Built by Revenium
FAQs
Transparent TypeScript middleware for automatic Revenium usage tracking with Google AI (Gemini)
We found that @revenium/google-genai demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?

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.

Company News
Socket won two 2026 Reppy Awards from RepVue, ranking in the top 5% of all sales orgs. AE Alexandra Lister shares what it's like to grow a sales career here.

Security News
NIST will stop enriching most CVEs under a new risk-based model, narrowing the NVD's scope as vulnerability submissions continue to surge.

Company News
/Security News
Socket is an initial recipient of OpenAI's Cybersecurity Grant Program, which commits $10M in API credits to defenders securing open source software.