Skip to content

Carbon Services

Carbon Connect integrates two external services for AI-powered operations and GHG Protocol-compliant emission calculations.


Claude Client

Source: backend/app/services/claude_client.py

The Claude client is a wrapper around the Anthropic Claude API with retry logic, streaming support, and cost estimation.

Supported Models

Model ID Input Cost Output Cost Use Case
Claude Sonnet 4 claude-sonnet-4-20250514 $3 / 1M tokens $15 / 1M tokens Application generation (default)
Claude Opus 4 claude-opus-4-20250514 $15 / 1M tokens $75 / 1M tokens Complex analysis, review
Claude Haiku 3.5 claude-3-5-haiku-20241022 $0.80 / 1M tokens $4 / 1M tokens Quick classification, extraction

Features

  • Retry logic with configurable max retries and exponential backoff
  • Streaming support for real-time text generation via generate_stream()
  • Cost estimation before generation to preview spend
  • Token counting for accurate billing and usage tracking
  • System instructions for specialized behavior (grant writing expert, carbon specialist)

Usage

from backend.app.services.claude_client import ClaudeClient, get_claude_client

# Factory function (reads API key from settings)
client = get_claude_client()

# Standard generation
result = await client.generate(
    prompt="Write an executive summary for a solar panel grant...",
    system_instruction="You are a grant writing expert specializing in EU funding.",
    temperature=0.7,
)
print(result.text)
print(f"Tokens used: {result.total_tokens}")

# Streaming generation
async for chunk in client.generate_stream("Write a project description..."):
    print(chunk, end="", flush=True)

# Cost estimation
cost = await client.estimate_cost(prompt, estimated_output_tokens=2000)
print(f"Estimated cost: ${cost:.4f}")

Configuration

Environment Variable Description Default
CLAUDE_API_KEY Anthropic API key Required
CLAUDE_MODEL Model to use claude-sonnet-4-20250514
CLAUDE_MAX_TOKENS Maximum output tokens 4096

Error Handling

The client wraps Anthropic API errors into application-specific exceptions:

  • Rate limiting is handled with automatic retry and backoff
  • Content filter responses are caught and re-raised as ContentFilterError
  • Network errors trigger retry with exponential backoff

Climatiq Client

Source: backend/app/services/climatiq_client.py

The Climatiq client provides GHG Protocol-compliant emission factor calculations via the Climatiq API. It supports Scope 1, 2, and 3 emissions across multiple activity types.

Scope Coverage

Scope Description Example Activities
Scope 1 Direct emissions Natural gas combustion, company vehicles, diesel generators
Scope 2 Indirect energy emissions Grid electricity, district heating
Scope 3 Value chain emissions Business travel, purchased goods, waste disposal

Regional Electricity Grids

The client includes pre-configured emission factors for European electricity grids:

COMMON_EMISSION_FACTORS = {
    # Scope 1 - Direct
    "natural_gas": "fuel_type_natural_gas-fuel_use_type_stationary_combustion",
    "diesel": "fuel_type_diesel-fuel_use_type_stationary_combustion",
    "petrol": "fuel_type_motor_gasoline-fuel_use_type_stationary_combustion",
    "company_car_petrol": "passenger_vehicle-vehicle_type_car-fuel_source_petrol",
    "company_car_diesel": "passenger_vehicle-vehicle_type_car-fuel_source_diesel",
    "company_car_electric": "passenger_vehicle-vehicle_type_car-fuel_source_bev",

    # Scope 2 - Indirect (Energy)
    "electricity_uk": "electricity-supply_grid-country_united_kingdom",
    "electricity_de": "electricity-supply_grid-country_germany",
    "electricity_fr": "electricity-supply_grid-country_france",
    "electricity_eu": "electricity-supply_grid-region_european_union",
}

Supported Activity Units

Category Units
Energy kWh, MWh, GJ, therm
Fuel l (liters), gal, kg, t (tonnes)
Distance km, mi, passenger-km, t-km
Currency (spend-based) eur, usd, gbp
Area m2, sq ft

Usage

from backend.app.services.climatiq_client import (
    ClimatiqClient,
    get_climatiq_client,
    ActivityUnit,
)

async with get_climatiq_client() as client:
    # Electricity by region
    result = await client.calculate_electricity(kwh=10000, region="DE")
    print(f"Emissions: {result.co2e} {result.co2e_unit}")

    # Natural gas
    gas_result = await client.calculate_natural_gas(kwh=5000)

    # Company vehicle travel
    car_result = await client.calculate_company_vehicle(
        km=15000, fuel_type="diesel"
    )

    # Custom activity
    custom = await client.calculate_emission(
        activity_id="electricity-supply_grid-country_united_kingdom",
        activity_value=1000,
        activity_unit=ActivityUnit.KWH,
    )

    # Search for emission factors
    factors = await client.search_emission_factors(
        query="electricity grid",
        region="EU",
        limit=10,
    )

Configuration

Environment Variable Description Default
CLIMATIQ_API_KEY Climatiq API key Required
CLIMATIQ_API_URL API base URL https://api.climatiq.io
CLIMATIQ_DATA_VERSION Emission factor version ^6

Integration with Matching Engine

The Climatiq client feeds into the matching engine's carbon scoring:

  1. Company carbon profiles are calculated using Climatiq emission factors
  2. Scope ½/3 totals are stored in the companies table
  3. The matching engine compares these against grant requirements (eligible_scopes, min_emission_reduction_percent)
  4. Carbon intensity metrics (tCO2e/EUR revenue, tCO2e/employee) are used for benchmarking
flowchart LR
    A[User Input<br/>Energy, Fuel, Travel] --> B[Climatiq API]
    B --> C[Emission Calculations<br/>Scope 1/2/3]
    C --> D[Company Carbon Profile]
    D --> E[Matching Engine<br/>Carbon Score 25%]