SyedHasanCronosPMC commited on
Commit
21bbf4f
·
verified ·
1 Parent(s): 1c64850

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -39
app.py CHANGED
@@ -1,43 +1,48 @@
 
 
1
  import gradio as gr
2
- from openai import OpenAI
3
-
4
- def generate_response(user_input):
5
- client = OpenAI()
6
- response = client.responses.create(
7
- model="gpt-4o",
8
- input=[
9
- {
10
- "role": "system",
11
- "content": [
12
- {
13
- "type": "input_text",
14
- "text": user_input
15
- }
16
- ]
17
- }
18
- ],
19
- text={
20
- "format": {
21
- "type": "text"
22
- }
23
- },
24
- reasoning={},
25
- tools=[],
26
- temperature=1,
27
- max_output_tokens=2048,
28
- top_p=1,
29
- store=True
30
- )
31
 
32
- return response.text # Adjust based on OpenAI response format
33
-
34
- # Gradio UI
35
- demo = gr.Interface(
36
- fn=generate_response,
37
- inputs=gr.Textbox(label="Enter your prompt"),
38
- outputs=gr.Textbox(label="Generated Response"),
39
- title="OpenAI GPT-4o Bot Guide Generator",
40
- description="Enter a request, and the bot will generate a response using OpenAI's API."
 
 
41
  )
42
 
43
- demo.launch()
 
 
 
1
+ import os
2
+ import openai
3
  import gradio as gr
4
+
5
+ # Retrieve OpenAI API key from Hugging Face Secrets
6
+ openai_api_key = os.getenv("OPENAI_API_KEY")
7
+
8
+ # Initialize OpenAI client
9
+ client = openai.OpenAI(api_key=openai_api_key)
10
+
11
+ # Chatbot function
12
+ def chatbot(user_input, history=[]):
13
+ if not openai_api_key:
14
+ return "⚠️ API key is missing. Please configure it in Hugging Face Secrets.", history
15
+
16
+ history.append({"role": "user", "content": user_input})
17
+
18
+ try:
19
+ response = client.chat.completions.create(
20
+ model="gpt-4o",
21
+ messages=history,
22
+ temperature=0.7,
23
+ max_tokens=200,
24
+ top_p=1
25
+ )
26
+
27
+ bot_reply = response.choices[0].message.content
28
+ history.append({"role": "assistant", "content": bot_reply})
29
+
30
+ except Exception as e:
31
+ bot_reply = f"❌ Error: {str(e)}"
 
32
 
33
+ return bot_reply, history
34
+
35
+ # Gradio Interface
36
+ chatbot_ui = gr.ChatInterface(
37
+ fn=chatbot,
38
+ title="AI Chatbot",
39
+ description="A simple chatbot powered by GPT-4o.",
40
+ theme="soft",
41
+ retry_btn="🔄 Retry",
42
+ undo_btn="↩️ Undo",
43
+ clear_btn="🗑️ Clear"
44
  )
45
 
46
+ # Launch the app
47
+ if __name__ == "__main__":
48
+ chatbot_ui.launch()