Repository navigation
Calculate AI usage costs with cached token pricing #929
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
Merged
Merged
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| """Exercise statistics without initializing deployment config, Redis or MySQL.""" | ||
| import ast | ||
| from collections import defaultdict | ||
| from copy import deepcopy | ||
| from datetime import datetime | ||
| import logging | ||
| from pathlib import Path | ||
| import unittest | ||
| from unittest.mock import MagicMock | ||
|
|
||
|
|
||
| SOURCE = Path(__file__).resolve().parents[1] / 'dtable_events' | ||
|
|
||
|
|
||
| def load_definitions(path, names, namespace): | ||
| tree = ast.parse(path.read_text()) | ||
| tree.body = [node for node in tree.body if isinstance(node, (ast.ClassDef, ast.FunctionDef)) and node.name in names] | ||
| exec(compile(tree, str(path), 'exec'), namespace) | ||
| return namespace | ||
|
|
||
|
|
||
| class CachedTokensTest(unittest.TestCase): | ||
| def setUp(self): | ||
| self.prices = {'test-model': {'input_tokens': 2, 'cached_tokens': 0.5, 'output_tokens': 4}} | ||
| self.namespace = load_definitions(SOURCE / 'tasks/ai_stats_worker.py', | ||
| {'AIStatsWorker', 'calculate_usage_cost'}, { | ||
| 'AI_PRICES': self.prices, | ||
| 'defaultdict': defaultdict, | ||
| 'deepcopy': deepcopy, | ||
| 'datetime': datetime, | ||
| 'logger': logging.getLogger(__name__), | ||
| 'text': lambda sql: sql, | ||
| 'uuid_str_to_32_chars': lambda uuid: uuid.replace('-', ''), | ||
| }) | ||
| worker_class = self.namespace['AIStatsWorker'] | ||
| self.worker = worker_class.__new__(worker_class) | ||
| self.worker.reset_stats() | ||
| self.worker._get_dtable_owner_info = MagicMock(return_value={'owner': 'owner', 'org_id': 1}) | ||
|
|
||
| def save(self, cached_tokens=None, canonical=False): | ||
| usage = {'input_tokens': 1000, 'output_tokens': 100} if canonical else {'prompt_tokens': 1000, 'completion_tokens': 100} | ||
| if cached_tokens is not None: | ||
| usage['cached_tokens'] = cached_tokens | ||
| self.worker.save_to_memory({ | ||
| 'model': 'test-model', 'dtable_uuid': 'base', 'usage': usage, | ||
| 'scenario': 'app_page_generation', | ||
| }, MagicMock()) | ||
|
|
||
| def test_normalize_and_aggregate(self): | ||
| for value, expected in [(None, 0), (0, 0), (400, 400), (1000, 1000), (-10, 0), (2000, 1000), ('bad', 0)]: | ||
| with self.subTest(cached_tokens=value): | ||
| self.worker.reset_stats() | ||
| self.save(value) | ||
| self.save(value, canonical=True) | ||
| expected_usage = {'input_tokens': 2000, 'cached_tokens': expected * 2, 'output_tokens': 200} | ||
| self.assertEqual(self.worker.org_stats[1]['test-model'], expected_usage) | ||
| self.assertEqual(self.worker.owner_stats['owner']['test-model'], expected_usage) | ||
| self.assertEqual(self.worker.dtable_stats['base'][('test-model', 'app_page_generation')], expected_usage) | ||
|
|
||
| def test_cost_and_default_price(self): | ||
| calculate = self.namespace['calculate_usage_cost'] | ||
| for cached, expected in [(0, 0.0024), (400, 0.0018), (1000, 0.0009)]: | ||
| self.assertAlmostEqual(calculate('test-model', 1000, cached, 100), expected) | ||
| self.prices['test-model']['cached_tokens'] = 0 | ||
| self.assertAlmostEqual(calculate('test-model', 1000, 400, 100), 0.0016) | ||
| del self.prices['test-model']['cached_tokens'] | ||
| self.assertAlmostEqual(calculate('test-model', 1000, 400, 100), 0.0024) | ||
|
|
||
| def test_flush_all_three_statistics_tables(self): | ||
| self.save(400) | ||
| self.worker.stats_lock = MagicMock() | ||
| self.worker.query_dtable_owners = MagicMock(return_value={'base': {'owner': 'owner', 'org_id': 1}}) | ||
| session = MagicMock() | ||
| self.worker._db_session_class = MagicMock(return_value=session) | ||
| self.worker.stats_worker() | ||
| self.assertEqual(session.execute.call_count, 3) | ||
| for call in session.execute.call_args_list: | ||
| sql, rows = call.args | ||
| self.assertIn('`cached_tokens`', sql) | ||
| self.assertEqual(rows[0]['cached_tokens'], 400) | ||
| self.assertAlmostEqual(rows[0]['cost'], 0.0018) | ||
| session.commit.assert_called_once() | ||
|
|
||
| def test_price_configuration(self): | ||
| parse = load_definitions(SOURCE / 'app/config.py', {'get_llm_prices'}, {})['get_llm_prices'] | ||
| for price, expected in [(2, 2), ({'input_tokens': 2}, 2), ({'input_tokens': 2, 'cached_tokens': 0}, 0), | ||
| ({'input_tokens': 2, 'cached_tokens': 0.5}, 0.5)]: | ||
| with self.subTest(price=price): | ||
| self.assertEqual(parse([{'model': 'test-model', 'price': price}])['test-model']['cached_tokens'], expected) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| unittest.main() | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[Warning] 新计价测试未接入 CI
影响:当前工作流仅调用 test.sh 的 SQL 测试和 dtable_events.webhook.tests,不会发现此目录的四项新测试;本次成功的 CI 日志也只有原有 6 项和 16 项测试。因此缓存扣费、默认价格及三表写入回归仍可能在 CI 全绿时漏过。
建议修复:在工作流或 run_tests 中显式执行 python -m unittest discover -s tests -p test_cached_tokens.py -v,并让失败退出码传递给 Actions。