### Install Revenium Middleware and Provider SDKs Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Installs the core Revenium middleware package and necessary provider SDKs as peer dependencies. Ensure you install the SDKs corresponding to the AI providers you intend to use. ```bash npm install @revenium/middleware # Install provider SDKs as peer dependencies npm install openai # For OpenAI / Azure OpenAI / Perplexity npm install @anthropic-ai/sdk # For Anthropic npm install @google/genai # For Google GenAI npm install google-auth-library # For Google Vertex AI npm install @fal-ai/client # For fal.ai ``` -------------------------------- ### Initialize OpenAI Provider Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Example showing the initialization and client retrieval pattern for tracking OpenAI requests. ```typescript import { Initialize, GetClient } from "@revenium/middleware/openai"; Initialize(); const client = GetClient(); const response = await client.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: "Hello!" }], }); ``` -------------------------------- ### Initialize Google GenAI Provider Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Example showing how to use the GoogleGenAIController to track content generation requests. ```typescript import { GoogleGenAIController } from "@revenium/middleware/google/genai"; const controller = new GoogleGenAIController({ reveniumApiKey: process.env.REVENIUM_METERING_API_KEY!, }); const response = await controller.generateContent({ model: "gemini-2.0-flash", contents: "Hello!", }); ``` -------------------------------- ### Initialize Anthropic Provider Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Example showing how to enable automatic tracking for Anthropic by importing the middleware package. ```typescript import "@revenium/middleware/anthropic"; import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic(); const response = await client.messages.create({ model: "claude-sonnet-4-20250514", max_tokens: 1024, messages: [{ role: "user", content: "Hello!" }], }); ``` -------------------------------- ### Install Revenium Middleware and Dependencies Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Commands to install the core Revenium middleware package and the required peer dependencies for specific AI providers. ```bash npm install @revenium/middleware npm install openai @anthropic-ai/sdk @google/genai google-auth-library @fal-ai/client ``` -------------------------------- ### Initialize and use Anthropic provider Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Demonstrates auto-initialization of the Anthropic provider and manual configuration for custom API settings. It includes examples for basic message creation and streaming responses using the standard Anthropic SDK. ```typescript import "@revenium/middleware/anthropic"; import Anthropic from "@anthropic-ai/sdk"; const client = new Anthropic(); // Basic message const response = await client.messages.create({ model: "claude-sonnet-4-20250514", max_tokens: 1024, messages: [ { role: "user", content: "Explain quantum computing in simple terms." } ] }); console.log(response.content[0].text); // Streaming response const stream = await client.messages.stream({ model: "claude-sonnet-4-20250514", max_tokens: 1024, messages: [{ role: "user", content: "Write a haiku about programming." }] }); for await (const event of stream) { if (event.type === "content_block_delta" && event.delta.type === "text_delta") { process.stdout.write(event.delta.text); } } // Manual initialization with custom config import { configure, initialize, getStatus, reset } from "@revenium/middleware/anthropic"; configure({ reveniumApiKey: "hak_your_key", reveniumBaseUrl: "https://api.revenium.ai", debug: true }); console.log(getStatus()); ``` -------------------------------- ### Initialize and Use fal.ai Provider for Multi-Modal AI (TypeScript) Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Initializes the fal.ai client and demonstrates its usage for various AI tasks including image, video, and audio generation, LLM interactions, direct runs, and streaming. It also shows how to access underlying clients for storage, queue, and real-time operations. Requires @revenium/middleware/fal. ```typescript import { Initialize, GetClient } from "@revenium/middleware/fal"; Initialize(); const fal = GetClient(); // Image generation with Flux const imageResult = await fal.subscribe("fal-ai/flux/schnell", { input: { prompt: "A cyberpunk cityscape at night with neon lights", image_size: "landscape_16_9", num_images: 1 } }, { subscriber: { id: "user_123" }, traceId: "req_abc789" }); console.log(imageResult.data.images[0].url); // Video generation with Kling const videoResult = await fal.subscribe("fal-ai/kling-video/v2/master/text-to-video", { input: { prompt: "Ocean waves crashing on rocks at sunset", duration: 5, aspect_ratio: "16:9" } }); console.log(videoResult.data.video.url); // Audio generation (text-to-speech) const audioResult = await fal.subscribe("fal-ai/kokoro/american-english", { input: { prompt: "Welcome to the future of AI-powered applications!", voice: "af_heart" } }); console.log(audioResult.data.audio.url); // LLM via OpenRouter const chatResult = await fal.subscribe("openrouter/router", { input: { prompt: "Explain quantum computing in simple terms", model: "google/gemini-2.5-flash" } }); console.log(chatResult.data.output); // Direct run for low-latency models const quickResult = await fal.run("fal-ai/flux/schnell", { input: { prompt: "A simple geometric pattern" } }); console.log(quickResult.data.images[0].url); // Streaming for real-time progress const stream = await fal.stream("fal-ai/flux-pro", { input: { prompt: "High-quality landscape photo" } }); stream.on("data", (chunk) => console.log("Progress:", chunk)); stream.on("done", (result) => console.log("Complete:", result)); // Access underlying clients const storage = fal.storage; // File storage operations const queue = fal.queue; // Queue management const realtime = fal.realtime; // Real-time connections ``` -------------------------------- ### Initialize and Use fal.ai Client with Revenium Middleware for Various Media Generations Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Initializes the Revenium middleware for fal.ai, requiring FAL_KEY and REVENIUM_METERING_API_KEY. It demonstrates image, video, audio generation, and LLM calls via OpenRouter, with optional cost attribution metadata. ```typescript import { Initialize, GetClient } from "@revenium/middleware/fal"; Initialize(); const fal = GetClient(); // Image generation (with cost attribution metadata) const image = await fal.subscribe( "fal-ai/flux/schnell", { input: { prompt: "a futuristic cityscape at sunset" }, }, { subscriber: { id: "user_123" }, traceId: "req_abc789" }, ); console.log(image.data.images[0].url); // Video generation const video = await fal.subscribe("fal-ai/kling-video/v2/master/text-to-video", { input: { prompt: "ocean waves crashing on rocks", duration: 5 }, }); console.log(video.data.video.url); // Audio generation (text-to-speech) const audio = await fal.subscribe("fal-ai/kokoro/american-english", { input: { prompt: "Hello from Revenium!", voice: "af_heart" }, }); console.log(audio.data.audio.url); // LLM via OpenRouter const chat = await fal.subscribe("openrouter/router", { input: { prompt: "Explain quantum computing", model: "google/gemini-2.5-flash" }, }); console.log(chat.data.output); ``` -------------------------------- ### Initialize and Use LiteLLM Provider for HTTP Client Tracking (TypeScript) Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Initializes the LiteLLM provider to patch HTTP client calls for usage tracking via a LiteLLM proxy. Demonstrates initialization from environment variables, programmatic configuration, status checks, and temporary disabling/enabling of tracking. Requires @revenium/middleware/litellm. ```typescript import { initialize, configure, getStatus, enable, disable, reset } from "@revenium/middleware/litellm"; // Initialize from environment (LITELLM_PROXY_URL required) initialize(); console.log(getStatus()); // { initialized: true, patched: true, hasConfig: true, proxyUrl: 'http://localhost:4000' } // Make requests through your LiteLLM proxy - they're automatically tracked const response = await fetch("http://localhost:4000/v1/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer sk-your-litellm-key" }, body: JSON.stringify({ model: "gpt-4", messages: [{ role: "user", content: "Hello!" }] }) }); // Programmatic configuration configure({ reveniumMeteringApiKey: "hak_your_key", reveniumMeteringBaseUrl: "https://api.revenium.ai", litellmProxyUrl: "http://localhost:4000", litellmApiKey: "sk-your-litellm-key", organizationName: "My Organization" }); // Temporarily disable tracking disable(); // ... untracked requests ... enable(); // Reset all state reset(); ``` -------------------------------- ### Initialize LiteLLM Middleware with Revenium Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Initializes the Revenium middleware for LiteLLM. This is a simple initialization step required before using LiteLLM functionalities with Revenium's tracking. ```typescript import { initialize } from "@revenium/middleware/litellm"; initialize(); ``` -------------------------------- ### Initialize and Use Perplexity Client with Revenium Middleware Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Initializes the Revenium middleware for Perplexity and retrieves a client instance. This client can then be used to make chat completions with specified models. ```typescript import { Initialize, GetClient } from "@revenium/middleware/perplexity"; Initialize(); const client = GetClient(); const response = await client.chat.completions.create({ model: "sonar", messages: [{ role: "user", content: "Hello!" }], }); ``` -------------------------------- ### OpenAI Provider Integration with Revenium Middleware Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Demonstrates initializing the Revenium middleware for the OpenAI provider and using its client to interact with various OpenAI API endpoints, including chat completions, streaming, embeddings, image generation, audio transcription, and text-to-speech. It supports automatic Azure detection if Azure environment variables are set. ```typescript import { Initialize, GetClient } from "@revenium/middleware/openai"; import fs from "fs"; // Initialize from environment variables Initialize(); const client = GetClient(); // Chat completion const chatResponse = await client.chat().completions.create({ model: "gpt-4o-mini", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "What is the capital of France?" } ], temperature: 0.7 }); console.log(chatResponse.choices[0].message.content); // Streaming chat completion const stream = await client.chat().completions.create({ model: "gpt-4o", messages: [{ role: "user", content: "Write a short poem about coding." }], stream: true }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ""); } // Embeddings const embeddings = await client.embeddings().create({ model: "text-embedding-3-small", input: "The quick brown fox jumps over the lazy dog" }); console.log(embeddings.data[0].embedding.slice(0, 5)); // Image generation const image = await client.images().generate({ model: "dall-e-3", prompt: "A futuristic city at sunset", size: "1024x1024" }); console.log(image.data[0].url); // Audio transcription const transcription = await client.audio().transcriptions.create({ model: "whisper-1", file: fs.createReadStream("audio.mp3") }); console.log(transcription.text); // Text-to-speech const speech = await client.audio().speech.create({ model: "tts-1", voice: "alloy", input: "Hello, welcome to Revenium!" }); ``` -------------------------------- ### Utility Functions API Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Helper functions for managing provider initialization, configuration detection, and response parsing. ```APIDOC ## [UTILITY] Provider Management ### Description Functions to initialize, reset, and check the status of provider clients (OpenAI, Anthropic, etc.). ### Methods - **IsInitialized()** (boolean) - Returns initialization status. - **Reset()** (void) - Clears global client state. - **patchAnthropic() / unpatchAnthropic()** (void) - Toggles request interception for Anthropic. ## [UTILITY] Data Parsing ### Description Helpers for extracting provider-specific information from model strings or response data. ### Methods - **extractProvider(modelString)** (string) - Returns provider name from model identifier. - **detectMediaType(model, data)** (string) - Identifies media type (IMAGE, VIDEO, etc.) for fal.ai responses. ``` -------------------------------- ### Initialize and Use Azure OpenAI Client with Revenium Middleware Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Initializes the Revenium middleware for Azure OpenAI and retrieves a client instance. Azure is auto-detected if AZURE_OPENAI_API_KEY and AZURE_OPENAI_ENDPOINT are set. This client can then be used to make chat completions. ```typescript import { Initialize, GetClient } from "@revenium/middleware/openai"; Initialize(); const client = GetClient(); const response = await client.chat.completions.create({ model: "my-deployment-name", messages: [{ role: "user", content: "Hello!" }], }); ``` -------------------------------- ### Initialize and Use Google Vertex AI Controller with Revenium Middleware Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Initializes the VertexAIController from the Revenium middleware for Google Vertex AI. This controller requires a Revenium metering API key and can be used to generate content using specified models. ```typescript import { VertexAIController } from "@revenium/middleware/google/vertex"; const controller = new VertexAIController({ reveniumApiKey: process.env.REVENIUM_METERING_API_KEY!, }); const response = await controller.generateContent({ model: "gemini-2.0-flash", contents: "Hello!", }); ``` -------------------------------- ### Configure Revenium Environment Variables Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Sets up essential environment variables for Revenium metering and provider-specific API keys in a `.env` file. This configuration is crucial for the middleware to authenticate and track usage correctly. ```env # Required for all providers REVENIUM_METERING_API_KEY=hak_your_revenium_api_key_here REVENIUM_METERING_BASE_URL=https://api.revenium.ai # Provider-specific keys (add as needed) OPENAI_API_KEY=sk-your-openai-api-key ANTHROPIC_API_KEY=sk-ant-your-anthropic-api-key GOOGLE_API_KEY=your-google-ai-studio-api-key PERPLEXITY_API_KEY=pplx-your-perplexity-api-key FAL_KEY=your-fal-api-key # Optional settings REVENIUM_DEBUG=false REVENIUM_PRINT_SUMMARY=false REVENIUM_TEAM_ID=your-team-id ``` -------------------------------- ### Azure OpenAI Provider Integration with Revenium Middleware Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Shows how to integrate with Azure OpenAI using Revenium Middleware. It covers automatic detection via environment variables and programmatic configuration. The API usage mirrors the standard OpenAI provider, but uses Azure deployment names as models. ```typescript import { Initialize, GetClient } from "@revenium/middleware/openai"; // Set Azure environment variables // AZURE_OPENAI_API_KEY=your-azure-key // AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/ // AZURE_OPENAI_API_VERSION=2024-02-15-preview Initialize(); const client = GetClient(); // Use your deployment name as the model const response = await client.chat().completions.create({ model: "my-gpt4-deployment", // Your Azure deployment name messages: [{ role: "user", content: "Hello from Azure!" }] }); console.log(response.choices[0].message.content); // Programmatic configuration import { Configure, GetClient } from "@revenium/middleware/openai"; Configure({ reveniumApiKey: "hak_your_key", azure: { apiKey: "your-azure-api-key", endpoint: "https://your-resource.openai.azure.com/", apiVersion: "2024-02-15-preview" } }); const azureClient = GetClient(); ``` -------------------------------- ### Integrate Google GenAI provider Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Utilizes the GoogleGenAIController to perform text generation, multi-turn conversations, streaming, embeddings, and media generation tasks like image and video creation. ```typescript import { GoogleGenAIController } from "@revenium/middleware/google/genai"; const controller = new GoogleGenAIController(); // Basic text generation const response = await controller.createChat( ["What are the benefits of TypeScript?"], "gemini-2.0-flash" ); console.log(response.text); // Multi-turn conversation const chatResponse = await controller.createChat( [ "My name is Alice.", "What's my name?", "Tell me a joke about it." ], "gemini-2.0-flash", { traceId: "conversation-123" } ); console.log(chatResponse.text); // Streaming response const streamResponse = await controller.createStreaming( ["Write a short story about a robot."], "gemini-2.0-flash" ); for await (const chunk of streamResponse.stream) { process.stdout.write(chunk.text || ""); } // Embeddings const embedding = await controller.createEmbedding( "The quick brown fox", "text-embedding-004" ); console.log(embedding.embedding.slice(0, 5)); // Image generation const imageResult = await controller.generateImage({ model: "imagen-3.0-generate-002", prompt: "A serene mountain landscape", numberOfImages: 1 }); console.log(imageResult.images[0]); // Video generation const videoResult = await controller.generateVideo({ model: "veo-2.0-generate-001", prompt: "Ocean waves at sunset", aspectRatio: "16:9" }); console.log(videoResult.video); ``` -------------------------------- ### Trace Visualization Environment Variables Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Environment variables that can be set to configure distributed tracing and analytics for Revenium. ```APIDOC ## Trace Visualization Environment Variables ### Description Environment variables for distributed tracing and analytics. ### Environment Variables - **REVENIUM_ENVIRONMENT** (string) - Deployment environment (production, staging, development). - **REVENIUM_REGION** (string) - Cloud region (auto-detected from AWS/Azure/GCP if not set). - **REVENIUM_CREDENTIAL_ALIAS** (string) - Human-readable credential name. - **REVENIUM_TRACE_TYPE** (string) - Categorical identifier (alphanumeric, hyphens, underscores, max 128 chars). - **REVENIUM_TRACE_NAME** (string) - Human-readable label for trace instances (max 256 chars). - **REVENIUM_PARENT_TRANSACTION_ID** (string) - Parent transaction reference for distributed tracing. - **REVENIUM_TRANSACTION_NAME** (string) - Human-friendly operation label. - **REVENIUM_RETRY_NUMBER** (string) - Retry attempt number (0 for first attempt). ``` -------------------------------- ### Attach Usage Metadata to Provider Requests Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Demonstrates how to inject custom metadata into provider requests (e.g., OpenAI) for billing attribution, organization context, and trace visualization. ```typescript import { Initialize, GetClient } from "@revenium/middleware/openai"; Initialize(); const client = GetClient(); const response = await client.chat().completions.create({ model: "gpt-4o", messages: [{ role: "user", content: "Analyze this report." }] }, { usageMetadata: { subscriber: { id: "user_12345", email: "user@example.com", credential: { name: "api_key", value: "key_abc" } }, organizationName: "Acme Corporation", traceId: "conversation-session-789", responseQualityScore: 0.95 } }); ``` -------------------------------- ### Meter Tool Calls with Context - TypeScript Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md This snippet demonstrates how to set the tool context and then use `meterTool` to wrap an asynchronous function. The `meterTool` function automatically tracks the execution of the provided function, including timing, success, and errors. Metadata can be provided to enrich the tracking data. ```typescript import { meterTool, setToolContext } from "@revenium/middleware/tools"; setToolContext({ agent: "my-agent", traceId: "session-123", }); const result = await meterTool( "weather-api", async () => { return await fetch("https://api.example.com/weather"); }, { operation: "get_forecast", outputFields: ["temperature", "humidity"], }, ); ``` -------------------------------- ### Provider Utility Functions Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Collection of helper functions for various AI providers including OpenAI, Anthropic, Google, fal.ai, and LiteLLM to manage initialization, patching, and data extraction. ```typescript import { IsInitialized, Reset } from "@revenium/middleware/openai"; import { patchAnthropic, unpatchAnthropic } from "@revenium/middleware/anthropic"; import { detectMediaType } from "@revenium/middleware/fal"; import { extractProvider } from "@revenium/middleware/litellm"; console.log(IsInitialized()); unpatchAnthropic(); patchAnthropic(); const mediaType = detectMediaType("fal-ai/flux/schnell", responseData); console.log(extractProvider("openai/gpt-4")); ``` -------------------------------- ### Integrate Google Vertex AI provider Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Provides an interface for Google Cloud's enterprise AI platform using VertexAIController. Supports text generation, streaming, and embedding operations. ```typescript import { VertexAIController } from "@revenium/middleware/google/vertex"; const controller = new VertexAIController(); // Text generation const response = await controller.createChat( ["Explain machine learning in business terms."], "gemini-2.0-flash", { organizationName: "Acme Corp" } ); console.log(response.text); // Streaming with Vertex AI const streamResponse = await controller.createStreaming( ["Generate a product description for smart headphones."], "gemini-2.0-flash" ); for await (const chunk of streamResponse.stream) { process.stdout.write(chunk.text || ""); } // Embeddings const embedding = await controller.createEmbedding( "Enterprise AI solutions", "text-embedding-004" ); console.log(embedding.embedding.length); ``` -------------------------------- ### Integrate Perplexity provider Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Uses the Perplexity provider to perform search-augmented chat completions. Includes support for streaming and metadata tracking for billing and attribution. ```typescript import { Initialize, GetClient } from "@revenium/middleware/perplexity"; Initialize(); const client = GetClient(); // Search-augmented chat completion const response = await client.chat().completions.create({ model: "sonar", messages: [ { role: "user", content: "What are the latest developments in AI regulation?" } ] }); console.log(response.choices[0].message.content); // Streaming response const stream = await client.chat().completions.create({ model: "sonar-pro", messages: [ { role: "user", content: "Summarize today's tech news." } ], stream: true }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ""); } // With usage metadata for billing attribution const trackedResponse = await client.chat().completions.create({ model: "sonar", messages: [{ role: "user", content: "What is GraphQL?" }] }, { usageMetadata: { traceId: "session-456", subscriber: { id: "user_789" }, organizationName: "Tech Corp" } }); ``` -------------------------------- ### Usage Metadata API Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Methods for attaching billing attribution and trace visualization metadata to provider requests. ```APIDOC ## [METHOD] client.chat().completions.create ### Description Extends standard provider client requests with custom usageMetadata for billing and tracing. ### Request Body - **usageMetadata** (object) - Required - Contains subscriber info, organization context, traceId, and quality metrics. ### Request Example { "usageMetadata": { "subscriber": { "id": "user_123" }, "organizationName": "Acme Corp", "traceId": "session-789" } } ``` -------------------------------- ### Configure Revenium Environment Variables Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md Required environment variables for authenticating with the Revenium metering service. ```env REVENIUM_METERING_API_KEY=hak_your_revenium_api_key_here REVENIUM_METERING_BASE_URL=https://api.revenium.ai ``` -------------------------------- ### Tool Metering API Source: https://github.com/revenium/revenium-middleware-node/blob/main/README.md This section details the functions available for tool metering, allowing you to wrap functions for automatic tracking of their execution, including timing, success/failure, and errors. ```APIDOC ## Tool Metering Functions ### `meterTool(toolId, fn, metadata?)` #### Description Wrap a function with automatic metering (timing, success/failure, errors). #### Method N/A (Function wrapper) #### Parameters ##### Function Parameters - **toolId** (string) - Required - Identifier for the tool being metered. - **fn** (function) - Required - The asynchronous function to wrap and meter. - **metadata** (object) - Optional - Additional metadata for the tool call. ##### Metadata Options - **operation** (string) - Tool operation name (e.g., "search", "scrape"). - **outputFields** (array of strings) - Array of field names to auto-extract from the result. - **usageMetadata** (object) - Custom metrics (e.g., tokens, results count). - **traceId** (string) - Unique identifier for session or conversation tracking. - **taskType** (string) - Type of AI task (e.g., "chat", "embedding"). - **agent** (string) - AI agent or bot identifier. - **organizationName** (string) - Organization or company name. - **productName** (string) - Product or feature name. - **subscriptionId** (string) - Subscription plan identifier. - **responseQualityScore** (number) - Custom quality rating (0.0-1.0). - **subscriber.id** (string) - Unique user identifier. - **subscriber.email** (string) - User email address. - **subscriber.credential** (object) - Authentication credential (`name` and `value`). - **agent** (string) - Agent identifier (inherited from context). - **traceId** (string) - Trace identifier (inherited from context). - **organizationName** (string) - Organization name (inherited from context). - **productName** (string) - Product name (inherited from context). - **subscriberCredential** (string) - Subscriber credential string (inherited from context). - **workflowId** (string) - Workflow identifier (inherited from context). - **transactionId** (string) - Transaction identifier (inherited from context). ### `reportToolCall(toolId, report)` #### Description Manually report an already-executed tool call. #### Method N/A (Function) #### Parameters - **toolId** (string) - Required - Identifier for the tool call. - **report** (object) - Required - The report object containing details of the tool call. ### `setToolContext(ctx)` #### Description Set context for all subsequent tool calls. #### Method N/A (Function) #### Parameters - **ctx** (object) - Required - The context object to set. - **agent** (string) - Required - Agent identifier. - **traceId** (string) - Required - Trace identifier. ### `getToolContext()` #### Description Get current context. #### Method N/A (Function) ### `clearToolContext()` #### Description Clear context. #### Method N/A (Function) ### `runWithToolContext(ctx, fn)` #### Description Run function with scoped context (uses AsyncLocalStorage). #### Method N/A (Function) #### Parameters - **ctx** (object) - Required - The context object to use for the scoped execution. - **fn** (function) - Required - The function to run within the scoped context. ### Request Example ```typescript import { meterTool, setToolContext } from "@revenium/middleware/tools"; setToolContext({ agent: "my-agent", traceId: "session-123", }); const result = await meterTool( "weather-api", async () => { return await fetch("https://api.example.com/weather"); }, { operation: "get_forecast", outputFields: ["temperature", "humidity"], }, ); ``` ### Response #### Success Response (200) - **result** (any) - The result of the executed function. #### Response Example (Depends on the return type of the wrapped function `fn`) ``` -------------------------------- ### Tool Metering API Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Functions for tracking tool and external API execution, including automatic timing, success/failure status, and contextual metadata. ```APIDOC ## [FUNCTION] meterTool ### Description Wraps an asynchronous or synchronous function to automatically track execution duration, success status, and usage metadata. ### Parameters - **toolName** (string) - Required - The identifier for the tool or API. - **fn** (function) - Required - The function to execute and meter. - **options** (object) - Optional - Configuration including operation name, output fields, and usage metadata. ### Request Example await meterTool("weather-api", async () => { ... }, { operation: "get_weather" }); ## [FUNCTION] reportToolCall ### Description Manually reports execution metrics for tools that were executed outside of the meterTool wrapper. ### Parameters - **toolName** (string) - Required - The identifier for the tool. - **metrics** (object) - Required - Object containing durationMs, success, operation, and usageMetadata. ``` -------------------------------- ### Track Tool and API Calls with Metering Source: https://context7.com/revenium/revenium-middleware-node/llms.txt Provides mechanisms to track tool execution, including automatic timing, success/failure status, and metadata collection. Supports both async and sync functions, manual reporting, and scoped context management via AsyncLocalStorage. ```typescript import { meterTool, reportToolCall, setToolContext, getToolContext, clearToolContext, runWithToolContext } from "@revenium/middleware/tools"; setToolContext({ agent: "customer-support-bot", traceId: "session-12345", organizationName: "Acme Corp", workflowId: "support-workflow-1" }); const weatherData = await meterTool( "weather-api", async () => { const response = await fetch("https://api.weather.com/v1/current?city=NYC"); return response.json(); }, { operation: "get_current_weather", outputFields: ["temperature", "humidity", "conditions"], usageMetadata: { city: "NYC" } } ); reportToolCall("database-query", { operation: "SELECT", durationMs: 45, success: true, timestamp: new Date().toISOString(), usageMetadata: { rowsReturned: 150, tableName: "users" } }); await runWithToolContext( { agent: "data-processor", traceId: "batch-job-1" }, async () => { await meterTool("step-1", async () => processStep1()); } ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.