File size: 1,343 Bytes
363a6ec
5216c03
 
 
399f8c1
 
 
5216c03
399f8c1
363a6ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02db51d
399f8c1
 
 
 
f7da31b
399f8c1
 
 
 
 
 
0fb236b
399f8c1
 
 
f7da31b
 
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
import requests
import gradio as gr


def chat_with_openai(api_key, prompt):
    if not api_key.strip() or not prompt.strip():
        return "Please provide both an API key and a prompt."

    try:
        api_url = "https://api.openai.com/v1/chat/completions"

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }
        data = {
            "model": "gpt-4o-mini",
            "messages": [
                {"role": "user", "content": prompt}
            ],
        }

        response = requests.post(api_url, headers=headers, json=data)
        if response.status_code == 200:
            tmp = response.json()
            result = tmp['choices'][0]['message']['content']
            return result
        else:
            print("ERROR: Failed: ", response.text)
            return None

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


gradio_app = gr.Interface(
    fn=chat_with_openai,
    inputs=[
        gr.Textbox(label="OpenAI API Key", placeholder="sk-...", type="password"),
        gr.Textbox(label="Prompt", placeholder="Tell me a joke"),
    ],
    outputs="text",
    title="OpenAI Example; V0.0.7",
    description="Enter your OpenAI API key and a prompt like 'Tell me a joke'."
)

if __name__ == "__main__":
    gradio_app.launch()