DrishtiSharma commited on
Commit
9edc889
·
verified ·
1 Parent(s): 38fafef

Create interim2.py

Browse files
Files changed (1) hide show
  1. lab/interim2.py +143 -0
lab/interim2.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from graph import EssayWriter, RouteQuery, GraphState
3
+ from crew import *
4
+ import os
5
+ import base64
6
+
7
+ st.set_page_config(page_title="Multi-Agent Essay Writer", page_icon="🤖")
8
+
9
+ # Ensure session state variables are initialized properly
10
+ if "messages" not in st.session_state:
11
+ st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
12
+
13
+ if "app" not in st.session_state:
14
+ st.session_state["app"] = None
15
+
16
+ if "chat_active" not in st.session_state:
17
+ st.session_state["chat_active"] = True
18
+
19
+ # Sidebar with essay settings and user-defined length
20
+ with st.sidebar:
21
+ st.subheader("📌 About:")
22
+ st.info("🔹 This app uses the 'gpt-4o-mini-2024-07-18' model.\n"
23
+ "🔹 Writing essays may take approximately 1-2 minutes.")
24
+
25
+ # API Key Retrieval
26
+ openai_key = st.secrets.get("OPENAI_API_KEY", "")
27
+
28
+ st.divider()
29
+
30
+ # User-defined essay length selection
31
+ st.subheader("📝 Essay Settings:")
32
+ essay_length = st.number_input(
33
+ "Select Essay Length (words):",
34
+ min_value=150,
35
+ max_value=350,
36
+ value=250,
37
+ step=50
38
+ )
39
+
40
+ st.divider()
41
+
42
+ # Reference section
43
+ st.subheader("📖 References:")
44
+ st.markdown(
45
+ "[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)",
46
+ unsafe_allow_html=True
47
+ )
48
+
49
+ # Initialize agents function
50
+ def initialize_agents():
51
+ if not openai_key:
52
+ st.error("⚠️ OpenAI API key is missing! Please provide a valid key through Hugging Face Secrets.")
53
+ st.session_state["chat_active"] = True
54
+ return None
55
+
56
+ os.environ["OPENAI_API_KEY"] = openai_key
57
+ try:
58
+ if st.session_state["app"] is not None:
59
+ return st.session_state["app"] # Prevent re-initialization
60
+
61
+ essay_writer = EssayWriter().graph
62
+ st.session_state["chat_active"] = False
63
+
64
+ # Success message
65
+ st.success("✅ Agents successfully initialized!")
66
+ return essay_writer
67
+ except Exception as e:
68
+ st.error(f"❌ Error initializing agents: {e}")
69
+ st.session_state["chat_active"] = True
70
+ return None
71
+
72
+ # Automatically initialize agents on app load
73
+ if st.session_state["app"] is None:
74
+ st.session_state["app"] = initialize_agents()
75
+
76
+ if st.session_state["app"] is None:
77
+ st.error("⚠️ Failed to initialize agents. Please check your API key and restart the app.")
78
+
79
+ app = st.session_state["app"]
80
+
81
+ # Function to invoke the agent and generate a response
82
+ def generate_response(topic, length):
83
+ if not app:
84
+ st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
85
+ return {"response": "Error: Agents not initialized."}
86
+
87
+ return app.invoke(input={"topic": topic, "length": length})
88
+
89
+ # Display chat messages from the session
90
+ if "messages" in st.session_state:
91
+ for message in st.session_state["messages"]:
92
+ with st.chat_message(message["role"]):
93
+ st.markdown(message["content"], unsafe_allow_html=True)
94
+
95
+ # Handle user input
96
+ if topic := st.chat_input(placeholder="📝 Ask a question or provide an essay topic...", disabled=st.session_state["chat_active"]):
97
+ st.chat_message("user").markdown(topic)
98
+ st.session_state["messages"].append({"role": "user", "content": topic})
99
+
100
+ with st.spinner("⏳ Generating your essay..."):
101
+ response = generate_response(topic, essay_length)
102
+
103
+ # Handle the assistant's response
104
+ with st.chat_message("assistant"):
105
+ if "essay" in response: # Display essay preview and download link
106
+ st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
107
+ st.markdown(f"#### {response['essay']['header']}")
108
+ st.markdown(response["essay"]["entry"])
109
+ for para in response["essay"]["paragraphs"]:
110
+ st.markdown(f"**{para['sub_header']}**")
111
+ st.markdown(para["paragraph"])
112
+ st.markdown("**🖊️ Conclusion:**")
113
+ st.markdown(response["essay"]["conclusion"])
114
+
115
+ # Provide download link for the PDF
116
+ with open(response["pdf_name"], "rb") as pdf_file:
117
+ b64 = base64.b64encode(pdf_file.read()).decode()
118
+ href = f"<a href='data:application/octet-stream;base64,{b64}' download='{response['pdf_name']}'>📄 Click here to download the PDF</a>"
119
+ st.markdown(href, unsafe_allow_html=True)
120
+
121
+ # Save the assistant's message to session state
122
+ st.session_state["messages"].append(
123
+ {"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
124
+ )
125
+ else: # For other responses (e.g., general answers)
126
+ st.markdown(response["response"])
127
+ st.session_state["messages"].append({"role": "assistant", "content": response["response"]})
128
+
129
+ # Acknowledgment Section
130
+ st.markdown("---")
131
+ st.markdown("---")
132
+ st.markdown(
133
+ """
134
+ <div style="text-align: center; font-size: 14px; color: #555;">
135
+ <strong>Acknowledgment:</strong> This project is based on Mesut Duman's work:
136
+ <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
137
+ target="_blank" style="color: #007BFF; text-decoration: none;">
138
+ CrewAI Essay Writer
139
+ </a>
140
+ </div>
141
+ """,
142
+ unsafe_allow_html=True,
143
+ )