Gary MZhaovo Chuan Hu Keldos commited on
Commit
ff3263f
·
1 Parent(s): e19e894

feat: 新增显示当前api_key的余额 (#372)

Browse files

* feat: 支持显示余额

* fix: 修复余额解析错误

* perf: 优化展示效果;优化获取使用情况的方法

* 优化显示样式

* style: 统一变量名;文字靠左对齐

* Update ChuanhuChatbot.py

* perf: 更新key时自动更新API使用情况

* chore: 微调usage_display样式

---------

Co-authored-by: mzlegion <mzhao.ouo@gmail.com>
Co-authored-by: Chuan Hu <51039745+GaiZhenbiao@users.noreply.github.com>
Co-authored-by: Keldos <i@keldos.me>

ChuanhuChatbot.py CHANGED
@@ -9,6 +9,7 @@ from modules.utils import *
9
  from modules.presets import *
10
  from modules.overwrites import *
11
  from modules.chat_func import *
 
12
 
13
  logging.basicConfig(
14
  level=logging.DEBUG,
@@ -101,6 +102,8 @@ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
101
  visible=not HIDE_MY_KEY,
102
  label="API-Key",
103
  )
 
 
104
  model_select_dropdown = gr.Dropdown(
105
  label="选择模型", choices=MODELS, multiselect=False, value=MODELS[0]
106
  )
@@ -260,11 +263,13 @@ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
260
  fn=transfer_input, inputs=[user_input], outputs=[user_question, user_input, submitBtn, cancelBtn], show_progress=True
261
  )
262
 
263
- keyTxt.submit(submit_key, keyTxt, [user_api_key, status_display])
264
- keyTxt.change(submit_key, keyTxt, [user_api_key, status_display])
265
  # Chatbot
266
  cancelBtn.click(cancel_outputing, [], [])
267
 
 
 
268
  user_input.submit(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
269
 
270
  submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
 
9
  from modules.presets import *
10
  from modules.overwrites import *
11
  from modules.chat_func import *
12
+ from modules.openai_func import get_usage
13
 
14
  logging.basicConfig(
15
  level=logging.DEBUG,
 
102
  visible=not HIDE_MY_KEY,
103
  label="API-Key",
104
  )
105
+ usageTxt = gr.Markdown(get_usage(my_api_key), elem_id="usage_display")
106
+ usageUpdateBtn = gr.Button("🔄 更新API使用情况")
107
  model_select_dropdown = gr.Dropdown(
108
  label="选择模型", choices=MODELS, multiselect=False, value=MODELS[0]
109
  )
 
263
  fn=transfer_input, inputs=[user_input], outputs=[user_question, user_input, submitBtn, cancelBtn], show_progress=True
264
  )
265
 
266
+ keyTxt.submit(submit_key, keyTxt, [user_api_key, status_display, usageTxt])
267
+ keyTxt.change(submit_key, keyTxt, [user_api_key, status_display, usageTxt])
268
  # Chatbot
269
  cancelBtn.click(cancel_outputing, [], [])
270
 
271
+ usageUpdateBtn.click(get_usage, [user_api_key], [usageTxt], show_progress=True)
272
+
273
  user_input.submit(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
274
 
275
  submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
assets/custom.css CHANGED
@@ -19,6 +19,17 @@
19
  #chuanhu_chatbot, #status_display {
20
  transition: all 0.6s;
21
  }
 
 
 
 
 
 
 
 
 
 
 
22
  /* list */
23
  ol:not(.options), ul:not(.options) {
24
  padding-inline-start: 2em !important;
 
19
  #chuanhu_chatbot, #status_display {
20
  transition: all 0.6s;
21
  }
22
+
23
+ /* usage_display */
24
+ #usage_display {
25
+ height: 1em;
26
+ }
27
+ #usage_display p{
28
+ padding: 0 1em;
29
+ font-size: .85em;
30
+ font-family: monospace;
31
+ color: var(--body-text-color-subdued);
32
+ }
33
  /* list */
34
  ol:not(.options), ul:not(.options) {
35
  padding-inline-start: 2em !important;
modules/openai_func.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import logging
3
+ from modules.presets import timeout_all, BALANCE_API_URL,standard_error_msg,connection_timeout_prompt,error_retrieve_prompt,read_timeout_prompt
4
+ from modules import shared
5
+ import os
6
+
7
+
8
+ def get_usage_response(openai_api_key):
9
+ headers = {
10
+ "Content-Type": "application/json",
11
+ "Authorization": f"Bearer {openai_api_key}",
12
+ }
13
+
14
+ timeout = timeout_all
15
+
16
+ # 获取环境变量中的代理设置
17
+ http_proxy = os.environ.get("HTTP_PROXY") or os.environ.get("http_proxy")
18
+ https_proxy = os.environ.get(
19
+ "HTTPS_PROXY") or os.environ.get("https_proxy")
20
+
21
+ # 如果存在代理设置,使用它们
22
+ proxies = {}
23
+ if http_proxy:
24
+ logging.info(f"使用 HTTP 代理: {http_proxy}")
25
+ proxies["http"] = http_proxy
26
+ if https_proxy:
27
+ logging.info(f"使用 HTTPS 代理: {https_proxy}")
28
+ proxies["https"] = https_proxy
29
+
30
+ # 如果有代理,使用代理发送请求,否则使用默认设置发送请求
31
+ """
32
+ 暂不支持修改
33
+ if shared.state.balance_api_url != BALANCE_API_URL:
34
+ logging.info(f"使用自定义BALANCE API URL: {shared.state.balance_api_url}")
35
+ """
36
+ if proxies:
37
+ response = requests.get(
38
+ BALANCE_API_URL,
39
+ headers=headers,
40
+ timeout=timeout,
41
+ proxies=proxies,
42
+ )
43
+ else:
44
+ response = requests.get(
45
+ BALANCE_API_URL,
46
+ headers=headers,
47
+ timeout=timeout,
48
+ )
49
+ return response
50
+
51
+ def get_usage(openai_api_key):
52
+ try:
53
+ response=get_usage_response(openai_api_key=openai_api_key)
54
+ print(response.json())
55
+ try:
56
+ balance = response.json().get("total_available") if response.json().get(
57
+ "total_available") else 0
58
+ total_used = response.json().get("total_used") if response.json().get(
59
+ "total_used") else 0
60
+ except Exception as e:
61
+ logging.error(f"API使用情况解析失败:"+str(e))
62
+ balance = 0
63
+ total_used=0
64
+ return f"**API使用情况**(已用/余额)\u3000{total_used}$ / {balance}$"
65
+ except requests.exceptions.ConnectTimeout:
66
+ status_text = standard_error_msg + connection_timeout_prompt + error_retrieve_prompt
67
+ return status_text
68
+ except requests.exceptions.ReadTimeout:
69
+ status_text = standard_error_msg + read_timeout_prompt + error_retrieve_prompt
70
+ return status_text
71
+
modules/presets.py CHANGED
@@ -4,6 +4,7 @@ import gradio as gr
4
  # ChatGPT 设置
5
  initial_prompt = "You are a helpful assistant."
6
  API_URL = "https://api.openai.com/v1/chat/completions"
 
7
  HISTORY_DIR = "history"
8
  TEMPLATES_DIR = "templates"
9
 
 
4
  # ChatGPT 设置
5
  initial_prompt = "You are a helpful assistant."
6
  API_URL = "https://api.openai.com/v1/chat/completions"
7
+ BALANCE_API_URL="https://api.openai.com/dashboard/billing/credit_grants"
8
  HISTORY_DIR = "history"
9
  TEMPLATES_DIR = "templates"
10
 
modules/utils.py CHANGED
@@ -22,6 +22,7 @@ from pygments.formatters import HtmlFormatter
22
 
23
  from modules.presets import *
24
  import modules.shared as shared
 
25
 
26
  logging.basicConfig(
27
  level=logging.INFO,
@@ -349,7 +350,7 @@ def submit_key(key):
349
  key = key.strip()
350
  msg = f"API密钥更改为了{hide_middle_chars(key)}"
351
  logging.info(msg)
352
- return key, msg
353
 
354
 
355
  def sha1sum(filename):
 
22
 
23
  from modules.presets import *
24
  import modules.shared as shared
25
+ from modules.openai_func import get_usage
26
 
27
  logging.basicConfig(
28
  level=logging.INFO,
 
350
  key = key.strip()
351
  msg = f"API密钥更改为了{hide_middle_chars(key)}"
352
  logging.info(msg)
353
+ return key, msg, get_usage(key)
354
 
355
 
356
  def sha1sum(filename):