File size: 2,047 Bytes
13ee22c
 
a0c5c60
 
 
 
13ee22c
 
 
 
 
 
 
 
 
 
a0c5c60
 
13ee22c
a0c5c60
 
13ee22c
 
 
 
 
 
 
 
a0c5c60
 
13ee22c
 
a0c5c60
 
 
 
13ee22c
 
 
 
 
 
 
 
 
 
 
 
 
 
a0c5c60
13ee22c
 
 
 
 
 
 
 
 
 
 
a0c5c60
 
13ee22c
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import openai
import gradio as gr
import os

# New API (openai>=1.0.0)
from openai import OpenAI

# Pricing for GPT-3.5-turbo (as of June 2024)
INPUT_COST_PER_1K = 0.0015
OUTPUT_COST_PER_1K = 0.002

def ask_question(api_key, user_question):
    if not api_key:
        return "❌ Please enter your OpenAI API key.", "", ""
    
    try:
        # Use the OpenAI client with your key
        client = OpenAI(api_key=api_key)

        # Send a chat completion request
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": user_question}
            ],
            temperature=0.5
        )

        # Extract the answer
        answer = response.choices[0].message.content

        # Token usage
        usage = response.usage
        input_tokens = usage.prompt_tokens
        output_tokens = usage.completion_tokens
        total_tokens = usage.total_tokens

        # Cost calculation
        input_cost = input_tokens * INPUT_COST_PER_1K / 1000
        output_cost = output_tokens * OUTPUT_COST_PER_1K / 1000
        total_cost = input_cost + output_cost

        token_info = f"🔢 Tokens Used: {total_tokens} (Input: {input_tokens}, Output: {output_tokens})"
        cost_info = f"💰 Estimated Cost: ${total_cost:.6f}"

        return answer, token_info, cost_info

    except Exception as e:
        return f"❌ Error: {str(e)}", "", ""

# Gradio Interface
iface = gr.Interface(
    fn=ask_question,
    inputs=[
        gr.Textbox(label="🔐 OpenAI API Key", type="password", placeholder="sk-..."),
        gr.Textbox(label="❓ Your Question", placeholder="Ask anything...")
    ],
    outputs=[
        gr.Textbox(label="🤖 GPT Response"),
        gr.Textbox(label="📊 Token Info"),
        gr.Textbox(label="💵 Cost Estimate")
    ],
    title="🧠 Ask GPT-3.5 with Your API Key",
    description="Uses latest openai>=1.0.0 SDK"
)

iface.launch()