feat(usage): meter embedding tokens as embeddings_queries on both paths

embeddings_queries now records the embedding request's token count (the unit
upstream providers bill on) instead of an operation count, and fires on the
indexing path too. Previously only semantic search recorded it (value=1), so a
re-indexing run produced no embeddings_queries events at all — only pages_chunks.

- Provider layer: additive embed_with_usage / embed_batch_with_usage surface the
  per-request token count (Mistral/OpenAI usage.total_tokens, Bedrock Titan
  inputTextTokenCount, Ollama prompt_eval_count); a char-based estimate is the
  fallback (Simple, and any provider/response without a token field). Gateway and
  EmbeddingService forward through. The count travels as a return value / a
  per-request SearchAlgorithm attribute — never on the singleton — so concurrent
  indexing + search can't mis-attribute bills.
- Indexing (vector/processor.py): records embeddings_queries (value=batch tokens)
  alongside the existing pages_chunks event.
- Search (server/semantic.py): value is now the query embedding's token count,
  relayed from BM25HybridSearchAlgorithm via query_token_count.

The astrolabe_embeddings_queries Stripe meter (sum aggregation) now sums tokens
with no CP/Terraform change. The meter "queries"->tokens naming/unit
clarification (homelab-terraform #254) + CP rollup/portal copy is a follow-up.

Deck #67.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Chris Coutinho
2026-06-08 00:53:58 +02:00
co-authored by Claude Opus 4.8
parent fe17994c4d
commit 64318f0b25
17 changed files with 647 additions and 35 deletions
+34 -4
View File
@@ -164,6 +164,16 @@ class BedrockProvider(Provider):
NotImplementedError: If embeddings not enabled (no embedding_model)
ClientError: If Bedrock API call fails
"""
embedding, _ = await self.embed_with_usage(text)
return embedding
async def embed_with_usage(self, text: str) -> tuple[list[float], int]:
"""Embed one text, reporting the request's token count.
Titan Embed responses carry ``inputTextTokenCount``; for Cohere /
unknown models (no token field) this falls back to a char-based
estimate. Used by the usage-metering hooks (Deck #67).
"""
if not self.supports_embeddings:
raise NotImplementedError(
"Embedding not supported - no embedding_model configured"
@@ -182,7 +192,13 @@ class BedrockProvider(Provider):
response_body = json.loads(response["body"].read())
embedding = self._parse_embedding_response(response_body)
return embedding
token_count = response_body.get("inputTextTokenCount")
tokens = (
int(token_count)
if isinstance(token_count, (int, float))
else self._estimate_tokens([text])
)
return embedding, tokens
except (BotoCoreError, ClientError) as e:
logger.error("Bedrock embedding error: %s", e)
@@ -205,16 +221,30 @@ class BedrockProvider(Provider):
NotImplementedError: If embeddings not enabled (no embedding_model)
ClientError: If Bedrock API call fails
"""
embeddings, _ = await self.embed_batch_with_usage(texts)
return embeddings
async def embed_batch_with_usage(
self, texts: list[str]
) -> tuple[list[list[float]], int]:
"""Embed multiple texts, summing the per-call token counts.
Bedrock has no batch embedding API, so requests run sequentially and
the token total is the sum of each call's ``inputTextTokenCount``
(Titan) or estimate (Cohere/unknown).
"""
if not self.supports_embeddings:
raise NotImplementedError(
"Embedding not supported - no embedding_model configured"
)
embeddings = []
embeddings: list[list[float]] = []
total_tokens = 0
for text in texts:
embedding = await self.embed(text)
embedding, tokens = await self.embed_with_usage(text)
embeddings.append(embedding)
return embeddings
total_tokens += tokens
return embeddings, total_tokens
async def _detect_dimension(self):
"""