Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add wordpress-publisher agent #179

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions wordpress-publisher/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.env
__pycache__/
74 changes: 74 additions & 0 deletions wordpress-publisher/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# WordpressPublisher Crew

Welcome to the WordpressPublisher Crew project, powered by [crewAI](https://crewai.com). This template is designed to help you set up a multi-agent AI system with ease, leveraging the powerful and flexible framework provided by crewAI. Our goal is to enable your agents to collaborate effectively on complex tasks, maximizing their collective intelligence and capabilities.

## Installation

Ensure you have Python >=3.10 <=3.13 installed on your system. This project uses [Poetry](https://python-poetry.org/) for dependency management and package handling, offering a seamless setup and execution experience.

First, if you haven't already, install Poetry:

```bash
pip install poetry
```

Next, navigate to your project directory and install the dependencies:

1. First lock the dependencies and install them by using the CLI command:
```bash
crewai install
```
### Customizing

- Modify `src/agencia_noticias/config/agents.yaml` to define your agents
- Modify `src/agencia_noticias/config/tasks.yaml` to define your tasks
- Modify `src/agencia_noticias/crew.py` to add your own logic, tools and specific args
- Modify `src/agencia_noticias/main.py` to add custom inputs for your agents and tasks

## Running the Project

To kickstart your crew of AI agents and begin task execution, run this from the root folder of your project:

```bash
$ crewai run
```

This command initializes the agencia_noticias Crew, assembling the agents and assigning them tasks as defined in your configuration.

This example, unmodified, will run the create a `report_ptbr.md` file with the output of a research on LLMs in the root folder.

## Understanding Your Crew

The agencia_noticias Crew is composed of multiple AI agents, each with unique roles, goals, and tools. These agents collaborate on a series of tasks, defined in `config/tasks.yaml`, leveraging their collective skills to achieve complex objectives. The `config/agents.yaml` file outlines the capabilities and configurations of each agent in your crew.

## About this Crew
This crew simulates a Content News Agency, with content research, report, translating and publishing news from any subject.

Agents:
- researcher
- reporting_analyst
- translator (in this case, translating for Brazilian pt-br)
- blog_publisher (in this case, specific for WP)

Tasks:
- research_task
- reporting_task
- translate_task
- publish_task

Tools:
- wp_publisher: for the task that will be executed by the publisher agent.

## You will need
- Openai Api Key [OpenAIDocs](https://platform.openai.com/api-keys)
- Serper API Key [Serper](https://serper.dev/)
- Wordpress Rest API Token -- Follow steps in the Plugin link [WPToken](https://br.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/)

**Add your `KEYS` into the `.env` file**

## Support

For support, questions, or feedback regarding the AgenciaNoticias Crew or crewAI.
- Visit our [documentation](https://docs.crewai.com)

Let's create wonders together with the power and simplicity of crewAI.
6,752 changes: 6,752 additions & 0 deletions wordpress-publisher/poetry.lock

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions wordpress-publisher/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[tool.poetry]
name = "agencia_noticias"
version = "0.1.0"
description = "agencia_noticias using crewAI"
authors = ["Your Name <[email protected]>"]

[tool.poetry.dependencies]
python = ">=3.10,<=3.13"
crewai = { extras = ["tools"], version = ">=0.70.1,<1.0.0" }


[tool.poetry.scripts]
agencia_noticias = "agencia_noticias.main:run"
run_crew = "agencia_noticias.main:run"
train = "agencia_noticias.main:train"
replay = "agencia_noticias.main:replay"
test = "agencia_noticias.main:test"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
45 changes: 45 additions & 0 deletions wordpress-publisher/report_ptbr.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# O Futuro da Inteligência Artificial: Tendências para 2024

A tecnologia da inteligência artificial (IA) está em constante evolução e, em 2024, diversas tendências moldarão seu futuro. Este relatório apresenta uma análise abrangente das principais áreas que estão emergindo e transformando o panorama da inteligência artificial.

## 1. Ecossistemas de Dados em Nuvem

A adoção de ecossistemas de dados em nuvem deverá chegar a novos patamares em 2024. As plataformas de nuvem estão cada vez mais equipadas para fornecer conjuntos de dados unificados, oferecendo escalabilidade e acessibilidade. Isso permitirá que as empresas integrem grandes quantidades de dados de diferentes origens, otimizando o processamento e a análise. Com essa abordagem, as aplicações de IA poderão funcionar de maneira mais eficiente, além de facilitar a colaboração em tempo real e a análise preditiva.

## 2. Automação de Processos

Uma das promessas mais impactantes da IA é a automação de processos. Em 2024, essa tendência se intensificará, com sistemas de IA capazes de realizar tarefas operacionais rotineiras de forma mais eficiente. Isso liberará os trabalhadores qualificados para se concentrarem em atividades que requerem julgamento crítico e soluções criativas. Além disso, a redução de erros humanos nas tarefas automatizadas deverá aumentar a eficiência organizacional, reduzindo custos operacionais e melhorando a qualidade do serviço.

## 3. IA Generativa

A IA generativa, que se refere a sistemas que podem criar novos conteúdos, como textos e imagens, está se tornando uma ferramenta poderosa para as empresas. Em 2024, esperam-se avanços significativos nesta área, aumentando a produtividade e proporcionando novas opções criativas para as marcas. A capacidade de gerar conteúdo automaticamente não só otimiza processos, mas também pode ser usada para campanhas de marketing personalizadas, design de produtos e desenvolvimento de materiais de treinamento, entre outras aplicações.

## 4. Sofisticação do Machine Learning

Os algoritmos de machine learning passarão por uma evolução significativa em 2024, tornando-se mais autônomos e eficientes. A expectativa é que esses algoritmos consigam descobrir insights valiosos e realizar previsões com maior precisão, utilizando técnicas avançadas e maiores volumes de dados. Isso permitirá que as empresas tomem decisões mais informadas e se adaptem rapidamente às mudanças do mercado, melhorando suas estratégias e oferta de produtos.

## 5. Acessibilidade e Segurança da IA

Em 2024, a redução dos custos das tecnologias de IA permitirá que um número crescente de organizações adote essas soluções. Contudo, com essa acessibilidade, haverá uma necessidade crítica de segurança cibernética. As empresas precisarão implementar medidas robustas para proteger suas inovações contra ataques potencialmente prejudiciais. A proteção de dados e as questões de privacidade estarão no centro da discussão, destacando a importância de integrar segurança em todas as fases do desenvolvimento e operação da IA.

## 6. Personalização da Experiência do Consumidor

Os algoritmos de IA têm o potencial de transformar a forma como as empresas interagem com seus clientes. Em 2024, espera-se que as empresas utilizem a IA para oferecer experiências personalizadas, utilizando dados para entender melhor as preferências dos clientes e atender a suas necessidades específicas. Essa abordagem não só aumenta a satisfação do cliente, mas também promove a fidelidade, resultando em um aumento nas taxas de retenção e, consequentemente, nas receitas.

## 7. Evolução dos Chatbots

Os chatbots estão se tornando mais sofisticados, incorporando aprendizado de máquina e processamento de linguagem natural para melhorar a interação com o cliente. Para 2024, espera-se que esses sistemas sejam capazes de manter conversas mais naturais, entender contextos complexos e fornecer suporte mais eficaz. Com isso, as empresas poderão oferecer um atendimento ao cliente mais rápido e eficiente, melhorando a experiência geral do consumidor.

## 8. Regulamentações para IA

Em 2024, novas regulamentações para a IA estão sendo esperadas, enfocando questões éticas, de privacidade e a segurança no uso da tecnologia. À medida que a IA se torna mais prevalente e impacta mais vidas, a necessidade de um quadro regulatório claro e robusto será essencial. Os governos e organizações estarão sob pressão para garantir que a IA seja implementada de maneira responsável e que a privacidade dos dados dos usuários seja protegida.

## 9. Modelo de Licenciamento para Startups de IA

As startups de inteligência artificial estão cada vez mais optando por acordos de licenciamento com grandes empresas de tecnologia. Essa estratégia não apenas oferece uma oportunidade de sobrevivência financeira, mas também permite que essas startups acessem capital e expertise técnica sem a necessidade de uma fusão ou aquisição total. Esse modelo pode impulsionar a inovação e facilitar a colaboração entre grandes empresas e novos talentos no cenário de IA.

## 10. IA Quântica

A IA quântica está emergindo como uma área promissora, com avanços potenciais significativos em 2024. A pesquisa e a aplicação de IA quântica podem revolucionar setores como finanças, saúde e segurança cibernética, trazendo novas capacidades de processamento e análise de dados que estavam além do alcance das tecnologias clássicas. Esse desenvolvimento pode não só otimizar operações, mas também abrir novas oportunidades de negócios e soluções inovadoras em diversas indústrias.

Esse relatório destaca as tendências que moldarão a inteligência artificial nos próximos anos, proporcionando um entendimento das mudanças que estão por vir e como essas transformações impactarão as organizações e consumidores. Acompanhar essas tendências é essencial para a inovação e a competitividade no mercado global.
Empty file.
41 changes: 41 additions & 0 deletions wordpress-publisher/src/agencia_noticias/config/agents.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
researcher:
role: >
{topic} Senior Data Researcher
goal: >
Uncover cutting-edge developments in {topic}
backstory: >
You're a seasoned researcher with a knack for uncovering the latest
news in {topic}. Known for your ability to find the most relevant
information and present it in a clear and concise manner.
You always provide the source (link) to the information you find.

reporting_analyst:
role: >
{topic} Reporting Analyst
goal: >
Create detailed reports based on {topic} data analysis and research findings
backstory: >
You're a meticulous analyst with a keen eye for detail. You're known for
your ability to turn complex data into clear and concise reports, making
it easy for others to understand and act on the information you provide.

translator:
role: >
{topic} Translator
goal: >
Translate the information to Brazilian Portuguese
backstory: >
You're a skilled translator with a deep understanding of {topic}. You're
known for your ability to accurately translate complex information into
Brazilian Portuguese, making it accessible to a wider audience.

blog_publisher:
role: >
{topic} Blog Publisher
goal: >
Publish the finalized report in {topic} to the WordPress blog.
backstory: >
You are an expert in content management and blog publishing. Your goal
is to ensure the report reaches the target audience by posting it
accurately and promptly on the WordPress blog. You make sure the
formatting is correct and that the blog post is properly tagged.
32 changes: 32 additions & 0 deletions wordpress-publisher/src/agencia_noticias/config/tasks.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
research_task:
description: >
Conduct a thorough research about {topic}
Make sure you find any interesting and relevant information given
the current year is 2024.
expected_output: >
A list with 10 bullet points of the most relevant information about {topic}
agent: researcher

reporting_task:
description: >
Review the context you got and expand each topic into a full section for a report.
Make sure the report is detailed and contains any and all relevant information.
expected_output: >
A fully fledge reports with the mains topics, each with a full section of information.
Formatted as markdown without '```'
agent: reporting_analyst

translate_task:
description: >
Translate the information to Brazilian Portuguese
expected_output: >
A fully translated report in Brazilian Portuguese
Formated as markdown with out '```'

publish_task:
description: >
Post the fully translated report to the WordPress blog.
The content is stored in the file 'report_ptbr.md'.
expected_output: >
The report should be published to the WordPress blog with the appropriate title, tags, and content.
agent: blog_publisher
103 changes: 103 additions & 0 deletions wordpress-publisher/src/agencia_noticias/crew.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
import os

# Uncomment the following line to use an example of a custom tool
# from agencia_noticias.tools.custom_tool import MyCustomTool

from crewai_tools import ScrapeWebsiteTool
from crewai_tools import SerperDevTool

# Adicionar a ferramenta para publicar no WordPress
# Assumindo que você tem uma ferramenta personalizada chamada WordPressPublishTool
from agencia_noticias.tools.wp_publisher import WordPressPublishTool

scrape_tool = ScrapeWebsiteTool()
search_tool = SerperDevTool()

wordpress_tool = WordPressPublishTool(
blog_url="https://your-website.com/", # URL do seu blog WordPress
token=os.getenv('BLOG_API') # Token JWT ou credenciais de API
) # Ferramenta personalizada para publicação no WordPress

@CrewBase
class AgenciaNoticiasCrew():
"""AgenciaNoticias crew"""

agents_config = 'config/agents.yaml'
tasks_config = 'config/tasks.yaml'

@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
tools=[
scrape_tool,
search_tool
],
verbose=True
)

@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'],
verbose=True
)

@agent
def translator(self) -> Agent:
return Agent(
config=self.agents_config['translator'],
verbose=True
)

# Novo agente para publicação no WordPress
@agent
def blog_publisher(self) -> Agent:
return Agent(
config=self.agents_config['blog_publisher'],
tools=[wordpress_tool], # Ferramenta de publicação no WordPress
verbose=True
)

@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_task'],
)

@task
def reporting_task(self) -> Task:
return Task(
config=self.tasks_config['reporting_task'],
output_file='report.md'
)

@task
def translate_task(self) -> Task:
return Task(
config=self.tasks_config['translate_task'],
agent=self.translator(),
output_file='report_ptbr.md'
)

# Nova tarefa para publicar no blog WordPress
@task
def publish_task(self) -> Task:
return Task(
config=self.tasks_config['publish_task'],
agent=self.blog_publisher(), # Agente de publicação
input_file='report_ptbr.md' # O arquivo que será publicado
)

@crew
def crew(self) -> Crew:
"""Creates the AgenciaNoticias crew"""
return Crew(
agents=self.agents, # Automatically created by the @agent decorator
tasks=self.tasks, # Automatically created by the @task decorator
process=Process.sequential,
verbose=True,
# process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/
)
55 changes: 55 additions & 0 deletions wordpress-publisher/src/agencia_noticias/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env python
import sys
from agencia_noticias.crew import AgenciaNoticiasCrew
input_cmd = sys.argv[1]

# This main file is intended to be a way for your to run your
# crew locally, so refrain from adding necessary logic into this file.
# Replace with inputs you want to test with, it will automatically
# interpolate any tasks and agents information

def run():
"""
Run the crew.
"""
inputs = {
'topic': input_cmd
}
AgenciaNoticiasCrew().crew().kickoff(inputs=inputs)


def train():
"""
Train the crew for a given number of iterations.
"""
inputs = {
"topic": "AI LLMs"
}
try:
AgenciaNoticiasCrew().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs)

except Exception as e:
raise Exception(f"An error occurred while training the crew: {e}")

def replay():
"""
Replay the crew execution from a specific task.
"""
try:
AgenciaNoticiasCrew().crew().replay(task_id=sys.argv[1])

except Exception as e:
raise Exception(f"An error occurred while replaying the crew: {e}")

def test():
"""
Test the crew execution and returns the results.
"""
inputs = {
"topic": "AI LLMs"
}
try:
AgenciaNoticiasCrew().crew().test(n_iterations=int(sys.argv[1]), openai_model_name=sys.argv[2], inputs=inputs)

except Exception as e:
raise Exception(f"An error occurred while replaying the crew: {e}")
Empty file.
12 changes: 12 additions & 0 deletions wordpress-publisher/src/agencia_noticias/tools/custom_tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from crewai_tools import BaseTool


class MyCustomTool(BaseTool):
name: str = "Name of my tool"
description: str = (
"Clear description for what this tool is useful for, you agent will need this information to use it."
)

def _run(self, argument: str) -> str:
# Implementation goes here
return "this is an example of a tool output, ignore it and move along."
Loading