Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add token_usage_callback to openai llm plugin #614

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ def __init__(
base_url: str | None = None,
user: str | None = None,
client: openai.AsyncClient | None = None,
token_usage_callback: Callable[[Dict[str, Any]], None] | None = None
temperature: float | None = None,
) -> None:
"""
Expand Down Expand Up @@ -411,11 +412,12 @@ def chat(
n=n,
temperature=temperature,
stream=True,
stream_options={"include_usage": True if self.token_usage_callback else False},
user=user,
**opts,
)

return LLMStream(oai_stream=cmp, chat_ctx=chat_ctx, fnc_ctx=fnc_ctx)
return LLMStream(oai_stream=cmp, chat_ctx=chat_ctx, fnc_ctx=fnc_ctx, token_usage_callback=self.token_usage_callback)


class LLMStream(llm.LLMStream):
Expand All @@ -425,8 +427,10 @@ def __init__(
oai_stream: Awaitable[openai.AsyncStream[ChatCompletionChunk]],
chat_ctx: llm.ChatContext,
fnc_ctx: llm.FunctionContext | None,
token_usage_callback: Callable[[Dict[str, Any]], None] | None = None
) -> None:
super().__init__(chat_ctx=chat_ctx, fnc_ctx=fnc_ctx)
self.token_usage_callback = token_usage_callback
self._awaitable_oai_stream = oai_stream
self._oai_stream: openai.AsyncStream[ChatCompletionChunk] | None = None

Expand All @@ -446,6 +450,9 @@ async def __anext__(self):
self._oai_stream = await self._awaitable_oai_stream

async for chunk in self._oai_stream:
if chunk.usage and self.token_usage_callback:
self.token_usage_callback(chunk.usage)

for choice in chunk.choices:
chat_chunk = self._parse_choice(choice)
if chat_chunk is not None:
Expand Down