import gradio as gr import os import requests from langchain.prompts import PromptTemplate from langchain_openai import ChatOpenAI from langchain.schema import HumanMessage from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail secretcode = os.environ["SECRETCODE"] # Replace with your verified sender email from_email = os.environ["PLP_RETURN_EMAIL_ADDRESS"] # Initialize the OpenAI model llm = ChatOpenAI(model="gpt-4o", temperature=.4) # Define a reusable prompt template using LangChain template = """ Turn these questions and answers into a five-paragraph (six-sentences equals one paragraph) essay about my approach to leadership. Please be sure to include summaries of all questions that have been answered. Please write the essay in the first person, using a conversational and engaging style, as if talking with a friend. Use simple, relatable language and avoid formalities. If needed, add a little content to add texture and depth to answers as long as it aligns with the research on effective leadership. Questions and Answers: 1. Treating others with dignity and respect is critical. I strive to accomplish this by: {q1} 2. A few of my core values are: {q2} 3. I believe in continuous learning. Here’s how I stay committed to my development: {q3} 4. When I’m at my best, I: {q4} 5. Under stress, you may notice that I: {q5} 6. I gain energy and inspiration from: {q6} 7. A personal motto or philosophy I live by is: {q7} 8. My favorite quote about leadership is ___ because of ____ : {q8} 9. Others have described my leadership or management style as: {q9} 10. People who work for me are most successful when they: {q10} 11. People sometimes perceive me as: {q11} 12. To gain my trust and respect, you should: {q12} 13. You have my full permission to: {q13} 14. “Hot-button” behaviors that frustrate me include: {q14} 15. Here’s how I like to give and receive feedback: {q15} 16. If we encounter a disagreement, I prefer to resolve it by: {q16} 17. Three things you should know about our department’s culture are: {q17} 18. Three things that define the culture of our organization include: {q18} 19. I love our work because we: {q19} 20. The type of environment we strive to create for our team is: {q20} 21. Key principles or practices that make our department unique are: {q21} 22. Our team’s mission and what it means to us day-to-day is: {q22} 23. The kind of reputation we aim to build as a department/organization is: {q23} 24. We define success in our department by: {q24} """ # Create a LangChain prompt template object prompt = PromptTemplate( input_variables=["q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15", "q16", "q17", "q18", "q19", "q20", "q21", "q22", "q23", "q24"], template=template, ) def send_sendgrid_email(essay, email): print(from_email) message = Mail( from_email=from_email, to_emails=email, subject='Personal Leadership Profile Results', plain_text_content=essay) try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) return "Email Sent" except Exception as e: print(e) return "Email Failed" # Add an alert box to notify the user if the email was sent correctly def show_alert(result): gr.Info(result) # Function to generate the essay using the template and answers def stream_leadership_essay(*answers): # Check if the email is valid if "@" not in answers[28]: yield "Invalid email address. Please enter a valid email address." return if (answers[29] != secretcode): yield "Invalid secret code. Please try again." return # Format the prompt with the answers # Ensure at least 10 properties are filled, but only the ones that are textboxes filled_answers = [answer for i, answer in enumerate(answers[:27]) if isinstance(inputs[i], gr.Textbox) and answer.strip() != ""] if len(filled_answers) < 10: yield "Please complete at least 10 questions with a minimum of two sentences for each answer." return filled_prompt = prompt.format( q1=answers[1], q2=answers[2], q3=answers[3], q4=answers[4], q5=answers[5], q6=answers[6], q7=answers[7], q8=answers[8], q9=answers[10], q10=answers[11],q11=answers[12], q12=answers[13], q13=answers[14], q14=answers[15], q15=answers[16], q16=answers[17], q17=answers[19], q18=answers[20], q19=answers[21], q20=answers[22], q21=answers[23], q22=answers[24], q23=answers[25], q24=answers[26] ) # Send the prompt as a HumanMessage and stream the response response_stream = llm.stream([HumanMessage(content=filled_prompt)]) # Yield the content chunk-by-chunk essay = "" for chunk in response_stream: essay += chunk.content #yield essay, filled_prompt # Yield partial essay to the Gradio output in real-time yield essay essay = essay + "\n\n -- Prompt & Questions Below -- \n\n" + filled_prompt result = send_sendgrid_email(essay, answers[28]) print(result) show_alert(result) css = """ html, body, gradio-app { background-color: #55c9e8 !important; margin: 0; padding: 0; font-family: 'Arial', sans-serif; } gradio-app label { color: blue !important; /* Change label text color to blue */ font-weight: bold; /* Make it bold (optional) */ font-size: 16px; /* Adjust size (optional) */ } .block { background-color: #0167a3; padding: 10px; color:red } .block textarea { background-color: #ffffff color: black; } .md h1 { color:white !important; } .md p { color:white !important; } .md p strong { color:white !important; } .svelte-1gfkn6j { color: white; !important; } .md h3 { color:white !important; } #sjaicon { background-color: white; padding: 10px; border-radius: 5px; } #header { background-color: #0167a3; padding: 20px; border-radius: 5px; color:white } #content { padding: 10px; } """ # Define the Gradio interface (form layout) with gr.Blocks( theme=gr.themes.Base(), css=css, ) as demo: gr.Image("sjaicon.png", elem_id="sjaicon", show_fullscreen_button=False, show_download_button=False, show_label=False), gr.Markdown("# Personal Leadership Profile", elem_id="header") gr.Markdown(""" According to 40 years of research by Kouzes and Posner, the most influential leaders have a clear Personal Leadership Philosophy (PLP) and communicate it frequently. Like a great coach, you have an explicit philosophy or approach to work that is clearly communicated to others. Whether you’re a seasoned leader or just getting started in a leadership role, a PLP will allow you to articulate your values, goals, and the type of leader you aspire to be. The result is a strategic tool to help you improve your culture. **Please choose TEN or more of the following questions to answer. Please provide a minimum of two sentences for each answer.** Based on your answers, we will build a “draft” for you to revise, build upon, and use as a roadmap. Thank you for completing the PLP questions - It will be a cornerstone of your continued growth and development. """, elem_id="content") with gr.Group(): inputs = [ gr.Markdown("### About Me:", elem_id="header"), gr.Textbox(label="Treating others with dignity and respect is critical. I strive to accomplish this by...",), gr.Textbox(label="A few of my core values are..."), gr.Textbox(label="I believe in continuous learning. Here’s how I stay committed to my development..."), gr.Textbox(label="When I’m at my best, I..."), gr.Textbox(label="Under stress, you may notice that I..."), gr.Textbox(label="I gain energy and inspiration from..."), gr.Textbox(label="A personal motto or philosophy I live by is..."), gr.Textbox(label="My favorite quote about leadership is ______ because _______"), ] with gr.Group(): inputs += [ gr.Markdown("### About Working With Me:", elem_id="header"), gr.Textbox(label="Others have described my leadership or management style as..."), gr.Textbox(label="People who work for me are most successful when they..."), gr.Textbox(label="People sometimes perceive me as..."), gr.Textbox(label="To gain my trust and respect, you should..."), gr.Textbox(label="You have my full permission to..."), gr.Textbox(label="\"Hot-button\" behaviors that frustrate me include..."), gr.Textbox(label="Here’s how I like to give and receive feedback..."), gr.Textbox(label="If we encounter a disagreement, I prefer to resolve it by..."), ] with gr.Group(): inputs += [ gr.Markdown("### About Our Department/Organization:", elem_id="header"), gr.Textbox(label="Three things you should know about our department’s culture are..."), gr.Textbox(label="Three things that define the culture of our organization include..."), gr.Textbox(label="I love our work because we..."), gr.Textbox(label="The type of environment we strive to create for our team is..."), gr.Textbox(label="Key principles or practices that make our department unique are..."), gr.Textbox(label="Our team’s mission and what it means to us day-to-day is..."), gr.Textbox(label="The kind of reputation we aim to build as a department/organization is..."), gr.Textbox(label="We define success in our department by..."), ] with gr.Group(): inputs += [ gr.Markdown("### Validation Input:", elem_id="header"), gr.Textbox(label="We will email you a copy of your PLP. Please enter your address below."), gr.Textbox(label="Enter the password to generate your PLP.") ] gr.Markdown("### I acknowledge that this is for learning purposes only.", elem_id="header") submit_button = gr.Button("Submit") # Output area for the response summary output = gr.Textbox(label="Your generated Personal Leadership Profile", lines=10, elem_id="header") #prompt_template = gr.Textbox(label="This is the prompt that was sent to ChatGPT", lines=10) # Link the submit button with the function submit_button.click( stream_leadership_essay, inputs=inputs, #outputs=[output, prompt_template] outputs=output ) # Launch the Gradio app demo.launch() # Automated testing function """ def test_form_submission(): mock_data = [ "I treat others with dignity and respect by listening to their concerns.", "My core values are integrity, honesty, and empathy.", "I stay committed to my development by reading books and attending workshops.", "When I’m at my best, I am focused and productive.", "Under stress, you may notice that I become quiet and introspective.", "I gain energy and inspiration from nature and music.", "A personal motto I live by is 'Never give up.'", "My favorite quote about leadership is 'Leadership is not about being in charge. It is about taking care of those in your charge.' because it emphasizes the importance of caring for others.", "Others have described my leadership style as supportive and empowering.", "People who work for me are most successful when they are proactive and communicative.", "People sometimes perceive me as reserved and thoughtful.", "To gain my trust and respect, you should be honest and reliable.", "You have my full permission to provide constructive feedback.", "Hot-button behaviors that frustrate me include dishonesty and lack of accountability.", "Here’s how I like to give and receive feedback: I prefer direct and constructive feedback.", "If we encounter a disagreement, I prefer to resolve it by having an open and honest conversation.", "Three things you should know about our department’s culture are...", "Three things that define the culture of our organization include...", "I love our work because we...", "The type of environment we strive to create for our team is...", "Key principles or practices that make our department unique are...", "Our team’s mission and what it means to us day-to-day is...", "The kind of reputation we aim to build as a department/organization is...", "We define success in our department by...", "PLP" ] # Simulate form submission result_generator = stream_leadership_essay(*mock_data) for result in result_generator: print(result) # Run the test test_form_submission() """