Tonic's picture
Update app.py
5c2d571
raw
history blame
3.26 kB
import gradio as gr
import openai
from dotenv import load_dotenv
import os
import time
current_thread_id = None
title = "# Welcome to 🙋🏻‍♂️Tonic's🕵🏻‍♂️Bulbi🪴Plant👩🏻‍⚕️Doctor!"
description = """Here you can use Bulbi - an OpenAI agent that helps you save your plants!
OpenAI doesnt let you use Agents without paying for it, so I made you an interface you can use for free !
### How to use:
- Introduce your🌵plant below.
- Be as🌿descriptive as possible.
- **Respond with additional🗣️information when prompted.**
- Save your plants with👨🏻‍⚕️Bulbi Plant Doctor!
### Join us:
[Join my active builders' server on discord](https://discord.gg/VqTxc76K3u). Let's build together!
Big thanks to 🤗Huggingface Organisation for the🫂Community Grant"""
examples = [
["My Eucalyptus tree is struggling outside in the cold weather in Europe"],
["My calathea house plant is yellowing."],
["We have a cactus at work that suddenly started yellowing and wilting."]
]
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):
global current_thread_id
try:
if current_thread_id is None:
thread = client.beta.threads.create()
current_thread_id = thread.id
else:
thread = client.beta.threads.retrieve(thread_id=current_thread_id)
client.beta.threads.messages.create(
thread_id=current_thread_id,
role="user",
content=question,
)
run = client.beta.threads.runs.create(
thread_id=current_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=current_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=current_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=current_thread_id,
message_id=message_id
)
if message.content and message.content[0].type == 'text':
return message.content[0].text.value
return "No response."
except Exception as e:
return f"An error occurred: {str(e)}"
iface = gr.Interface(
title=title,
description=description,
fn=ask_openai,
inputs=gr.Textbox(lines=5, placeholder="Hi there, I have a plant that's..."),
outputs=gr.Markdown(),
examples=examples
)