File size: 5,617 Bytes
01561b2
8dfe0d1
d528d5e
01561b2
 
 
9c95c37
 
d65790b
80fcc20
 
 
 
 
 
 
 
 
 
bb69e55
01561b2
7a51495
 
 
 
 
bb69e55
 
 
 
 
 
 
277e39f
bb69e55
 
 
8e69660
bb69e55
 
 
01561b2
a640174
bb69e55
 
 
f0b58d7
d65790b
f0b58d7
 
 
b8d133e
6d07543
bb69e55
c43aa42
80fcc20
6d07543
 
bb69e55
37d4fdf
80fcc20
 
a1cef55
37d4fdf
80fcc20
c43aa42
d65790b
7a51495
37d4fdf
 
c43aa42
80fcc20
37d4fdf
 
d175fc5
80fcc20
 
01561b2
80fcc20
c43aa42
278419b
80fcc20
01561b2
b8d133e
671111d
278419b
c43aa42
278419b
 
671111d
 
b8d133e
80fcc20
 
 
 
01561b2
b8d133e
80fcc20
01561b2
80fcc20
a6e96e2
d65790b
bb69e55
01561b2
b8d133e
01561b2
b8d133e
c43aa42
b8d133e
 
 
 
 
c43aa42
b8d133e
 
 
 
 
c43aa42
b8d133e
 
 
80fcc20
a39afe6
b8d133e
 
01561b2
80fcc20
dfaa012
d65790b
7b8f2a8
0b62430
 
 
 
 
 
 
 
 
 
49776fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import streamlit as st
from graph import EssayWriter, RouteQuery, GraphState
from crew import *
import os
import base64

#st.title("Multi-Agent Essay Writing Assistant")
st.set_page_config(page_title="Multi-Agent Essay Writing Assistant", page_icon="🤖🤖🤖✍️", layout = "centered")

# 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* This app uses the 'gpt-4o-mini-2024-07-18' model."
        "\n\n* 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=400,
        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:
        if st.session_state["app"] is not None:
            return st.session_state["app"]  # Prevent re-initialization
        
        essay_writer = EssayWriter().graph
        st.session_state["chat_active"] = False

        # Success message
        #st.success("✅ Agents successfully initialized!")
        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:
        st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
        return {"response": "Error: Agents not initialized."}

    return app.invoke(input={"topic": topic, "length": length})

# Display chat messages from the session
if "messages" in st.session_state:
    for message in st.session_state["messages"]:
        with st.chat_message(message["role"]):
            st.markdown(message["content"], unsafe_allow_html=True)

# Handle user input
if topic := st.chat_input(placeholder="📝 Ask a question or provide an essay topic...", disabled=st.session_state["chat_active"]):
    st.chat_message("user").markdown(topic)
    st.session_state["messages"].append({"role": "user", "content": topic})

    with st.spinner("⏳ Generating your essay..."):
        response = generate_response(topic, essay_length)  

    # Handle the assistant's response
    with st.chat_message("assistant"):
        if "essay" in response:  # Display essay preview and download link
            st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
            st.markdown(f"#### {response['essay']['header']}")
            st.markdown(response["essay"]["entry"])
            for para in response["essay"]["paragraphs"]:
                st.markdown(f"**{para['sub_header']}**")
                st.markdown(para["paragraph"])
            st.markdown("**🖊️ Conclusion:**")
            st.markdown(response["essay"]["conclusion"])

            # Provide download link for the PDF
            with open(response["pdf_name"], "rb") as pdf_file:
                b64 = base64.b64encode(pdf_file.read()).decode()
                href = f"<a href='data:application/octet-stream;base64,{b64}' download='{response['pdf_name']}'>📄 Click here to download the PDF</a>"
                st.markdown(href, unsafe_allow_html=True)

            # Save the assistant's message to session state
            st.session_state["messages"].append(
                {"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
            )
        else:  # For other responses (e.g., general answers)
            st.markdown(response["response"])
            st.session_state["messages"].append({"role": "assistant", "content": response["response"]})

# Acknowledgment Section
st.markdown(
    """
    <div style="text-align: center; font-size: 14px; color: #555; padding-top: 250px; margin-top: 250px;">
        <strong>Acknowledgment:</strong> This app is based on Mesut Duman's work: 
        <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main" 
           target="_blank" style="color: #007BFF; text-decoration: none;">
           CrewAI Essay Writer
        </a>
    </div>
    """,
    unsafe_allow_html=True,
    )