File size: 12,511 Bytes
c3fdfdd
 
 
dc93c04
0793539
dc93c04
 
 
c3fdfdd
dc93c04
f9bf036
dc93c04
 
f9bf036
dc93c04
 
a61f8e8
dc93c04
f9bf036
dc93c04
 
f9bf036
 
dc93c04
 
f9bf036
dc93c04
 
f9bf036
c3fdfdd
0793539
 
dc93c04
 
 
 
0793539
dc93c04
 
 
 
 
 
0793539
 
 
 
 
c3fdfdd
 
dc93c04
 
c3fdfdd
 
 
0793539
 
c3fdfdd
 
 
 
dc93c04
 
c3fdfdd
 
0793539
 
c3fdfdd
 
 
 
 
 
 
0793539
 
c3fdfdd
 
 
dc93c04
 
 
c3fdfdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc93c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3fdfdd
 
 
dc93c04
 
 
c3fdfdd
 
dc93c04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3fdfdd
dc93c04
 
 
 
 
 
c3fdfdd
 
dc93c04
c3fdfdd
 
 
2aee27c
dc93c04
0793539
 
 
 
dc93c04
 
0793539
c3fdfdd
 
8bbbd7a
c3fdfdd
 
0793539
dc93c04
 
c3fdfdd
 
2967cfa
 
 
 
0793539
 
2967cfa
c3fdfdd
dc93c04
0793539
dc93c04
 
 
 
 
 
 
 
 
 
0793539
dc93c04
 
 
0793539
dc93c04
 
 
 
 
c3fdfdd
2967cfa
dc93c04
 
 
 
 
 
 
 
 
 
2967cfa
 
0793539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3fdfdd
 
dc93c04
c3fdfdd
 
 
 
 
 
 
f9bf036
dc93c04
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
from crewai import Agent, Task, Crew
import gradio as gr
import asyncio
from typing import List, Generator, Any, Dict, Union
from langchain_openai import ChatOpenAI
import queue
import threading
import os

class AgentMessageQueue:
    def __init__(self):
        self.message_queue = queue.Queue()
        self.final_output = None
        
    def add_message(self, message: Dict):
        self.message_queue.put(message)
        
    def get_messages(self) -> List[Dict]:
        messages = []
        while not self.message_queue.empty():
            messages.append(self.message_queue.get())
        return messages
    
    def set_final_output(self, output: str):
        self.final_output = output
    
    def get_final_output(self) -> str:
        return self.final_output

class ArticleCrew:
    def __init__(self, api_key: str = None):
        self.api_key = api_key
        self.message_queue = AgentMessageQueue()
        self.planner = None
        self.writer = None
        self.editor = None
    
    def initialize_agents(self, topic: str):
        if not self.api_key:
            raise ValueError("OpenAI API key is required")
            
        os.environ["OPENAI_API_KEY"] = self.api_key
        
        llm = ChatOpenAI(
            temperature=0.7,
            model="gpt-4"
        )
        
        self.planner = Agent(
            role="Content Planner",
            goal=f"Plan engaging and factually accurate content on {topic}",
            backstory=f"You're working on planning a blog article about the topic: {topic}. "
                     "You collect information that helps the audience learn something "
                     "and make informed decisions.",
            allow_delegation=False,
            verbose=True,
            llm=llm
        )
        
        self.writer = Agent(
            role="Content Writer",
            goal=f"Write insightful and factually accurate opinion piece about the topic: {topic}",
            backstory=f"You're working on writing a new opinion piece about the topic: {topic}. "
                     "You base your writing on the work of the Content Planner.",
            allow_delegation=False,
            verbose=True,
            llm=llm
        )
        
        self.editor = Agent(
            role="Editor",
            goal="Edit a given blog post to align with the writing style",
            backstory="You are an editor who receives a blog post from the Content Writer.",
            allow_delegation=False,
            verbose=True,
            llm=llm
        )

    def create_tasks(self, topic: str):
        if not self.planner or not self.writer or not self.editor:
            self.initialize_agents(topic)
            
        plan_task = Task(
            description=(
                f"1. Prioritize the latest trends, key players, and noteworthy news on {topic}.\n"
                f"2. Identify the target audience, considering their interests and pain points.\n"
                f"3. Develop a detailed content outline including introduction, key points, and call to action.\n"
                f"4. Include SEO keywords and relevant data or sources."
            ),
            expected_output="A comprehensive content plan document with an outline, audience analysis, SEO keywords, and resources.",
            agent=self.planner
        )

        write_task = Task(
            description=(
                "1. Use the content plan to craft a compelling blog post.\n"
                "2. Incorporate SEO keywords naturally.\n"
                "3. Sections/Subtitles are properly named in an engaging manner.\n"
                "4. Ensure proper structure with introduction, body, and conclusion.\n"
                "5. Proofread for grammatical errors."
            ),
            expected_output="A well-written blog post in markdown format, ready for publication.",
            agent=self.writer
        )

        edit_task = Task(
            description="Proofread the given blog post for grammatical errors and alignment with the brand's voice.",
            expected_output="A well-written blog post in markdown format, ready for publication.",
            agent=self.editor
        )

        return [plan_task, write_task, edit_task]

    async def process_article(self, topic: str) -> Generator[List[Dict], None, None]:
        def step_callback(output: Any) -> None:
            try:
                output_str = str(output).strip()
                
                # Extract agent name
                if "# Agent:" in output_str:
                    agent_name = output_str.split("# Agent:")[1].split("\n")[0].strip()
                else:
                    agent_name = "Agent"
                
                # Extract task or final answer
                if "## Task:" in output_str:
                    content = output_str.split("## Task:")[1].split("\n#")[0].strip()
                    self.message_queue.add_message({
                        "role": "assistant",
                        "content": content,
                        "metadata": {"title": f"πŸ“‹ {agent_name}'s Task"}
                    })
                elif "## Final Answer:" in output_str:
                    content = output_str.split("## Final Answer:")[1].strip()
                    if agent_name == "Editor":
                        # For Editor's final answer, store it for later
                        self.message_queue.set_final_output(content)
                    self.message_queue.add_message({
                        "role": "assistant",
                        "content": content,
                        "metadata": {"title": f"βœ… {agent_name}'s Output"}
                    })
                else:
                    self.message_queue.add_message({
                        "role": "assistant",
                        "content": output_str,
                        "metadata": {"title": f"πŸ’­ {agent_name} thinking"}
                    })
                    
            except Exception as e:
                print(f"Error in step_callback: {str(e)}")

        def task_callback(output: Any) -> None:
            try:
                content = str(output)
                if hasattr(output, 'agent'):
                    agent_name = str(output.agent)
                else:
                    agent_name = "Agent"
                
                self.message_queue.add_message({
                    "role": "assistant",
                    "content": content.strip(),
                    "metadata": {"title": f"βœ… Task completed by {agent_name}"}
                })
                
                # If this is the Editor's task completion, add the final article
                if agent_name == "Editor":
                    final_content = self.message_queue.get_final_output()
                    if final_content:
                        self.message_queue.add_message({
                            "role": "assistant",
                            "content": "Here's your completed article:",
                            "metadata": {"title": "πŸ“ Final Article"}
                        })
                        self.message_queue.add_message({
                            "role": "assistant",
                            "content": final_content
                        })
                        self.message_queue.add_message({
                            "role": "assistant",
                            "content": "Article generation completed!",
                            "metadata": {"title": "✨ Complete"}
                        })
                
            except Exception as e:
                print(f"Error in task_callback: {str(e)}")

        self.initialize_agents(topic)
        
        crew = Crew(
            agents=[self.planner, self.writer, self.editor],
            tasks=self.create_tasks(topic),
            verbose=True,
            step_callback=step_callback,
            task_callback=task_callback
        )
        
        # Start notification
        yield [{
            "role": "assistant",
            "content": "Starting work on your article...",
            "metadata": {"title": "πŸš€ Process Started"}
        }]
        
        # Run crew in a separate thread
        result_container = []
        def run_crew():
            try:
                result = crew.kickoff(inputs={"topic": topic})
                result_container.append(result)
            except Exception as e:
                result_container.append(e)
                print(f"Error occurred: {str(e)}")
        
        thread = threading.Thread(target=run_crew)
        thread.start()
        
        # Stream messages while crew is working
        while thread.is_alive() or not self.message_queue.message_queue.empty():
            messages = self.message_queue.get_messages()
            if messages:
                yield messages
            await asyncio.sleep(0.1)

def create_demo():
    article_crew = None
    
    with gr.Blocks(theme=gr.themes.Soft()) as demo:
        gr.Markdown("# πŸ“ AI Article Writing Crew")
        gr.Markdown("Watch as this AI Crew collaborates to create your article! This application utilizes [CrewAI](https://www.crewai.com/) agents: Content Planner, Content Writer, and Content Editor, to write an article on any topic you choose. To get started, enter your OpenAI API Key below and press Enter!")
        
        openai_api_key = gr.Textbox(
            label='OpenAI API Key', 
            type='password', 
            placeholder='Type your OpenAI API key and press Enter!', 
            interactive=True
        )

        chatbot = gr.Chatbot(
            label="Writing Process",
            avatar_images=(None, "https://avatars.githubusercontent.com/u/170677839?v=4"),
            height=700,
            type="messages",
            show_label=True,
            visible=False,
            value=[]
        )
        
        with gr.Row(equal_height=True):
            topic = gr.Textbox(
                label="Article Topic",
                placeholder="Enter the topic you want an article about...",
                scale=4,
                visible=False
            )
            
            async def process_input(topic, history, api_key):
                nonlocal article_crew
                if not api_key:
                    history.append({
                        "role": "assistant",
                        "content": "Please provide an OpenAI API key first.",
                        "metadata": {"title": "❌ Error"}
                    })
                    yield history  # Changed from return to yield
                    return  # Early return without value
                
                # Initialize or update ArticleCrew with API key
                if article_crew is None:
                    article_crew = ArticleCrew(api_key=api_key)
                else:
                    article_crew.api_key = api_key
                
                # Add user message
                history.append({
                    "role": "user", 
                    "content": f"Write an article about: {topic}"
                })
                yield history
                
                try:
                    async for messages in article_crew.process_article(topic):
                        history.extend(messages)
                        yield history
                except Exception as e:
                    history.append({
                        "role": "assistant",
                        "content": f"An error occurred: {str(e)}",
                        "metadata": {"title": "❌ Error"}
                    })
                    yield history
            
            btn = gr.Button("Write Article", variant="primary", scale=1, visible=False)

        def show_interface():
            return {
                openai_api_key: gr.Textbox(visible=False),
                chatbot: gr.Chatbot(visible=True),
                topic: gr.Textbox(visible=True),
                btn: gr.Button(visible=True)
            }

        openai_api_key.submit(
            show_interface,
            None,
            [openai_api_key, chatbot, topic, btn]
        )

        btn.click(
            process_input,
            inputs=[topic, chatbot, openai_api_key],  # Added openai_api_key back as input
            outputs=[chatbot]
        )

    return demo

if __name__ == "__main__":
    demo = create_demo()
    demo.queue()
    demo.launch(debug=True)