asad231 commited on
Commit
492eb9f
·
verified ·
1 Parent(s): 535a18c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -36
app.py CHANGED
@@ -1,39 +1,41 @@
1
- import streamlit as st
2
  import openai
3
  import os
4
 
5
- # Set API key from environment variable
6
- api_key = os.getenv("OPENAI_API_KEY")
7
-
8
- st.set_page_config(page_title="AI Calculator", page_icon="🧮")
9
-
10
- st.title("🧠 AI Math Calculator")
11
- st.write("Enter two numbers and choose an operation:")
12
-
13
- if not api_key:
14
- st.error("Please add your OpenAI API key in the Hugging Face secrets as OPENAI_API_KEY")
15
- else:
16
- openai.api_key = api_key
17
-
18
- num1 = st.number_input("Enter first number", format="%.2f")
19
- num2 = st.number_input("Enter second number", format="%.2f")
20
- operation = st.selectbox("Choose operation", ["add", "subtract", "multiply", "divide"])
21
-
22
- if st.button("Calculate"):
23
- prompt = f"""You are a smart calculator. Perform the operation between two numbers and return the result.
24
-
25
- Input: {num1}, {num2}, {operation}
26
- Output:"""
27
-
28
- try:
29
- response = openai.Completion.create(
30
- engine="text-davinci-003",
31
- prompt=prompt,
32
- temperature=0,
33
- max_tokens=50
34
- )
35
-
36
- result = response.choices[0].text.strip()
37
- st.success(f"Result: {result}")
38
- except Exception as e:
39
- st.error(f"Error from OpenAI: {str(e)}")
 
 
 
1
+ import gradio as gr
2
  import openai
3
  import os
4
 
5
+ # Get OpenAI API key from environment
6
+ openai.api_key = os.getenv("OPENAI_API_KEY")
7
+
8
+ def ai_calculator(num1, num2, operation):
9
+ if not openai.api_key:
10
+ return " OpenAI API key not set."
11
+
12
+ prompt = f"""You are a smart calculator. Perform the following operation:
13
+ Input: {num1}, {num2}, {operation}
14
+ Output:"""
15
+
16
+ try:
17
+ response = openai.Completion.create(
18
+ engine="text-davinci-003",
19
+ prompt=prompt,
20
+ temperature=0,
21
+ max_tokens=50,
22
+ )
23
+ result = response.choices[0].text.strip()
24
+ return f"✅ Result: {result}"
25
+ except Exception as e:
26
+ return f"❌ Error: {str(e)}"
27
+
28
+ demo = gr.Interface(
29
+ fn=ai_calculator,
30
+ inputs=[
31
+ gr.Number(label="Enter First Number"),
32
+ gr.Number(label="Enter Second Number"),
33
+ gr.Radio(["add", "subtract", "multiply", "divide"], label="Operation"),
34
+ ],
35
+ outputs="text",
36
+ title="🧠 AI Calculator",
37
+ description="A simple calculator using OpenAI GPT. Choose numbers and operation to get result.",
38
+ )
39
+
40
+ if __name__ == "__main__":
41
+ demo.launch()