Skip to content

Commit 0f15fdc

Browse files
authored
Merge pull request #2181 from yrangana/feat/openai-embedding-token-tracking
feat: Add token tracking support to openai_embed function
2 parents f1e0110 + ae9f4ae commit 0f15fdc

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

lightrag/llm/openai.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,7 @@ async def openai_embed(
579579
base_url: str | None = None,
580580
api_key: str | None = None,
581581
client_configs: dict[str, Any] | None = None,
582+
token_tracker: Any | None = None,
582583
) -> np.ndarray:
583584
"""Generate embeddings for a list of texts using OpenAI's API.
584585
@@ -590,6 +591,7 @@ async def openai_embed(
590591
client_configs: Additional configuration options for the AsyncOpenAI client.
591592
These will override any default configurations but will be overridden by
592593
explicit parameters (api_key, base_url).
594+
token_tracker: Optional token usage tracker for monitoring API usage.
593595
594596
Returns:
595597
A numpy array of embeddings, one per input text.
@@ -608,6 +610,14 @@ async def openai_embed(
608610
response = await openai_async_client.embeddings.create(
609611
model=model, input=texts, encoding_format="base64"
610612
)
613+
614+
if token_tracker and hasattr(response, "usage"):
615+
token_counts = {
616+
"prompt_tokens": getattr(response.usage, "prompt_tokens", 0),
617+
"total_tokens": getattr(response.usage, "total_tokens", 0),
618+
}
619+
token_tracker.add_usage(token_counts)
620+
611621
return np.array(
612622
[
613623
np.array(dp.embedding, dtype=np.float32)

0 commit comments

Comments
 (0)