conversation-app / language.py
adamespi's picture
Update language.py
988671f verified
import gradio as gr
import re
import os
from openai import OpenAI
from string import Template
# Initialize the OpenAI client with API key from environment variable
client = OpenAI(api_key="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")
# Initial system message
messages = [
{"role": "system", "content": "You are Dani, a Language Exchange Partner. You are going to have conversations with ESL students who natively speak Spanish. As they respond, prompt them for more conversation and correct mistakes. If their response is non-sensical, ask them to say what they meant to say in their native language so that chatGPT can fine-tune their responses. In addition to your conversational responses, repeat to the student what you understood they said (make this part of your response be in Spanish). This is important: make sure your responses include as much English as possible!"},
]
# Flag for iterating through questions
question_iterating_flag = False
# Initialize an empty iterator for questions
qs_iter = iter([])
# Function to try getting the next question from the iterator
def try_q_iter(qs_iter, messages):
try:
elem = qs_iter.__next__()
return elem, qs_iter
except StopIteration:
print("generating new questions!")
# If no more questions, generate a new set
chat = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
qs = chat.choices[0].message.content
qs_list = list(filter(lambda x: len(re.sub(r"[\n\t\s]*", "", x)) > 0, qs.split("?")))
print(qs_list)
qs_iter = iter(qs_list)
return try_q_iter(qs_iter, messages)
# Function for the chatbot
def hpi_bot(history):
print(history)
if history:
global qs_iter
user_reply = history[-1][0]
messages.append({"role": "user", "content": user_reply})
# If no more questions, generate a new set
chat = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
next_q = chat.choices[0].message.content
messages.append({"role": "assistant", "content": next_q})
history[-1][1] = next_q
return history
# Function to add text to history
def add_text(history, text):
history = history + [(text, None)]
return history, ""
# Function to add a file to history
def add_file(history, file):
history = history + [((file.name,), None)]
return history
# Function to finish the conversation
def finish_fx(final_messages):
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": "You are a proficient AI with a specialty in distilling information into key points. Based on the following text, identify and list the main points that were discussed or brought up. These should be the most important ideas, findings, or topics that are crucial to the essence of the discussion. Your goal is to provide a list that someone could read to quickly understand what was talked about."
},
*messages
],
temperature=0
)
response_content = response.choices[0].message.content
return response_content
# Gradio interface setup
with gr.Blocks() as demo:
gr.Markdown("# Language Exchange Parner App ")
chatbot = gr.Chatbot([(None, "Hi, I'm Dani, your language exchange partner!\n You can practice your English skills with me. Talk to me like a human and ask me questions if you want. Talk to me in English if you can. If you are confused, you can talk to me in Spanish!\n What do you want to talk about? We can talk about anything (your favorite movie, your pet, etc.)\nHola, soy Dani, tu compañero de intercambio de idiomas. Puedes practicar tus habilidades en inglés conmigo. Háblame como si fuera una persona y hazme preguntas si lo deseas. Háblame en inglés si puedes. Si estás confundido, también puedes hablar conmigo en español.\n¿Sobre qué te gustaría hablar? Podemos conversar sobre cualquier cosa (tu película favorita, tu mascota, etc.).")], elem_id="chatbot")
# output = gr.Textbox(label="Output Box")
state = gr.State()
message = gr.Textbox(
scale=8,
show_label=False,
placeholder="Enter text and press enter, or upload an image",
)
# btn = gr.UploadButton("📁", file_types=["image", "video", "audio"])
# with gr.Row():
# btn_done = gr.Button("Summarize Conversation")
# btn_done.click(fn=finish_fx, inputs=chatbot, outputs=output)
submit = gr.Button("Send")
message.submit(add_text, [chatbot, message], [chatbot, message]).then(
hpi_bot, chatbot, chatbot
)
# btn.upload(add_file, [chatbot, btn], [chatbot]).then(
# hpi_bot, chatbot, chatbot
# )
if __name__ == "__main__":
demo.launch(share=True, auth=[("admin", "JohnnieFarris123"), ("student", "password1234!")])