agentcore-metering 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. agentcore_metering-0.1.0/LICENSE +202 -0
  2. agentcore_metering-0.1.0/MANIFEST.in +13 -0
  3. agentcore_metering-0.1.0/PKG-INFO +339 -0
  4. agentcore_metering-0.1.0/README.md +294 -0
  5. agentcore_metering-0.1.0/README.zh-CN.md +289 -0
  6. agentcore_metering-0.1.0/agentcore_metering/__init__.py +6 -0
  7. agentcore_metering-0.1.0/agentcore_metering/adapters/__init__.py +1 -0
  8. agentcore_metering-0.1.0/agentcore_metering/adapters/django/__init__.py +14 -0
  9. agentcore_metering-0.1.0/agentcore_metering/adapters/django/admin.py +64 -0
  10. agentcore_metering-0.1.0/agentcore_metering/adapters/django/apps.py +11 -0
  11. agentcore_metering-0.1.0/agentcore_metering/adapters/django/cleanup.py +91 -0
  12. agentcore_metering-0.1.0/agentcore_metering/adapters/django/conf.py +174 -0
  13. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/README.md +25 -0
  14. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/__init__.py +2 -0
  15. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/capability_labels.yaml +12 -0
  16. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/load.py +135 -0
  17. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/mode_to_model_type.yaml +7 -0
  18. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/amazon_nova.yaml +13 -0
  19. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/anthropic.yaml +59 -0
  20. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/azure_openai.yaml +60 -0
  21. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/dashscope.yaml +48 -0
  22. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/deepseek.yaml +42 -0
  23. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/gemini.yaml +62 -0
  24. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/index.yaml +19 -0
  25. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/meta_llama.yaml +13 -0
  26. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/minimax.yaml +25 -0
  27. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/mistral.yaml +31 -0
  28. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/moonshot.yaml +33 -0
  29. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/nvidia_nim.yaml +13 -0
  30. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/openai.yaml +114 -0
  31. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/openai_compatible.yaml +6 -0
  32. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/openrouter.yaml +31 -0
  33. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/volcengine.yaml +18 -0
  34. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/xai.yaml +25 -0
  35. agentcore_metering-0.1.0/agentcore_metering/adapters/django/llm_static/providers/zai.yaml +24 -0
  36. agentcore_metering-0.1.0/agentcore_metering/adapters/django/locale/zh_Hans/LC_MESSAGES/django.mo +0 -0
  37. agentcore_metering-0.1.0/agentcore_metering/adapters/django/locale/zh_Hans/LC_MESSAGES/django.po +41 -0
  38. agentcore_metering-0.1.0/agentcore_metering/adapters/django/management/__init__.py +0 -0
  39. agentcore_metering-0.1.0/agentcore_metering/adapters/django/management/commands/__init__.py +0 -0
  40. agentcore_metering-0.1.0/agentcore_metering/adapters/django/management/commands/aggregate_llm_usage_series.py +97 -0
  41. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0001_initial.py +166 -0
  42. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0002_add_llm_config.py +105 -0
  43. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0003_llm_config_single_config.py +55 -0
  44. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0004_add_llm_usage_cost_usd.py +25 -0
  45. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0005_cost_and_currency.py +56 -0
  46. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0006_llm_config_list_and_strategy.py +126 -0
  47. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0007_remove_modelstrategy.py +14 -0
  48. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0008_llmconfig_add_uuid.py +47 -0
  49. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0009_rename_llm_track_user_created_idx_llm_tracker_user_id_5800dd_idx_and_more.py +96 -0
  50. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0010_remove_llmconfig_order.py +16 -0
  51. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0011_llmconfig_is_default.py +23 -0
  52. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0012_alter_llmconfig_options_alter_llmconfig_is_default.py +22 -0
  53. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0013_llmusage_started_at.py +24 -0
  54. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0014_alter_llmusage_created_at_alter_llmusage_started_at.py +32 -0
  55. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0015_llmusage_is_streaming_first_chunk_at.py +35 -0
  56. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0016_llmusageseries.py +79 -0
  57. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0017_meteringconfig.py +56 -0
  58. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/0018_alter_llmusageseries_options_and_more.py +73 -0
  59. agentcore_metering-0.1.0/agentcore_metering/adapters/django/migrations/__init__.py +0 -0
  60. agentcore_metering-0.1.0/agentcore_metering/adapters/django/models.py +342 -0
  61. agentcore_metering-0.1.0/agentcore_metering/adapters/django/periodic_tasks.py +47 -0
  62. agentcore_metering-0.1.0/agentcore_metering/adapters/django/serializers.py +509 -0
  63. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/__init__.py +44 -0
  64. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/config_source.py +159 -0
  65. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/litellm_params.py +332 -0
  66. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/litellm_retry.py +293 -0
  67. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/metering_config.py +39 -0
  68. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/model_catalog.py +82 -0
  69. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/runtime_config.py +603 -0
  70. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/usage_aggregation.py +455 -0
  71. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/usage_chart_series.py +470 -0
  72. agentcore_metering-0.1.0/agentcore_metering/adapters/django/services/usage_list.py +146 -0
  73. agentcore_metering-0.1.0/agentcore_metering/adapters/django/tasks/__init__.py +14 -0
  74. agentcore_metering-0.1.0/agentcore_metering/adapters/django/tasks/aggregate.py +226 -0
  75. agentcore_metering-0.1.0/agentcore_metering/adapters/django/tasks/cleanup.py +95 -0
  76. agentcore_metering-0.1.0/agentcore_metering/adapters/django/trackers/__init__.py +8 -0
  77. agentcore_metering-0.1.0/agentcore_metering/adapters/django/trackers/llm.py +1226 -0
  78. agentcore_metering-0.1.0/agentcore_metering/adapters/django/trackers/llm_usage.py +214 -0
  79. agentcore_metering-0.1.0/agentcore_metering/adapters/django/urls.py +86 -0
  80. agentcore_metering-0.1.0/agentcore_metering/adapters/django/utils.py +44 -0
  81. agentcore_metering-0.1.0/agentcore_metering/adapters/django/views/__init__.py +42 -0
  82. agentcore_metering-0.1.0/agentcore_metering/adapters/django/views/config_catalog.py +68 -0
  83. agentcore_metering-0.1.0/agentcore_metering/adapters/django/views/config_management.py +487 -0
  84. agentcore_metering-0.1.0/agentcore_metering/adapters/django/views/config_validation.py +173 -0
  85. agentcore_metering-0.1.0/agentcore_metering/adapters/django/views/metering_config.py +98 -0
  86. agentcore_metering-0.1.0/agentcore_metering/adapters/django/views/usage.py +166 -0
  87. agentcore_metering-0.1.0/agentcore_metering/adapters/django/views/users.py +54 -0
  88. agentcore_metering-0.1.0/agentcore_metering/constants.py +25 -0
  89. agentcore_metering-0.1.0/agentcore_metering.egg-info/PKG-INFO +339 -0
  90. agentcore_metering-0.1.0/agentcore_metering.egg-info/SOURCES.txt +107 -0
  91. agentcore_metering-0.1.0/agentcore_metering.egg-info/dependency_links.txt +1 -0
  92. agentcore_metering-0.1.0/agentcore_metering.egg-info/requires.txt +12 -0
  93. agentcore_metering-0.1.0/agentcore_metering.egg-info/top_level.txt +1 -0
  94. agentcore_metering-0.1.0/docs/DESIGN.md +87 -0
  95. agentcore_metering-0.1.0/docs/DESIGN.zh-CN.md +87 -0
  96. agentcore_metering-0.1.0/pyproject.toml +81 -0
  97. agentcore_metering-0.1.0/setup.cfg +4 -0
  98. agentcore_metering-0.1.0/tests/__init__.py +1 -0
  99. agentcore_metering-0.1.0/tests/conftest.py +46 -0
  100. agentcore_metering-0.1.0/tests/settings.py +25 -0
  101. agentcore_metering-0.1.0/tests/test_api_views.py +89 -0
  102. agentcore_metering-0.1.0/tests/test_litellm_retry.py +162 -0
  103. agentcore_metering-0.1.0/tests/test_llm_config_api.py +255 -0
  104. agentcore_metering-0.1.0/tests/test_llm_service.py +141 -0
  105. agentcore_metering-0.1.0/tests/test_llm_tracker.py +1519 -0
  106. agentcore_metering-0.1.0/tests/test_llm_usage.py +277 -0
  107. agentcore_metering-0.1.0/tests/test_llm_usage_stats.py +391 -0
  108. agentcore_metering-0.1.0/tests/test_runtime_config_service.py +721 -0
  109. agentcore_metering-0.1.0/tests/urls.py +8 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Cloud2AI
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,13 @@
1
+ include LICENSE
2
+ include README.md
3
+ include README.zh-CN.md
4
+ include pyproject.toml
5
+
6
+ recursive-include agentcore_metering/adapters/django/llm_static *.yaml *.md
7
+ recursive-include agentcore_metering/adapters/django/locale *.po *.mo
8
+
9
+ recursive-include docs *.md
10
+ recursive-include tests *.py
11
+
12
+ global-exclude *.py[cod]
13
+ global-exclude __pycache__
@@ -0,0 +1,339 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentcore-metering
3
+ Version: 0.1.0
4
+ Summary: Unified observability for LLM/text, image, and video calls (Django adapter)
5
+ Author: Cloud2AI
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/cloud2ai/agentcore-metering
8
+ Project-URL: Repository, https://github.com/cloud2ai/agentcore-metering
9
+ Project-URL: Issues, https://github.com/cloud2ai/agentcore-metering/issues
10
+ Project-URL: Changelog, https://github.com/cloud2ai/agentcore-metering/releases
11
+ Keywords: django,llm,litellm,metering,observability,cost,agentcore
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Framework :: Django
15
+ Classifier: Framework :: Django :: 4.2
16
+ Classifier: Framework :: Django :: 5.0
17
+ Classifier: Framework :: Django :: 5.1
18
+ Classifier: Framework :: Django :: 5.2
19
+ Classifier: Framework :: Django :: 6.0
20
+ Classifier: Framework :: Django :: 6.1
21
+ Classifier: Framework :: Celery
22
+ Classifier: Operating System :: OS Independent
23
+ Classifier: Programming Language :: Python :: 3
24
+ Classifier: Programming Language :: Python :: 3.10
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3.13
28
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
29
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
30
+ Requires-Python: >=3.10
31
+ Description-Content-Type: text/markdown
32
+ License-File: LICENSE
33
+ Requires-Dist: django>=4.2
34
+ Requires-Dist: djangorestframework>=3.14
35
+ Requires-Dist: drf-spectacular>=0.27.0
36
+ Requires-Dist: litellm<=1.91.3,>=1.0.0
37
+ Requires-Dist: json-repair>=0.25.0
38
+ Requires-Dist: pyyaml>=6.0
39
+ Requires-Dist: celery>=5.0
40
+ Requires-Dist: agentcore-task>=0.1.0
41
+ Provides-Extra: dev
42
+ Requires-Dist: pytest; extra == "dev"
43
+ Requires-Dist: pytest-django; extra == "dev"
44
+ Dynamic: license-file
45
+
46
+ # Agentcore Metering
47
+
48
+ [中文](README.zh-CN.md)
49
+
50
+ Unified module for AI service invocation and statistics in Django projects.
51
+
52
+ - Uses **LiteLLM** for completion and cost metering.
53
+ - Stores cost as amount + currency (e.g. `cost`, `cost_currency`).
54
+ - Uses USD as default cost currency from LiteLLM.
55
+
56
+ ---
57
+
58
+ ## Install
59
+
60
+ - **Not on PyPI**, install only from GitHub.
61
+
62
+ **From GitHub** (editable after clone):
63
+ ```bash
64
+ pip install -e git+https://github.com/cloud2ai/agentcore-metering.git
65
+ ```
66
+ Or, when the host project uses it as a submodule, from repo root:
67
+ ```bash
68
+ pip install -e path/to/agentcore-metering
69
+ ```
70
+ - The host project Dockerfile should iterate over `agentcore/`
71
+ submodules and run `pip install -e`.
72
+ - See the host project README for details.
73
+
74
+ ---
75
+
76
+ ## Testing
77
+
78
+ Install with dev extras, then run pytest from the package root:
79
+
80
+ ```bash
81
+ pip install -e ".[dev]"
82
+ pytest tests -v
83
+ ```
84
+
85
+ - Unit tests cover:
86
+ - `llm_usage_stats` (parse, summary, by_model, series)
87
+ - `llm_usage` (paginated list and query parsing)
88
+ - API tests cover:
89
+ - `GET .../token-stats/`
90
+ - `GET .../llm-usage/`
91
+ - `llm-config` endpoints (auth and response shape)
92
+
93
+ ---
94
+
95
+ ## Backend: usage
96
+
97
+ 1. **Register**
98
+ - Add `'agentcore_metering.adapters.django'` to `INSTALLED_APPS`
99
+ - Add `path('api/v1/admin/', include('agentcore_metering.adapters.django.urls'))` to root URLconf
100
+ 2. **Call LLM and persist usage**:
101
+ ```python
102
+ from agentcore_metering.adapters.django import LLMTracker
103
+ content, usage = LLMTracker.call_and_track(
104
+ messages=[{"role": "user", "content": "..."}],
105
+ node_name="my_node",
106
+ state=request_state,
107
+ )
108
+ ```
109
+ - `state` is optional (task/user context).
110
+ - If `state` contains `user_id`, per-user LLM config (if set) is used. Pass `model_uuid` to use a specific config; otherwise the earliest enabled model is used.
111
+ - For `json_mode=True` (non-stream), tracker does JSON repair + validation and retries by default (`json_attempts=3`; configurable).
112
+ - For `stream=True`, JSON repair is skipped (stream output is unchanged).
113
+ 3. **Config**
114
+ - All config can be managed by admin APIs (global defaults + optional per-user overrides).
115
+ - When model_uuid is not provided, resolution uses the earliest enabled config (by is_default then created_at): user scope -> global scope; no settings fallback, raises if no DB config.
116
+ - LLM calls go through **LiteLLM**.
117
+ - Cost (USD) is estimated from LiteLLM reference pricing and stored per call and in stats.
118
+
119
+ ### Supported providers
120
+
121
+ - Each provider uses a smallest/cheapest default model to reduce
122
+ misconfiguration cost.
123
+ - You can override `model` and optionally `api_base`/`deployment`
124
+ in `config`.
125
+ - **All providers support `api_base` (URL)**:
126
+ - official endpoint when omitted
127
+ - proxy/forwarding URL when needed
128
+ - If you are using an **official model endpoint**, choose the native provider
129
+ for that vendor, for example `minimax`.
130
+ - If you are using a **third-party forwarding platform** through an
131
+ **OpenAI Compatible** endpoint, choose `openai_compatible`.
132
+ - Do not rely on model strings to infer provider automatically; choose the
133
+ provider based on the actual integration path.
134
+
135
+ | Provider | Default model / notes |
136
+ |-----------------|------------------------|
137
+ | `openai` | gpt-4o-mini (official default URL) |
138
+ | `azure_openai` | gpt-4o-mini (requires `api_base` and `deployment`) |
139
+ | `gemini` | gemini-2.0-flash |
140
+ | `anthropic` | claude-3-5-haiku |
141
+ | `mistral` | mistral-tiny |
142
+ | `dashscope` | qwen-turbo (Alibaba Qwen) |
143
+ | `deepseek` | deepseek-chat |
144
+ | `xai` | grok-3-mini-beta (Grok) |
145
+ | `meta_llama` | Llama-3.3-8B-Instruct |
146
+ | `amazon_nova` | nova-micro-v1 |
147
+ | `nvidia_nim` | meta/llama3-8b (Nemotron / NIM) |
148
+ | `minimax` | MiniMax-M2.1 |
149
+ | `openai_compatible` | Depends on the gateway vendor (OpenAI Compatible endpoint) |
150
+ | `moonshot` | moonshot-v1-8k (Kimi) |
151
+ | `zai` | glm-4.5-flash (Z.AI GLM) |
152
+ | `volcengine` | doubao-pro-32k (ByteDance Doubao) |
153
+ | `openrouter` | google/gemma-2-9b-it:free |
154
+
155
+ - Config is from DB only (admin API); no Django settings fallback. At least one enabled global or user config is required for calls.
156
+
157
+ ---
158
+
159
+ ## API reference
160
+
161
+ - Mount under an admin prefix (e.g. `api/v1/admin/`).
162
+ - **Auth**: `IsAdminUser` (staff or superuser), otherwise 403.
163
+ - If the main project uses drf-spectacular, endpoints appear in
164
+ Swagger UI (e.g. `/swagger`) under **llm-metering**.
165
+
166
+ ### LLM configuration (global and per-user)
167
+
168
+ | Method | Path | Description |
169
+ |--------|------|-------------|
170
+ | GET | `.../llm-config/` | List global LLM configs (ordered by created_at, id) |
171
+ | POST | `.../llm-config/` | Create one config. Body: `provider`, `config` (optional `scope`, `user_id`, `is_active`) |
172
+ | GET | `.../llm-config/all/` | List all LLM configs (global + user). Optional `scope=all|global|user`, `user_id` |
173
+ | GET | `.../llm-config/<pk>/` | Get one config by id |
174
+ | PUT | `.../llm-config/<pk>/` | Update one config by id |
175
+ | DELETE | `.../llm-config/<pk>/` | Delete one config by id |
176
+ | GET | `.../llm-config/providers/` | Per-provider param schema (required/optional/editable keys, default model and api_base) for building provider-specific forms |
177
+ | GET | `.../llm-config/models/` | Provider list and model list with capability tags (text-to-text / vision / code / reasoning, etc.) |
178
+ | POST | `.../llm-config/test/` | Validate credentials without saving. Body: `provider`, `config` |
179
+ | POST | `.../llm-config/test-call/` | Run one completion and persist usage. Body: `config_uuid` (or legacy `config_id`), `prompt`, optional `max_tokens`, optional `stream` (see below) |
180
+ | GET | `.../llm-config/users/` | List per-user configs (optional `?user_id=` filter) |
181
+ | GET | `.../llm-config/users/<user_id>/` | Get one user's config (404 if not set) |
182
+ | PUT | `.../llm-config/users/<user_id>/` | Create or update that user's config |
183
+ | DELETE | `.../llm-config/users/<user_id>/` | Remove user config (they fall back to global default) |
184
+
185
+ - **POST/PUT body**
186
+ - `provider` (default `openai`)
187
+ - `config` (single JSON object, e.g. `api_key`, `model`, `api_base`,
188
+ `deployment`, `max_tokens`, `temperature`, `top_p`,
189
+ `request_timeout_seconds`, `num_retries`)
190
+ - `num_retries` defaults to `3`, accepts `0` to disable retries, and is
191
+ applied within the single `request_timeout_seconds` budget
192
+ - for create/list workflows: optional `scope`, `user_id`, `is_active`,
193
+ optional `model_type`
194
+ - required/optional keys differ by provider (e.g. Azure needs
195
+ `api_base` and `deployment`)
196
+ - use `GET .../llm-config/providers/` to fetch schema
197
+ - on GET, `config.api_key` and `config.key` are masked (e.g. `sk-**xxxx`); `is_default` is true when this config is the current default (earliest enabled global config used when model_uuid is not set), so the frontend can highlight the default model.
198
+
199
+ - **GET `.../llm-config/providers/`**
200
+ - returns `{ "providers": { "<provider>": { "required": [...], "optional": [...], "editable_params": [...], "default_model": "...", "default_api_base": "..." } } }`
201
+ - use it to render provider-specific forms and placeholders
202
+
203
+ - **POST `.../llm-config/test/`**
204
+ - body: `provider`, `config` (same as PUT)
205
+ - runs a minimal completion to verify key and endpoint
206
+ - success: `200` + `{ "ok": true }`
207
+ - validation/completion failure: `200` + `{ "ok": false, "detail": "..." }`
208
+ - invalid payload: `400`
209
+
210
+ - **POST `.../llm-config/test-call/`**
211
+ - body: `config_uuid` (preferred) or legacy `config_id`, `prompt`, optional `max_tokens` (default 512, max 4096), optional `stream` (default false)
212
+ - when `stream` is false (default): JSON response. success: `{ "ok": true, "content": "...", "usage": { ... } }`; failure: `{ "ok": false, "detail": "..." }`
213
+ - when `stream` is true: response is SSE (`Content-Type: text/event-stream`). Events: `data: {"type":"chunk","content":"<fragment>"}` for each content fragment; final event `data: {"type":"done","ok":true,"usage":{...}}` or `data: {"type":"done","ok":false,"detail":"..."}`
214
+ - call is persisted to usage records; streaming calls are recorded with `is_streaming=true` and optional TTFT (`first_chunk_at`)
215
+
216
+ ### GET `.../token-stats/`
217
+
218
+ - Returns aggregates and optional time series.
219
+ - Query params are all optional:
220
+
221
+ | Param | Type | Description |
222
+ |--------------|--------|-------------|
223
+ | start_date | string | Start time, ISO or date-only (e.g. 2025-01-01) |
224
+ | end_date | string | End time; date-only is end of that day |
225
+ | user_id | int | Filter by user id |
226
+ | granularity | string | Time bucket: `day` (hour), `month` (day), `year` (month); omit for no series |
227
+ | use_series | string | `1` / `true` / `yes`: when set with granularity and date range, also return `series_by_model` from pre-aggregated LLMUsageSeries (for per-model trend charts) |
228
+
229
+ **200** (JSON):
230
+
231
+ ```json
232
+ {
233
+ "summary": { ... },
234
+ "by_model": [ ... ],
235
+ "series": null,
236
+ "series_by_model": null
237
+ }
238
+ ```
239
+
240
+ - `series` is non-null only when `granularity` is set:
241
+ `{ "granularity": "day", "items": [ { "bucket": "...", "total_tokens": 0, ... } ] }`
242
+ - `series_by_model` is non-null only when `use_series=1` (or `true`/`yes`) and `granularity` and `start_date`/`end_date` are set. It is a list of `{ "bucket", "model", "call_count", "success_count", "avg_e2e_latency_sec", "avg_ttft_sec", "avg_output_tps", "total_prompt_tokens", "total_completion_tokens", "total_tokens", "total_cached_tokens", "total_reasoning_tokens", "total_cost", "cost_currency" }` from the pre-aggregated table (global scope; not filtered by `user_id`). Use it for “Token trend by model” and “Cost trend by model” charts.
243
+ - invalid `granularity` returns `400` + `{ "detail": "..." }`
244
+
245
+ ---
246
+
247
+ ### GET / PATCH `.../metering-config/`
248
+
249
+ - **GET**: Returns effective metering config (retention, cleanup and aggregation schedules).
250
+ - **PATCH**: Update config. Body fields are optional: `retention_days` (1–3650), `cleanup_enabled`, `cleanup_crontab`, `aggregation_crontab` (five-field cron expressions).
251
+
252
+ **GET 200** (JSON):
253
+
254
+ ```json
255
+ {
256
+ "retention_days": 365,
257
+ "cleanup_enabled": true,
258
+ "cleanup_crontab": "0 2 * * *",
259
+ "aggregation_crontab": "5 * * * *"
260
+ }
261
+ ```
262
+
263
+ - Used by the admin UI “Data settings” / “Scheduled tasks” page to configure how long to keep data and when cleanup/aggregation run.
264
+
265
+ ---
266
+
267
+ ### GET `.../llm-usage/`
268
+
269
+ - Returns a paginated usage list.
270
+ - Query params:
271
+
272
+ | Param | Type | Description |
273
+ |------------|--------|-------------|
274
+ | page | int | Page number, default 1 |
275
+ | page_size | int | Page size, default 20, max 100 |
276
+ | user_id | int | Filter by user id |
277
+ | model | string | Model name (icontains) |
278
+ | success | string | `true` / `false` |
279
+ | start_date | string | Start time |
280
+ | end_date | string | End time |
281
+
282
+ **200** (JSON):
283
+
284
+ ```json
285
+ {
286
+ "results": [
287
+ {
288
+ "id": "uuid",
289
+ "user_id": "uuid-or-null",
290
+ "username": "string-or-null",
291
+ "model": "gpt-4",
292
+ "prompt_tokens": 100,
293
+ "completion_tokens": 50,
294
+ "total_tokens": 150,
295
+ "cost": 0.0012,
296
+ "cost_currency": "USD",
297
+ "success": true,
298
+ "error": null,
299
+ "created_at": "2025-01-01T12:00:00+00:00",
300
+ "metadata": {}
301
+ }
302
+ ],
303
+ "total": 100,
304
+ "page": 1,
305
+ "page_size": 20
306
+ }
307
+ ```
308
+
309
+ ---
310
+
311
+ - **UX**
312
+ - use `token-stats` for dashboards and trend charts
313
+ - use `llm-usage` for filterable, paginated call logs
314
+
315
+ ---
316
+
317
+ ## Pre-aggregated series (LLMUsageSeries)
318
+
319
+ - **Table**: `llm_usage_series` stores pre-aggregated usage per **(granularity, bucket, model)**. Granularities: `hour` (for “day” view), `day` (for “month” view), `month` (for “year” view).
320
+ - **Fields per row**: `bucket`, `model`, `call_count`, `success_count`, `avg_e2e_latency_sec`, `avg_ttft_sec`, `avg_output_tps`, token totals (`total_prompt_tokens`, `total_completion_tokens`, `total_tokens`, `total_cached_tokens`, `total_reasoning_tokens`), `total_cost`, `cost_currency`.
321
+ - **Population**: Celery task `aggregate_llm_usage_series_task` (hour + day + month in one run when invoked from beat) aggregates from `llm_tracker_usage` into `llm_usage_series`. Use it for fast “by model” trend charts without querying raw usage on each request.
322
+ - **API**: `GET .../token-stats/?use_series=1&granularity=...&start_date=...&end_date=...` returns `series_by_model` (list of the above rows) for charting.
323
+
324
+ ---
325
+
326
+ ## Metering config and scheduled tasks
327
+
328
+ - **Config model**: `MeteringConfig` (single row) holds `retention_days` (default 365), `cleanup_enabled`, `cleanup_crontab`, `aggregation_crontab`. API: `GET` / `PATCH` `.../metering-config/` (see above).
329
+ - **Celery tasks** (require Celery and `agentcore-task`; registered with django-celery-beat):
330
+ - **Cleanup**: `cleanup_old_llm_usage_task` — deletes `llm_tracker_usage` and `llm_usage_series` older than `retention_days`. No-op if `cleanup_enabled` is false.
331
+ - **Aggregation**: `aggregate_llm_usage_series_task` — runs hour, day, and month aggregation in one go (when called from beat without args); populates `llm_usage_series`.
332
+ - **Task tracking**: Both tasks register with **agentcore-task** `TaskTracker` (module `agentcore_metering`). Executions appear in the unified task list and stats (status, result, error).
333
+
334
+ ---
335
+
336
+ ## Data and layout
337
+
338
+ - **Tables**: `llm_tracker_usage` (usage records), `llm_usage_series` (pre-aggregated series), `agentcore_metering_llm_config` (LLM provider config), `MeteringConfig` (retention and cron settings).
339
+ - **Package**: `agentcore_metering.adapters.django` is a full Django app (models, views, urls, admin, migrations). The public API for LLM metering lives under `trackers/` (e.g. `trackers/llm.py`); import `LLMTracker` from `agentcore_metering.adapters.django` or `agentcore_metering.adapters.django.trackers.llm`. Additional tracker types may be added under `trackers/` (e.g. `trackers/other.py`).