From 7ca7ff0fd5b5cbc0bc4ec3357ace43a939c1bcf6 Mon Sep 17 00:00:00 2001 From: Hassieb Pakzad <68423100+hassiebp@users.noreply.github.com> Date: Wed, 27 Aug 2025 16:04:29 +0200 Subject: [PATCH] feat(openai): add openrouter cost tracking --- langfuse/openai.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/langfuse/openai.py b/langfuse/openai.py index 5f163db48..7dea644d9 100644 --- a/langfuse/openai.py +++ b/langfuse/openai.py @@ -494,6 +494,7 @@ def _create_langfuse_update( if usage is not None: update["usage_details"] = _parse_usage(usage) + update["cost_details"] = _parse_cost(usage) generation.update(**update) @@ -523,6 +524,18 @@ def _parse_usage(usage: Optional[Any] = None) -> Any: return usage_dict +def _parse_cost(usage: Optional[Any] = None) -> Any: + if usage is None: + return + + # OpenRouter is returning total cost of the invocation + # https://openrouter.ai/docs/use-cases/usage-accounting#cost-breakdown + if hasattr(usage, "cost") and isinstance(getattr(usage, "cost"), float): + return {"total": getattr(usage, "cost")} + + return None + + def _extract_streamed_response_api_response(chunks: Any) -> Any: completion, model, usage = None, None, None metadata = {}