Tonic commited on
Commit
b19cc72
·
1 Parent(s): 8d9a2e1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+
4
+
5
+ # Load environment variables from .env file
6
+ load_dotenv()
7
+
8
+ # Set your OpenAI API key
9
+ openai.api_key = os.getenv('OPENAI_API_KEY')
10
+
11
+ assistant_id=os.getenv('ASSISTANT_ID')
12
+
13
+ # Initialize OpenAI client
14
+ client = openai.OpenAI(api_key=openai.api_key)
15
+
16
+ # Function to interact with OpenAI Assistant
17
+ def ask_openai(question):
18
+ # Step 2: Create a Thread
19
+ thread = client.beta.threads.create()
20
+
21
+ # Step 3: Add a Message to a Thread
22
+ client.beta.threads.messages.create(
23
+ thread_id=thread.id,
24
+ role="user",
25
+ content=question
26
+ )
27
+
28
+ # Step 4: Run the Assistant
29
+ run = client.beta.threads.runs.create(
30
+ thread_id=thread.id,
31
+ )
32
+
33
+ # Step 5: Check the Run status
34
+ run = client.beta.threads.runs.retrieve(
35
+ thread_id=thread.id,
36
+ run_id=run.id
37
+ )
38
+
39
+ # Step 6: Display the Assistant's Response
40
+ messages = client.beta.threads.messages.list(
41
+ thread_id=thread.id
42
+ )
43
+
44
+ # Extracting the assistant's response
45
+ response = next((msg for msg in messages['data'] if msg['role'] == 'assistant'), None)
46
+ return response['content'][0]['text']['value'] if response else "No response."
47
+
48
+ # Create Gradio Interface
49
+ iface = gr.Interface(
50
+ fn=ask_openai,
51
+ inputs=gr.inputs.Textbox(lines=2, placeholder="Ask a question..."),
52
+ outputs="text",
53
+ title="OpenAI Assistant",
54
+ description="Ask any question to the OpenAI Assistant!"
55
+ )
56
+
57
+ # Run the Gradio app
58
+ iface.launch()