Dua Rajper commited on
Commit
f2d0e2c
·
verified ·
1 Parent(s): a33ceb6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -0
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from openai import OpenAI
4
+ from dotenv import load_dotenv
5
+
6
+ # Load environment variables from .env file
7
+ load_dotenv()
8
+
9
+ # Retrieve API key from environment variables
10
+ api_key = os.getenv("OPENAI_API_KEY")
11
+
12
+ # Ensure the API key is available
13
+ if not api_key:
14
+ raise ValueError("API key not found. Please set OPENAI_API_KEY in your .env file.")
15
+
16
+ # Initialize OpenAI client
17
+ client = OpenAI(api_key=api_key)
18
+
19
+ # Define chatbot function
20
+ def chatbot(prompt):
21
+ try:
22
+ response = client.chat.completions.create(
23
+ model="gpt-4o",
24
+ messages=[
25
+ {"role": "system", "content": "You are a helpful assistant."},
26
+ {"role": "user", "content": prompt},
27
+ ]
28
+ )
29
+ return response.choices[0].message.content
30
+ except Exception as e:
31
+ return f"Error: {str(e)}"
32
+
33
+ # Create Gradio interface
34
+ iface = gr.Interface(
35
+ fn=chatbot,
36
+ inputs=gr.Textbox(lines=2, placeholder="Ask me anything..."),
37
+ outputs="text",
38
+ title="AI Chatbot",
39
+ description="Chat with AI using OpenAI GPT-4o",
40
+ theme="compact",
41
+ )
42
+
43
+ # Launch Gradio app
44
+ if __name__ == "__main__":
45
+ iface.launch()