-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
fix(provider): 补充独立模型调用统计 #9692
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
Open
RhoninSeiei
wants to merge
8
commits into
AstrBotDevs:master
Choose a base branch
from
RhoninSeiei:fix/provider-stats-call-coverage
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ee100e4
test: cover provider stats call paths
4b93c4e
fix: record provider stats for detached calls
ef3ed0f
test: cover failed detached provider stats
5a43deb
fix: preserve detached provider stats on failures
5149f2e
test: cover cancellation and fallback attribution
b711bac
fix: preserve provider attribution on fallback
9abb4c8
merge: update provider stats PR with upstream master
5051916
fix: address provider stats review feedback
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from typing import Any | ||
|
|
||
| from astrbot import logger | ||
| from astrbot.core.db import BaseDatabase | ||
| from astrbot.core.provider.entities import LLMResponse, ProviderRequest, TokenUsage | ||
|
|
||
|
|
||
| @dataclass(slots=True) | ||
| class ProviderStatSegment: | ||
| provider: Any | ||
| usage: TokenUsage | ||
| start_time: float | ||
| end_time: float | ||
| status: str = "error" | ||
|
|
||
|
|
||
| def _provider_id(provider: Any) -> str: | ||
| provider_config = getattr(provider, "provider_config", {}) or {} | ||
| return provider_config.get("id", "") or provider.meta().id | ||
|
|
||
|
|
||
| def _response_status(response: LLMResponse | None) -> str: | ||
| if response is None or response.role == "err": | ||
| return "error" | ||
| return "completed" | ||
|
|
||
|
|
||
| def _runner_status(response: LLMResponse | None, aborted: bool) -> str: | ||
| if aborted: | ||
| return "aborted" | ||
| if response is None or response.role == "err": | ||
| return "error" | ||
| return "completed" | ||
|
|
||
|
|
||
| def _token_usage_dict(usage: TokenUsage) -> dict[str, int]: | ||
| return { | ||
| "input_other": usage.input_other, | ||
| "input_cached": usage.input_cached, | ||
| "output": usage.output, | ||
| } | ||
|
|
||
|
|
||
| async def record_agent_runner_stats( | ||
| db: BaseDatabase, | ||
| *, | ||
| umo: str, | ||
| request: ProviderRequest | None, | ||
| agent_runner: Any, | ||
| final_response: LLMResponse | None, | ||
| agent_type: str = "internal", | ||
| ) -> None: | ||
| """Persist aggregate agent runner stats without affecting its response.""" | ||
| if agent_runner is None: | ||
| return | ||
|
|
||
| provider = getattr(agent_runner, "provider", None) | ||
| stats = getattr(agent_runner, "stats", None) | ||
| if provider is None or stats is None: | ||
| return | ||
|
|
||
| try: | ||
| conversation_id = ( | ||
| request.conversation.cid | ||
| if request is not None and request.conversation is not None | ||
| else None | ||
| ) | ||
| segments: list[ProviderStatSegment] = list( | ||
| getattr(agent_runner, "provider_stat_segments", ()) | ||
| ) | ||
| segmented_usage = TokenUsage() | ||
| for segment in segments: | ||
| segmented_usage += segment.usage | ||
| await db.insert_provider_stat( | ||
| umo=umo, | ||
| conversation_id=conversation_id, | ||
| provider_id=_provider_id(segment.provider), | ||
| provider_model=segment.provider.get_model(), | ||
| status=segment.status, | ||
| stats={ | ||
| "token_usage": _token_usage_dict(segment.usage), | ||
| "start_time": segment.start_time, | ||
| "end_time": segment.end_time, | ||
| "time_to_first_token": 0.0, | ||
| }, | ||
| agent_type=agent_type, | ||
| ) | ||
|
|
||
| aggregate_stats = stats.to_dict() | ||
| aggregate_usage = stats.token_usage - segmented_usage | ||
| aggregate_stats["token_usage"] = { | ||
| "input_other": max(0, aggregate_usage.input_other), | ||
| "input_cached": max(0, aggregate_usage.input_cached), | ||
| "output": max(0, aggregate_usage.output), | ||
| } | ||
| if segments: | ||
| original_start = aggregate_stats["start_time"] | ||
| aggregate_start = max( | ||
| original_start, | ||
| max(segment.end_time for segment in segments), | ||
| ) | ||
| aggregate_stats["start_time"] = aggregate_start | ||
| aggregate_stats["time_to_first_token"] = max( | ||
| 0.0, | ||
| aggregate_stats["time_to_first_token"] | ||
| - (aggregate_start - original_start), | ||
| ) | ||
|
|
||
| await db.insert_provider_stat( | ||
| umo=umo, | ||
| conversation_id=conversation_id, | ||
| provider_id=_provider_id(provider), | ||
| provider_model=provider.get_model(), | ||
| status=_runner_status( | ||
| final_response, | ||
| agent_runner.was_aborted(), | ||
| ), | ||
| stats=aggregate_stats, | ||
| agent_type=agent_type, | ||
| ) | ||
| except Exception as exc: # noqa: BLE001 | ||
| logger.warning("Persist provider stats failed: %s", exc, exc_info=True) | ||
|
|
||
|
|
||
| async def record_llm_response_stats( | ||
| db: BaseDatabase, | ||
| *, | ||
| umo: str, | ||
| provider: Any, | ||
| response: LLMResponse | None, | ||
| start_time: float, | ||
| end_time: float, | ||
| conversation_id: str | None = None, | ||
| agent_type: str = "internal", | ||
| ) -> None: | ||
| """Persist stats for one direct provider request.""" | ||
| try: | ||
| usage = response.usage if response and response.usage else TokenUsage() | ||
| await db.insert_provider_stat( | ||
| umo=umo, | ||
| conversation_id=conversation_id, | ||
| provider_id=_provider_id(provider), | ||
| provider_model=provider.get_model(), | ||
| status=_response_status(response), | ||
| stats={ | ||
| "token_usage": _token_usage_dict(usage), | ||
| "start_time": start_time, | ||
| "end_time": end_time, | ||
| "time_to_first_token": 0.0, | ||
| }, | ||
| agent_type=agent_type, | ||
| ) | ||
| except Exception as exc: # noqa: BLE001 | ||
| logger.warning("Persist provider stats failed: %s", exc, exc_info=True) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.