cryogenic22 commited on
Commit
0722d11
·
verified ·
1 Parent(s): 804b8a9

Update multi_agent_book_workflow.py

Browse files
Files changed (1) hide show
  1. multi_agent_book_workflow.py +122 -64
multi_agent_book_workflow.py CHANGED
@@ -8,6 +8,7 @@ from typing import Dict, List, Any
8
  import uuid
9
  import chromadb
10
  import numpy as np
 
11
 
12
  # Agent and LLM Frameworks
13
  from crewai import Agent, Task, Crew
@@ -24,39 +25,57 @@ class BookWritingOrchestrator:
24
  Args:
25
  api_key (str, optional): API key for models if not using environment variables
26
  """
27
- # API Key handling
28
- self.openai_api_key = api_key or os.getenv('OPENAI_API_KEY')
29
- self.anthropic_api_key = api_key or os.getenv('ANTHROPIC_API_KEY')
30
-
31
- # Vector Store for Context Management
32
- self.chroma_client = chromadb.Client()
33
- self.context_store = self.chroma_client.create_collection(
34
- name=f"book_context_{str(uuid.uuid4())}"
35
- )
36
-
37
- # Embedding Model
38
- self.embeddings = OpenAIEmbeddings(api_key=self.openai_api_key)
39
-
40
- # LLM Configurations
41
- self.openai_llm = ChatOpenAI(
42
- model="gpt-4-turbo",
43
- temperature=0.7,
44
- api_key=self.openai_api_key
45
- )
46
- self.anthropic_llm = ChatAnthropic(
47
- model='claude-3-opus-20240229',
48
- temperature=0.7,
49
- api_key=self.anthropic_api_key
50
- )
51
-
52
- # Agent Memory
53
- self.global_memory = ConversationBufferMemory(
54
- memory_key="chat_history",
55
- return_messages=True
56
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- # Initialize Specialized Agents
59
- self.setup_agents()
 
60
 
61
  def setup_agents(self):
62
  """
@@ -219,15 +238,18 @@ class BookWritingOrchestrator:
219
  context_key (str): Unique identifier for the context
220
  content (str): Content to store
221
  """
222
- # Generate embedding
223
- embedding = self.embeddings.embed_documents([content])[0]
224
-
225
- # Store in Chroma
226
- self.context_store.add(
227
- embeddings=[embedding],
228
- documents=[content],
229
- ids=[f"{self.project_id}_{context_key}"]
230
- )
 
 
 
231
 
232
  def _retrieve_context(
233
  self,
@@ -244,23 +266,27 @@ class BookWritingOrchestrator:
244
  Returns:
245
  List of contextually relevant content
246
  """
247
- # Retrieve previous chapters
248
- previous_chapters = [
249
- f'chapter_{i}' for i in range(1, chapter_number)
250
- ]
251
-
252
- # Search context
253
- retrieved_contexts = []
254
- for chapter_key in previous_chapters:
255
- search_embedding = self.embeddings.embed_documents([chapter_key])[0]
256
- results = self.context_store.query(
257
- query_embeddings=[search_embedding],
258
- n_results=top_k
259
- )
260
 
261
- retrieved_contexts.extend(results['documents'][0])
262
-
263
- return retrieved_contexts
 
 
 
 
 
 
 
 
 
 
 
 
264
 
265
  def _parse_concept(self, concept_result: str) -> Dict[str, Any]:
266
  """
@@ -272,10 +298,42 @@ class BookWritingOrchestrator:
272
  Returns:
273
  Structured book concept dictionary
274
  """
275
- # Implement robust parsing logic
276
- # This could use another AI call or regex-based extraction
277
- return {
278
- 'title': 'Parsed Book Title',
279
- 'genre': 'Parsed Genre',
280
- 'chapters': [] # Parsed chapter outline
281
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  import uuid
9
  import chromadb
10
  import numpy as np
11
+ import streamlit as st
12
 
13
  # Agent and LLM Frameworks
14
  from crewai import Agent, Task, Crew
 
25
  Args:
26
  api_key (str, optional): API key for models if not using environment variables
27
  """
28
+ # Generate a unique project ID
29
+ self.project_id = str(uuid.uuid4())
30
+
31
+ # API Key handling with more robust error checking
32
+ try:
33
+ # Try getting API keys from environment or passed parameter
34
+ self.openai_api_key = api_key or os.getenv('OPENAI_API_KEY')
35
+ self.anthropic_api_key = api_key or os.getenv('ANTHROPIC_API_KEY')
36
+
37
+ # Validate API keys
38
+ if not self.openai_api_key:
39
+ st.warning("OpenAI API key is missing. Some features may be limited.")
40
+
41
+ if not self.anthropic_api_key:
42
+ st.warning("Anthropic API key is missing. Some features may be limited.")
43
+
44
+ # Vector Store for Context Management
45
+ self.chroma_client = chromadb.Client()
46
+ self.context_store = self.chroma_client.create_collection(
47
+ name=f"book_context_{self.project_id}"
48
+ )
49
+
50
+ # Embedding Model
51
+ self.embeddings = OpenAIEmbeddings(
52
+ api_key=self.openai_api_key
53
+ )
54
+
55
+ # LLM Configurations
56
+ self.openai_llm = ChatOpenAI(
57
+ model="gpt-4-turbo",
58
+ temperature=0.7,
59
+ api_key=self.openai_api_key
60
+ )
61
+ self.anthropic_llm = ChatAnthropic(
62
+ model='claude-3-opus-20240229',
63
+ temperature=0.7,
64
+ api_key=self.anthropic_api_key
65
+ )
66
+
67
+ # Agent Memory
68
+ self.global_memory = ConversationBufferMemory(
69
+ memory_key="chat_history",
70
+ return_messages=True
71
+ )
72
+
73
+ # Initialize Specialized Agents
74
+ self.setup_agents()
75
 
76
+ except Exception as e:
77
+ st.error(f"Error initializing BookWritingOrchestrator: {e}")
78
+ raise
79
 
80
  def setup_agents(self):
81
  """
 
238
  context_key (str): Unique identifier for the context
239
  content (str): Content to store
240
  """
241
+ try:
242
+ # Generate embedding
243
+ embedding = self.embeddings.embed_documents([content])[0]
244
+
245
+ # Store in Chroma
246
+ self.context_store.add(
247
+ embeddings=[embedding],
248
+ documents=[content],
249
+ ids=[f"{self.project_id}_{context_key}"]
250
+ )
251
+ except Exception as e:
252
+ st.error(f"Error storing context: {e}")
253
 
254
  def _retrieve_context(
255
  self,
 
266
  Returns:
267
  List of contextually relevant content
268
  """
269
+ try:
270
+ # Retrieve previous chapters
271
+ previous_chapters = [
272
+ f'chapter_{i}' for i in range(1, chapter_number)
273
+ ]
 
 
 
 
 
 
 
 
274
 
275
+ # Search context
276
+ retrieved_contexts = []
277
+ for chapter_key in previous_chapters:
278
+ search_embedding = self.embeddings.embed_documents([chapter_key])[0]
279
+ results = self.context_store.query(
280
+ query_embeddings=[search_embedding],
281
+ n_results=top_k
282
+ )
283
+
284
+ retrieved_contexts.extend(results['documents'][0])
285
+
286
+ return retrieved_contexts
287
+ except Exception as e:
288
+ st.error(f"Error retrieving context: {e}")
289
+ return []
290
 
291
  def _parse_concept(self, concept_result: str) -> Dict[str, Any]:
292
  """
 
298
  Returns:
299
  Structured book concept dictionary
300
  """
301
+ # Basic parsing with error handling
302
+ try:
303
+ # This is a placeholder. In a real implementation,
304
+ # you might use NLP techniques or another AI call to parse
305
+ return {
306
+ 'title': 'Book Title',
307
+ 'genre': 'Fiction',
308
+ 'chapters': ['Chapter 1', 'Chapter 2', 'Chapter 3']
309
+ }
310
+ except Exception as e:
311
+ st.error(f"Error parsing concept: {e}")
312
+ return {
313
+ 'title': 'Untitled',
314
+ 'genre': 'Unspecified',
315
+ 'chapters': []
316
+ }
317
+
318
+ def main():
319
+ """
320
+ Demonstration of BookWritingOrchestrator
321
+ """
322
+ try:
323
+ # Example usage
324
+ orchestrator = BookWritingOrchestrator()
325
+
326
+ # Generate book concept
327
+ initial_prompt = "A science fiction story about space exploration"
328
+ book_concept = orchestrator.generate_book_concept(initial_prompt)
329
+ print("Book Concept:", book_concept)
330
+
331
+ # Generate first chapter
332
+ first_chapter = orchestrator.generate_chapter_content(book_concept, 1)
333
+ print("\nFirst Chapter:\n", first_chapter)
334
+
335
+ except Exception as e:
336
+ print(f"An error occurred: {e}")
337
+
338
+ if __name__ == "__main__":
339
+ main()