-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07-crewai-research-write-article.py
More file actions
473 lines (372 loc) · 11.5 KB
/
07-crewai-research-write-article.py
File metadata and controls
473 lines (372 loc) · 11.5 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "crewai==0.102.0",
# "httpx==0.28.1",
# "ipython==8.32.0",
# "marimo",
# "python-dotenv==1.0.1",
# "utils==1.0.2",
# ]
# ///
import marimo
__generated_with = "0.11.0"
app = marimo.App()
@app.cell
def _():
import marimo as mo
return (mo,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""You can download the `requirements.txt` for this course from the workspace of this lab. `File --> Open...`""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# L2: Create Agents to Explore and Write an Article
In this lesson, you will be introduced to the foundational concepts of multi-agent systems and get an overview of the crewAI framework.
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
The libraries are already installed in the classroom. If you're running this notebook on your own machine, you can install the following:
```Python
!pip install crewai==0.28.8 crewai_tools==0.1.6 langchain_community==0.0.29
```
"""
)
return
@app.cell
def _():
# Warning control
import warnings
warnings.filterwarnings('ignore')
return (warnings,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""- Import from the crewAI libray.""")
return
@app.cell
def _():
from crewai import Agent, Task, Crew
return Agent, Crew, Task
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
- As a LLM for your agents, you'll be using OpenAI's `gpt-3.5-turbo`.
**Optional Note:** crewAI also allow other popular models to be used as a LLM for your Agents. You can see some of the examples at the [bottom of the notebook](#1).
"""
)
return
@app.cell
def _(os):
# Delete if not using in UTSA
os.environ["http_proxy"] = "http://xa-proxy.utsarr.net:80"
os.environ["https_proxy"] = "http://xa-proxy.utsarr.net:80"
return
@app.cell
def _():
import os
from dotenv import load_dotenv, find_dotenv
working_dir = os.getcwd()
status = load_dotenv(
find_dotenv(
filename=f'{working_dir}/AgenticAISystems/.env',
raise_error_if_not_found=True
)
)
openai_api_key = os.getenv("OPENAI_API_KEY")
os.environ["OPENAI_MODEL_NAME"] = 'gpt-3.5-turbo'
# Disable sending telemetry data
os.environ["OTEL_SDK_DISABLED"] = "true"
return find_dotenv, load_dotenv, openai_api_key, os, status, working_dir
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
## Creating Agents
- Define your Agents, and provide them a `role`, `goal` and `backstory`.
- It has been seen that LLMs perform better when they are role playing.
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
### Agent: Planner
**Note**: The benefit of using _multiple strings_ :
```Python
varname = "line 1 of text"
"line 2 of text"
```
versus the _triple quote docstring_:
```Python
varname = \"\"\"line 1 of text
line 2 of text
\"\"\"
```
is that it can avoid adding those whitespaces and newline characters, making it better formatted to be passed to the LLM.
"""
)
return
@app.cell
def _(Agent):
planner = Agent(
role="Content Planner",
goal="Plan engaging and factually accurate content on {topic}",
backstory="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. "
"Your work is the basis for "
"the Content Writer to write an article on this topic.",
allow_delegation=False,
verbose=True
)
return (planner,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""### Agent: Writer""")
return
@app.cell
def _(Agent):
writer = Agent(
role="Content Writer",
goal="Write insightful and factually accurate "
"opinion piece about the topic: {topic}",
backstory="You're working on a writing "
"a new opinion piece about the topic: {topic}. "
"You base your writing on the work of "
"the Content Planner, who provides an outline "
"and relevant context about the topic. "
"You follow the main objectives and "
"direction of the outline, "
"as provide by the Content Planner. "
"You also provide objective and impartial insights "
"and back them up with information "
"provide by the Content Planner. "
"You acknowledge in your opinion piece "
"when your statements are opinions "
"as opposed to objective statements.",
allow_delegation=False,
verbose=True
)
return (writer,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""### Agent: Editor""")
return
@app.cell
def _(Agent):
editor = Agent(
role="Editor",
goal="Edit a given blog post to align with "
"the writing style of the organization. ",
backstory="You are an editor who receives a blog post "
"from the Content Writer. "
"Your goal is to review the blog post "
"to ensure that it follows journalistic best practices,"
"provides balanced viewpoints "
"when providing opinions or assertions, "
"and also avoids major controversial topics "
"or opinions when possible.",
allow_delegation=False,
verbose=True
)
return (editor,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
## Creating Tasks
- Define your Tasks, and provide them a `description`, `expected_output` and `agent`.
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""### Task: Plan""")
return
@app.cell
def _(Task, planner):
plan = Task(
description=(
"1. Prioritize the latest trends, key players, "
"and noteworthy news on {topic}.\n"
"2. Identify the target audience, considering "
"their interests and pain points.\n"
"3. Develop a detailed content outline including "
"an introduction, key points, and a call to action.\n"
"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=planner,
)
return (plan,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""### Task: Write""")
return
@app.cell
def _(Task, writer):
write = Task(
description=(
"1. Use the content plan to craft a compelling "
"blog post on {topic}.\n"
"2. Incorporate SEO keywords naturally.\n"
"3. Sections/Subtitles are properly named "
"in an engaging manner.\n"
"4. Ensure the post is structured with an "
"engaging introduction, insightful body, "
"and a summarizing conclusion.\n"
"5. Proofread for grammatical errors and "
"alignment with the brand's voice.\n"
),
expected_output="A well-written blog post "
"in markdown format, ready for publication, "
"each section should have 2 or 3 paragraphs.",
agent=writer,
)
return (write,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""### Task: Edit""")
return
@app.cell
def _(Task, editor):
edit = 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, "
"each section should have 2 or 3 paragraphs.",
agent=editor
)
return (edit,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
## Creating the Crew
- Create your crew of Agents
- Pass the tasks to be performed by those agents.
- **Note**: *For this simple example*, the tasks will be performed sequentially (i.e they are dependent on each other), so the _order_ of the task in the list _matters_.
- `verbose=2` allows you to see all the logs of the execution.
"""
)
return
@app.cell
def _(Crew, edit, editor, plan, planner, write, writer):
crew = Crew(
agents=[planner, writer, editor],
tasks=[plan, write, edit],
verbose=True
)
return (crew,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""## Running the Crew""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""**Note**: LLMs can provide different outputs for they same input, so what you get might be different than what you see in the video.""")
return
@app.cell
def _(crew):
result = crew.kickoff(inputs={"topic": "Artificial Intelligence"})
return (result,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""- Display the results of your execution as markdown in the notebook.""")
return
@app.cell
def _(mo, result):
mo.md(result.raw.replace("```", ""))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
## Try it Yourself
- Pass in a topic of your choice and see what the agents come up with!
"""
)
return
@app.cell
def _(crew):
topic = 'How does CrewAI Work?'
result_1 = crew.kickoff(inputs={'topic': topic})
return result_1, topic
@app.cell
def _(result_1):
result_1
return
@app.cell
def _(mo, result_1):
mo.md(result_1.raw)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""## Other Popular Models as LLM for your Agents""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
#### Hugging Face (HuggingFaceHub endpoint)
```Python
from langchain_community.llms import HuggingFaceHub
llm = HuggingFaceHub(
repo_id="HuggingFaceH4/zephyr-7b-beta",
huggingfacehub_api_token="<HF_TOKEN_HERE>",
task="text-generation",
)
### you will pass "llm" to your agent function
```
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
#### Mistral API
```Python
OPENAI_API_KEY=your-mistral-api-key
OPENAI_API_BASE=https://api.mistral.ai/v1
OPENAI_MODEL_NAME="mistral-small"
```
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
#### Cohere
```Python
from langchain_community.chat_models import ChatCohere
# Initialize language model
os.environ["COHERE_API_KEY"] = "your-cohere-api-key"
llm = ChatCohere()
### you will pass "llm" to your agent function
```
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""### For using Llama locally with Ollama and more, checkout the crewAI documentation on [Connecting to any LLM](https://docs.crewai.com/how-to/LLM-Connections/).""")
return
if __name__ == "__main__":
app.run()