File size: 2,399 Bytes
d7697ac
 
67164b3
694caf5
48c7413
d7697ac
 
 
 
 
 
 
7a67fb8
 
d62df08
7a67fb8
 
 
 
 
d62df08
7a67fb8
 
 
 
 
 
3309025
7a67fb8
 
 
 
 
 
 
 
 
 
d62df08
7a67fb8
 
 
 
d62df08
7a67fb8
d62df08
7a67fb8
d62df08
 
 
 
 
 
 
 
 
 
7a67fb8
 
 
d62df08
 
d7697ac
 
 
 
 
 
 
 
d5140c7
db4a355
3109f0f
 
95986fb
d7697ac
 
890f2c9
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import gradio as gr
import openai
from dotenv import load_dotenv
import os
import time

load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
assistant_id=os.getenv('ASSISTANT_ID')
client = openai.OpenAI(api_key=openai.api_key)

def ask_openai(question):
    try:
        thread = client.beta.threads.create()

        client.beta.threads.messages.create(
            thread_id=thread.id,
            role="user",
            content=question,
        )

        run = client.beta.threads.runs.create(
            thread_id=thread.id,
            assistant_id=assistant_id
        )

        response_received = False
        timeout = 150
        start_time = time.time()

        while not response_received and time.time() - start_time < timeout:
            run_status = client.beta.threads.runs.retrieve(
                thread_id=thread.id,
                run_id=run.id,
            )
            if run_status.status == 'completed':
                response_received = True
            else:
                time.sleep(4)  

        if not response_received:
            return "Response timed out."

        steps = client.beta.threads.runs.steps.list(
            thread_id=thread.id,
            run_id=run.id
        )

        if steps.data:
            last_step = steps.data[-1]
            if last_step.type == 'message_creation':
                message_id = last_step.step_details.message_creation.message_id
                message = client.beta.threads.messages.retrieve(
                    thread_id=thread.id,
                    message_id=message_id
                )
                return message.content[0]['text']['value']

        return "No response."
    except Exception as e:
        return f"An error occurred: {str(e)}"  

examples = [
    ["My Eucalyptus tree is struggling outside in the cold weather in europe"],
    ["My callatea house plant is yellowing."],
    ["We have a catcus as work that suddently started yellowing and wilting."]
]

iface = gr.Interface(
    fn=ask_openai,
    inputs=gr.Textbox(lines=5, placeholder="Hi there, I have a plant that's..."),
    outputs=gr.Markdown(),
    title="Wecome to Tonic's Bulbi Plant Doctor",
    description="""Introduce your plant below. Be as descriptive as possible. Respond with additional information when prompted. Save your plants with Bulbi Plant Doctor""",
    examples=examples
)

iface.launch()