colossal_cave / app.py
Namanj46's picture
Update app.py
313637d verified
import os
import openai
import gradio as gr
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Set your OpenAI API key from environment variable
openai.api_key = os.getenv("OPENAI_API_KEY")
# Retrieve the existing Assistant
assistant_id = "asst_Fps5fdccFdhxF95G6iOAwIdQ"
assistant = openai.beta.assistants.retrieve(assistant_id)
# Initialize the Thread
thread = openai.beta.threads.create()
def chat(message, history):
# Add the user's message to the thread
openai.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content=message
)
# Run the Assistant
run = openai.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id
)
# Wait for the run to complete
while run.status != "completed":
run = openai.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
# Retrieve the assistant's messages
messages = openai.beta.threads.messages.list(thread_id=thread.id)
# Get the last message from the assistant
last_message = next(msg for msg in messages if msg.role == "assistant")
return last_message.content[0].text.value
# Create the Gradio interface
iface = gr.ChatInterface(
fn=chat,
title="Colossal Cave",
description="Ask me anything about Colossal Cave Adventure!"
)
# Launch the interface
iface.launch()