cryogenic22 commited on
Commit
080af87
·
verified ·
1 Parent(s): 7cb52d8

Create multi_agent_book_workflow.py

Browse files
Files changed (1) hide show
  1. multi_agent_book_workflow.py +278 -0
multi_agent_book_workflow.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File: multi_agent_book_workflow.py
2
+ # Location: /multi_agent_book_workflow.py (in root directory)
3
+ # Description: Core multi-agent book writing orchestration system
4
+ # Usage: Imported by app.py for book generation workflows
5
+
6
+ import os
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
14
+ from langchain_openai import ChatOpenAI
15
+ from langchain_anthropic import ChatAnthropic
16
+ from langchain.memory import ConversationBufferMemory
17
+ from langchain.embeddings import OpenAIEmbeddings
18
+
19
+ class BookWritingOrchestrator:
20
+ def __init__(self, project_id: str = None):
21
+ """
22
+ Initialize the book writing orchestrator with multi-agent setup
23
+
24
+ Args:
25
+ project_id (str, optional): Unique identifier for the book project
26
+ """
27
+ # Project Identification
28
+ self.project_id = project_id or str(uuid.uuid4())
29
+
30
+ # Vector Store for Context Management
31
+ self.chroma_client = chromadb.Client()
32
+ self.context_store = self.chroma_client.create_collection(
33
+ name=f"book_context_{self.project_id}"
34
+ )
35
+
36
+ # Embedding Model
37
+ self.embeddings = OpenAIEmbeddings()
38
+
39
+ # LLM Configurations
40
+ self.openai_llm = ChatOpenAI(
41
+ model="gpt-4-turbo",
42
+ temperature=0.7
43
+ )
44
+ self.anthropic_llm = ChatAnthropic(
45
+ model="claude-3-opus-20240229",
46
+ temperature=0.7
47
+ )
48
+
49
+ # Agent Memory
50
+ self.global_memory = ConversationBufferMemory(
51
+ memory_key="chat_history",
52
+ return_messages=True
53
+ )
54
+
55
+ # Initialize Specialized Agents
56
+ self.setup_agents()
57
+
58
+ def setup_agents(self):
59
+ """
60
+ Create specialized agents for book writing workflow
61
+ """
62
+ # Concept Development Agent
63
+ self.concept_agent = Agent(
64
+ role='Book Concept Architect',
65
+ goal='Develop a comprehensive and compelling book concept',
66
+ backstory='An expert literary strategist who transforms raw ideas into structured book frameworks',
67
+ verbose=True,
68
+ llm=self.openai_llm,
69
+ memory=True
70
+ )
71
+
72
+ # Research Agent
73
+ self.research_agent = Agent(
74
+ role='Literary Research Specialist',
75
+ goal='Conduct in-depth research to support the book\'s narrative and authenticity',
76
+ backstory='A meticulous researcher with expertise in gathering and synthesizing complex information',
77
+ verbose=True,
78
+ llm=self.anthropic_llm,
79
+ memory=True
80
+ )
81
+
82
+ # Content Generation Agent
83
+ self.writing_agent = Agent(
84
+ role='Master Storyteller',
85
+ goal='Create engaging, coherent, and stylistically consistent narrative content',
86
+ backstory='A versatile writer capable of crafting compelling prose across various genres',
87
+ verbose=True,
88
+ llm=self.openai_llm,
89
+ memory=True
90
+ )
91
+
92
+ # Editing Agent
93
+ self.editing_agent = Agent(
94
+ role='Narrative Refinement Specialist',
95
+ goal='Ensure narrative consistency, quality, and stylistic excellence',
96
+ backstory='A seasoned editor with a keen eye for storytelling nuance and structural integrity',
97
+ verbose=True,
98
+ llm=self.anthropic_llm,
99
+ memory=True
100
+ )
101
+
102
+ def generate_book_concept(self, initial_prompt: str) -> Dict[str, Any]:
103
+ """
104
+ Generate a comprehensive book concept using multi-agent collaboration
105
+
106
+ Args:
107
+ initial_prompt (str): User's initial book idea
108
+
109
+ Returns:
110
+ Dict containing book concept details
111
+ """
112
+ # Concept Development Task
113
+ concept_task = Task(
114
+ description=f"""
115
+ Develop a comprehensive book concept based on this initial idea:
116
+ {initial_prompt}
117
+
118
+ Provide detailed outputs including:
119
+ 1. Unique Book Title
120
+ 2. Genre and Subgenre
121
+ 3. Target Audience
122
+ 4. Core Narrative Premise
123
+ 5. Potential Chapter Outline
124
+ 6. Distinctive Narrative Approach
125
+ """,
126
+ agent=self.concept_agent,
127
+ expected_output="A detailed JSON-like structure of the book concept"
128
+ )
129
+
130
+ # Research Validation Task
131
+ research_task = Task(
132
+ description="Validate and enrich the book concept with additional research insights",
133
+ agent=self.research_agent,
134
+ expected_output="Research-backed annotations and potential depth areas"
135
+ )
136
+
137
+ # Create Crew for Collaborative Processing
138
+ book_concept_crew = Crew(
139
+ agents=[self.concept_agent, self.research_agent],
140
+ tasks=[concept_task, research_task],
141
+ verbose=2
142
+ )
143
+
144
+ # Execute Collaborative Workflow
145
+ result = book_concept_crew.kickoff()
146
+
147
+ # Store Context in Vector Database
148
+ self._store_context('book_concept', result)
149
+
150
+ return self._parse_concept(result)
151
+
152
+ def generate_chapter_content(
153
+ self,
154
+ book_concept: Dict[str, Any],
155
+ chapter_number: int
156
+ ) -> str:
157
+ """
158
+ Generate content for a specific chapter using multi-agent workflow
159
+
160
+ Args:
161
+ book_concept (Dict): Comprehensive book concept
162
+ chapter_number (int): Chapter to generate
163
+
164
+ Returns:
165
+ str: Generated chapter content
166
+ """
167
+ # Retrieve Previous Context
168
+ previous_context = self._retrieve_context(chapter_number)
169
+
170
+ # Content Generation Task
171
+ writing_task = Task(
172
+ description=f"""
173
+ Write Chapter {chapter_number} for the book
174
+
175
+ Book Concept: {book_concept}
176
+
177
+ Previous Context: {previous_context}
178
+
179
+ Generate a draft that:
180
+ 1. Maintains narrative continuity
181
+ 2. Advances the story
182
+ 3. Matches the established tone and style
183
+ 4. Incorporates research insights
184
+ """,
185
+ agent=self.writing_agent,
186
+ expected_output="A complete chapter draft with narrative coherence"
187
+ )
188
+
189
+ # Editing and Refinement Task
190
+ editing_task = Task(
191
+ description="Review and refine the generated chapter draft",
192
+ agent=self.editing_agent,
193
+ expected_output="Polished chapter content with suggested improvements"
194
+ )
195
+
196
+ # Create Crew for Chapter Generation
197
+ chapter_crew = Crew(
198
+ agents=[self.writing_agent, self.editing_agent],
199
+ tasks=[writing_task, editing_task],
200
+ verbose=2
201
+ )
202
+
203
+ # Execute Collaborative Workflow
204
+ chapter_content = chapter_crew.kickoff()
205
+
206
+ # Store Chapter Context
207
+ self._store_context(f'chapter_{chapter_number}', chapter_content)
208
+
209
+ return chapter_content
210
+
211
+ def _store_context(self, context_key: str, content: str):
212
+ """
213
+ Store context in vector database for retrieval
214
+
215
+ Args:
216
+ context_key (str): Unique identifier for the context
217
+ content (str): Content to store
218
+ """
219
+ # Generate embedding
220
+ embedding = self.embeddings.embed_documents([content])[0]
221
+
222
+ # Store in Chroma
223
+ self.context_store.add(
224
+ embeddings=[embedding],
225
+ documents=[content],
226
+ ids=[f"{self.project_id}_{context_key}"]
227
+ )
228
+
229
+ def _retrieve_context(
230
+ self,
231
+ chapter_number: int,
232
+ top_k: int = 3
233
+ ) -> List[str]:
234
+ """
235
+ Retrieve contextually relevant previous content
236
+
237
+ Args:
238
+ chapter_number (int): Current chapter number
239
+ top_k (int): Number of context pieces to retrieve
240
+
241
+ Returns:
242
+ List of contextually relevant content
243
+ """
244
+ # Retrieve previous chapters
245
+ previous_chapters = [
246
+ f'chapter_{i}' for i in range(1, chapter_number)
247
+ ]
248
+
249
+ # Search context
250
+ retrieved_contexts = []
251
+ for chapter_key in previous_chapters:
252
+ search_embedding = self.embeddings.embed_documents([chapter_key])[0]
253
+ results = self.context_store.query(
254
+ query_embeddings=[search_embedding],
255
+ n_results=top_k
256
+ )
257
+
258
+ retrieved_contexts.extend(results['documents'][0])
259
+
260
+ return retrieved_contexts
261
+
262
+ def _parse_concept(self, concept_result: str) -> Dict[str, Any]:
263
+ """
264
+ Parse and structure the book concept
265
+
266
+ Args:
267
+ concept_result (str): Raw concept generation result
268
+
269
+ Returns:
270
+ Structured book concept dictionary
271
+ """
272
+ # Implement robust parsing logic
273
+ # This could use another AI call or regex-based extraction
274
+ return {
275
+ 'title': 'Parsed Book Title',
276
+ 'genre': 'Parsed Genre',
277
+ 'chapters': [] # Parsed chapter outline
278
+ }