Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(blocks): dynamic COST_USD billing + close 8 cost-leak surfaces (#12909)

Zamil Majdyf8c123a8c3e4
diff --git a/autogpt_platform/backend/backend/blocks/baas/bots.py b/autogpt_platform/backend/backend/blocks/baas/bots.py
index 4c5d4215fc..5548074453 100644
--- a/autogpt_platform/backend/backend/blocks/baas/bots.py
+++ b/autogpt_platform/backend/backend/blocks/baas/bots.py
@@ -4,6 +4,7 @@ Meeting BaaS bot (recording) blocks.
from typing import Optional
+from backend.data.model import NodeExecutionStats
from backend.sdk import (
APIKeyCredentials,
Block,
@@ -21,13 +22,15 @@ from backend.sdk import (
from ._api import MeetingBaasAPI
from ._config import baas
+# Meeting BaaS recording rate: $0.69 per hour.
+_MEETING_BAAS_USD_PER_SECOND = 0.69 / 3600
+
+# Join bills a flat 30 cr commit (covers median short meeting);
+# FetchMeetingData bills the duration-scaled remainder from the
+# `duration_seconds` field on the API response. Long meetings no
+# longer under-bill.
+
-# Meeting BaaS charges $0.69/hour of recording. The Join block is the
-# trigger that starts the recording session; the meeting itself runs out
-# of band (we don't get duration back from the FetchMeetingData response
-# we use). 30 cr ≈ $0.30 covers a median 30-minute meeting with margin.
-# Interim until FetchMeetingData surfaces duration for post-flight
-# reconciliation.
@cost(BlockCost(cost_type=BlockCostType.RUN, cost_amount=30))
class BaasBotJoinMeetingBlock(Block):
"""
@@ -144,6 +147,7 @@ class BaasBotLeaveMeetingBlock(Block):
yield "left", left
+@cost(BlockCost(cost_type=BlockCostType.COST_USD, cost_amount=150))
class BaasBotFetchMeetingDataBlock(Block):
"""
Pull MP4 URL, transcript & metadata for a completed meeting.
@@ -186,9 +190,21 @@ class BaasBotFetchMeetingDataBlock(Block):
include_transcripts=input_data.include_transcripts,
)
+ bot_meta = data.get("bot_data", {}).get("bot", {}) or {}
+ # Bill recording duration via COST_USD so multi-hour meetings
+ # scale past the Join block's flat 30 cr deposit.
+ duration_seconds = float(bot_meta.get("duration_seconds") or 0)
+ if duration_seconds > 0:
+ self.merge_stats(
+ NodeExecutionStats(
+ provider_cost=duration_seconds * _MEETING_BAAS_USD_PER_SECOND,
+ provider_cost_type="cost_usd",
+ )
+ )
+
yield "mp4_url", data.get("mp4", "")
yield "transcript", data.get("bot_data", {}).get("transcripts", [])
- yield "metadata", data.get("bot_data", {}).get("bot", {})
+ yield "metadata", bot_meta
class BaasBotDeleteRecordingBlock(Block):
diff --git a/autogpt_platform/backend/backend/blocks/baas/bots_cost_test.py b/autogpt_platform/backend/backend/blocks/baas/bots_cost_test.py
new file mode 100644
index 0000000000..aea4f65620
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/baas/bots_cost_test.py
@@ -0,0 +1,86 @@
+"""Unit tests for Meeting BaaS duration-based cost emission."""
+
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from pydantic import SecretStr
+
+from backend.blocks.baas.bots import (
+ _MEETING_BAAS_USD_PER_SECOND,
+ BaasBotFetchMeetingDataBlock,
+)
+from backend.data.model import APIKeyCredentials, NodeExecutionStats
+
+TEST_CREDENTIALS = APIKeyCredentials(
+ id="01234567-89ab-cdef-0123-456789abcdef",
+ provider="baas",
+ title="Mock BaaS API Key",
+ api_key=SecretStr("mock-baas-api-key"),
+ expires_at=None,
+)
+
+
+def test_usd_per_second_derives_from_published_rate():
+ """$0.69/hour published rate → ~$0.000192/second."""
+ assert _MEETING_BAAS_USD_PER_SECOND == pytest.approx(0.69 / 3600)
+
+
+ "duration_seconds, expected_usd",
+ [
+ (3600, 0.69), # 1 hour
+ (1800, 0.345), # 30 min
+ (0, None), # no recording → no emission
+ (None, None), # missing duration field → no emission
+ ],
+)
+async def test_fetch_meeting_data_emits_duration_cost_usd(
+ duration_seconds, expected_usd
+):
+ """FetchMeetingData extracts duration_seconds from bot metadata and
+ emits provider_cost / cost_usd scaled by the published $0.69/hr rate.
+ Emission is skipped when duration is 0 or missing.
+ """
+ block = BaasBotFetchMeetingDataBlock()
+
+ bot_meta = {"id": "bot-xyz"}
+ if duration_seconds is not None:
+ bot_meta["duration_seconds"] = duration_seconds
+
+ mock_api = AsyncMock()
+ mock_api.get_meeting_data.return_value = {
+ "mp4": "https://example/recording.mp4",
+ "bot_data": {"bot": bot_meta, "transcripts": []},
+ }
+
+ captured: list[NodeExecutionStats] = []
+ with (
+ patch("backend.blocks.baas.bots.MeetingBaasAPI", return_value=mock_api),
+ patch.object(block, "merge_stats", side_effect=captured.append),
+ ):
+ outputs = []
+ async for name, val in block.run(
+ block.input_schema(
+ credentials={
+ "id": TEST_CREDENTIALS.id,
+ "provider": TEST_CREDENTIALS.provider,
+ "type": TEST_CREDENTIALS.type,
+ },
+ bot_id="bot-xyz",
+ include_transcripts=False,
+ ),
+ credentials=TEST_CREDENTIALS,
+ ):
+ outputs.append((name, val))
+
+ # Always yields the 3 outputs regardless of duration.
+ names = [n for n, _ in outputs]
+ assert "mp4_url" in names and "metadata" in names
+
+ if expected_usd is None:
+ assert captured == []
+ else:
+ assert len(captured) == 1
+ assert captured[0].provider_cost == pytest.approx(expected_usd)
+ assert captured[0].provider_cost_type == "cost_usd"
diff --git a/autogpt_platform/backend/backend/blocks/claude_code.py b/autogpt_platform/backend/backend/blocks/claude_code.py
index 2e870f02b6..03c8f70312 100644
--- a/autogpt_platform/backend/backend/blocks/claude_code.py
+++ b/autogpt_platform/backend/backend/blocks/claude_code.py
@@ -17,6 +17,7 @@ from backend.data.model import (
APIKeyCredentials,
CredentialsField,
CredentialsMetaInput,
+ NodeExecutionStats,
SchemaField,
)
from backend.integrations.providers import ProviderName
@@ -431,6 +432,7 @@ class ClaudeCodeBlock(Block):
# The JSON output contains the result
output_data = json.loads(raw_output)
response = output_data.get("result", raw_output)
+ self._record_cli_cost(output_data)
# Build conversation history entry
turn_entry = f"User: {prompt}\nClaude: {response}"
@@ -484,6 +486,23 @@ class ClaudeCodeBlock(Block):
escaped = prompt.replace("'", "'\"'\"'")
return f"'{escaped}'"
+ def _record_cli_cost(self, output_data: dict) -> None:
+ """Feed Claude Code CLI's `total_cost_usd` to the COST_USD resolver.
+
+ The CLI rolls up Anthropic LLM + internal tool-call spend into
+ ``total_cost_usd`` on its JSON response; piping it through
+ ``merge_stats`` lets the wallet reflect real spend.
+ """
+ total_cost_usd = output_data.get("total_cost_usd")
+ if total_cost_usd is None:
+ return
+ self.merge_stats(
+ NodeExecutionStats(
+ provider_cost=float(total_cost_usd),
+ provider_cost_type="cost_usd",
+ )
+ )
+
async def run(
self,
input_data: Input,
diff --git a/autogpt_platform/backend/backend/blocks/claude_code_cost_test.py b/autogpt_platform/backend/backend/blocks/claude_code_cost_test.py
new file mode 100644
index 0000000000..1e51d72f42
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/claude_code_cost_test.py
@@ -0,0 +1,106 @@
+"""Unit tests for ClaudeCodeBlock COST_USD billing migration.
+
+Verifies:
+- Block emits provider_cost / cost_usd when Claude Code CLI returns
+ total_cost_usd.
+- block_usage_cost resolves the COST_USD entry to the expected ceil(usd *
+ cost_amount) credit charge.
+- Missing total_cost_usd gracefully produces provider_cost=None (no bill).
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from backend.blocks._base import BlockCostType
+from backend.blocks.claude_code import ClaudeCodeBlock
+from backend.data.block_cost_config import BLOCK_COSTS
+from backend.data.model import NodeExecutionStats
+from backend.executor.utils import block_usage_cost
+
+
+def test_claude_code_registered_as_cost_usd_150():
+ """Sanity: BLOCK_COSTS holds the COST_USD, 150 cr/$ entry."""
+ entries = BLOCK_COSTS[ClaudeCodeBlock]
+ assert len(entries) == 1
+ entry = entries[0]
+ assert entry.cost_type == BlockCostType.COST_USD
+ assert entry.cost_amount == 150
+
+
+ "total_cost_usd, expected_credits",
+ [
+ (0.50, 75), # $0.50 × 150 = 75 cr
+ (1.00, 150), # $1.00 × 150 = 150 cr
+ (0.0134, 3), # ceil(0.0134 × 150) = ceil(2.01) = 3
+ (2.00, 300), # $2 × 150 = 300 cr
+ (0.001, 1), # ceil(0.001 × 150) = ceil(0.15) = 1 — no 0-cr leak on
+ # sub-cent runs
+ ],
+)
+def test_cost_usd_resolver_applies_150_multiplier(total_cost_usd, expected_credits):
+ """block_usage_cost with cost_usd stats returns ceil(usd * 150)."""
+ block = ClaudeCodeBlock()
+ # cost_filter requires matching e2b_credentials; supply the ones the
+ # registration uses so _is_cost_filter_match accepts the input.
+ entry = BLOCK_COSTS[ClaudeCodeBlock][0]
+ input_data = {"e2b_credentials": entry.cost_filter["e2b_credentials"]}
+ stats = NodeExecutionStats(
+ provider_cost=total_cost_usd,
+ provider_cost_type="cost_usd",
+ )
+ cost, matching_filter = block_usage_cost(
+ block=block, input_data=input_data, stats=stats
+ )
+ assert cost == expected_credits
+ assert matching_filter == entry.cost_filter
+
+
+def test_cost_usd_resolver_returns_zero_when_stats_missing_cost():
+ """Pre-flight (no stats) or unbilled run (provider_cost None) → 0."""
+ block = ClaudeCodeBlock()
+ entry = BLOCK_COSTS[ClaudeCodeBlock][0]
+ input_data = {"e2b_credentials": entry.cost_filter["e2b_credentials"]}
+ # No stats at all → pre-flight path, returns 0.
+ pre_cost, _ = block_usage_cost(block=block, input_data=input_data)
+ assert pre_cost == 0
+ # Stats present but no provider_cost → resolver can't bill.
+ stats = NodeExecutionStats()
+ post_cost, _ = block_usage_cost(block=block, input_data=input_data, stats=stats)
+ assert post_cost == 0
+
+
+def test_record_cli_cost_emits_provider_cost_when_total_cost_present():
+ """``_record_cli_cost`` (the helper called from ``execute_claude_code``)
+ must emit a single ``merge_stats`` with provider_cost + cost_usd tag
+ when the CLI JSON payload carries ``total_cost_usd``.
+ """
+ block = ClaudeCodeBlock()
+ captured: list[NodeExecutionStats] = []
+ with patch.object(block, "merge_stats", side_effect=captured.append):
+ block._record_cli_cost(
+ {
+ "result": "hello from claude",
+ "total_cost_usd": 0.0421,
+ "usage": {"input_tokens": 1234, "output_tokens": 56},
+ }
+ )
+
+ assert len(captured) == 1
+ stats = captured[0]
+ assert stats.provider_cost == pytest.approx(0.0421)
+ assert stats.provider_cost_type == "cost_usd"
+
+
+def test_record_cli_cost_skips_merge_when_total_cost_absent():
+ """If the CLI payload lacks ``total_cost_usd`` (legacy / non-JSON
+ output), ``_record_cli_cost`` must not call ``merge_stats`` — otherwise
+ we'd pollute telemetry with a ``cost_usd`` emission that has no real
+ cost attached.
+ """
+ block = ClaudeCodeBlock()
+ mock = MagicMock()
+ with patch.object(block, "merge_stats", mock):
+ block._record_cli_cost({"result": "hello"})
+ mock.assert_not_called()
diff --git a/autogpt_platform/backend/backend/blocks/codex.py b/autogpt_platform/backend/backend/blocks/codex.py
index 07dffec39f..0ff3eb4bc0 100644
--- a/autogpt_platform/backend/backend/blocks/codex.py
+++ b/autogpt_platform/backend/backend/blocks/codex.py
@@ -151,6 +151,17 @@ class CodeGenerationBlock(Block):
)
self.execution_stats = NodeExecutionStats()
+ # GPT-5.1-Codex published pricing: $1.25 / 1M input, $10 / 1M output.
+ _INPUT_USD_PER_1M = 1.25
+ _OUTPUT_USD_PER_1M = 10.0
+
+ @staticmethod
+ def _compute_token_usd(input_tokens: int, output_tokens: int) -> float:
+ return (
+ input_tokens * CodeGenerationBlock._INPUT_USD_PER_1M
+ + output_tokens * CodeGenerationBlock._OUTPUT_USD_PER_1M
+ ) / 1_000_000
+
async def call_codex(
self,
*,
@@ -189,13 +200,15 @@ class CodeGenerationBlock(Block):
response_id = response.id or ""
# Update usage stats
- self.execution_stats.input_token_count = (
- response.usage.input_tokens if response.usage else 0
- )
- self.execution_stats.output_token_count = (
- response.usage.output_tokens if response.usage else 0
- )
+ input_tokens = response.usage.input_tokens if response.usage else 0
+ output_tokens = response.usage.output_tokens if response.usage else 0
+ self.execution_stats.input_token_count = input_tokens
+ self.execution_stats.output_token_count = output_tokens
self.execution_stats.llm_call_count += 1
+ self.execution_stats.provider_cost = self._compute_token_usd(
+ input_tokens, output_tokens
+ )
+ self.execution_stats.provider_cost_type = "cost_usd"
return CodexCallResult(
response=text_output,
diff --git a/autogpt_platform/backend/backend/blocks/cost_leak_fixes_test.py b/autogpt_platform/backend/backend/blocks/cost_leak_fixes_test.py
new file mode 100644
index 0000000000..5f647466de
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/cost_leak_fixes_test.py
@@ -0,0 +1,226 @@
+"""Coverage tests for the cost-leak fixes in this PR.
+
+Each block's ``run()`` / helper emits provider_cost + cost_usd (or items)
+via merge_stats so the post-flight resolver bills real provider spend.
+Tests here drive that emission path directly so a regression on any one
+block surfaces immediately.
+"""
+
+from unittest.mock import patch
+
+import pytest
+from pydantic import SecretStr
+
+from backend.blocks._base import BlockCostType
+from backend.blocks.ai_condition import AIConditionBlock
+from backend.data.block_cost_config import BLOCK_COSTS, LLM_COST
+from backend.data.model import APIKeyCredentials, NodeExecutionStats
+
+# -------- AIConditionBlock registration --------
+
+
+def test_ai_condition_registered_under_llm_cost():
+ """AIConditionBlock was running wallet-free before this PR; verify it
+ now resolves through the same per-model LLM_COST table as every other
+ LLM block.
+ """
+ assert BLOCK_COSTS[AIConditionBlock] is LLM_COST
+
+
+# -------- Pinecone insert ITEMS emission --------
+
+
+async def test_pinecone_insert_emits_items_provider_cost():
+ from backend.blocks.pinecone import PineconeInsertBlock
+
+ block = PineconeInsertBlock()
+ captured: list[NodeExecutionStats] = []
+
+ class _FakeIndex:
+ def upsert(self, **_):
+ return None
+
+ class _FakePinecone:
+ def __init__(self, *_, **__):
+ pass
+
+ def Index(self, _name):
+ return _FakeIndex()
+
+ with (
+ patch("backend.blocks.pinecone.Pinecone", _FakePinecone),
+ patch.object(block, "merge_stats", side_effect=captured.append),
+ ):
+ input_data = block.input_schema(
+ credentials={
+ "id": "00000000-0000-0000-0000-000000000000",
+ "provider": "pinecone",
+ "type": "api_key",
+ },
+ index="my-index",
+ chunks=["alpha", "beta", "gamma"],
+ embeddings=[[0.1] * 4, [0.2] * 4, [0.3] * 4],
+ namespace="",
+ metadata={},
+ )
+
+ creds = APIKeyCredentials(
+ id="00000000-0000-0000-0000-000000000000",
+ provider="pinecone",
+ title="mock",
+ api_key=SecretStr("mock-key"),
+ expires_at=None,
+ )
+ outputs = [(n, v) async for n, v in block.run(input_data, credentials=creds)]
+
+ assert any(name == "upsert_response" for name, _ in outputs)
+ assert len(captured) == 1
+ stats = captured[0]
+ assert stats.provider_cost == pytest.approx(3.0)
+ assert stats.provider_cost_type == "items"
+
+
+# -------- Narration model-aware per-char rate --------
+
+
+ "model_id, expected_rate_per_char",
+ [
+ ("eleven_flash_v2_5", 0.000167 * 0.5),
+ ("eleven_turbo_v2_5", 0.000167 * 0.5),
+ ("eleven_multilingual_v2", 0.000167 * 1.0),
+ ("eleven_turbo_v2", 0.000167 * 1.0),
+ ],
+)
+def test_narration_per_char_rate_scales_with_model(model_id, expected_rate_per_char):
+ """Drive VideoNarrationBlock._record_script_cost directly so a regression
+ that drops the model-aware branching (e.g. hardcoding 1.0 cr/char for
+ all models) makes this test fail.
+ """
+ from backend.blocks.video.narration import VideoNarrationBlock
+
+ block = VideoNarrationBlock()
+ captured: list[NodeExecutionStats] = []
+ with patch.object(block, "merge_stats", side_effect=captured.append):
+ block._record_script_cost("x" * 5000, model_id)
+
+ assert len(captured) == 1
+ stats = captured[0]
+ assert stats.provider_cost == pytest.approx(5000 * expected_rate_per_char)
+ assert stats.provider_cost_type == "cost_usd"
+
+
+# -------- Perplexity None-guard on x-total-cost --------
+
+
+ "openrouter_cost, expect_type",
+ [
+ (0.0421, "cost_usd"), # concrete positive USD → tagged
+ (None, None), # header missing → no tag (keeps gap observable)
+ (0.0, None), # zero → no tag (wouldn't bill anything anyway)
+ ],
+)
+def test_perplexity_record_openrouter_cost_tags_only_on_concrete_value(
+ openrouter_cost, expect_type
+):
+ """Drive PerplexityBlock._record_openrouter_cost directly to verify the
+ None/0 guard. A regression that tags cost_usd unconditionally would
+ silently floor the user's bill to 0 via the resolver — this test
+ would catch it.
+ """
+ from backend.blocks.perplexity import PerplexityBlock
+
+ block = PerplexityBlock()
+ with patch(
+ "backend.blocks.perplexity.extract_openrouter_cost",
+ return_value=openrouter_cost,
+ ):
+ block._record_openrouter_cost(response=object())
+
+ assert block.execution_stats.provider_cost == openrouter_cost
+ assert block.execution_stats.provider_cost_type == expect_type
+
+
+# -------- Codex COST_USD registration --------
+
+
+def test_codex_registered_as_cost_usd_150():
+ from backend.blocks.codex import CodeGenerationBlock
+
+ entries = BLOCK_COSTS[CodeGenerationBlock]
+ assert len(entries) == 1
+ entry = entries[0]
+ assert entry.cost_type == BlockCostType.COST_USD
+ assert entry.cost_amount == 150
+
+
+ "input_tokens, output_tokens, expected_usd",
+ [
+ # GPT-5.1-Codex: $1.25 / 1M input, $10 / 1M output.
+ (1_000_000, 0, 1.25),
+ (0, 1_000_000, 10.0),
+ (100_000, 10_000, 0.225), # 0.125 + 0.100
+ (0, 0, 0.0),
+ ],
+)
+def test_codex_computes_provider_cost_usd_from_token_counts(
+ input_tokens, output_tokens, expected_usd
+):
+ """Drive CodeGenerationBlock._compute_token_usd directly. A regression
+ to the wrong rate constants (e.g. swapping the $1.25 input rate for
+ GPT-4o's $2.50) would fail this test.
+ """
+ from backend.blocks.codex import CodeGenerationBlock
+
+ assert CodeGenerationBlock._compute_token_usd(
+ input_tokens, output_tokens
+ ) == pytest.approx(expected_usd)
+
+
+# -------- ClaudeCode COST_USD registration sanity (already tested in claude_code_cost_test.py) --------
+
+
+# -------- Perplexity COST_USD registration for all 3 tiers --------
+
+
+def test_perplexity_sonar_all_tiers_registered_as_cost_usd_150():
+ from backend.blocks.perplexity import PerplexityBlock
+
+ entries = BLOCK_COSTS[PerplexityBlock]
+ # 3 tiers (SONAR, SONAR_PRO, SONAR_DEEP_RESEARCH) all COST_USD 150.
+ assert len(entries) == 3
+ for entry in entries:
+ assert entry.cost_type == BlockCostType.COST_USD
+ assert entry.cost_amount == 150
+
+
+# -------- Narration COST_USD registration --------
+
+
+def test_narration_registered_as_cost_usd_150():
+ from backend.blocks.video.narration import VideoNarrationBlock
+
+ entries = BLOCK_COSTS[VideoNarrationBlock]
+ assert len(entries) == 1
+ assert entries[0].cost_type == BlockCostType.COST_USD
+ assert entries[0].cost_amount == 150
+
+
+# -------- Pinecone registrations --------
+
+
+def test_pinecone_registrations():
+ from backend.blocks.pinecone import (
+ PineconeInitBlock,
+ PineconeInsertBlock,
+ PineconeQueryBlock,
+ )
+
+ assert BLOCK_COSTS[PineconeInitBlock][0].cost_type == BlockCostType.RUN
+ assert BLOCK_COSTS[PineconeQueryBlock][0].cost_type == BlockCostType.RUN
+ # Insert scales with item count.
+ assert BLOCK_COSTS[PineconeInsertBlock][0].cost_type == BlockCostType.ITEMS
+ assert BLOCK_COSTS[PineconeInsertBlock][0].cost_amount == 1
diff --git a/autogpt_platform/backend/backend/blocks/exa/answers.py b/autogpt_platform/backend/backend/blocks/exa/answers.py
index 9033d6b5f8..1017346e05 100644
--- a/autogpt_platform/backend/backend/blocks/exa/answers.py
+++ b/autogpt_platform/backend/backend/blocks/exa/answers.py
@@ -17,6 +17,7 @@ from backend.sdk import (
)
from ._config import exa
+from .helpers import merge_exa_cost
class AnswerCitation(BaseModel):
@@ -111,3 +112,7 @@ class ExaAnswerBlock(Block):
yield "citations", citations
for citation in citations:
yield "citation", citation
+
+ # Current SDK AnswerResponse dataclass omits cost_dollars; helper
+ # no-ops today, but keeps billing wired when exa_py adds the field.
+ merge_exa_cost(self, response)
diff --git a/autogpt_platform/backend/backend/blocks/exa/code_context.py b/autogpt_platform/backend/backend/blocks/exa/code_context.py
index 2855c1dc4a..c57844372b 100644
--- a/autogpt_platform/backend/backend/blocks/exa/code_context.py
+++ b/autogpt_platform/backend/backend/blocks/exa/code_context.py
@@ -9,7 +9,6 @@ from typing import Union
from pydantic import BaseModel
-from backend.data.model import NodeExecutionStats
from backend.sdk import (
APIKeyCredentials,
Block,
@@ -23,6 +22,7 @@ from backend.sdk import (
)
from ._config import exa
+from .helpers import merge_exa_cost
class CodeContextResponse(BaseModel):
@@ -118,9 +118,5 @@ class ExaCodeContextBlock(Block):
yield "search_time", context.search_time
yield "output_tokens", context.output_tokens
- # Parse cost_dollars (API returns as string, e.g. "0.005")
- try:
- cost_usd = float(context.cost_dollars)
- self.merge_stats(NodeExecutionStats(provider_cost=cost_usd))
- except (ValueError, TypeError):
- pass
+ # API returns costDollars as a bare numeric string like "0.005".
+ merge_exa_cost(self, data)
diff --git a/autogpt_platform/backend/backend/blocks/exa/contents.py b/autogpt_platform/backend/backend/blocks/exa/contents.py
index 8b2deaf036..b346cd746d 100644
--- a/autogpt_platform/backend/backend/blocks/exa/contents.py
+++ b/autogpt_platform/backend/backend/blocks/exa/contents.py
@@ -4,7 +4,6 @@ from typing import Optional
from exa_py import AsyncExa
from pydantic import BaseModel
-from backend.data.model import NodeExecutionStats
from backend.sdk import (
APIKeyCredentials,
Block,
@@ -24,6 +23,7 @@ from .helpers import (
HighlightSettings,
LivecrawlTypes,
SummarySettings,
+ merge_exa_cost,
)
@@ -224,6 +224,4 @@ class ExaContentsBlock(Block):
if response.cost_dollars:
yield "cost_dollars", response.cost_dollars
- self.merge_stats(
- NodeExecutionStats(provider_cost=response.cost_dollars.total)
- )
+ merge_exa_cost(self, response)
diff --git a/autogpt_platform/backend/backend/blocks/exa/cost_tracking_test.py b/autogpt_platform/backend/backend/blocks/exa/cost_tracking_test.py
index 1ee395e539..96d161c6b8 100644
--- a/autogpt_platform/backend/backend/blocks/exa/cost_tracking_test.py
+++ b/autogpt_platform/backend/backend/blocks/exa/cost_tracking_test.py
@@ -143,7 +143,9 @@ class TestExaContentsCostTracking:
mock_exa_cls.return_value = mock_exa
async for _ in block.run(
- block.Input(urls=["https://example.com"], credentials=TEST_CREDENTIALS_INPUT), # type: ignore[arg-type]
+ block.Input(
+ urls=["https://example.com"], credentials=TEST_CREDENTIALS_INPUT
+ ), # type: ignore[arg-type]
credentials=TEST_CREDENTIALS,
):
pass
@@ -172,7 +174,9 @@ class TestExaContentsCostTracking:
mock_exa_cls.return_value = mock_exa
async for _ in block.run(
- block.Input(urls=["https://example.com"], credentials=TEST_CREDENTIALS_INPUT), # type: ignore[arg-type]
+ block.Input(
+ urls=["https://example.com"], credentials=TEST_CREDENTIALS_INPUT
+ ), # type: ignore[arg-type]
credentials=TEST_CREDENTIALS,
):
pass
@@ -201,7 +205,9 @@ class TestExaContentsCostTracking:
mock_exa_cls.return_value = mock_exa
async for _ in block.run(
- block.Input(urls=["https://example.com"], credentials=TEST_CREDENTIALS_INPUT), # type: ignore[arg-type]
+ block.Input(
+ urls=["https://example.com"], credentials=TEST_CREDENTIALS_INPUT
+ ), # type: ignore[arg-type]
credentials=TEST_CREDENTIALS,
):
pass
@@ -297,7 +303,9 @@ class TestExaSimilarCostTracking:
mock_exa_cls.return_value = mock_exa
async for _ in block.run(
- block.Input(url="https://example.com", credentials=TEST_CREDENTIALS_INPUT), # type: ignore[arg-type]
+ block.Input(
+ url="https://example.com", credentials=TEST_CREDENTIALS_INPUT
+ ), # type: ignore[arg-type]
credentials=TEST_CREDENTIALS,
):
pass
@@ -326,7 +334,9 @@ class TestExaSimilarCostTracking:
mock_exa_cls.return_value = mock_exa
async for _ in block.run(
- block.Input(url="https://example.com", credentials=TEST_CREDENTIALS_INPUT), # type: ignore[arg-type]
+ block.Input(
+ url="https://example.com", credentials=TEST_CREDENTIALS_INPUT
+ ), # type: ignore[arg-type]
credentials=TEST_CREDENTIALS,
):
pass
diff --git a/autogpt_platform/backend/backend/blocks/exa/helpers.py b/autogpt_platform/backend/backend/blocks/exa/helpers.py
index f31f01c78a..a6049f0879 100644
--- a/autogpt_platform/backend/backend/blocks/exa/helpers.py
+++ b/autogpt_platform/backend/backend/blocks/exa/helpers.py
@@ -1,7 +1,8 @@
from enum import Enum
from typing import Any, Dict, Literal, Optional, Union
-from backend.sdk import BaseModel, MediaFileType, SchemaField
+from backend.data.model import NodeExecutionStats
+from backend.sdk import BaseModel, Block, MediaFileType, SchemaField
class LivecrawlTypes(str, Enum):
@@ -319,7 +320,7 @@ class CostDollars(BaseModel):
# Helper functions for payload processing
def process_text_field(
- text: Union[bool, TextEnabled, TextDisabled, TextAdvanced, None]
+ text: Union[bool, TextEnabled, TextDisabled, TextAdvanced, None],
) -> Optional[Union[bool, Dict[str, Any]]]:
"""Process text field for API payload."""
if text is None:
@@ -400,7 +401,7 @@ def process_contents_settings(contents: Optional[ContentSettings]) -> Dict[str,
def process_context_field(
- context: Union[bool, dict, ContextEnabled, ContextDisabled, ContextAdvanced, None]
+ context: Union[bool, dict, ContextEnabled, ContextDisabled, ContextAdvanced, None],
) -> Optional[Union[bool, Dict[str, int]]]:
"""Process context field for API payload."""
if context is None:
@@ -448,3 +449,65 @@ def add_optional_fields(
payload[api_field] = value.value
else:
payload[api_field] = value
+
+
+def extract_exa_cost_usd(response: Any) -> Optional[float]:
+ """Return ``cost_dollars.total`` (USD) from an Exa SDK response, or None.
+
+ Handles dataclass/pydantic responses (``response.cost_dollars.total``),
+ dicts with camelCase keys (``response["costDollars"]["total"]``), dicts
+ with snake_case keys, and bare numeric strings. Returns None whenever the
+ shape is missing cost info — the caller then skips merge_stats.
+ """
+ if response is None:
+ return None
+
+ # Dataclass / pydantic: response.cost_dollars
+ cost_obj = getattr(response, "cost_dollars", None)
+
+ # Dict payloads: try both camelCase and snake_case
+ if cost_obj is None and isinstance(response, dict):
+ cost_obj = response.get("costDollars") or response.get("cost_dollars")
+
+ if cost_obj is None:
+ return None
+
+ # Already a scalar (code_context endpoint returns a string)
+ if isinstance(cost_obj, (int, float)):
+ return max(0.0, float(cost_obj))
+ if isinstance(cost_obj, str):
+ try:
+ return max(0.0, float(cost_obj))
+ except ValueError:
+ return None
+
+ # Nested object/dict: grab the `total` field
+ total = getattr(cost_obj, "total", None)
+ if total is None and isinstance(cost_obj, dict):
+ total = cost_obj.get("total")
+
+ if total is None:
+ return None
+
+ try:
+ return max(0.0, float(total))
+ except (TypeError, ValueError):
+ return None
+
+
+def merge_exa_cost(block: Block, response: Any) -> None:
+ """Pull ``cost_dollars.total`` off an Exa response and merge it into stats.
+
+ No-op when the response shape has no cost info (e.g. webset CRUD where
+ the SDK does not expose per-call pricing) — emission happens only when
+ Exa actually reports a USD amount.
+ """
+ cost_usd = extract_exa_cost_usd(response)
+ if cost_usd is None:
+ return
+ block.merge_stats(
+ NodeExecutionStats(
+ provider_cost=cost_usd,
+ provider_cost_type="cost_usd",
+ )
+ )
diff --git a/autogpt_platform/backend/backend/blocks/exa/helpers_cost_test.py b/autogpt_platform/backend/backend/blocks/exa/helpers_cost_test.py
new file mode 100644
index 0000000000..9c321a7142
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/exa/helpers_cost_test.py
@@ -0,0 +1,65 @@
+"""Unit tests for exa/helpers cost-extraction + merge helpers."""
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+from backend.blocks.exa.helpers import extract_exa_cost_usd, merge_exa_cost
+from backend.data.model import NodeExecutionStats
+
+
+ "response, expected",
+ [
+ # Dataclass / SimpleNamespace with cost_dollars.total
+ (SimpleNamespace(cost_dollars=SimpleNamespace(total=0.05)), 0.05),
+ # Dict camelCase
+ ({"costDollars": {"total": 0.10}}, 0.10),
+ # Dict snake_case
+ ({"cost_dollars": {"total": 0.07}}, 0.07),
+ # code_context endpoint shape: plain numeric string
+ (SimpleNamespace(cost_dollars="0.005"), 0.005),
+ # Scalar float on cost_dollars directly
+ (SimpleNamespace(cost_dollars=0.02), 0.02),
+ # Scalar int on cost_dollars
+ (SimpleNamespace(cost_dollars=3), 3.0),
+ # Missing cost info — returns None
+ ({}, None),
+ (SimpleNamespace(other="foo"), None),
+ (None, None),
+ # Nested total=None
+ (SimpleNamespace(cost_dollars=SimpleNamespace(total=None)), None),
+ # Invalid numeric string
+ (SimpleNamespace(cost_dollars="not-a-number"), None),
+ # Negative values clamp to 0
+ (SimpleNamespace(cost_dollars=SimpleNamespace(total=-1.0)), 0.0),
+ ],
+)
+def test_extract_exa_cost_usd_handles_all_shapes(response, expected):
+ assert extract_exa_cost_usd(response) == expected
+
+
+def test_merge_exa_cost_emits_stats_when_cost_present():
+ block = MagicMock()
+ response = SimpleNamespace(cost_dollars=SimpleNamespace(total=0.0421))
+ merge_exa_cost(block, response)
+
+ block.merge_stats.assert_called_once()
+ stats: NodeExecutionStats = block.merge_stats.call_args.args[0]
+ assert stats.provider_cost == pytest.approx(0.0421)
+ assert stats.provider_cost_type == "cost_usd"
+
+
+def test_merge_exa_cost_noops_when_no_cost():
+ """Webset CRUD endpoints don't surface cost_dollars today — the helper
+ must silently skip instead of emitting a 0-cost telemetry record."""
+ block = MagicMock()
+ merge_exa_cost(block, SimpleNamespace(other_field="nothing"))
+ block.merge_stats.assert_not_called()
+
+
+def test_merge_exa_cost_noops_when_response_is_none():
+ block = MagicMock()
+ merge_exa_cost(block, None)
+ block.merge_stats.assert_not_called()
diff --git a/autogpt_platform/backend/backend/blocks/exa/research.py b/autogpt_platform/backend/backend/blocks/exa/research.py
index 575a88cc01..91693bbe0d 100644
--- a/autogpt_platform/backend/backend/blocks/exa/research.py
+++ b/autogpt_platform/backend/backend/blocks/exa/research.py
@@ -12,7 +12,6 @@ from typing import Any, Dict, List, Optional
from pydantic import BaseModel
-from backend.data.model import NodeExecutionStats
from backend.sdk import (
APIKeyCredentials,
Block,
@@ -26,6 +25,7 @@ from backend.sdk import (
)
from ._config import exa
+from .helpers import merge_exa_cost
class ResearchModel(str, Enum):
@@ -233,11 +233,7 @@ class ExaCreateResearchBlock(Block):
if research.cost_dollars:
yield "cost_total", research.cost_dollars.total
- self.merge_stats(
- NodeExecutionStats(
- provider_cost=research.cost_dollars.total
- )
- )
+ merge_exa_cost(self, research)
return
await asyncio.sleep(check_interval)
@@ -352,9 +348,7 @@ class ExaGetResearchBlock(Block):
yield "cost_searches", research.cost_dollars.num_searches
yield "cost_pages", research.cost_dollars.num_pages
yield "cost_reasoning_tokens", research.cost_dollars.reasoning_tokens
- self.merge_stats(
- NodeExecutionStats(provider_cost=research.cost_dollars.total)
- )
+ merge_exa_cost(self, research)
yield "error_message", research.error
@@ -441,9 +435,7 @@ class ExaWaitForResearchBlock(Block):
if research.cost_dollars:
yield "cost_total", research.cost_dollars.total
- self.merge_stats(
- NodeExecutionStats(provider_cost=research.cost_dollars.total)
- )
+ merge_exa_cost(self, research)
return
diff --git a/autogpt_platform/backend/backend/blocks/exa/search.py b/autogpt_platform/backend/backend/blocks/exa/search.py
index 5d9e99698f..4b17048707 100644
--- a/autogpt_platform/backend/backend/blocks/exa/search.py
+++ b/autogpt_platform/backend/backend/blocks/exa/search.py
@@ -4,7 +4,6 @@ from typing import Optional
from exa_py import AsyncExa
-from backend.data.model import NodeExecutionStats
from backend.sdk import (
APIKeyCredentials,
Block,
@@ -21,6 +20,7 @@ from .helpers import (
ContentSettings,
CostDollars,
ExaSearchResults,
+ merge_exa_cost,
process_contents_settings,
)
@@ -207,6 +207,4 @@ class ExaSearchBlock(Block):
if response.cost_dollars:
yield "cost_dollars", response.cost_dollars
- self.merge_stats(
- NodeExecutionStats(provider_cost=response.cost_dollars.total)
- )
+ merge_exa_cost(self, response)
diff --git a/autogpt_platform/backend/backend/blocks/exa/similar.py b/autogpt_platform/backend/backend/blocks/exa/similar.py
index 004dfec4d6..9a162480b4 100644
--- a/autogpt_platform/backend/backend/blocks/exa/similar.py
+++ b/autogpt_platform/backend/backend/blocks/exa/similar.py
@@ -3,7 +3,6 @@ from typing import Optional
from exa_py import AsyncExa
-from backend.data.model import NodeExecutionStats
from backend.sdk import (
APIKeyCredentials,
Block,
@@ -20,6 +19,7 @@ from .helpers import (
ContentSettings,
CostDollars,
ExaSearchResults,
+ merge_exa_cost,
process_contents_settings,
)
@@ -168,6 +168,4 @@ class ExaFindSimilarBlock(Block):
if response.cost_dollars:
yield "cost_dollars", response.cost_dollars
- self.merge_stats(
- NodeExecutionStats(provider_cost=response.cost_dollars.total)
- )
+ merge_exa_cost(self, response)
diff --git a/autogpt_platform/backend/backend/blocks/exa/websets.py b/autogpt_platform/backend/backend/blocks/exa/websets.py
index ce623ad410..99bbc64c57 100644
--- a/autogpt_platform/backend/backend/blocks/exa/websets.py
+++ b/autogpt_platform/backend/backend/blocks/exa/websets.py
@@ -39,6 +39,7 @@ from backend.sdk import (
)
from ._config import exa
+from .helpers import merge_exa_cost
class SearchEntityType(str, Enum):
@@ -394,6 +395,7 @@ class ExaCreateWebsetBlock(Block):
metadata=input_data.metadata,
)
)
+ merge_exa_cost(self, webset)
webset_result = Webset.model_validate(webset.model_dump(by_alias=True))
@@ -404,6 +406,7 @@ class ExaCreateWebsetBlock(Block):
timeout=input_data.polling_timeout,
poll_interval=5,
)
+ merge_exa_cost(self, final_webset)
completion_time = time.time() - start_time
item_count = 0
@@ -479,6 +482,7 @@ class ExaCreateOrFindWebsetBlock(Block):
try:
webset = await aexa.websets.get(id=input_data.external_id)
+ merge_exa_cost(self, webset)
webset_result = Webset.model_validate(webset.model_dump(by_alias=True))
yield "webset", webset_result
@@ -501,6 +505,7 @@ class ExaCreateOrFindWebsetBlock(Block):
metadata=input_data.metadata,
)
)
+ merge_exa_cost(self, webset)
webset_result = Webset.model_validate(webset.model_dump(by_alias=True))
@@ -555,6 +560,7 @@ class ExaUpdateWebsetBlock(Block):
payload["metadata"] = input_data.metadata
sdk_webset = await aexa.websets.update(id=input_data.webset_id, params=payload)
+ merge_exa_cost(self, sdk_webset)
status_str = (
sdk_webset.status.value
@@ -566,8 +572,9 @@ class ExaUpdateWebsetBlock(Block):
yield "status", status_str
yield "external_id", sdk_webset.external_id
yield "metadata", sdk_webset.metadata or {}
- yield "updated_at", (
- sdk_webset.updated_at.isoformat() if sdk_webset.updated_at else ""
+ yield (
+ "updated_at",
+ (sdk_webset.updated_at.isoformat() if sdk_webset.updated_at else ""),
)
@@ -621,6 +628,7 @@ class ExaListWebsetsBlock(Block):
cursor=input_data.cursor,
limit=input_data.limit,
)
+ merge_exa_cost(self, response)
websets_data = [
w.model_dump(by_alias=True, exclude_none=True) for w in response.data
@@ -679,6 +687,7 @@ class ExaGetWebsetBlock(Block):
aexa = AsyncExa(api_key=credentials.api_key.get_secret_value())
sdk_webset = await aexa.websets.get(id=input_data.webset_id)
+ merge_exa_cost(self, sdk_webset)
status_str = (
sdk_webset.status.value
@@ -706,11 +715,13 @@ class ExaGetWebsetBlock(Block):
yield "enrichments", enrichments_data
yield "monitors", monitors_data
yield "metadata", sdk_webset.metadata or {}
- yield "created_at", (
- sdk_webset.created_at.isoformat() if sdk_webset.created_at else ""
+ yield (
+ "created_at",
+ (sdk_webset.created_at.isoformat() if sdk_webset.created_at else ""),
)
- yield "updated_at", (
- sdk_webset.updated_at.isoformat() if sdk_webset.updated_at else ""
+ yield (
+ "updated_at",
+ (sdk_webset.updated_at.isoformat() if sdk_webset.updated_at else ""),
)
@@ -749,6 +760,7 @@ class ExaDeleteWebsetBlock(Block):
aexa = AsyncExa(api_key=credentials.api_key.get_secret_value())
deleted_webset = await aexa.websets.delete(id=input_data.webset_id)
+ merge_exa_cost(self, deleted_webset)
status_str = (
deleted_webset.status.value
@@ -799,6 +811,7 @@ class ExaCancelWebsetBlock(Block):
aexa = AsyncExa(api_key=credentials.api_key.get_secret_value())
canceled_webset = await aexa.websets.cancel(id=input_data.webset_id)
+ merge_exa_cost(self, canceled_webset)
status_str = (
canceled_webset.status.value
@@ -969,6 +982,7 @@ class ExaPreviewWebsetBlock(Block):
payload["entity"] = entity
sdk_preview = await aexa.websets.preview(params=payload)
+ merge_exa_cost(self, sdk_preview)
preview = PreviewWebsetModel.from_sdk(sdk_preview)
@@ -1052,6 +1066,7 @@ class ExaWebsetStatusBlock(Block):
aexa = AsyncExa(api_key=credentials.api_key.get_secret_value())
webset = await aexa.websets.get(id=input_data.webset_id)
+ merge_exa_cost(self, webset)
status = (
webset.status.value
@@ -1186,6 +1201,7 @@ class ExaWebsetSummaryBlock(Block):
aexa = AsyncExa(api_key=credentials.api_key.get_secret_value())
webset = await aexa.websets.get(id=input_data.webset_id)
+ merge_exa_cost(self, webset)
# Extract basic info
webset_id = webset.id
@@ -1214,6 +1230,7 @@ class ExaWebsetSummaryBlock(Block):
items_response = await aexa.websets.items.list(
webset_id=input_data.webset_id, limit=input_data.sample_size
)
+ merge_exa_cost(self, items_response)
sample_items_data = [
item.model_dump(by_alias=True, exclude_none=True)
for item in items_response.data
@@ -1363,6 +1380,7 @@ class ExaWebsetReadyCheckBlock(Block):
# Get webset details
webset = await aexa.websets.get(id=input_data.webset_id)
+ merge_exa_cost(self, webset)
status = (
webset.status.value
diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_enrichment.py b/autogpt_platform/backend/backend/blocks/exa/websets_enrichment.py
index f136b996b9..f442764bfc 100644
--- a/autogpt_platform/backend/backend/blocks/exa/websets_enrichment.py
+++ b/autogpt_platform/backend/backend/blocks/exa/websets_enrichment.py
@@ -25,6 +25,7 @@ from backend.sdk import (
)
from ._config import exa
+from .helpers import merge_exa_cost
# Mirrored model for stability
@@ -205,6 +206,7 @@ class ExaCreateEnrichmentBlock(Block):
sdk_enrichment = await aexa.websets.enrichments.create(
webset_id=input_data.webset_id, params=payload
)
+ merge_exa_cost(self, sdk_enrichment)
enrichment_id = sdk_enrichment.id
status = (
@@ -226,6 +228,7 @@ class ExaCreateEnrichmentBlock(Block):
current_enrich = await aexa.websets.enrichments.get(
webset_id=input_data.webset_id, id=enrichment_id
)
+ merge_exa_cost(self, current_enrich)
current_status = (
current_enrich.status.value
if hasattr(current_enrich.status, "value")
@@ -235,6 +238,7 @@ class ExaCreateEnrichmentBlock(Block):
if current_status in ["completed", "failed", "cancelled"]:
# Estimate items from webset searches
webset = await aexa.websets.get(id=input_data.webset_id)
+ merge_exa_cost(self, webset)
if webset.searches:
for search in webset.searches:
if search.progress:
@@ -332,6 +336,7 @@ class ExaGetEnrichmentBlock(Block):
sdk_enrichment = await aexa.websets.enrichments.get(
webset_id=input_data.webset_id, id=input_data.enrichment_id
)
+ merge_exa_cost(self, sdk_enrichment)
enrichment = WebsetEnrichmentModel.from_sdk(sdk_enrichment)
@@ -425,6 +430,7 @@ class ExaUpdateEnrichmentBlock(Block):
try:
response = await Requests().patch(url, headers=headers, json=payload)
data = response.json()
+ # PATCH /websets/{id}/enrichments/{id} doesn't return costDollars.
yield "enrichment_id", data.get("id", "")
yield "status", data.get("status", "")
@@ -477,6 +483,7 @@ class ExaDeleteEnrichmentBlock(Block):
deleted_enrichment = await aexa.websets.enrichments.delete(
webset_id=input_data.webset_id, id=input_data.enrichment_id
)
+ merge_exa_cost(self, deleted_enrichment)
yield "enrichment_id", deleted_enrichment.id
yield "success", "true"
@@ -528,12 +535,14 @@ class ExaCancelEnrichmentBlock(Block):
canceled_enrichment = await aexa.websets.enrichments.cancel(
webset_id=input_data.webset_id, id=input_data.enrichment_id
)
+ merge_exa_cost(self, canceled_enrichment)
# Try to estimate how many items were enriched before cancellation
items_enriched = 0
items_response = await aexa.websets.items.list(
webset_id=input_data.webset_id, limit=100
)
+ merge_exa_cost(self, items_response)
for sdk_item in items_response.data:
# Check if this enrichment is present
diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_import_export.py b/autogpt_platform/backend/backend/blocks/exa/websets_import_export.py
index e5a6137ed4..a865ff4bf3 100644
--- a/autogpt_platform/backend/backend/blocks/exa/websets_import_export.py
+++ b/autogpt_platform/backend/backend/blocks/exa/websets_import_export.py
@@ -29,6 +29,7 @@ from backend.sdk import (
from ._config import exa
from ._test import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT
+from .helpers import merge_exa_cost
# Mirrored model for stability - don't use SDK types directly in block outputs
@@ -297,6 +298,7 @@ class ExaCreateImportBlock(Block):
sdk_import = await aexa.websets.imports.create(
params=payload, csv_data=input_data.csv_data
)
+ merge_exa_cost(self, sdk_import)
import_obj = ImportModel.from_sdk(sdk_import)
@@ -361,6 +363,7 @@ class ExaGetImportBlock(Block):
aexa = AsyncExa(api_key=credentials.api_key.get_secret_value())
sdk_import = await aexa.websets.imports.get(import_id=input_data.import_id)
+ merge_exa_cost(self, sdk_import)
import_obj = ImportModel.from_sdk(sdk_import)
@@ -430,6 +433,7 @@ class ExaListImportsBlock(Block):
cursor=input_data.cursor,
limit=input_data.limit,
)
+ merge_exa_cost(self, response)
# Convert SDK imports to our stable models
imports = [ImportModel.from_sdk(i) for i in response.data]
@@ -477,6 +481,7 @@ class ExaDeleteImportBlock(Block):
deleted_import = await aexa.websets.imports.delete(
import_id=input_data.import_id
)
+ merge_exa_cost(self, deleted_import)
yield "import_id", deleted_import.id
yield "success", "true"
@@ -599,7 +604,7 @@ class ExaExportWebsetBlock(Block):
try:
all_items = []
- # Use SDK's list_all iterator to fetch items
+ # list_all paginates internally; cost_dollars is not surfaced per-page
item_iterator = aexa.websets.items.list_all(
webset_id=input_data.webset_id, limit=input_data.max_items
)
diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_items.py b/autogpt_platform/backend/backend/blocks/exa/websets_items.py
index cdccb89b8d..cf9b0fc9a3 100644
--- a/autogpt_platform/backend/backend/blocks/exa/websets_items.py
+++ b/autogpt_platform/backend/backend/blocks/exa/websets_items.py
@@ -30,6 +30,7 @@ from backend.sdk import (
)
from ._config import exa
+from .helpers import merge_exa_cost
# Mirrored model for enrichment results
@@ -181,6 +182,7 @@ class ExaGetWebsetItemBlock(Block):
sdk_item = await aexa.websets.items.get(
webset_id=input_data.webset_id, id=input_data.item_id
)
+ merge_exa_cost(self, sdk_item)
item = WebsetItemModel.from_sdk(sdk_item)
@@ -293,6 +295,7 @@ class ExaListWebsetItemsBlock(Block):
cursor=input_data.cursor,
limit=input_data.limit,
)
+ merge_exa_cost(self, response)
items = [WebsetItemModel.from_sdk(item) for item in response.data]
@@ -343,6 +346,7 @@ class ExaDeleteWebsetItemBlock(Block):
deleted_item = await aexa.websets.items.delete(
webset_id=input_data.webset_id, id=input_data.item_id
)
+ merge_exa_cost(self, deleted_item)
yield "item_id", deleted_item.id
yield "success", "true"
@@ -404,6 +408,7 @@ class ExaBulkWebsetItemsBlock(Block):
aexa = AsyncExa(api_key=credentials.api_key.get_secret_value())
all_items: List[WebsetItemModel] = []
+ # list_all paginates internally; cost_dollars is not surfaced per-page
item_iterator = aexa.websets.items.list_all(
webset_id=input_data.webset_id, limit=input_data.max_items
)
@@ -476,6 +481,7 @@ class ExaWebsetItemsSummaryBlock(Block):
aexa = AsyncExa(api_key=credentials.api_key.get_secret_value())
webset = await aexa.websets.get(id=input_data.webset_id)
+ merge_exa_cost(self, webset)
entity_type = "unknown"
if webset.searches:
@@ -498,6 +504,7 @@ class ExaWebsetItemsSummaryBlock(Block):
items_response = await aexa.websets.items.list(
webset_id=input_data.webset_id, limit=input_data.sample_size
)
+ merge_exa_cost(self, items_response)
# Convert to our stable models
sample_items = [
WebsetItemModel.from_sdk(item) for item in items_response.data
@@ -574,6 +581,7 @@ class ExaGetNewItemsBlock(Block):
cursor=input_data.since_cursor,
limit=input_data.max_items,
)
+ merge_exa_cost(self, response)
# Convert SDK items to our stable models
new_items = [WebsetItemModel.from_sdk(item) for item in response.data]
diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_monitor.py b/autogpt_platform/backend/backend/blocks/exa/websets_monitor.py
index 8f9836965e..9e1a13243d 100644
--- a/autogpt_platform/backend/backend/blocks/exa/websets_monitor.py
+++ b/autogpt_platform/backend/backend/blocks/exa/websets_monitor.py
@@ -25,6 +25,7 @@ from backend.sdk import (
from ._config import exa
from ._test import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT
+from .helpers import merge_exa_cost
# Mirrored model for stability - don't use SDK types directly in block outputs
@@ -321,6 +322,7 @@ class ExaCreateMonitorBlock(Block):
payload["metadata"] = input_data.metadata
sdk_monitor = await aexa.websets.monitors.create(params=payload)
+ merge_exa_cost(self, sdk_monitor)
monitor = MonitorModel.from_sdk(sdk_monitor)
@@ -385,6 +387,7 @@ class ExaGetMonitorBlock(Block):
aexa = AsyncExa(api_key=credentials.api_key.get_secret_value())
sdk_monitor = await aexa.websets.monitors.get(monitor_id=input_data.monitor_id)
+ merge_exa_cost(self, sdk_monitor)
monitor = MonitorModel.from_sdk(sdk_monitor)
@@ -479,6 +482,7 @@ class ExaUpdateMonitorBlock(Block):
sdk_monitor = await aexa.websets.monitors.update(
monitor_id=input_data.monitor_id, params=payload
)
+ merge_exa_cost(self, sdk_monitor)
# Convert to our stable model
monitor = MonitorModel.from_sdk(sdk_monitor)
@@ -525,6 +529,7 @@ class ExaDeleteMonitorBlock(Block):
deleted_monitor = await aexa.websets.monitors.delete(
monitor_id=input_data.monitor_id
)
+ merge_exa_cost(self, deleted_monitor)
yield "monitor_id", deleted_monitor.id
yield "success", "true"
@@ -586,6 +591,7 @@ class ExaListMonitorsBlock(Block):
limit=input_data.limit,
webset_id=input_data.webset_id,
)
+ merge_exa_cost(self, response)
# Convert SDK monitors to our stable models
monitors = [MonitorModel.from_sdk(m) for m in response.data]
diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_polling.py b/autogpt_platform/backend/backend/blocks/exa/websets_polling.py
index f4168f1446..07cdcb0cec 100644
--- a/autogpt_platform/backend/backend/blocks/exa/websets_polling.py
+++ b/autogpt_platform/backend/backend/blocks/exa/websets_polling.py
@@ -25,6 +25,7 @@ from backend.sdk import (
)
from ._config import exa
+from .helpers import merge_exa_cost
# Import WebsetItemModel for use in enrichment samples
# This is safe as websets_items doesn't import from websets_polling
@@ -126,6 +127,7 @@ class ExaWaitForWebsetBlock(Block):
timeout=input_data.timeout,
poll_interval=input_data.check_interval,
)
+ merge_exa_cost(self, final_webset)
elapsed = time.time() - start_time
@@ -165,6 +167,7 @@ class ExaWaitForWebsetBlock(Block):
while time.time() - start_time < input_data.timeout:
# Get current webset status
webset = await aexa.websets.get(id=input_data.webset_id)
+ merge_exa_cost(self, webset)
current_status = (
webset.status.value
if hasattr(webset.status, "value")
@@ -210,6 +213,7 @@ class ExaWaitForWebsetBlock(Block):
# Timeout reached
elapsed = time.time() - start_time
webset = await aexa.websets.get(id=input_data.webset_id)
+ merge_exa_cost(self, webset)
final_status = (
webset.status.value
if hasattr(webset.status, "value")
@@ -348,6 +352,7 @@ class ExaWaitForSearchBlock(Block):
search = await aexa.websets.searches.get(
webset_id=input_data.webset_id, id=input_data.search_id
)
+ merge_exa_cost(self, search)
# Extract status
status = (
@@ -404,6 +409,7 @@ class ExaWaitForSearchBlock(Block):
search = await aexa.websets.searches.get(
webset_id=input_data.webset_id, id=input_data.search_id
)
+ merge_exa_cost(self, search)
final_status = (
search.status.value
if hasattr(search.status, "value")
@@ -506,6 +512,7 @@ class ExaWaitForEnrichmentBlock(Block):
enrichment = await aexa.websets.enrichments.get(
webset_id=input_data.webset_id, id=input_data.enrichment_id
)
+ merge_exa_cost(self, enrichment)
# Extract status
status = (
@@ -523,16 +530,20 @@ class ExaWaitForEnrichmentBlock(Block):
items_enriched = 0
if input_data.sample_results and status == "completed":
- sample_data, items_enriched = (
- await self._get_sample_enrichments(
- input_data.webset_id, input_data.enrichment_id, aexa
- )
+ (
+ sample_data,
+ items_enriched,
+ ) = await self._get_sample_enrichments(
+ input_data.webset_id, input_data.enrichment_id, aexa
)
yield "enrichment_id", input_data.enrichment_id
yield "final_status", status
yield "items_enriched", items_enriched
- yield "enrichment_title", enrichment.title or enrichment.description or ""
+ yield (
+ "enrichment_title",
+ enrichment.title or enrichment.description or "",
+ )
yield "elapsed_time", elapsed
if input_data.sample_results:
yield "sample_data", sample_data
@@ -551,6 +562,7 @@ class ExaWaitForEnrichmentBlock(Block):
enrichment = await aexa.websets.enrichments.get(
webset_id=input_data.webset_id, id=input_data.enrichment_id
)
+ merge_exa_cost(self, enrichment)
final_status = (
enrichment.status.value
if hasattr(enrichment.status, "value")
@@ -576,6 +588,7 @@ class ExaWaitForEnrichmentBlock(Block):
"""Get sample enriched data and count."""
# Get a few items to see enrichment results using SDK
response = await aexa.websets.items.list(webset_id=webset_id, limit=5)
+ merge_exa_cost(self, response)
sample_data: list[SampleEnrichmentModel] = []
enriched_count = 0
diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_search.py b/autogpt_platform/backend/backend/blocks/exa/websets_search.py
index 77184b6cdf..77ba59d98d 100644
--- a/autogpt_platform/backend/backend/blocks/exa/websets_search.py
+++ b/autogpt_platform/backend/backend/blocks/exa/websets_search.py
@@ -24,6 +24,7 @@ from backend.sdk import (
)
from ._config import exa
+from .helpers import merge_exa_cost
# Mirrored model for stability
@@ -320,6 +321,7 @@ class ExaCreateWebsetSearchBlock(Block):
sdk_search = await aexa.websets.searches.create(
webset_id=input_data.webset_id, params=payload
)
+ merge_exa_cost(self, sdk_search)
search_id = sdk_search.id
status = (
@@ -353,6 +355,7 @@ class ExaCreateWebsetSearchBlock(Block):
current_search = await aexa.websets.searches.get(
webset_id=input_data.webset_id, id=search_id
)
+ merge_exa_cost(self, current_search)
current_status = (
current_search.status.value
if hasattr(current_search.status, "value")
@@ -445,6 +448,7 @@ class ExaGetWebsetSearchBlock(Block):
sdk_search = await aexa.websets.searches.get(
webset_id=input_data.webset_id, id=input_data.search_id
)
+ merge_exa_cost(self, sdk_search)
search = WebsetSearchModel.from_sdk(sdk_search)
@@ -526,6 +530,7 @@ class ExaCancelWebsetSearchBlock(Block):
canceled_search = await aexa.websets.searches.cancel(
webset_id=input_data.webset_id, id=input_data.search_id
)
+ merge_exa_cost(self, canceled_search)
# Extract items found before cancellation
items_found = 0
@@ -605,6 +610,7 @@ class ExaFindOrCreateSearchBlock(Block):
# Get webset to check existing searches
webset = await aexa.websets.get(id=input_data.webset_id)
+ merge_exa_cost(self, webset)
# Look for existing search with same query
existing_search = None
@@ -639,6 +645,7 @@ class ExaFindOrCreateSearchBlock(Block):
sdk_search = await aexa.websets.searches.create(
webset_id=input_data.webset_id, params=payload
)
+ merge_exa_cost(self, sdk_search)
search = WebsetSearchModel.from_sdk(sdk_search)
diff --git a/autogpt_platform/backend/backend/blocks/llm.py b/autogpt_platform/backend/backend/blocks/llm.py
index 4e922dda1b..86c8d96427 100644
--- a/autogpt_platform/backend/backend/blocks/llm.py
+++ b/autogpt_platform/backend/backend/blocks/llm.py
@@ -1624,6 +1624,11 @@ class AIStructuredResponseGeneratorBlock(AIBlockBase):
llm_call_count=retry_count + 1,
llm_retry_count=retry_count,
provider_cost=total_provider_cost,
+ provider_cost_type=(
+ "cost_usd"
+ if total_provider_cost is not None
+ else None
+ ),
)
)
yield "response", response_obj
@@ -1645,6 +1650,9 @@ class AIStructuredResponseGeneratorBlock(AIBlockBase):
llm_call_count=retry_count + 1,
llm_retry_count=retry_count,
provider_cost=total_provider_cost,
+ provider_cost_type=(
+ "cost_usd" if total_provider_cost is not None else None
+ ),
)
)
yield "response", {"response": response_text}
@@ -1679,7 +1687,12 @@ class AIStructuredResponseGeneratorBlock(AIBlockBase):
# All retries exhausted or user-error break: persist accumulated cost so
# the executor can still charge/report the spend even on failure.
if total_provider_cost is not None:
- self.merge_stats(NodeExecutionStats(provider_cost=total_provider_cost))
+ self.merge_stats(
+ NodeExecutionStats(
+ provider_cost=total_provider_cost,
+ provider_cost_type="cost_usd",
+ )
+ )
raise RuntimeError(error_feedback_message)
def response_format_instructions(
diff --git a/autogpt_platform/backend/backend/blocks/perplexity.py b/autogpt_platform/backend/backend/blocks/perplexity.py
index 26dbdda429..0cdf29a3de 100644
--- a/autogpt_platform/backend/backend/blocks/perplexity.py
+++ b/autogpt_platform/backend/backend/blocks/perplexity.py
@@ -250,14 +250,7 @@ class PerplexityBlock(Block):
self.execution_stats.output_token_count = (
response.usage.completion_tokens
)
- # OpenRouter's ``x-total-cost`` response header carries the real
- # per-request USD cost. Piping it into ``provider_cost`` lets the
- # direct-run ``PlatformCostLog`` flow
- # (``executor.cost_tracking::log_system_credential_cost``) record
- # the actual operator-side spend instead of inferring from tokens.
- # Always overwrite — ``execution_stats`` is instance state, so a
- # response without the header must not reuse a previous run's cost.
- self.execution_stats.provider_cost = extract_openrouter_cost(response)
+ self._record_openrouter_cost(response)
return {"response": response_content, "annotations": annotations or []}
@@ -265,6 +258,17 @@ class PerplexityBlock(Block):
logger.error(f"Error calling Perplexity: {e}")
raise
+ def _record_openrouter_cost(self, response: Any) -> None:
+ """Feed OpenRouter's ``x-total-cost`` USD into execution stats for
+ the COST_USD resolver. Tag as ``cost_usd`` only when the value is
+ concrete and positive — leaving it unset on None/0 keeps the
+ billing gap observable instead of silently floored to 0.
+ """
+ cost_usd = extract_openrouter_cost(response)
+ self.execution_stats.provider_cost = cost_usd
+ if cost_usd is not None and cost_usd > 0:
+ self.execution_stats.provider_cost_type = "cost_usd"
+
async def run(
self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs
) -> BlockOutput:
diff --git a/autogpt_platform/backend/backend/blocks/pinecone.py b/autogpt_platform/backend/backend/blocks/pinecone.py
index f882212ab2..270d224ecf 100644
--- a/autogpt_platform/backend/backend/blocks/pinecone.py
+++ b/autogpt_platform/backend/backend/blocks/pinecone.py
@@ -14,6 +14,7 @@ from backend.data.model import (
APIKeyCredentials,
CredentialsField,
CredentialsMetaInput,
+ NodeExecutionStats,
SchemaField,
)
from backend.integrations.providers import ProviderName
@@ -160,10 +161,13 @@ class PineconeQueryBlock(Block):
combined_text = "\n\n".join(texts)
# Return both the raw matches and combined text
- yield "results", {
- "matches": results["matches"],
- "combined_text": combined_text,
- }
+ yield (
+ "results",
+ {
+ "matches": results["matches"],
+ "combined_text": combined_text,
+ },
+ )
yield "combined_results", combined_text
except Exception as e:
@@ -228,6 +232,13 @@ class PineconeInsertBlock(Block):
)
idx.upsert(vectors=vectors, namespace=input_data.namespace)
+ self.merge_stats(
+ NodeExecutionStats(
+ provider_cost=float(len(vectors)),
+ provider_cost_type="items",
+ )
+ )
+
yield "upsert_response", "successfully upserted"
except Exception as e:
diff --git a/autogpt_platform/backend/backend/blocks/video/narration.py b/autogpt_platform/backend/backend/blocks/video/narration.py
index 39b9c481b0..ed3835ec03 100644
--- a/autogpt_platform/backend/backend/blocks/video/narration.py
+++ b/autogpt_platform/backend/backend/blocks/video/narration.py
@@ -27,7 +27,7 @@ from backend.blocks.video._utils import (
strip_chapters_inplace,
)
from backend.data.execution import ExecutionContext
-from backend.data.model import CredentialsField, SchemaField
+from backend.data.model import CredentialsField, NodeExecutionStats, SchemaField
from backend.util.exceptions import BlockExecutionError
from backend.util.file import MediaFileType, get_exec_file_path, store_media_file
@@ -44,7 +44,8 @@ class VideoNarrationBlock(Block):
)
script: str = SchemaField(description="Narration script text")
voice_id: str = SchemaField(
- description="ElevenLabs voice ID", default="21m00Tcm4TlvDq8ikWAM" # Rachel
+ description="ElevenLabs voice ID",
+ default="21m00Tcm4TlvDq8ikWAM", # Rachel
)
model_id: Literal[
"eleven_multilingual_v2",
@@ -124,6 +125,26 @@ class VideoNarrationBlock(Block):
return_format="for_block_output",
)
+ # Models that consume 0.5 credits per character (v2.5 tier). All other
+ # models default to 1.0 credit per character.
+ _HALF_RATE_MODELS = {"eleven_flash_v2_5", "eleven_turbo_v2_5"}
+ # ElevenLabs Starter plan: $5 / 30K credits = $0.000167 / credit.
+ _USD_PER_CREDIT = 0.000167
+
+ def _record_script_cost(self, script: str, model_id: str) -> None:
+ """Emit provider_cost (USD) for the narration run so the COST_USD
+ resolver can bill real ElevenLabs spend. Flash/Turbo v2.5 bill at
+ half the char rate of Multilingual/Turbo v2.
+ """
+ credits_per_char = 0.5 if model_id in self._HALF_RATE_MODELS else 1.0
+ script_usd = len(script) * self._USD_PER_CREDIT * credits_per_char
+ self.merge_stats(
+ NodeExecutionStats(
+ provider_cost=script_usd,
+ provider_cost_type="cost_usd",
+ )
+ )
+
def _generate_narration_audio(
self, api_key: str, script: str, voice_id: str, model_id: str
) -> bytes:
@@ -223,6 +244,8 @@ class VideoNarrationBlock(Block):
input_data.model_id,
)
+ self._record_script_cost(input_data.script, input_data.model_id)
+
# Save audio to exec file path
audio_filename = MediaFileType(f"{node_exec_id}_narration.mp3")
audio_abspath = get_exec_file_path(
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
index d25420bf03..5be93eb85e 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
@@ -265,20 +265,23 @@ class TestNewlyRegisteredBlockCosts:
"""
def test_perplexity_block_registered(self):
+ from backend.blocks._base import BlockCostType
from backend.blocks.perplexity import PerplexityBlock, PerplexityModel
from backend.data.block_cost_config import BLOCK_COSTS
assert PerplexityBlock in BLOCK_COSTS
entries = BLOCK_COSTS[PerplexityBlock]
- # Pin model->cost mapping so swapped prices fail the regression test.
- costs_by_model = {
- entry.cost_filter["model"]: entry.cost_amount for entry in entries
- }
- assert costs_by_model == {
- PerplexityModel.SONAR: 1,
- PerplexityModel.SONAR_PRO: 5,
- PerplexityModel.SONAR_DEEP_RESEARCH: 10,
+ # All 3 Perplexity tiers bill via COST_USD 150 cr/$ (OpenRouter
+ # returns x-total-cost on each response). Pin cost_type + amount
+ # so a regression to per-model flat RUN tiers fails this test.
+ assert {entry.cost_filter["model"] for entry in entries} == {
+ PerplexityModel.SONAR,
+ PerplexityModel.SONAR_PRO,
+ PerplexityModel.SONAR_DEEP_RESEARCH,
}
+ for entry in entries:
+ assert entry.cost_type == BlockCostType.COST_USD
+ assert entry.cost_amount == 150
def test_fact_checker_block_registered(self):
from backend.blocks.jina.fact_checker import FactCheckerBlock
@@ -345,19 +348,21 @@ class TestNewlyRegisteredBlockCosts:
def test_claude_code_block_registered(self):
"""ClaudeCodeBlock spawns an E2B sandbox + runs Claude inside it.
- Cost is dominated by the in-sandbox LLM spend ($0.50-$2/run typical),
- not the sandbox compute itself. Flat 100 credits ($1.00) is the
- conservative estimate until we wire the in-sandbox x-total-cost back
- into NodeExecutionStats.provider_cost.
+ Claude Code CLI returns ``total_cost_usd`` on every response; the
+ block pipes it into execution_stats and bills via COST_USD 150 cr/$
+ (1.5× margin matching TOKEN_COST).
"""
+ from backend.blocks._base import BlockCostType
from backend.blocks.claude_code import ClaudeCodeBlock
from backend.data.block_cost_config import BLOCK_COSTS
assert ClaudeCodeBlock in BLOCK_COSTS
- assert BLOCK_COSTS[ClaudeCodeBlock][0].cost_amount == 100
+ entry = BLOCK_COSTS[ClaudeCodeBlock][0]
+ assert entry.cost_type == BlockCostType.COST_USD
+ assert entry.cost_amount == 150
# Filter keys on `e2b_credentials` (not `credentials`) — verifies the
# cost gate matches the block's actual input field name.
- assert "e2b_credentials" in BLOCK_COSTS[ClaudeCodeBlock][0].cost_filter
+ assert "e2b_credentials" in entry.cost_filter
# ---------------------------------------------------------------------------
diff --git a/autogpt_platform/backend/backend/data/block_cost_config.py b/autogpt_platform/backend/backend/data/block_cost_config.py
index aa5a110089..80ecaa30e4 100644
--- a/autogpt_platform/backend/backend/data/block_cost_config.py
+++ b/autogpt_platform/backend/backend/data/block_cost_config.py
@@ -8,6 +8,7 @@ from backend.data.block import BlockInput
if TYPE_CHECKING:
from backend.data.model import NodeExecutionStats
+from backend.blocks.ai_condition import AIConditionBlock
from backend.blocks.ai_image_customizer import AIImageCustomizerBlock, GeminiImageModel
from backend.blocks.ai_image_generator_block import AIImageGeneratorBlock, ImageGenModel
from backend.blocks.ai_music_generator import AIMusicGeneratorBlock
@@ -57,6 +58,11 @@ from backend.blocks.mem0 import (
from backend.blocks.nvidia.deepfake import NvidiaDeepfakeDetectBlock
from backend.blocks.orchestrator import OrchestratorBlock
from backend.blocks.perplexity import PerplexityBlock, PerplexityModel
+from backend.blocks.pinecone import (
+ PineconeInitBlock,
+ PineconeInsertBlock,
+ PineconeQueryBlock,
+)
from backend.blocks.replicate.flux_advanced import ReplicateFluxAdvancedModelBlock
from backend.blocks.replicate.replicate_block import ReplicateModelBlock
from backend.blocks.screenshotone import ScreenshotWebPageBlock
@@ -235,101 +241,103 @@ class TokenRate(BaseModel):
# TOKEN_COST populates gradually as we migrate LLM blocks to the TOKENS
# cost type. Entries not yet listed fall back to the flat MODEL_COST tier
# via the RUN-based LLM_COST list. Rates below are credits/1M tokens at the
-# current credit-to-USD conversion (1 credit ≈ $0.01), with a 1.5x margin
-# over the published provider price.
+# current credit-to-USD conversion (1 credit ≈ $0.01), with a uniform 1.5x
+# margin over the published provider price (nearest-integer rounded).
TOKEN_COST: dict[LlmModel, TokenRate] = {
- # Anthropic Opus ($15/$75/$1.50/$18.75 per 1M).
+ # Anthropic Opus legacy ($15/$75/$1.50/$18.75 per 1M).
LlmModel.CLAUDE_4_1_OPUS: TokenRate(
- input=2250, output=11250, cache_read=225, cache_creation=2812
+ input=2250, output=11250, cache_read=225, cache_creation=2813
),
LlmModel.CLAUDE_4_OPUS: TokenRate(
- input=2250, output=11250, cache_read=225, cache_creation=2812
+ input=2250, output=11250, cache_read=225, cache_creation=2813
),
+ # Anthropic Opus current ($5/$25/$0.50/$6.25 per 1M).
LlmModel.CLAUDE_4_6_OPUS: TokenRate(
- input=2250, output=11250, cache_read=225, cache_creation=2812
+ input=750, output=3750, cache_read=75, cache_creation=938
),
LlmModel.CLAUDE_4_5_OPUS: TokenRate(
- input=2250, output=11250, cache_read=225, cache_creation=2812
+ input=750, output=3750, cache_read=75, cache_creation=938
),
# Anthropic Sonnet ($3/$15/$0.30/$3.75).
LlmModel.CLAUDE_4_SONNET: TokenRate(
- input=450, output=2250, cache_read=45, cache_creation=562
+ input=450, output=2250, cache_read=45, cache_creation=563
),
LlmModel.CLAUDE_4_6_SONNET: TokenRate(
- input=450, output=2250, cache_read=45, cache_creation=562
+ input=450, output=2250, cache_read=45, cache_creation=563
),
LlmModel.CLAUDE_4_5_SONNET: TokenRate(
- input=450, output=2250, cache_read=45, cache_creation=562
+ input=450, output=2250, cache_read=45, cache_creation=563
),
- # Anthropic Haiku ($0.80/$4/$0.08/$1).
+ # Anthropic Haiku 4.5 ($1/$5/$0.10/$1.25).
LlmModel.CLAUDE_4_5_HAIKU: TokenRate(
- input=120, output=600, cache_read=12, cache_creation=150
+ input=150, output=750, cache_read=15, cache_creation=188
),
- LlmModel.CLAUDE_3_HAIKU: TokenRate(input=37, output=187),
+ # Claude 3 Haiku ($0.25/$1.25) — legacy, no cache fields wired.
+ LlmModel.CLAUDE_3_HAIKU: TokenRate(input=38, output=188),
# OpenAI
- LlmModel.GPT5_2: TokenRate(input=600, output=2400),
- LlmModel.GPT5_1: TokenRate(input=450, output=1800),
- LlmModel.GPT5: TokenRate(input=375, output=1500),
- LlmModel.GPT5_MINI: TokenRate(input=22, output=90),
- LlmModel.GPT5_NANO: TokenRate(input=7, output=30),
- LlmModel.GPT5_CHAT: TokenRate(input=375, output=1500),
+ LlmModel.GPT5_2: TokenRate(input=263, output=2100),
+ LlmModel.GPT5_1: TokenRate(input=188, output=1500),
+ LlmModel.GPT5: TokenRate(input=94, output=750),
+ LlmModel.GPT5_MINI: TokenRate(input=38, output=300),
+ LlmModel.GPT5_NANO: TokenRate(input=8, output=60),
+ LlmModel.GPT5_CHAT: TokenRate(input=188, output=1500),
LlmModel.GPT4O: TokenRate(input=375, output=1500),
- LlmModel.GPT4O_MINI: TokenRate(input=22, output=90),
+ LlmModel.GPT4O_MINI: TokenRate(input=23, output=90),
LlmModel.GPT41: TokenRate(input=300, output=1200),
LlmModel.GPT41_MINI: TokenRate(input=60, output=240),
LlmModel.GPT4_TURBO: TokenRate(input=1500, output=4500),
- LlmModel.O3: TokenRate(input=1500, output=6000),
+ LlmModel.O3: TokenRate(input=300, output=1200),
LlmModel.O3_MINI: TokenRate(input=165, output=660),
LlmModel.O1: TokenRate(input=2250, output=9000),
LlmModel.O1_MINI: TokenRate(input=165, output=660),
- # Google Gemini
- LlmModel.GEMINI_2_5_PRO: TokenRate(input=187, output=750),
- LlmModel.GEMINI_2_5_PRO_PREVIEW: TokenRate(input=187, output=750),
- LlmModel.GEMINI_2_5_FLASH: TokenRate(input=11, output=45),
- LlmModel.GEMINI_2_5_FLASH_LITE_PREVIEW: TokenRate(input=5, output=22),
- LlmModel.GEMINI_2_0_FLASH: TokenRate(input=11, output=45),
- LlmModel.GEMINI_2_0_FLASH_LITE: TokenRate(input=5, output=22),
- LlmModel.GEMINI_3_1_PRO_PREVIEW: TokenRate(input=750, output=3000),
- LlmModel.GEMINI_3_FLASH_PREVIEW: TokenRate(input=15, output=60),
- LlmModel.GEMINI_3_1_FLASH_LITE_PREVIEW: TokenRate(input=5, output=22),
+ # Google Gemini (uses <=200k context tier pricing).
+ LlmModel.GEMINI_2_5_PRO: TokenRate(input=188, output=1500),
+ LlmModel.GEMINI_2_5_PRO_PREVIEW: TokenRate(input=188, output=1500),
+ LlmModel.GEMINI_2_5_FLASH: TokenRate(input=45, output=375),
+ LlmModel.GEMINI_2_5_FLASH_LITE_PREVIEW: TokenRate(input=15, output=60),
+ LlmModel.GEMINI_2_0_FLASH: TokenRate(input=15, output=60),
+ LlmModel.GEMINI_2_0_FLASH_LITE: TokenRate(input=11, output=45),
+ LlmModel.GEMINI_3_1_PRO_PREVIEW: TokenRate(input=300, output=1800),
+ LlmModel.GEMINI_3_FLASH_PREVIEW: TokenRate(input=75, output=450),
+ LlmModel.GEMINI_3_1_FLASH_LITE_PREVIEW: TokenRate(input=38, output=225),
# xAI Grok
LlmModel.GROK_3: TokenRate(input=450, output=2250),
- LlmModel.GROK_4: TokenRate(input=2250, output=11250),
- LlmModel.GROK_4_FAST: TokenRate(input=37, output=150),
- LlmModel.GROK_4_1_FAST: TokenRate(input=37, output=150),
- LlmModel.GROK_4_20: TokenRate(input=750, output=3000),
- LlmModel.GROK_CODE_FAST_1: TokenRate(input=37, output=150),
- # DeepSeek
- LlmModel.DEEPSEEK_CHAT: TokenRate(input=40, output=165),
- LlmModel.DEEPSEEK_R1_0528: TokenRate(input=82, output=328),
+ LlmModel.GROK_4: TokenRate(input=450, output=2250),
+ LlmModel.GROK_4_FAST: TokenRate(input=30, output=75),
+ LlmModel.GROK_4_1_FAST: TokenRate(input=30, output=75),
+ LlmModel.GROK_4_20: TokenRate(input=300, output=900),
+ LlmModel.GROK_CODE_FAST_1: TokenRate(input=30, output=225),
+ # DeepSeek (deepseek-chat = V3.2 at $0.28/$0.42; reasoner at $0.55/$2.19).
+ LlmModel.DEEPSEEK_CHAT: TokenRate(input=42, output=63),
+ LlmModel.DEEPSEEK_R1_0528: TokenRate(input=82, output=329),
# Mistral
LlmModel.MISTRAL_LARGE_3: TokenRate(input=300, output=900),
- LlmModel.MISTRAL_MEDIUM_3_1: TokenRate(input=405, output=1215),
+ LlmModel.MISTRAL_MEDIUM_3_1: TokenRate(input=60, output=300),
LlmModel.MISTRAL_SMALL_3_2: TokenRate(input=15, output=45),
- LlmModel.MISTRAL_NEMO: TokenRate(input=15, output=45),
- LlmModel.CODESTRAL: TokenRate(input=22, output=67),
+ LlmModel.MISTRAL_NEMO: TokenRate(input=3, output=6),
+ LlmModel.CODESTRAL: TokenRate(input=45, output=135),
# Cohere
- LlmModel.COHERE_COMMAND_R_08_2024: TokenRate(input=22, output=90),
+ LlmModel.COHERE_COMMAND_R_08_2024: TokenRate(input=23, output=90),
LlmModel.COHERE_COMMAND_R_PLUS_08_2024: TokenRate(input=375, output=1500),
- LlmModel.COHERE_COMMAND_A_03_2025: TokenRate(input=187, output=750),
+ LlmModel.COHERE_COMMAND_A_03_2025: TokenRate(input=375, output=1500),
# Moonshot Kimi
LlmModel.KIMI_K2: TokenRate(input=90, output=375),
- LlmModel.KIMI_K2_0905: TokenRate(input=90, output=375),
- LlmModel.KIMI_K2_5: TokenRate(input=90, output=375),
- LlmModel.KIMI_K2_6: TokenRate(input=225, output=900),
- LlmModel.KIMI_K2_THINKING: TokenRate(input=225, output=900),
+ LlmModel.KIMI_K2_0905: TokenRate(input=82, output=330),
+ LlmModel.KIMI_K2_5: TokenRate(input=90, output=450),
+ LlmModel.KIMI_K2_6: TokenRate(input=143, output=600),
+ LlmModel.KIMI_K2_THINKING: TokenRate(input=90, output=375),
# Perplexity Sonar
- LlmModel.PERPLEXITY_SONAR: TokenRate(input=30, output=30),
- LlmModel.PERPLEXITY_SONAR_PRO: TokenRate(input=150, output=150),
- LlmModel.PERPLEXITY_SONAR_REASONING_PRO: TokenRate(input=150, output=750),
- LlmModel.PERPLEXITY_SONAR_DEEP_RESEARCH: TokenRate(input=750, output=3750),
- # Groq (LLama + OpenAI OSS)
- LlmModel.LLAMA3_3_70B: TokenRate(input=88, output=118),
- LlmModel.LLAMA3_1_8B: TokenRate(input=7, output=12),
- LlmModel.META_LLAMA_4_SCOUT: TokenRate(input=22, output=75),
- LlmModel.META_LLAMA_4_MAVERICK: TokenRate(input=45, output=97),
- LlmModel.OPENAI_GPT_OSS_120B: TokenRate(input=22, output=67),
- LlmModel.OPENAI_GPT_OSS_20B: TokenRate(input=15, output=45),
+ LlmModel.PERPLEXITY_SONAR: TokenRate(input=150, output=150),
+ LlmModel.PERPLEXITY_SONAR_PRO: TokenRate(input=450, output=2250),
+ LlmModel.PERPLEXITY_SONAR_REASONING_PRO: TokenRate(input=300, output=1200),
+ LlmModel.PERPLEXITY_SONAR_DEEP_RESEARCH: TokenRate(input=300, output=1200),
+ # Groq (LLama + OpenAI OSS). Maverick not listed on Groq; using Meta rate.
+ LlmModel.LLAMA3_3_70B: TokenRate(input=89, output=119),
+ LlmModel.LLAMA3_1_8B: TokenRate(input=8, output=12),
+ LlmModel.META_LLAMA_4_SCOUT: TokenRate(input=17, output=51),
+ LlmModel.META_LLAMA_4_MAVERICK: TokenRate(input=30, output=90),
+ LlmModel.OPENAI_GPT_OSS_120B: TokenRate(input=23, output=90),
+ LlmModel.OPENAI_GPT_OSS_20B: TokenRate(input=11, output=45),
}
@@ -423,10 +431,13 @@ LLM_COST = (
for model, cost in MODEL_COST.items()
if MODEL_METADATA[model].provider == "groq"
]
- # Open Router Models
+ # Open Router Models: OpenRouter returns x-total-cost on every
+ # response. Bill 150 cr/$ (1.5x margin) against the authoritative
+ # USD value instead of maintaining per-model TOKEN_COST rates —
+ # provider pricing drift is handled upstream.
+ [
BlockCost(
- cost_type=BlockCostType.TOKENS,
+ cost_type=BlockCostType.COST_USD,
cost_filter={
"model": model,
"credentials": {
@@ -435,9 +446,9 @@ LLM_COST = (
"type": open_router_credentials.type,
},
},
- cost_amount=cost,
+ cost_amount=150,
)
- for model, cost in MODEL_COST.items()
+ for model in MODEL_COST.keys()
if MODEL_METADATA[model].provider == "open_router"
]
# Llama API Models
@@ -513,14 +524,20 @@ LLM_COST = (
# boundary.
BLOCK_COSTS: dict[Type[Block], list[BlockCost]] = {
+ AIConditionBlock: LLM_COST,
AIConversationBlock: LLM_COST,
AITextGeneratorBlock: LLM_COST,
AIStructuredResponseGeneratorBlock: LLM_COST,
AITextSummarizerBlock: LLM_COST,
AIListGeneratorBlock: LLM_COST,
+ # CodeGenerationBlock (Codex): block computes USD from
+ # response.usage.input_tokens/output_tokens using GPT-5.1-Codex rates
+ # ($1.25/$10 per 1M) and emits provider_cost + cost_usd. COST_USD 150
+ # cr/$ matches the TOKEN_COST margin — a 30K-token generation
+ # (~25K in + 5K out) ≈ $0.081 → 13 cr, vs the prior flat 5 cr.
CodeGenerationBlock: [
BlockCost(
- cost_type=BlockCostType.RUN,
+ cost_type=BlockCostType.COST_USD,
cost_filter={
"model": CodexModel.GPT5_1_CODEX,
"credentials": {
@@ -529,7 +546,7 @@ BLOCK_COSTS: dict[Type[Block], list[BlockCost]] = {
"type": openai_credentials.type,
},
},
- cost_amount=5,
+ cost_amount=150,
)
],
CreateTalkingAvatarVideoBlock: [
@@ -948,16 +965,16 @@ BLOCK_COSTS: dict[Type[Block], list[BlockCost]] = {
},
),
],
+ # PerplexityBlock: OpenRouter returns x-total-cost per request; block
+ # emits provider_cost + cost_usd via execution_stats. COST_USD at 150
+ # cr/$ matches the 1.5× margin baked into TOKEN_COST. Deep Research at
+ # $0.20 → 30 cr; Sonar at $0.001 → 1 cr (ceil). Replaces the prior
+ # per-model flat RUN tiers (1/5/10 cr) that severely under-billed
+ # Deep Research sessions.
PerplexityBlock: [
- # Sonar Deep Research: up to $5/1K searches + $8/1M reasoning tokens.
- # Flat-charge 10 credits mirrors the LLM table's SONAR_DEEP_RESEARCH
- # entry. Block execution decrements only the user credit wallet via
- # spend_credits(); the microdollar rate-limit counter is not touched
- # for run_block invocations. The actual per-run provider spend is
- # recorded separately as provider_cost on PlatformCostLog when
- # OpenRouter reports usage.
BlockCost(
- cost_amount=10,
+ cost_amount=150,
+ cost_type=BlockCostType.COST_USD,
cost_filter={
"model": PerplexityModel.SONAR_DEEP_RESEARCH,
"credentials": {
@@ -967,9 +984,9 @@ BLOCK_COSTS: dict[Type[Block], list[BlockCost]] = {
},
},
),
- # Sonar Pro: $1/1M input + $1/1M output + $0.005/search.
BlockCost(
- cost_amount=5,
+ cost_amount=150,
+ cost_type=BlockCostType.COST_USD,
cost_filter={
"model": PerplexityModel.SONAR_PRO,
"credentials": {
@@ -979,9 +996,9 @@ BLOCK_COSTS: dict[Type[Block], list[BlockCost]] = {
},
},
),
- # Sonar (default): $0.2/1M input + $0.2/1M output + $0.005/search.
BlockCost(
- cost_amount=1,
+ cost_amount=150,
+ cost_type=BlockCostType.COST_USD,
cost_filter={
"model": PerplexityModel.SONAR,
"credentials": {
@@ -1005,9 +1022,14 @@ BLOCK_COSTS: dict[Type[Block], list[BlockCost]] = {
)
],
OrchestratorBlock: LLM_COST,
+ # VideoNarrationBlock: block computes ElevenLabs USD from script
+ # length (~$0.000167/char Starter tier) and emits cost_usd. 150 cr/$
+ # margin matches TOKEN_COST — a 5K-char narration ≈ $0.83 → 125 cr
+ # (was flat 5 cr, ~25× under-bill on long scripts).
VideoNarrationBlock: [
BlockCost(
- cost_amount=5, # ElevenLabs TTS cost
+ cost_amount=150,
+ cost_type=BlockCostType.COST_USD,
cost_filter={
"credentials": {
"id": elevenlabs_credentials.id,
@@ -1229,12 +1251,16 @@ BLOCK_COSTS: dict[Type[Block], list[BlockCost]] = {
},
)
],
- # ClaudeCodeBlock runs an E2B sandbox AND executes Claude Sonnet inside it.
- # Real cost $0.50-$2/run; flat 100 credits is conservative until we pipe
- # x-total-cost from the in-sandbox Claude calls into provider_cost.
+ # ClaudeCodeBlock: bill via Claude Code CLI's `total_cost_usd` field,
+ # which rolls up all Anthropic LLM + internal tool-call spend across
+ # the run. Block emits provider_cost/cost_usd via merge_stats; 150 cr/$
+ # matches the 1.5× margin already baked into TOKEN_COST for every
+ # direct LLM block. E2B sandbox infra (~$0.00028/s) is absorbed into
+ # the margin.
ClaudeCodeBlock: [
BlockCost(
- cost_amount=100,
+ cost_amount=150,
+ cost_type=BlockCostType.COST_USD,
cost_filter={
"e2b_credentials": {
"id": e2b_credentials.id,
@@ -1248,6 +1274,18 @@ BLOCK_COSTS: dict[Type[Block], list[BlockCost]] = {
# class (see backend/blocks/ayrshare/_cost.py). They can't be listed here
# because post_to_*.py imports from backend.sdk, which imports from this
# module — registering via decorator avoids the circular import.
+ # Pinecone: user brings their own Pinecone API key — they pay the
+ # provider directly. 1 cr/run covers platform execution overhead. Upserts
+ # use ITEMS (scales with batch size) so high-volume ingestion pays
+ # proportionally.
+ PineconeInitBlock: [BlockCost(cost_amount=1, cost_type=BlockCostType.RUN)],
+ PineconeQueryBlock: [BlockCost(cost_amount=1, cost_type=BlockCostType.RUN)],
+ PineconeInsertBlock: [
+ BlockCost(
+ cost_amount=1,
+ cost_type=BlockCostType.ITEMS,
+ )
+ ],
# Jina chunking: $0.02/1M tokens. Flat 1 credit floor so the block is not
# wallet-free; embedding/search already have their own entries.
JinaChunkingBlock: [