Add OpenAI API usage

This commit is contained in:
SillyLossy
2023-04-23 18:48:46 +03:00
parent f41d853d72
commit 388d982040
3 changed files with 27 additions and 2 deletions

View File

@ -917,7 +917,7 @@
<div class="online_status_text4">No connection...</div>
</div>
<div>
<a href="https://platform.openai.com/account/usage" target="_blank">View API Usage Metrics</a>
<a id="openai_api_usage" href="javascript:void(0);">View API Usage Metrics</a>
</div>
<br>
</div>

View File

@ -741,6 +741,29 @@ async function saveOpenAIPreset(name, settings) {
}
}
async function showApiKeyUsage() {
const body = JSON.stringify({ key: oai_settings.api_key_openai });
try {
const response = await fetch('/openai_usage', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': token },
body: body,
});
if (response.ok) {
const data = await response.json();
const text = `<h3>Total usage this month: $${Number(data.total_usage / 100).toFixed(2)}</h3>
<a href="https://platform.openai.com/account/usage" target="_blank">Learn more (OpenAI platform website)</a>`;
callPopup(text, 'text');
}
}
catch (err) {
console.error(err);
callPopup('Invalid API key', 'text');
}
}
$(document).ready(function () {
$(document).on('input', '#temp_openai', function () {
oai_settings.temp_openai = $(this).val();
@ -970,4 +993,6 @@ $(document).ready(function () {
oai_settings.reverse_proxy = $(this).val();
saveSettingsDebounced();
});
$("#openai_api_usage").on('click', showApiKeyUsage);
});

View File

@ -2176,7 +2176,7 @@ app.post("/getstatus_openai", jsonParser, function (request, response_getstatus_
});
// Shamelessly stolen from Agnai
app.post("/openai_usage", jsonParser, async function (_, response) {
app.post("/openai_usage", jsonParser, async function (request, response) {
if (!request.body) return response.sendStatus(400);
const key = request.body.key;
const api_url = new URL(request.body.reverse_proxy || api_openai).toString();