luca-litellm 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.
- luca_litellm-0.1.0/LICENSE +201 -0
- luca_litellm-0.1.0/NOTICE +4 -0
- luca_litellm-0.1.0/PKG-INFO +74 -0
- luca_litellm-0.1.0/README.md +53 -0
- luca_litellm-0.1.0/luca_litellm/__init__.py +241 -0
- luca_litellm-0.1.0/luca_litellm.egg-info/PKG-INFO +74 -0
- luca_litellm-0.1.0/luca_litellm.egg-info/SOURCES.txt +11 -0
- luca_litellm-0.1.0/luca_litellm.egg-info/dependency_links.txt +1 -0
- luca_litellm-0.1.0/luca_litellm.egg-info/requires.txt +2 -0
- luca_litellm-0.1.0/luca_litellm.egg-info/top_level.txt +1 -0
- luca_litellm-0.1.0/pyproject.toml +28 -0
- luca_litellm-0.1.0/setup.cfg +4 -0
- luca_litellm-0.1.0/tests/test_luca_litellm.py +140 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Luca
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: luca-litellm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Send the cost of each LiteLLM call to Luca for accounting, without prompts or responses
|
|
5
|
+
Author-email: Luca <hello@luca.network>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://luca.network/developers
|
|
8
|
+
Project-URL: Documentation, https://luca.network/developers#litellm
|
|
9
|
+
Project-URL: Repository, https://github.com/luca-network/luca-litellm
|
|
10
|
+
Keywords: litellm,ai spend,accounting,finops,cost of revenue,llm cost,gateway
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Office/Business :: Financial :: Accounting
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
License-File: NOTICE
|
|
18
|
+
Requires-Dist: litellm>=1.70
|
|
19
|
+
Requires-Dist: httpx>=0.27
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# luca-litellm
|
|
23
|
+
|
|
24
|
+
Send the cost of every call through your LiteLLM proxy to Luca, so your finance team gets AI spend by customer, team and model, accrued and matched to each provider's invoice, with journal entries for the ERP.
|
|
25
|
+
|
|
26
|
+
Only the fields accounting needs leave your network: when the call was made, the provider and model, the cost and token counts, and the team, key, project, customer, tags and MCP server LiteLLM records with it. The plugin drops the prompt, the response, tool arguments and tool results before anything is sent. Email addresses are left out unless you turn them on.
|
|
27
|
+
|
|
28
|
+
## Set up
|
|
29
|
+
|
|
30
|
+
1. In Luca, add a **LiteLLM AI gateway** connection. Luca shows its webhook URL. Make an ingest token for it:
|
|
31
|
+
`openssl rand -hex 32`
|
|
32
|
+
2. On the machine that runs the proxy:
|
|
33
|
+
```
|
|
34
|
+
pip install luca-litellm
|
|
35
|
+
```
|
|
36
|
+
3. Add the plugin to the proxy's `config.yaml`:
|
|
37
|
+
```yaml
|
|
38
|
+
litellm_settings:
|
|
39
|
+
callbacks: ["luca_litellm.handler"]
|
|
40
|
+
```
|
|
41
|
+
4. Set two environment variables for the proxy:
|
|
42
|
+
```
|
|
43
|
+
LUCA_LITELLM_URL=<the webhook URL Luca shows>
|
|
44
|
+
LUCA_LITELLM_TOKEN=<the ingest token>
|
|
45
|
+
```
|
|
46
|
+
5. Restart the proxy.
|
|
47
|
+
|
|
48
|
+
The plugin sends calls in batches (every 10 seconds, or every 200 calls), outside the request path, so it adds no time to your calls. If Luca can't be reached, it keeps the calls and tries again.
|
|
49
|
+
|
|
50
|
+
## Which customer a call served
|
|
51
|
+
|
|
52
|
+
LiteLLM records a customer for each call when your app passes `user` in the request, or when the call uses a key or team set up for that customer. Luca uses it to show AI cost by customer.
|
|
53
|
+
|
|
54
|
+
## Options
|
|
55
|
+
|
|
56
|
+
| Variable | What it does |
|
|
57
|
+
|---|---|
|
|
58
|
+
| `LUCA_LITELLM_URL` | The connection's webhook URL (required) |
|
|
59
|
+
| `LUCA_LITELLM_TOKEN` | The connection's ingest token (required) |
|
|
60
|
+
| `LUCA_LITELLM_INCLUDE_EMAIL` | `true` to send the user's email address with each call (off by default) |
|
|
61
|
+
|
|
62
|
+
To use it from the LiteLLM Python SDK instead of the proxy:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import litellm
|
|
66
|
+
from luca_litellm import LucaLogger
|
|
67
|
+
litellm.callbacks = [LucaLogger(url="https://…", token="…")]
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Without installing a package
|
|
71
|
+
|
|
72
|
+
LiteLLM's built-in webhook callback can send the same calls. Luca shows that configuration on the connection too. With it, turn message logging off (`turn_off_message_logging: true`) so prompts and responses are not sent.
|
|
73
|
+
|
|
74
|
+
Apache-2.0. Questions: hello@luca.network
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# luca-litellm
|
|
2
|
+
|
|
3
|
+
Send the cost of every call through your LiteLLM proxy to Luca, so your finance team gets AI spend by customer, team and model, accrued and matched to each provider's invoice, with journal entries for the ERP.
|
|
4
|
+
|
|
5
|
+
Only the fields accounting needs leave your network: when the call was made, the provider and model, the cost and token counts, and the team, key, project, customer, tags and MCP server LiteLLM records with it. The plugin drops the prompt, the response, tool arguments and tool results before anything is sent. Email addresses are left out unless you turn them on.
|
|
6
|
+
|
|
7
|
+
## Set up
|
|
8
|
+
|
|
9
|
+
1. In Luca, add a **LiteLLM AI gateway** connection. Luca shows its webhook URL. Make an ingest token for it:
|
|
10
|
+
`openssl rand -hex 32`
|
|
11
|
+
2. On the machine that runs the proxy:
|
|
12
|
+
```
|
|
13
|
+
pip install luca-litellm
|
|
14
|
+
```
|
|
15
|
+
3. Add the plugin to the proxy's `config.yaml`:
|
|
16
|
+
```yaml
|
|
17
|
+
litellm_settings:
|
|
18
|
+
callbacks: ["luca_litellm.handler"]
|
|
19
|
+
```
|
|
20
|
+
4. Set two environment variables for the proxy:
|
|
21
|
+
```
|
|
22
|
+
LUCA_LITELLM_URL=<the webhook URL Luca shows>
|
|
23
|
+
LUCA_LITELLM_TOKEN=<the ingest token>
|
|
24
|
+
```
|
|
25
|
+
5. Restart the proxy.
|
|
26
|
+
|
|
27
|
+
The plugin sends calls in batches (every 10 seconds, or every 200 calls), outside the request path, so it adds no time to your calls. If Luca can't be reached, it keeps the calls and tries again.
|
|
28
|
+
|
|
29
|
+
## Which customer a call served
|
|
30
|
+
|
|
31
|
+
LiteLLM records a customer for each call when your app passes `user` in the request, or when the call uses a key or team set up for that customer. Luca uses it to show AI cost by customer.
|
|
32
|
+
|
|
33
|
+
## Options
|
|
34
|
+
|
|
35
|
+
| Variable | What it does |
|
|
36
|
+
|---|---|
|
|
37
|
+
| `LUCA_LITELLM_URL` | The connection's webhook URL (required) |
|
|
38
|
+
| `LUCA_LITELLM_TOKEN` | The connection's ingest token (required) |
|
|
39
|
+
| `LUCA_LITELLM_INCLUDE_EMAIL` | `true` to send the user's email address with each call (off by default) |
|
|
40
|
+
|
|
41
|
+
To use it from the LiteLLM Python SDK instead of the proxy:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import litellm
|
|
45
|
+
from luca_litellm import LucaLogger
|
|
46
|
+
litellm.callbacks = [LucaLogger(url="https://…", token="…")]
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Without installing a package
|
|
50
|
+
|
|
51
|
+
LiteLLM's built-in webhook callback can send the same calls. Luca shows that configuration on the connection too. With it, turn message logging off (`turn_off_message_logging: true`) so prompts and responses are not sent.
|
|
52
|
+
|
|
53
|
+
Apache-2.0. Questions: hello@luca.network
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Send the cost of each LiteLLM call to Luca, without prompts or responses.
|
|
2
|
+
|
|
3
|
+
Add to the proxy's config.yaml:
|
|
4
|
+
|
|
5
|
+
litellm_settings:
|
|
6
|
+
callbacks: ["luca_litellm.handler"]
|
|
7
|
+
|
|
8
|
+
and set two environment variables on the proxy:
|
|
9
|
+
|
|
10
|
+
LUCA_LITELLM_URL the webhook URL Luca shows for the connection
|
|
11
|
+
LUCA_LITELLM_TOKEN the ingest token you gave the connection
|
|
12
|
+
|
|
13
|
+
Only the fields accounting needs leave the proxy: when the call was made, the provider and model, the cost and
|
|
14
|
+
token counts, and the team, key, project, customer, tags and MCP server LiteLLM records with it. The prompt, the
|
|
15
|
+
response, tool arguments and tool results are dropped here, before anything is sent.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import atexit
|
|
22
|
+
import logging
|
|
23
|
+
import os
|
|
24
|
+
import threading
|
|
25
|
+
from typing import Any
|
|
26
|
+
from urllib.parse import urlsplit
|
|
27
|
+
|
|
28
|
+
import httpx
|
|
29
|
+
from litellm.integrations.custom_logger import CustomLogger
|
|
30
|
+
|
|
31
|
+
__all__ = ["LucaLogger", "to_record", "handler", "__version__"]
|
|
32
|
+
__version__ = "0.1.0"
|
|
33
|
+
|
|
34
|
+
log = logging.getLogger("luca_litellm")
|
|
35
|
+
|
|
36
|
+
# The top-level fields of LiteLLM's standard logging payload that Luca reads. Nothing else is sent.
|
|
37
|
+
_TOP = (
|
|
38
|
+
"id", "status", "call_type", "startTime", "endTime", "model", "model_group", "model_id", "custom_llm_provider",
|
|
39
|
+
"response_cost", "prompt_tokens", "completion_tokens", "total_tokens", "cache_hit", "end_user",
|
|
40
|
+
)
|
|
41
|
+
# From the call's metadata: who made it and for whom. The user's email address is left out unless
|
|
42
|
+
# LUCA_LITELLM_INCLUDE_EMAIL is set; the user's ID is enough for Luca to split usage by user.
|
|
43
|
+
_META = (
|
|
44
|
+
"user_api_key_hash", "user_api_key_alias", "user_api_key_team_id", "user_api_key_team_alias",
|
|
45
|
+
"user_api_key_user_id", "user_api_key_project_id", "user_api_key_project_alias", "user_api_key_end_user_id",
|
|
46
|
+
"user_api_key_org_id", "user_api_key_org_alias", "team_id", "team_alias",
|
|
47
|
+
)
|
|
48
|
+
# From the usage object: only the cached-token counts, which change the cost.
|
|
49
|
+
_USAGE = ("cache_read_input_tokens", "cache_creation_input_tokens")
|
|
50
|
+
|
|
51
|
+
_MAX_QUEUE = 20_000
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _host(api_base: Any) -> str | None:
|
|
55
|
+
"""The provider's address without its path or query, which can hold a deployment name or a key."""
|
|
56
|
+
if not isinstance(api_base, str) or not api_base:
|
|
57
|
+
return None
|
|
58
|
+
p = urlsplit(api_base if "://" in api_base else f"https://{api_base}")
|
|
59
|
+
return f"{p.scheme}://{p.hostname}" if p.hostname else None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def to_record(payload: Any, include_email: bool = False) -> dict | None:
|
|
63
|
+
"""The part of one call that Luca keeps, or None when there is nothing to send (no payload, a failed call)."""
|
|
64
|
+
if not isinstance(payload, dict) or not payload.get("id"):
|
|
65
|
+
return None
|
|
66
|
+
if payload.get("status") not in (None, "success"):
|
|
67
|
+
return None
|
|
68
|
+
rec: dict[str, Any] = {k: payload[k] for k in _TOP if payload.get(k) is not None}
|
|
69
|
+
host = _host(payload.get("api_base"))
|
|
70
|
+
if host:
|
|
71
|
+
rec["api_base"] = host
|
|
72
|
+
tags = payload.get("request_tags")
|
|
73
|
+
# LiteLLM adds the client's User-Agent as tags; those say nothing about who the call served.
|
|
74
|
+
tags = [str(t) for t in tags if not str(t).startswith("User-Agent:")] if isinstance(tags, list) else []
|
|
75
|
+
if tags:
|
|
76
|
+
rec["request_tags"] = tags
|
|
77
|
+
md = payload.get("metadata") or {}
|
|
78
|
+
meta: dict[str, Any] = {k: md[k] for k in _META if md.get(k) is not None}
|
|
79
|
+
if include_email and md.get("user_api_key_user_email"):
|
|
80
|
+
meta["user_api_key_user_email"] = md["user_api_key_user_email"]
|
|
81
|
+
usage = md.get("usage_object") or {}
|
|
82
|
+
if isinstance(usage, dict):
|
|
83
|
+
u: dict[str, Any] = {k: usage[k] for k in _USAGE if usage.get(k) is not None}
|
|
84
|
+
cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
|
|
85
|
+
if cached is not None:
|
|
86
|
+
u["prompt_tokens_details"] = {"cached_tokens": cached}
|
|
87
|
+
if u:
|
|
88
|
+
meta["usage_object"] = u
|
|
89
|
+
mcp = md.get("mcp_tool_call_metadata") or {}
|
|
90
|
+
if isinstance(mcp, dict) and (mcp.get("mcp_server_name") or mcp.get("name")):
|
|
91
|
+
meta["mcp_tool_call_metadata"] = {k: mcp[k] for k in ("mcp_server_name", "name") if mcp.get(k)}
|
|
92
|
+
if meta:
|
|
93
|
+
rec["metadata"] = meta
|
|
94
|
+
return rec
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class LucaLogger(CustomLogger):
|
|
98
|
+
"""A LiteLLM callback that batches each successful call's cost fields and posts them to Luca."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, url: str | None = None, token: str | None = None, batch_size: int = 200,
|
|
101
|
+
flush_seconds: float = 10.0, timeout: float = 10.0, include_email: bool | None = None, **kwargs: Any):
|
|
102
|
+
super().__init__(**kwargs)
|
|
103
|
+
self._url = url
|
|
104
|
+
self._token = token
|
|
105
|
+
self.batch_size = max(1, min(int(batch_size), 1000))
|
|
106
|
+
self.flush_seconds = max(1.0, float(flush_seconds))
|
|
107
|
+
self.timeout = float(timeout)
|
|
108
|
+
self._include_email = include_email
|
|
109
|
+
self._queue: list[dict] = []
|
|
110
|
+
self._lock = threading.Lock()
|
|
111
|
+
self._task: asyncio.Task | None = None
|
|
112
|
+
self._warned = False
|
|
113
|
+
self._seen: dict[str, None] = {}
|
|
114
|
+
atexit.register(self.flush)
|
|
115
|
+
|
|
116
|
+
# Settings are read when first needed, so the module can be imported before the environment is set.
|
|
117
|
+
@property
|
|
118
|
+
def url(self) -> str | None:
|
|
119
|
+
return self._url or os.environ.get("LUCA_LITELLM_URL")
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def token(self) -> str | None:
|
|
123
|
+
return self._token or os.environ.get("LUCA_LITELLM_TOKEN")
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def include_email(self) -> bool:
|
|
127
|
+
if self._include_email is not None:
|
|
128
|
+
return self._include_email
|
|
129
|
+
return os.environ.get("LUCA_LITELLM_INCLUDE_EMAIL", "").lower() in ("1", "true", "yes")
|
|
130
|
+
|
|
131
|
+
def _ready(self) -> bool:
|
|
132
|
+
if self.url and self.token:
|
|
133
|
+
return True
|
|
134
|
+
if not self._warned:
|
|
135
|
+
log.warning("luca_litellm: set LUCA_LITELLM_URL and LUCA_LITELLM_TOKEN; nothing is sent until both are set")
|
|
136
|
+
self._warned = True
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
def _add(self, kwargs: dict) -> bool:
|
|
140
|
+
rec = to_record(kwargs.get("standard_logging_object"), self.include_email)
|
|
141
|
+
if rec is None:
|
|
142
|
+
return False
|
|
143
|
+
with self._lock:
|
|
144
|
+
# LiteLLM can report one call to both the sync and the async hook; send it once.
|
|
145
|
+
if rec["id"] in self._seen:
|
|
146
|
+
return False
|
|
147
|
+
self._seen[rec["id"]] = None
|
|
148
|
+
if len(self._seen) > _MAX_QUEUE:
|
|
149
|
+
del self._seen[next(iter(self._seen))]
|
|
150
|
+
self._queue.append(rec)
|
|
151
|
+
if len(self._queue) > _MAX_QUEUE:
|
|
152
|
+
dropped = len(self._queue) - _MAX_QUEUE
|
|
153
|
+
del self._queue[:dropped]
|
|
154
|
+
log.warning("luca_litellm: Luca could not be reached; %d oldest calls dropped from the queue", dropped)
|
|
155
|
+
return len(self._queue) >= self.batch_size
|
|
156
|
+
|
|
157
|
+
def _take(self) -> list[dict]:
|
|
158
|
+
with self._lock:
|
|
159
|
+
batch, self._queue = self._queue[: self.batch_size], self._queue[self.batch_size:]
|
|
160
|
+
return batch
|
|
161
|
+
|
|
162
|
+
def _put_back(self, batch: list[dict]) -> None:
|
|
163
|
+
with self._lock:
|
|
164
|
+
self._queue[:0] = batch
|
|
165
|
+
|
|
166
|
+
def _headers(self) -> dict[str, str]:
|
|
167
|
+
return {"Authorization": f"Bearer {self.token}", "Content-Type": "application/json",
|
|
168
|
+
"User-Agent": f"luca-litellm/{__version__}"}
|
|
169
|
+
|
|
170
|
+
@staticmethod
|
|
171
|
+
def _ok(res: httpx.Response) -> bool:
|
|
172
|
+
if res.status_code < 300:
|
|
173
|
+
return True
|
|
174
|
+
# A rejected delivery (bad token, wrong URL) would fail again; keep it only for errors that may pass.
|
|
175
|
+
if res.status_code in (408, 429) or res.status_code >= 500:
|
|
176
|
+
return False
|
|
177
|
+
log.error("luca_litellm: Luca refused the delivery (%s): %s", res.status_code, res.text[:300])
|
|
178
|
+
return True
|
|
179
|
+
|
|
180
|
+
async def async_flush(self) -> None:
|
|
181
|
+
if not self._ready():
|
|
182
|
+
return
|
|
183
|
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
184
|
+
while True:
|
|
185
|
+
batch = self._take()
|
|
186
|
+
if not batch:
|
|
187
|
+
return
|
|
188
|
+
try:
|
|
189
|
+
if not self._ok(await client.post(self.url, json=batch, headers=self._headers())):
|
|
190
|
+
self._put_back(batch)
|
|
191
|
+
return
|
|
192
|
+
except httpx.HTTPError as e:
|
|
193
|
+
log.warning("luca_litellm: could not reach Luca (%s); will retry", e)
|
|
194
|
+
self._put_back(batch)
|
|
195
|
+
return
|
|
196
|
+
|
|
197
|
+
def flush(self) -> None:
|
|
198
|
+
if not self._queue or not self._ready():
|
|
199
|
+
return
|
|
200
|
+
with httpx.Client(timeout=self.timeout) as client:
|
|
201
|
+
while True:
|
|
202
|
+
batch = self._take()
|
|
203
|
+
if not batch:
|
|
204
|
+
return
|
|
205
|
+
try:
|
|
206
|
+
if not self._ok(client.post(self.url, json=batch, headers=self._headers())):
|
|
207
|
+
self._put_back(batch)
|
|
208
|
+
return
|
|
209
|
+
except httpx.HTTPError as e:
|
|
210
|
+
log.warning("luca_litellm: could not reach Luca (%s); will retry", e)
|
|
211
|
+
self._put_back(batch)
|
|
212
|
+
return
|
|
213
|
+
|
|
214
|
+
async def _every(self) -> None:
|
|
215
|
+
while True:
|
|
216
|
+
await asyncio.sleep(self.flush_seconds)
|
|
217
|
+
try:
|
|
218
|
+
await self.async_flush()
|
|
219
|
+
except Exception: # never let the background loop die
|
|
220
|
+
log.exception("luca_litellm: flush failed")
|
|
221
|
+
|
|
222
|
+
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
|
|
223
|
+
try:
|
|
224
|
+
full = self._add(kwargs)
|
|
225
|
+
if self._task is None or self._task.done():
|
|
226
|
+
self._task = asyncio.get_running_loop().create_task(self._every())
|
|
227
|
+
if full:
|
|
228
|
+
await self.async_flush()
|
|
229
|
+
except Exception: # logging must never affect the call itself
|
|
230
|
+
log.exception("luca_litellm: could not record a call")
|
|
231
|
+
|
|
232
|
+
def log_success_event(self, kwargs, response_obj, start_time, end_time):
|
|
233
|
+
try:
|
|
234
|
+
if self._add(kwargs):
|
|
235
|
+
self.flush()
|
|
236
|
+
except Exception:
|
|
237
|
+
log.exception("luca_litellm: could not record a call")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
# The instance the proxy's config names: callbacks: ["luca_litellm.handler"]
|
|
241
|
+
handler = LucaLogger()
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: luca-litellm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Send the cost of each LiteLLM call to Luca for accounting, without prompts or responses
|
|
5
|
+
Author-email: Luca <hello@luca.network>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://luca.network/developers
|
|
8
|
+
Project-URL: Documentation, https://luca.network/developers#litellm
|
|
9
|
+
Project-URL: Repository, https://github.com/luca-network/luca-litellm
|
|
10
|
+
Keywords: litellm,ai spend,accounting,finops,cost of revenue,llm cost,gateway
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Office/Business :: Financial :: Accounting
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
License-File: NOTICE
|
|
18
|
+
Requires-Dist: litellm>=1.70
|
|
19
|
+
Requires-Dist: httpx>=0.27
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# luca-litellm
|
|
23
|
+
|
|
24
|
+
Send the cost of every call through your LiteLLM proxy to Luca, so your finance team gets AI spend by customer, team and model, accrued and matched to each provider's invoice, with journal entries for the ERP.
|
|
25
|
+
|
|
26
|
+
Only the fields accounting needs leave your network: when the call was made, the provider and model, the cost and token counts, and the team, key, project, customer, tags and MCP server LiteLLM records with it. The plugin drops the prompt, the response, tool arguments and tool results before anything is sent. Email addresses are left out unless you turn them on.
|
|
27
|
+
|
|
28
|
+
## Set up
|
|
29
|
+
|
|
30
|
+
1. In Luca, add a **LiteLLM AI gateway** connection. Luca shows its webhook URL. Make an ingest token for it:
|
|
31
|
+
`openssl rand -hex 32`
|
|
32
|
+
2. On the machine that runs the proxy:
|
|
33
|
+
```
|
|
34
|
+
pip install luca-litellm
|
|
35
|
+
```
|
|
36
|
+
3. Add the plugin to the proxy's `config.yaml`:
|
|
37
|
+
```yaml
|
|
38
|
+
litellm_settings:
|
|
39
|
+
callbacks: ["luca_litellm.handler"]
|
|
40
|
+
```
|
|
41
|
+
4. Set two environment variables for the proxy:
|
|
42
|
+
```
|
|
43
|
+
LUCA_LITELLM_URL=<the webhook URL Luca shows>
|
|
44
|
+
LUCA_LITELLM_TOKEN=<the ingest token>
|
|
45
|
+
```
|
|
46
|
+
5. Restart the proxy.
|
|
47
|
+
|
|
48
|
+
The plugin sends calls in batches (every 10 seconds, or every 200 calls), outside the request path, so it adds no time to your calls. If Luca can't be reached, it keeps the calls and tries again.
|
|
49
|
+
|
|
50
|
+
## Which customer a call served
|
|
51
|
+
|
|
52
|
+
LiteLLM records a customer for each call when your app passes `user` in the request, or when the call uses a key or team set up for that customer. Luca uses it to show AI cost by customer.
|
|
53
|
+
|
|
54
|
+
## Options
|
|
55
|
+
|
|
56
|
+
| Variable | What it does |
|
|
57
|
+
|---|---|
|
|
58
|
+
| `LUCA_LITELLM_URL` | The connection's webhook URL (required) |
|
|
59
|
+
| `LUCA_LITELLM_TOKEN` | The connection's ingest token (required) |
|
|
60
|
+
| `LUCA_LITELLM_INCLUDE_EMAIL` | `true` to send the user's email address with each call (off by default) |
|
|
61
|
+
|
|
62
|
+
To use it from the LiteLLM Python SDK instead of the proxy:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import litellm
|
|
66
|
+
from luca_litellm import LucaLogger
|
|
67
|
+
litellm.callbacks = [LucaLogger(url="https://…", token="…")]
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Without installing a package
|
|
71
|
+
|
|
72
|
+
LiteLLM's built-in webhook callback can send the same calls. Luca shows that configuration on the connection too. With it, turn message logging off (`turn_off_message_logging: true`) so prompts and responses are not sent.
|
|
73
|
+
|
|
74
|
+
Apache-2.0. Questions: hello@luca.network
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
NOTICE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
luca_litellm/__init__.py
|
|
6
|
+
luca_litellm.egg-info/PKG-INFO
|
|
7
|
+
luca_litellm.egg-info/SOURCES.txt
|
|
8
|
+
luca_litellm.egg-info/dependency_links.txt
|
|
9
|
+
luca_litellm.egg-info/requires.txt
|
|
10
|
+
luca_litellm.egg-info/top_level.txt
|
|
11
|
+
tests/test_luca_litellm.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
luca_litellm
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "luca-litellm"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Send the cost of each LiteLLM call to Luca for accounting, without prompts or responses"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "Apache-2.0" }
|
|
11
|
+
authors = [{ name = "Luca", email = "hello@luca.network" }]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
dependencies = ["litellm>=1.70", "httpx>=0.27"]
|
|
14
|
+
keywords = ["litellm", "ai spend", "accounting", "finops", "cost of revenue", "llm cost", "gateway"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"License :: OSI Approved :: Apache Software License",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Office/Business :: Financial :: Accounting",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://luca.network/developers"
|
|
23
|
+
Documentation = "https://luca.network/developers#litellm"
|
|
24
|
+
Repository = "https://github.com/luca-network/luca-litellm"
|
|
25
|
+
|
|
26
|
+
[tool.setuptools]
|
|
27
|
+
packages = ["luca_litellm"]
|
|
28
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""luca-litellm: what leaves the proxy, batching, retries, and a real LiteLLM call through the callback."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
9
|
+
|
|
10
|
+
import litellm
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
from luca_litellm import LucaLogger, to_record
|
|
14
|
+
|
|
15
|
+
PAYLOAD = {
|
|
16
|
+
"id": "call-1", "status": "success", "call_type": "acompletion", "startTime": 1791072000.5, "endTime": 1791072001.0,
|
|
17
|
+
"model": "gpt-4o", "model_group": "gpt-4o", "custom_llm_provider": "openai",
|
|
18
|
+
"api_base": "https://myco.openai.azure.com/openai/deployments/prod?api-key=SECRETKEY",
|
|
19
|
+
"response_cost": 0.0123, "prompt_tokens": 120, "completion_tokens": 30, "total_tokens": 150, "cache_hit": False,
|
|
20
|
+
"end_user": "acme-prod", "request_tags": ["batch"],
|
|
21
|
+
"messages": [{"role": "user", "content": "secret prompt"}], "response": {"text": "secret answer"},
|
|
22
|
+
"model_parameters": {"temperature": 0}, "requester_ip_address": "10.0.0.8",
|
|
23
|
+
"metadata": {
|
|
24
|
+
"user_api_key_hash": "hash1", "user_api_key_team_id": "t_1", "user_api_key_team_alias": "Support",
|
|
25
|
+
"user_api_key_user_id": "u_9", "user_api_key_user_email": "person@myco.example",
|
|
26
|
+
"usage_object": {"prompt_tokens_details": {"cached_tokens": 20}, "completion_tokens": 30},
|
|
27
|
+
"mcp_tool_call_metadata": {"name": "search", "mcp_server_name": "github", "arguments": {"q": "secret"}, "result": {"r": "secret"}},
|
|
28
|
+
"requester_metadata": {"note": "secret"},
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_only_the_fields_accounting_needs_leave_the_proxy():
|
|
34
|
+
r = to_record(PAYLOAD)
|
|
35
|
+
text = json.dumps(r)
|
|
36
|
+
assert "secret" not in text.lower() and "SECRETKEY" not in text, "no prompt, response, tool arguments or key"
|
|
37
|
+
assert "person@myco.example" not in text, "no email address unless asked for"
|
|
38
|
+
assert "10.0.0.8" not in text
|
|
39
|
+
assert r["api_base"] == "https://myco.openai.azure.com"
|
|
40
|
+
assert r["response_cost"] == 0.0123 and r["prompt_tokens"] == 120
|
|
41
|
+
assert r["end_user"] == "acme-prod" and r["request_tags"] == ["batch"]
|
|
42
|
+
assert r["metadata"]["user_api_key_team_alias"] == "Support"
|
|
43
|
+
assert r["metadata"]["usage_object"] == {"prompt_tokens_details": {"cached_tokens": 20}}
|
|
44
|
+
assert r["metadata"]["mcp_tool_call_metadata"] == {"mcp_server_name": "github", "name": "search"}
|
|
45
|
+
assert to_record(PAYLOAD, include_email=True)["metadata"]["user_api_key_user_email"] == "person@myco.example"
|
|
46
|
+
assert to_record({**PAYLOAD, "status": "failure"}) is None
|
|
47
|
+
assert to_record(None) is None and to_record({"status": "success"}) is None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Receiver:
|
|
51
|
+
"""A local stand-in for Luca's webhook: records each delivery, and can fail the first few."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, fail_first=0, status=503):
|
|
54
|
+
self.deliveries, self.headers, self.fail_left, self.status = [], [], fail_first, status
|
|
55
|
+
outer = self
|
|
56
|
+
|
|
57
|
+
class H(BaseHTTPRequestHandler):
|
|
58
|
+
def do_POST(self):
|
|
59
|
+
body = self.rfile.read(int(self.headers["Content-Length"]))
|
|
60
|
+
if outer.fail_left > 0:
|
|
61
|
+
outer.fail_left -= 1
|
|
62
|
+
self.send_response(outer.status); self.end_headers(); return
|
|
63
|
+
outer.deliveries.append(json.loads(body)); outer.headers.append(dict(self.headers))
|
|
64
|
+
self.send_response(200); self.send_header("content-type", "application/json"); self.end_headers()
|
|
65
|
+
self.wfile.write(b'{"stored":1}')
|
|
66
|
+
|
|
67
|
+
def log_message(self, *a):
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
self.server = HTTPServer(("127.0.0.1", 0), H)
|
|
71
|
+
self.url = f"http://127.0.0.1:{self.server.server_port}/v1/hooks/litellm/conn_1"
|
|
72
|
+
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
|
73
|
+
|
|
74
|
+
def close(self):
|
|
75
|
+
self.server.shutdown()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_batches_retries_and_never_sends_without_settings(monkeypatch):
|
|
79
|
+
monkeypatch.delenv("LUCA_LITELLM_URL", raising=False)
|
|
80
|
+
monkeypatch.delenv("LUCA_LITELLM_TOKEN", raising=False)
|
|
81
|
+
idle = LucaLogger()
|
|
82
|
+
idle.log_success_event({"standard_logging_object": PAYLOAD}, None, None, None)
|
|
83
|
+
idle.flush() # no URL or token: nothing is sent, nothing raises
|
|
84
|
+
assert len(idle._queue) == 1
|
|
85
|
+
|
|
86
|
+
rx = Receiver(fail_first=1)
|
|
87
|
+
try:
|
|
88
|
+
lg = LucaLogger(url=rx.url, token="t" * 40, batch_size=2)
|
|
89
|
+
lg.log_success_event({"standard_logging_object": PAYLOAD}, None, None, None)
|
|
90
|
+
lg.log_success_event({"standard_logging_object": PAYLOAD}, None, None, None) # the same call twice: kept once
|
|
91
|
+
assert rx.deliveries == [] and len(lg._queue) == 1
|
|
92
|
+
lg.log_success_event({"standard_logging_object": {**PAYLOAD, "id": "call-2"}}, None, None, None)
|
|
93
|
+
assert rx.deliveries == [], "Luca was down: the batch is kept"
|
|
94
|
+
assert len(lg._queue) == 2
|
|
95
|
+
lg.flush()
|
|
96
|
+
assert [r["id"] for r in rx.deliveries[0]] == ["call-1", "call-2"]
|
|
97
|
+
assert rx.headers[0]["Authorization"] == "Bearer " + "t" * 40
|
|
98
|
+
assert lg._queue == []
|
|
99
|
+
finally:
|
|
100
|
+
rx.close()
|
|
101
|
+
|
|
102
|
+
bad = Receiver(fail_first=1, status=401)
|
|
103
|
+
try:
|
|
104
|
+
lg = LucaLogger(url=bad.url, token="t" * 40)
|
|
105
|
+
lg.log_success_event({"standard_logging_object": PAYLOAD}, None, None, None)
|
|
106
|
+
lg.flush()
|
|
107
|
+
assert lg._queue == [], "a refused delivery (wrong token) is not retried for ever"
|
|
108
|
+
finally:
|
|
109
|
+
bad.close()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_a_real_litellm_call_through_the_callback():
|
|
113
|
+
rx = Receiver()
|
|
114
|
+
try:
|
|
115
|
+
lg = LucaLogger(url=rx.url, token="t" * 40, flush_seconds=1)
|
|
116
|
+
|
|
117
|
+
async def go():
|
|
118
|
+
await litellm.acompletion(
|
|
119
|
+
model="gpt-4o", messages=[{"role": "user", "content": "a secret question"}],
|
|
120
|
+
mock_response="a secret answer", callbacks=[lg], user="acme-prod",
|
|
121
|
+
metadata={"tags": ["batch"]},
|
|
122
|
+
)
|
|
123
|
+
for _ in range(50):
|
|
124
|
+
await asyncio.sleep(0.1)
|
|
125
|
+
if lg._queue or rx.deliveries:
|
|
126
|
+
break
|
|
127
|
+
await lg.async_flush()
|
|
128
|
+
|
|
129
|
+
asyncio.run(go())
|
|
130
|
+
sent = [r for d in rx.deliveries for r in d]
|
|
131
|
+
assert len(sent) == 1, sent
|
|
132
|
+
r = sent[0]
|
|
133
|
+
assert r["model"] == "gpt-4o" and r["status"] == "success" and r["prompt_tokens"] > 0
|
|
134
|
+
assert "secret" not in json.dumps(r)
|
|
135
|
+
out = os.environ.get("LUCA_LITELLM_SAMPLE")
|
|
136
|
+
if out: # the delivery, kept for luca-core's own test of reading it
|
|
137
|
+
with open(out, "w") as f:
|
|
138
|
+
json.dump(rx.deliveries[0], f, indent=1)
|
|
139
|
+
finally:
|
|
140
|
+
rx.close()
|