Yatheshr commited on
Commit
13ee22c
·
verified ·
1 Parent(s): f2e44da

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import gradio as gr
3
+
4
+ # Pricing for GPT-3.5-turbo (as of June 2024)
5
+ INPUT_COST_PER_1K = 0.0015
6
+ OUTPUT_COST_PER_1K = 0.002
7
+
8
+ def ask_question(api_key, user_question):
9
+ if not api_key:
10
+ return "❌ Please enter your OpenAI API key.", "", ""
11
+
12
+ try:
13
+ # Set the OpenAI API key
14
+ openai.api_key = api_key
15
+
16
+ # Query GPT-3.5
17
+ response = openai.ChatCompletion.create(
18
+ model="gpt-3.5-turbo",
19
+ messages=[
20
+ {"role": "system", "content": "You are a helpful assistant."},
21
+ {"role": "user", "content": user_question}
22
+ ],
23
+ temperature=0.5
24
+ )
25
+
26
+ # Extract response
27
+ answer = response["choices"][0]["message"]["content"]
28
+
29
+ # Token usage
30
+ usage = response["usage"]
31
+ input_tokens = usage['prompt_tokens']
32
+ output_tokens = usage['completion_tokens']
33
+ total_tokens = usage['total_tokens']
34
+
35
+ # Cost calculation
36
+ input_cost = input_tokens * INPUT_COST_PER_1K / 1000
37
+ output_cost = output_tokens * OUTPUT_COST_PER_1K / 1000
38
+ total_cost = input_cost + output_cost
39
+
40
+ token_info = f"🔢 Tokens Used: {total_tokens} (Input: {input_tokens}, Output: {output_tokens})"
41
+ cost_info = f"💰 Estimated Cost: ${total_cost:.6f}"
42
+
43
+ return answer, token_info, cost_info
44
+
45
+ except Exception as e:
46
+ return f"❌ Error: {str(e)}", "", ""
47
+
48
+ # Create Gradio Interface
49
+ iface = gr.Interface(
50
+ fn=ask_question,
51
+ inputs=[
52
+ gr.Textbox(label="🔐 OpenAI API Key", type="password", placeholder="sk-..."),
53
+ gr.Textbox(label="❓ Your Question", placeholder="Ask anything...")
54
+ ],
55
+ outputs=[
56
+ gr.Textbox(label="🤖 GPT Response"),
57
+ gr.Textbox(label="📊 Token Info"),
58
+ gr.Textbox(label="💵 Cost Estimate")
59
+ ],
60
+ title="🧠 Ask GPT-3.5 with Your Own API Key",
61
+ description="Enter your OpenAI API key and a question. It will respond using GPT-3.5 and show token usage + cost."
62
+ )
63
+
64
+ iface.launch()