cryogenic22 commited on
Commit
d65d305
·
verified ·
1 Parent(s): adb6a76

Update learning_platform.py

Browse files
Files changed (1) hide show
  1. learning_platform.py +81 -42
learning_platform.py CHANGED
@@ -119,58 +119,73 @@ Return JSON:
119
  class CourseBuilder:
120
  def __init__(self, api_key: str):
121
  self.api_key = api_key
 
122
  self.embeddings = OpenAIEmbeddings(openai_api_key=api_key)
123
  self.vector_store = FAISS.from_texts(
124
  ["Initial course content"],
125
  embedding=self.embeddings
126
  )
 
127
  self.llm = ChatOpenAI(
128
  temperature=0.7,
129
  model="gpt-4",
130
  openai_api_key=api_key
131
  )
132
  self.prompts = CoursePrompts()
133
- self.setup_graph() # Remove setup_tools() call
134
 
135
- def setup_graph(self):
136
- """Set up the agent workflow graph"""
137
- workflow = StateGraph(CourseState)
138
 
139
- # Add nodes for each agent role
140
- workflow.add_node("planner", self.plan_course)
141
- workflow.add_node("creator", self.create_content)
142
- workflow.add_node("reviewer", self.review_content)
 
 
143
 
144
- # Define edges and conditions
145
- workflow.add_edge("planner", "creator")
146
- workflow.add_conditional_edges(
147
- "creator",
148
- self.should_review,
149
- {
150
- "review": "reviewer",
151
- "complete": END
152
- }
153
  )
154
- workflow.add_edge("reviewer", "creator")
155
 
156
- self.graph = workflow.compile()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  async def create_content(self, state: CourseState) -> CourseState:
159
- """Agent for creating module content using RAG"""
160
  st.session_state.agent_logs.append(f"📝 Creating module {state['current_module'] + 1}...")
161
 
162
  messages = state["messages"]
163
  current_plan = json.loads(messages[-1].content)
164
  current_module = current_plan["modules"][state["current_module"]]
165
 
166
- # Use RAG to find similar content
167
  similar_content = self.vector_store.similarity_search(
168
  current_module["title"],
169
- k=3 # Get top 3 similar documents
170
  )
171
  context = "\n".join([doc.page_content for doc in similar_content])
172
 
173
- # Generate enhanced content using RAG results
174
  prompt = self.prompts.module_content_prompt()
175
  content = await self.llm.apredict(
176
  prompt.format(
@@ -180,13 +195,16 @@ class CourseBuilder:
180
  )
181
  )
182
 
183
- # Add new content to vector store for future RAG
184
  try:
185
  content_json = json.loads(content)
186
  for section in content_json.get("sections", []):
187
  self.vector_store.add_texts(
188
  [section["content"]],
189
- metadatas=[{"title": section["title"], "module": current_module["title"]}]
 
 
 
190
  )
191
  except Exception as e:
192
  st.session_state.agent_logs.append(f"⚠️ Warning: Couldn't index content: {str(e)}")
@@ -199,32 +217,24 @@ class CourseBuilder:
199
  }
200
 
201
  async def review_content(self, state: CourseState) -> CourseState:
202
- """Agent for reviewing and improving content"""
203
  st.session_state.agent_logs.append("🔍 Reviewing content quality...")
204
 
205
  messages = state["messages"]
206
  content = messages[-1].content
207
 
208
- # Use RAG to find similar content for comparison
209
- try:
210
- content_json = json.loads(content)
211
- similar_contents = []
212
- for section in content_json.get("sections", []):
213
- similar = self.vector_store.similarity_search(
214
- section["content"],
215
- k=2
216
- )
217
- similar_contents.extend([doc.page_content for doc in similar])
218
- except Exception as e:
219
- similar_contents = []
220
- st.session_state.agent_logs.append(f"⚠️ Warning: RAG search failed: {str(e)}")
221
-
222
- # Review with context from RAG
223
  prompt = self.prompts.review_prompt()
224
  review = await self.llm.apredict(
225
  prompt.format(
226
  content=content,
227
- similar_content="\n".join(similar_contents)
228
  )
229
  )
230
 
@@ -245,6 +255,35 @@ class CourseBuilder:
245
  "status": "needs_revision"
246
  }
247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  class LearningPlatform:
249
  def __init__(self, api_key: str = None):
250
  self.api_key = api_key or os.getenv("OPENAI_API_KEY")
 
119
  class CourseBuilder:
120
  def __init__(self, api_key: str):
121
  self.api_key = api_key
122
+ # Initialize RAG components
123
  self.embeddings = OpenAIEmbeddings(openai_api_key=api_key)
124
  self.vector_store = FAISS.from_texts(
125
  ["Initial course content"],
126
  embedding=self.embeddings
127
  )
128
+ # Initialize LLM
129
  self.llm = ChatOpenAI(
130
  temperature=0.7,
131
  model="gpt-4",
132
  openai_api_key=api_key
133
  )
134
  self.prompts = CoursePrompts()
135
+ self.setup_graph()
136
 
137
+ async def plan_course(self, state: CourseState) -> CourseState:
138
+ """Planner agent for course structure"""
139
+ st.session_state.agent_logs.append("📋 Planning course structure...")
140
 
141
+ # Use RAG to find similar course structures
142
+ similar_courses = self.vector_store.similarity_search(
143
+ f"{state['topic']} {state['difficulty']} course",
144
+ k=2
145
+ )
146
+ context = "\n".join([doc.page_content for doc in similar_courses])
147
 
148
+ prompt = self.prompts.course_planning_prompt()
149
+ response = await self.llm.apredict(
150
+ prompt.format(
151
+ topic=state["topic"],
152
+ difficulty=state["difficulty"],
153
+ context=context
154
+ )
 
 
155
  )
 
156
 
157
+ # Index the course plan for future reference
158
+ try:
159
+ course_plan = json.loads(response)
160
+ self.vector_store.add_texts(
161
+ [json.dumps(course_plan)],
162
+ metadatas=[{"type": "course_plan", "topic": state["topic"]}]
163
+ )
164
+ except Exception as e:
165
+ st.session_state.agent_logs.append(f"⚠️ Warning: Couldn't index course plan: {str(e)}")
166
+
167
+ st.session_state.agent_logs.append("✅ Course structure planned")
168
+ return {
169
+ **state,
170
+ "messages": [AIMessage(content=response)],
171
+ "status": "planning_complete"
172
+ }
173
 
174
  async def create_content(self, state: CourseState) -> CourseState:
175
+ """Content creator agent using RAG"""
176
  st.session_state.agent_logs.append(f"📝 Creating module {state['current_module'] + 1}...")
177
 
178
  messages = state["messages"]
179
  current_plan = json.loads(messages[-1].content)
180
  current_module = current_plan["modules"][state["current_module"]]
181
 
182
+ # Use RAG for content enhancement
183
  similar_content = self.vector_store.similarity_search(
184
  current_module["title"],
185
+ k=3
186
  )
187
  context = "\n".join([doc.page_content for doc in similar_content])
188
 
 
189
  prompt = self.prompts.module_content_prompt()
190
  content = await self.llm.apredict(
191
  prompt.format(
 
195
  )
196
  )
197
 
198
+ # Index new content
199
  try:
200
  content_json = json.loads(content)
201
  for section in content_json.get("sections", []):
202
  self.vector_store.add_texts(
203
  [section["content"]],
204
+ metadatas=[{
205
+ "type": "module_content",
206
+ "module": current_module["title"]
207
+ }]
208
  )
209
  except Exception as e:
210
  st.session_state.agent_logs.append(f"⚠️ Warning: Couldn't index content: {str(e)}")
 
217
  }
218
 
219
  async def review_content(self, state: CourseState) -> CourseState:
220
+ """Content reviewer agent with RAG"""
221
  st.session_state.agent_logs.append("🔍 Reviewing content quality...")
222
 
223
  messages = state["messages"]
224
  content = messages[-1].content
225
 
226
+ # Use RAG for content review
227
+ similar_contents = self.vector_store.similarity_search(
228
+ content,
229
+ k=2
230
+ )
231
+ context = "\n".join([doc.page_content for doc in similar_contents])
232
+
 
 
 
 
 
 
 
 
233
  prompt = self.prompts.review_prompt()
234
  review = await self.llm.apredict(
235
  prompt.format(
236
  content=content,
237
+ context=context
238
  )
239
  )
240
 
 
255
  "status": "needs_revision"
256
  }
257
 
258
+ def should_review(self, state: CourseState) -> Literal["review", "complete"]:
259
+ """Decision node for content review"""
260
+ if "needs_review" in state["messages"][-1].content.lower():
261
+ return "review"
262
+ return "complete"
263
+
264
+ def setup_graph(self):
265
+ """Set up the agent workflow graph"""
266
+ workflow = StateGraph(CourseState)
267
+
268
+ # Add agent nodes
269
+ workflow.add_node("planner", self.plan_course)
270
+ workflow.add_node("creator", self.create_content)
271
+ workflow.add_node("reviewer", self.review_content)
272
+
273
+ # Define workflow
274
+ workflow.add_edge("planner", "creator")
275
+ workflow.add_conditional_edges(
276
+ "creator",
277
+ self.should_review,
278
+ {
279
+ "review": "reviewer",
280
+ "complete": END
281
+ }
282
+ )
283
+ workflow.add_edge("reviewer", "creator")
284
+
285
+ self.graph = workflow.compile()
286
+
287
  class LearningPlatform:
288
  def __init__(self, api_key: str = None):
289
  self.api_key = api_key or os.getenv("OPENAI_API_KEY")