Skip to main content

A Python library that meters Anthropic usage to Revenium.

Project description

🤖 Revenium Middleware for Anthropic

PyPI version Python Versions Documentation Status License: Apache 2.0

A middleware library for metering and monitoring Anthropic API usage in Python applications. 🐍✨

✨ Features

  • 📊 Precise Usage Tracking: Monitor tokens, costs, and request counts across all Anthropic API endpoints
  • 🔌 Seamless Integration: Drop-in middleware that works with minimal code changes
  • ⚙️ Flexible Configuration: Customize metering behavior to suit your application needs

📥 Installation

pip install revenium-middleware-anthropic

🔧 Usage

🔄 Zero-Config Integration

Simply export your REVENIUM_METERING_API_KEY and import the middleware. Your Anthropic calls will be metered automatically:

import anthropic
import revenium_middleware_anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-3-7-sonnet-20250219",
    max_tokens=20000,
    temperature=1,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                     "text": "What is the meaning of life, the universe and everything?",
                }
            ]
        }
    ]
)
print(message.content)

The middleware automatically intercepts Anthropic API calls and sends metering data to Revenium without requiring any changes to your existing code. Make sure to set the REVENIUM_METERING_API_KEY environment variable for authentication with the Revenium service.

📈 Enhanced Tracking with Metadata

For more granular usage tracking and detailed reporting, add the usage_metadata parameter:

import anthropic
import revenium_middleware_anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-3-7-sonnet-20250219",
    max_tokens=20000,
    temperature=1,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What is the meaning of life, the universe and everything?",
                }
            ]
        }
    ],
    usage_metadata={
        "trace_id": "conv-28a7e9d4-1c3b-4e5f-8a9b-7d1e3f2c1b4a",
        "task_id": "chat-summary-af23c910",
        "task_type": "text-classification",
        "subscriber_email": "customer-email@example.com",
        "organization_id": "acme-corporation-12345",
        "subscription_id": "startup-plan-quarterly-2025-Q1",
        "product_id": "intelligent-document-processor-v3",
        "agent": "customer-support-assistant-v2",
    }
)
print(message.content)

🔄 Streaming Support

The middleware also supports Anthropic's streaming API. For streaming responses, use the usage_context to set metadata before making the streaming call. The middleware will automatically track token usage and send metering data when the stream completes.

import anthropic
from revenium_middleware_anthropic import usage_context

usage_context.set({
    "task_id": "task-41921",
    "agent": "network-traffic-analyzer",
    "subscriber_email": "ai@revenium.io",
    "organization_id": "devops-team-emea",
    "response_quality_score": 0.5,
})

with client.messages.stream(
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello, Claude"}],
    model="claude-3-5-sonnet-latest",
) as stream:
    for text in stream.text_stream:
        print("\n>>>" + text, end="", flush=True)

🏷️ Metadata Fields

The usage_metadata parameter supports the following fields:

Field Description Use Case
trace_id Unique identifier for a conversation or session Track multi-turn conversations
task_id Identifier for a specific AI task Group related API calls for a single task
task_type Classification of the AI operation Categorize usage by purpose (e.g., classification, summarization)
subscriber_email The email address of the subscriber Track usage by individual users
subscriber_credential The credential associated with the subscriber Track usage by individual users
organization_id Customer or department identifier Allocate costs to business units
subscription_id Reference to a billing plan Associate usage with specific subscriptions
product_id The product or feature using AI Track usage across different products
agent Identifier for the specific AI agent Compare performance across different AI agents
response_quality_score The quality of the AI response (0..1) Track AI response quality

All metadata fields are optional. Adding them enables more detailed reporting and analytics in Revenium.

🔄 Compatibility

  • 🐍 Python 3.8+
  • 🤖 Anthropic Python SDK

🔍 Logging

This module uses Python's standard logging system. You can control the log level by setting the REVENIUM_LOG_LEVEL environment variable:

# Enable debug logging
export REVENIUM_LOG_LEVEL=DEBUG

# Or when running your script
REVENIUM_LOG_LEVEL=DEBUG python your_script.py

Available log levels:

  • DEBUG: Detailed debugging information
  • INFO: General information (default)
  • WARNING: Warning messages only
  • ERROR: Error messages only
  • CRITICAL: Critical error messages only

📚 Documentation

Full documentation is available at https://revenium-middleware-anthropic.readthedocs.io/

👥 Contributing

Contributions are welcome! Please check out our contributing guidelines for details.

  1. 🍴 Fork the repository
  2. 🌿 Create your feature branch (git checkout -b feature/amazing-feature)
  3. 💾 Commit your changes (git commit -m 'Add some amazing feature')
  4. 🚀 Push to the branch (git push origin feature/amazing-feature)
  5. 🔍 Open a Pull Request

📄 License

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

🙏 Acknowledgments

  • 🔥 Thanks to the Anthropic team for creating an excellent API
  • 💖 Built with ❤️ by the Revenium team

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

revenium_middleware_anthropic-0.2.8.tar.gz (15.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

revenium_middleware_anthropic-0.2.8-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

Details for the file revenium_middleware_anthropic-0.2.8.tar.gz.

File metadata

File hashes

Hashes for revenium_middleware_anthropic-0.2.8.tar.gz
Algorithm Hash digest
SHA256 87e8788e4186e111ae22e1cebbf67c2b880d1458de36a0fe059d7bd4d381ad25
MD5 eb0359c4f802c703b26287da3a900694
BLAKE2b-256 e96e56db2863296754764bf00ebbf5a8ccffe91701da2329e5120356d5b24b63

See more details on using hashes here.

File details

Details for the file revenium_middleware_anthropic-0.2.8-py3-none-any.whl.

File metadata

File hashes

Hashes for revenium_middleware_anthropic-0.2.8-py3-none-any.whl
Algorithm Hash digest
SHA256 243434ca7102a9cfc85a7fc9bd3466d3cd4ac67fb28f08aa2295a5d8bea7d9ce
MD5 5e340bd02dd8e851d94c4f47ae9112ca
BLAKE2b-256 4053242c95a7ccdbfc682f74e562d5b0f101261f7d04e0e922dd72c956753a7a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page