Massimiliano Pippi
commited on
Commit
•
5e3bf9a
1
Parent(s):
d7804a7
first commit
Browse files
main.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import gradio as gr
|
4 |
+
import openai
|
5 |
+
import tiktoken
|
6 |
+
|
7 |
+
# Config
|
8 |
+
MODEL = "gpt-3.5-turbo"
|
9 |
+
TOKEN_PRICE = 0.002 / 1000
|
10 |
+
|
11 |
+
# Private
|
12 |
+
_tokens: int = 0
|
13 |
+
_encoding = tiktoken.encoding_for_model(MODEL)
|
14 |
+
_api_key = os.environ.get("OPENAI_API_KEY", "")
|
15 |
+
_show_openai_settings = _api_key == ""
|
16 |
+
|
17 |
+
|
18 |
+
def count_tokens(prompt_text: str) -> int:
|
19 |
+
"""Return the number of tokens in the prompt text"""
|
20 |
+
return len(_encoding.encode(str(prompt_text)))
|
21 |
+
|
22 |
+
|
23 |
+
def get_cost(tokens: int) -> float:
|
24 |
+
return TOKEN_PRICE * tokens
|
25 |
+
|
26 |
+
|
27 |
+
def prompt(prompt_text: str, api_key: str) -> str:
|
28 |
+
global _tokens
|
29 |
+
|
30 |
+
_tokens += count_tokens(prompt_text)
|
31 |
+
|
32 |
+
openai.api_key = api_key
|
33 |
+
content = openai.ChatCompletion.create(
|
34 |
+
model=MODEL,
|
35 |
+
messages=[
|
36 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
37 |
+
{"role": "user", "content": prompt_text},
|
38 |
+
],
|
39 |
+
temperature=0,
|
40 |
+
)["choices"][0]["message"]["content"]
|
41 |
+
|
42 |
+
_tokens += count_tokens(content)
|
43 |
+
cost = get_cost(_tokens)
|
44 |
+
|
45 |
+
return (
|
46 |
+
content,
|
47 |
+
_tokens,
|
48 |
+
cost,
|
49 |
+
)
|
50 |
+
|
51 |
+
|
52 |
+
with gr.Blocks() as demo:
|
53 |
+
gr.Markdown("## Test your prompts and see how much it costs!")
|
54 |
+
with gr.Row():
|
55 |
+
with gr.Column(scale=1):
|
56 |
+
txt_api_key = gr.Textbox(
|
57 |
+
label="OpenAI API Key",
|
58 |
+
value=_api_key,
|
59 |
+
visible=_show_openai_settings,
|
60 |
+
type="password",
|
61 |
+
placeholder="sk-...",
|
62 |
+
)
|
63 |
+
num_tokens = gr.Number(value=0, label="Tokens used")
|
64 |
+
num_cost = gr.Number(value=0, label="Estimated cost in $", precision=3)
|
65 |
+
with gr.Column(scale=3):
|
66 |
+
txt_prompt = gr.Textbox(label="Prompt")
|
67 |
+
txt_response = gr.TextArea(label="Model response")
|
68 |
+
with gr.Row():
|
69 |
+
gr.Button("Prompt").click(
|
70 |
+
fn=prompt,
|
71 |
+
inputs=[txt_prompt, txt_api_key],
|
72 |
+
outputs=[txt_response, num_tokens, num_cost],
|
73 |
+
)
|
74 |
+
gr.Button("Clear").click(
|
75 |
+
fn=lambda _: ("", ""),
|
76 |
+
inputs=txt_prompt,
|
77 |
+
outputs=[txt_prompt, txt_response],
|
78 |
+
)
|
79 |
+
|
80 |
+
|
81 |
+
demo.launch()
|