import streamlit as st from graph import EssayWriter, RouteQuery, GraphState from crew import * import os import traceback import base64 # Install Graphviz if not found if os.system("which dot") != 0: os.system("apt-get update && apt-get install -y graphviz") st.markdown( """

Multi-Agent Essay Writing Assistant

""", unsafe_allow_html=True ) # Ensure session state variables are initialized properly if "messages" not in st.session_state: st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}] if "app" not in st.session_state: st.session_state["app"] = None if "chat_active" not in st.session_state: st.session_state["chat_active"] = True # Sidebar with essay settings and user-defined length with st.sidebar: st.subheader("About:") st.info( "\n\n 1. This app uses the 'gpt-4o-mini-2024-07-18' model." "\n\n 2. Writing essays may take some time, approximately 1-2 minutes." ) # API Key Retrieval openai_key = st.secrets.get("OPENAI_API_KEY", "") st.divider() # User-defined essay length selection st.subheader("๐Ÿ“ Configure Essay Settings:") essay_length = st.number_input( "Select Essay Length (words):", min_value=150, max_value=500, value=250, step=50 ) st.divider() # Reference section st.subheader("๐Ÿ“– References:") st.markdown( "[1. Multi-Agent System with CrewAI and LangChain](https://discuss.streamlit.io/t/new-project-i-have-build-a-multi-agent-system-with-crewai-and-langchain/84002)", unsafe_allow_html=True ) # Initialize agents function def initialize_agents(): if not openai_key: st.error("โš ๏ธ OpenAI API key is missing! Please provide a valid key through Hugging Face Secrets.") st.session_state["chat_active"] = True return None os.environ["OPENAI_API_KEY"] = openai_key try: # Prevent re-initialization if "app" in st.session_state and st.session_state["app"] is not None: return st.session_state["app"] # Initialize the full EssayWriter instance essay_writer = EssayWriter() # Store the full instance st.session_state["app"] = essay_writer # Now contains `graph` st.session_state["chat_active"] = False # Enable chat after successful initialization return essay_writer except Exception as e: st.error(f"โŒ Error initializing agents: {e}") st.session_state["chat_active"] = True return None # Automatically initialize agents on app load if st.session_state["app"] is None: st.session_state["app"] = initialize_agents() if st.session_state["app"] is None: st.error("โš ๏ธ Failed to initialize agents. Please check your API key and restart the app.") app = st.session_state["app"] # Function to invoke the agent and generate a response def generate_response(topic, length): if not app or not hasattr(app, "graph"): st.error("โš ๏ธ Agents are not initialized. Please check the system or restart the app.") return {"response": "Error: Agents not initialized."} # Refined prompt for better essay generation refined_prompt = f""" Write a well-structured, engaging, and informative essay on "{topic}". The essay should be approximately {length} words and follow this structured format: ## 1. Title - Generate a compelling, creative, and relevant title that encapsulates the theme of the essay. ## 2. Introduction (100-150 words) - Clearly define the topic and its importance in the broader context. - Provide a strong **thesis statement** that outlines the essayโ€™s key argument. - Briefly mention the **key themes** that will be explored in the body. - Engage the reader with a thought-provoking fact, quote, or question. ## 3. Main Body (Ensure clear organization and logical transitions) Each section should: - **Have a distinct, engaging subheading**. - **Begin with a topic sentence** introducing the sectionโ€™s main idea. - **Include real-world examples, historical references, or statistical data**. - **Maintain smooth transitions** between sections for cohesive reading. ### Suggested Sections (Modify as Needed) - **Historical Context**: Trace the origins and evolution of the topic over time. - **Key Aspects**: Break down essential components (e.g., cultural, political, economic influences). - **Modern Challenges & Debates**: Discuss **contemporary issues** and **conflicting viewpoints**. - **Impact & Future Trends**: Examine how the topic influences the present and future. ## 4. Conclusion (100-150 words) - Concisely summarize key insights and arguments. - Reinforce the essayโ€™s thesis in light of the discussion. - End with a **thought-provoking final statement**, such as: - A **rhetorical question**. - A **call to action**. - A **broader reflection** on the topicโ€™s long-term significance. ## 5. Writing & Formatting Guidelines - Maintain **formal, engaging, and precise** language. - Ensure **clear paragraph structure and logical progression**. - Avoid redundancy; keep insights sharp and impactful. - Use **examples, expert opinions, or historical events** to strengthen arguments. - Provide **citations or references** when possible. """ response = app.graph.invoke(input={"topic": topic, "length": length, "prompt": refined_prompt}) return response # Define Tabs tab1, tab2 = st.tabs(["๐Ÿ“œ Essay Generation", "๐Ÿ“Š Workflow Viz"]) # ๐Ÿ“œ Tab 1: Essay Generation with tab1: # Display chat messages from the session if "messages" not in st.session_state: st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}] for message in st.session_state["messages"]: with st.chat_message(message["role"]): st.markdown(message["content"], unsafe_allow_html=True) # Use text_input to allow a default value, but do not trigger generation immediately topic = st.text_input("๐Ÿ“ Provide an essay topic:", value="Write an essay on the cultural diversity of India") # Add a button to trigger essay generation if st.button("Generate Essay"): if topic: # Store user message in the chat st.chat_message("user").markdown(topic) st.session_state["messages"].append({"role": "user", "content": topic}) with st.spinner("โณ Generating your essay..."): response = None if app: response = app.write_essay({"topic": topic}) else: st.error("โš ๏ธ Agents are not initialized. Please check the system or restart the app.") # Store assistant response and display it with st.chat_message("assistant"): if response and "essay" in response: # Display essay preview and allow editing essay = response["essay"] # Store response in session state assistant_response = f"Here is your {essay_length}-word essay preview and the download link." st.session_state["messages"].append({"role": "assistant", "content": assistant_response}) # Create Two-Column Layout col1, col2 = st.columns(2) with col1: st.markdown(f"### ๐Ÿ“ Essay Preview ({essay_length} words)") st.markdown(f"#### {essay['header']}") st.markdown(essay["entry"]) for para in essay["paragraphs"]: st.markdown(f"**{para['sub_header']}**") st.markdown(para["paragraph"]) st.markdown("**๐Ÿ–Š๏ธ Conclusion:**") st.markdown(essay["conclusion"]) with col2: st.markdown("### โœ๏ธ Edit Your Essay:") # Combine all parts of the essay into one editable text field full_essay_text = f"## {essay['header']}\n\n{essay['entry']}\n\n" for para in essay["paragraphs"]: full_essay_text += f"### {para['sub_header']}\n{para['paragraph']}\n\n" full_essay_text += f"**Conclusion:**\n{essay['conclusion']}" # Editable text area for the user edited_essay = st.text_area("Edit Here:", value=full_essay_text, height=300) # Save and Download buttons save_col1, save_col2 = st.columns(2) with save_col1: if st.button("๐Ÿ’พ Save as TXT"): with open("edited_essay.txt", "w", encoding="utf-8") as file: file.write(edited_essay) with open("edited_essay.txt", "rb") as file: st.download_button(label="โฌ‡๏ธ Download TXT", data=file, file_name="edited_essay.txt", mime="text/plain") with save_col2: if st.button("๐Ÿ“„ Save as PDF"): from fpdf import FPDF pdf = FPDF() pdf.set_auto_page_break(auto=True, margin=15) pdf.add_page() pdf.set_font("Arial", size=12) for line in edited_essay.split("\n"): pdf.cell(200, 10, txt=line, ln=True, align='L') pdf.output("edited_essay.pdf") with open("edited_essay.pdf", "rb") as file: st.download_button(label="โฌ‡๏ธ Download PDF", data=file, file_name="edited_essay.pdf", mime="application/pdf") # Provide download link for the original PDF pdf_name = response.get("pdf_name") if pdf_name and os.path.exists(pdf_name): with open(pdf_name, "rb") as pdf_file: b64 = base64.b64encode(pdf_file.read()).decode() href = f"๐Ÿ“„ Click here to download the original PDF" st.markdown(href, unsafe_allow_html=True) # Save response in session state st.session_state["messages"].append( {"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."} ) elif response: st.markdown(response["response"]) st.session_state["messages"].append({"role": "assistant", "content": response["response"]}) else: st.error("โš ๏ธ No response received. Please try again.") # ๐Ÿ“Š Tab 2: Workflow Visualization with tab2: #st.subheader("๐Ÿ“Š Multi-Agent Essay Writer Workflow Viz") try: graph_path = "/tmp/graph.png" if os.path.exists(graph_path): st.image(graph_path, caption="Multi-Agent Essay Writer Workflow Visualization", use_container_width=True) else: st.warning("โš ๏ธ Workflow graph not found. Please run `graph.py` to regenerate `graph.png`.") except Exception as e: st.error("โŒ An error occurred while generating the workflow visualization.") st.text_area("Error Details:", traceback.format_exc(), height=200) # Acknowledgement Section st.markdown( """
Acknowledgement: This app is based on Mesut Duman's work: CrewAI Essay Writer
""", unsafe_allow_html=True, )