perf(providers): estimate missing usage outside the event loop
This commit is contained in:
1 parent
e604c23fca
commit
7177ca05e3
5 files changed
+381
-23
No files matched your search
@@ -29,6 +29,7 @@ from nanobot.events import (
|
||||
)
|
||||
from nanobot.llm_usage.types import LLMUsage as LLMUsage
|
||||
from nanobot.providers.generation import GenerationSettings as GenerationSettings
|
||||
from nanobot.utils.cancellation import shield_and_drain
|
||||
from nanobot.utils.helpers import sanitize_surrogates_deep
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -433,6 +434,7 @@ class LLMProvider(ABC):
|
||||
self.provider_name = provider_name
|
||||
self.generation: GenerationSettings = GenerationSettings()
|
||||
self._llm_call_observer: LLMCallObserver | None = None
|
||||
self._usage_estimation_slots = asyncio.Semaphore(2)
|
||||
|
||||
def set_llm_call_observer(self, observer: LLMCallObserver | None) -> None:
|
||||
"""Attach a fail-open observer for each physical retry-managed call."""
|
||||
@@ -497,7 +499,59 @@ class LLMProvider(ABC):
|
||||
observer = self._llm_call_observer
|
||||
if observer is None:
|
||||
return response
|
||||
finished_at_ns = time.monotonic_ns()
|
||||
usage = self._usage_for_call(response, kwargs)
|
||||
return self._record_llm_call(
|
||||
response, kwargs, observer=observer, usage=usage,
|
||||
started_at_ms=started_at_ms, started_at_ns=started_at_ns,
|
||||
finished_at_ns=finished_at_ns, stream=stream,
|
||||
)
|
||||
|
||||
async def _observe_llm_call_async(
|
||||
self,
|
||||
response: LLMResponse,
|
||||
kwargs: dict[str, Any],
|
||||
*,
|
||||
started_at_ms: int,
|
||||
started_at_ns: int,
|
||||
stream: bool,
|
||||
) -> LLMResponse:
|
||||
observer = self._llm_call_observer
|
||||
if (
|
||||
observer is None
|
||||
or response.finish_reason in {"error", "cancelled"}
|
||||
or (response.usage is not None and response.usage.total_tokens > 0)
|
||||
):
|
||||
return self._observe_llm_call(
|
||||
response, kwargs, started_at_ms=started_at_ms,
|
||||
started_at_ns=started_at_ns, stream=stream,
|
||||
)
|
||||
finished_at_ns = time.monotonic_ns()
|
||||
|
||||
async def observe() -> LLMResponse:
|
||||
async with self._usage_estimation_slots:
|
||||
usage = await asyncio.to_thread(self._usage_for_call, response, kwargs)
|
||||
return self._record_llm_call(
|
||||
response, kwargs, observer=observer, usage=usage,
|
||||
started_at_ms=started_at_ms, started_at_ns=started_at_ns,
|
||||
finished_at_ns=finished_at_ns, stream=stream,
|
||||
)
|
||||
|
||||
# Once the request completes, settle its usage and observer before cancellation.
|
||||
return await shield_and_drain(observe())
|
||||
|
||||
def _record_llm_call(
|
||||
self,
|
||||
response: LLMResponse,
|
||||
kwargs: dict[str, Any],
|
||||
*,
|
||||
observer: LLMCallObserver,
|
||||
usage: LLMUsage | None,
|
||||
started_at_ms: int,
|
||||
started_at_ns: int,
|
||||
finished_at_ns: int,
|
||||
stream: bool,
|
||||
) -> LLMResponse:
|
||||
if usage is not None:
|
||||
response.usage = usage
|
||||
model_value = kwargs.get("model")
|
||||
@@ -508,7 +562,7 @@ class LLMProvider(ABC):
|
||||
|
||||
observer(LLMCallRecord(
|
||||
started_at_ms=started_at_ms,
|
||||
duration_ms=max(0, (time.monotonic_ns() - started_at_ns) // 1_000_000),
|
||||
duration_ms=max(0, (finished_at_ns - started_at_ns) // 1_000_000),
|
||||
provider=self.provider_name,
|
||||
model=model,
|
||||
source=current_llm_usage_source(),
|
||||
@@ -1014,7 +1068,7 @@ class LLMProvider(ABC):
|
||||
raise
|
||||
except Exception as exc:
|
||||
response = self._error_response_from_exception(exc)
|
||||
return self._observe_llm_call(
|
||||
return await self._observe_llm_call_async(
|
||||
response,
|
||||
kwargs,
|
||||
started_at_ms=started_at_ms,
|
||||
@@ -1159,7 +1213,7 @@ class LLMProvider(ABC):
|
||||
raise
|
||||
except Exception as exc:
|
||||
response = self._error_response_from_exception(exc)
|
||||
return self._observe_llm_call(
|
||||
return await self._observe_llm_call_async(
|
||||
_attach_stream_timing(response),
|
||||
kwargs,
|
||||
started_at_ms=started_at_ms,
|
||||
|
||||
@@ -3,8 +3,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Awaitable
|
||||
from typing import TypeVar
|
||||
|
||||
_T = TypeVar("_T")
|
||||
|
||||
|
||||
def task_is_cancelling() -> bool:
|
||||
task = asyncio.current_task()
|
||||
return task is not None and task.cancelling() > 0
|
||||
|
||||
|
||||
async def shield_and_drain(awaitable: Awaitable[_T]) -> _T:
|
||||
"""Finish an accepted operation before propagating caller cancellation.
|
||||
|
||||
Thread workers cannot be stopped by cancelling their awaiting task. Keep
|
||||
their result and any subsequent settlement attached until both finish.
|
||||
"""
|
||||
settlement = asyncio.ensure_future(awaitable)
|
||||
cancellation: asyncio.CancelledError | None = None
|
||||
|
||||
while not settlement.done():
|
||||
try:
|
||||
result = await asyncio.shield(settlement)
|
||||
except asyncio.CancelledError as exc:
|
||||
cancellation = cancellation or exc
|
||||
except BaseException:
|
||||
if cancellation is None:
|
||||
raise
|
||||
break
|
||||
else:
|
||||
if cancellation is not None:
|
||||
raise cancellation
|
||||
return result
|
||||
|
||||
if cancellation is not None:
|
||||
try:
|
||||
settlement.result()
|
||||
except BaseException:
|
||||
# Cancellation wins after the operation's outcome has been observed.
|
||||
pass
|
||||
raise cancellation
|
||||
return settlement.result()
|
||||
+21
-14
@@ -14,6 +14,7 @@ from collections.abc import Iterable
|
||||
from contextlib import suppress
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
from typing import TYPE_CHECKING, Any, TypeVar, cast, overload
|
||||
|
||||
from loguru import logger
|
||||
@@ -29,6 +30,7 @@ if TYPE_CHECKING:
|
||||
|
||||
_TOOLS_TOKEN_CACHE_MAX_ENTRIES = 64
|
||||
_TOOLS_TOKEN_CACHE: dict[int, tuple[tuple[int, ...], dict[bool, int]]] = {}
|
||||
_TOOLS_TOKEN_CACHE_LOCK = Lock()
|
||||
_T = TypeVar("_T")
|
||||
|
||||
|
||||
@@ -112,12 +114,16 @@ def _cache_tools_token_count(
|
||||
fingerprint: tuple[int, ...],
|
||||
counts: dict[bool, int],
|
||||
) -> None:
|
||||
if (
|
||||
tools_id not in _TOOLS_TOKEN_CACHE
|
||||
and len(_TOOLS_TOKEN_CACHE) >= _TOOLS_TOKEN_CACHE_MAX_ENTRIES
|
||||
):
|
||||
_TOOLS_TOKEN_CACHE.pop(next(iter(_TOOLS_TOKEN_CACHE)))
|
||||
_TOOLS_TOKEN_CACHE[tools_id] = (fingerprint, counts)
|
||||
with _TOOLS_TOKEN_CACHE_LOCK:
|
||||
cached = _TOOLS_TOKEN_CACHE.get(tools_id)
|
||||
if cached is not None and cached[0] == fingerprint:
|
||||
counts = {**cached[1], **counts}
|
||||
if (
|
||||
tools_id not in _TOOLS_TOKEN_CACHE
|
||||
and len(_TOOLS_TOKEN_CACHE) >= _TOOLS_TOKEN_CACHE_MAX_ENTRIES
|
||||
):
|
||||
_TOOLS_TOKEN_CACHE.pop(next(iter(_TOOLS_TOKEN_CACHE)))
|
||||
_TOOLS_TOKEN_CACHE[tools_id] = (fingerprint, counts)
|
||||
|
||||
|
||||
def _estimate_tools_tokens(
|
||||
@@ -130,14 +136,15 @@ def _estimate_tools_tokens(
|
||||
# ToolRegistry keeps the returned definitions list alive until the registry changes.
|
||||
tools_id = id(tools)
|
||||
fingerprint = tuple(id(tool) for tool in tools)
|
||||
cached = _TOOLS_TOKEN_CACHE.get(tools_id)
|
||||
if cached and cached[0] == fingerprint:
|
||||
token_count = cached[1].get(leading_separator)
|
||||
if token_count is not None:
|
||||
return token_count
|
||||
counts = cached[1]
|
||||
else:
|
||||
counts = {}
|
||||
with _TOOLS_TOKEN_CACHE_LOCK:
|
||||
cached = _TOOLS_TOKEN_CACHE.get(tools_id)
|
||||
if cached and cached[0] == fingerprint:
|
||||
token_count = cached[1].get(leading_separator)
|
||||
if token_count is not None:
|
||||
return token_count
|
||||
counts = dict(cached[1])
|
||||
else:
|
||||
counts = {}
|
||||
|
||||
rendered = json.dumps(tools, ensure_ascii=False)
|
||||
if leading_separator:
|
||||
|
||||
Reference in new issue
Block a user