Skip to content

Commit b2cd133

Browse files
authored
fix(docs): restore missing code block in pt-BR first-flow guide (#5780)
* fix(docs): restore missing code block in pt-BR first-flow guide The pt-BR translation of the 'Build Your First Flow' guide had a placeholder comment '# [CÓDIGO NÃO TRADUZIDO, MANTER COMO ESTÁ]' instead of the actual Python code in Step 5. This restores the full main.py code block from the English source, matching the original since code should not be translated. * Translate code comments to pt-BR in first-flow guide Code comments in the tutorial should be in Portuguese for the pt-BR audience, since they are part of the guide's educational content.
1 parent ba523f4 commit b2cd133

1 file changed

Lines changed: 159 additions & 1 deletion

File tree

docs/pt-BR/guides/flows/first-flow.mdx

Lines changed: 159 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,165 @@ Nosso flow irá:
266266
Vamos criar nosso flow no arquivo `main.py`:
267267

268268
```python
269-
# [CÓDIGO NÃO TRADUZIDO, MANTER COMO ESTÁ]
269+
#!/usr/bin/env python
270+
import json
271+
import os
272+
from typing import List, Dict
273+
from pydantic import BaseModel, Field
274+
from crewai import LLM
275+
from crewai.flow.flow import Flow, listen, start
276+
from guide_creator_flow.crews.content_crew.content_crew import ContentCrew
277+
278+
# Definir nossos modelos para dados estruturados
279+
class Section(BaseModel):
280+
title: str = Field(description="Title of the section")
281+
description: str = Field(description="Brief description of what the section should cover")
282+
283+
class GuideOutline(BaseModel):
284+
title: str = Field(description="Title of the guide")
285+
introduction: str = Field(description="Introduction to the topic")
286+
target_audience: str = Field(description="Description of the target audience")
287+
sections: List[Section] = Field(description="List of sections in the guide")
288+
conclusion: str = Field(description="Conclusion or summary of the guide")
289+
290+
# Definir o estado do nosso flow
291+
class GuideCreatorState(BaseModel):
292+
topic: str = ""
293+
audience_level: str = ""
294+
guide_outline: GuideOutline = None
295+
sections_content: Dict[str, str] = {}
296+
297+
class GuideCreatorFlow(Flow[GuideCreatorState]):
298+
"""Flow para criar um guia abrangente sobre qualquer tópico"""
299+
300+
@start()
301+
def get_user_input(self):
302+
"""Obter entrada do usuário sobre o tópico e público do guia"""
303+
print("\n=== Create Your Comprehensive Guide ===\n")
304+
305+
# Obter entrada do usuário
306+
self.state.topic = input("What topic would you like to create a guide for? ")
307+
308+
# Obter nível do público com validação
309+
while True:
310+
audience = input("Who is your target audience? (beginner/intermediate/advanced) ").lower()
311+
if audience in ["beginner", "intermediate", "advanced"]:
312+
self.state.audience_level = audience
313+
break
314+
print("Please enter 'beginner', 'intermediate', or 'advanced'")
315+
316+
print(f"\nCreating a guide on {self.state.topic} for {self.state.audience_level} audience...\n")
317+
return self.state
318+
319+
@listen(get_user_input)
320+
def create_guide_outline(self, state):
321+
"""Criar um esboço estruturado para o guia usando uma chamada direta ao LLM"""
322+
print("Creating guide outline...")
323+
324+
# Inicializar o LLM
325+
llm = LLM(model="openai/gpt-4o-mini", response_format=GuideOutline)
326+
327+
# Criar as mensagens para o esboço
328+
messages = [
329+
{"role": "system", "content": "You are a helpful assistant designed to output JSON."},
330+
{"role": "user", "content": f"""
331+
Create a detailed outline for a comprehensive guide on "{state.topic}" for {state.audience_level} level learners.
332+
333+
The outline should include:
334+
1. A compelling title for the guide
335+
2. An introduction to the topic
336+
3. 4-6 main sections that cover the most important aspects of the topic
337+
4. A conclusion or summary
338+
339+
For each section, provide a clear title and a brief description of what it should cover.
340+
"""}
341+
]
342+
343+
# Fazer a chamada ao LLM com formato de resposta JSON
344+
response = llm.call(messages=messages)
345+
346+
# Analisar a resposta JSON
347+
outline_dict = json.loads(response)
348+
self.state.guide_outline = GuideOutline(**outline_dict)
349+
350+
# Garantir que o diretório de saída exista antes de salvar
351+
os.makedirs("output", exist_ok=True)
352+
353+
# Salvar o esboço em um arquivo
354+
with open("output/guide_outline.json", "w") as f:
355+
json.dump(outline_dict, f, indent=2)
356+
357+
print(f"Guide outline created with {len(self.state.guide_outline.sections)} sections")
358+
return self.state.guide_outline
359+
360+
@listen(create_guide_outline)
361+
def write_and_compile_guide(self, outline):
362+
"""Escrever todas as seções e compilar o guia"""
363+
print("Writing guide sections and compiling...")
364+
completed_sections = []
365+
366+
# Processar seções uma por uma para manter o fluxo de contexto
367+
for section in outline.sections:
368+
print(f"Processing section: {section.title}")
369+
370+
# Construir contexto a partir das seções anteriores
371+
previous_sections_text = ""
372+
if completed_sections:
373+
previous_sections_text = "# Previously Written Sections\n\n"
374+
for title in completed_sections:
375+
previous_sections_text += f"## {title}\n\n"
376+
previous_sections_text += self.state.sections_content.get(title, "") + "\n\n"
377+
else:
378+
previous_sections_text = "No previous sections written yet."
379+
380+
# Executar a crew de conteúdo para esta seção
381+
result = ContentCrew().crew().kickoff(inputs={
382+
"section_title": section.title,
383+
"section_description": section.description,
384+
"audience_level": self.state.audience_level,
385+
"previous_sections": previous_sections_text,
386+
"draft_content": ""
387+
})
388+
389+
# Armazenar o conteúdo
390+
self.state.sections_content[section.title] = result.raw
391+
completed_sections.append(section.title)
392+
print(f"Section completed: {section.title}")
393+
394+
# Compilar o guia final
395+
guide_content = f"# {outline.title}\n\n"
396+
guide_content += f"## Introduction\n\n{outline.introduction}\n\n"
397+
398+
# Adicionar cada seção em ordem
399+
for section in outline.sections:
400+
section_content = self.state.sections_content.get(section.title, "")
401+
guide_content += f"\n\n{section_content}\n\n"
402+
403+
# Adicionar conclusão
404+
guide_content += f"## Conclusion\n\n{outline.conclusion}\n\n"
405+
406+
# Salvar o guia
407+
with open("output/complete_guide.md", "w") as f:
408+
f.write(guide_content)
409+
410+
print("\nComplete guide compiled and saved to output/complete_guide.md")
411+
return "Guide creation completed successfully"
412+
413+
def kickoff():
414+
"""Executar o flow criador de guias"""
415+
GuideCreatorFlow().kickoff()
416+
print("\n=== Flow Complete ===")
417+
print("Your comprehensive guide is ready in the output directory.")
418+
print("Open output/complete_guide.md to view it.")
419+
420+
def plot():
421+
"""Gerar uma visualização do flow"""
422+
flow = GuideCreatorFlow()
423+
flow.plot("guide_creator_flow")
424+
print("Flow visualization saved to guide_creator_flow.html")
425+
426+
if __name__ == "__main__":
427+
kickoff()
270428
```
271429

272430
Vamos analisar o que está acontecendo neste flow:

0 commit comments

Comments
 (0)