0Pricing
AI Agents · Aula

Construindo um agente de briefing diário

Resumo matinal: notícias + agenda + resumo de e-mails entregues automaticamente.

Construindo um agente de briefing diário é uma aula grátis de AI Agents no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de AI Agents, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de AI Agents inclui 4 aulas no total.

O que é um agente de resumo diário?

Um agente de resumo diário é executado em um horário programado todas as manhãs, reúne informações de várias fontes (calendário, e-mail e notícias), sintetiza-as com um LLM e entrega um resumo personalizado. É o exemplo clássico de um agente pessoal programado.

Arquitetura do resumo

O fluxo do resumo tem cinco etapas:

  • Acionamento: a tarefa cron das 8h inicia o agente
  • Busca: reúne eventos do calendário, e-mails não lidos e manchetes de notícias (em paralelo)
  • Síntese: o LLM cria um resumo coeso com base em todos os dados
  • Personalização: adapta o tom e o conteúdo às preferências do usuário
  • Entrega: envia por e-mail ou DM do Slack
from dataclasses import dataclass, field
from typing import List, Dict, Any

@dataclass
class DailyBriefingData:
    date: str
    calendar_events: List[Dict] = field(default_factory=list)
    unread_emails: List[Dict] = field(default_factory=list)
    news_headlines: List[Dict] = field(default_factory=list)
    weather: Dict = field(default_factory=dict)
    briefing_text: str = ''
    delivery_status: str = 'pending'

print('Daily briefing data structure defined')

Agendamento com APScheduler

Programe o resumo para ser executado às 8h em todos os dias úteis. Use o APScheduler com persistência no SQLite para que a tarefa sobreviva às reinicializações do servidor.

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.triggers.cron import CronTrigger
import asyncio

scheduler = BackgroundScheduler(
    jobstores={'default': SQLAlchemyJobStore(url='sqlite:///jobs.db')},
    timezone='America/New_York'
)

def run_briefing_job():
    print('Daily briefing job triggered')
    asyncio.run(generate_and_deliver_briefing('user-42'))

# 8am Monday-Friday
scheduler.add_job(
    run_briefing_job,
    CronTrigger(day_of_week='mon-fri', hour=8, minute=0),
    id='daily_briefing_user_42',
    replace_existing=True
)

scheduler.start()
print('Briefing scheduler started: runs Mon-Fri at 8am ET')

Busca de eventos do calendário

Busque os eventos do calendário de hoje usando a API do Google Calendar. O agente precisa saber quais reuniões estão agendadas para poder incluí-las no resumo.

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from datetime import datetime, timedelta
import pytz

def get_todays_calendar_events(token_path: str = 'token.json', timezone: str = 'America/New_York') -> list:
    creds = Credentials.from_authorized_user_file(token_path)
    service = build('calendar', 'v3', credentials=creds)
    
    tz = pytz.timezone(timezone)
    now = datetime.now(tz)
    start_of_day = now.replace(hour=0, minute=0, second=0, microsecond=0)
    end_of_day = now.replace(hour=23, minute=59, second=59)
    
    result = service.events().list(
        calendarId='primary',
        timeMin=start_of_day.isoformat(),
        timeMax=end_of_day.isoformat(),
        singleEvents=True,
        orderBy='startTime'
    ).execute()
    
    events = []
    for item in result.get('items', []):
        start = item.get('start', {}).get('dateTime', item.get('start', {}).get('date'))
        events.append({
            'title': item.get('summary', 'Untitled'),
            'start': start,
            'attendees': len(item.get('attendees', [])),
            'location': item.get('location', '')
        })
    return events

Busca de e-mails não lidos

Busque os e-mails não lidos mais recentes. O agente de resumo precisa apenas de resumos — títulos e remetentes — e não do conteúdo completo, para manter o contexto do LLM sob controle.

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
import base64

def get_email_summaries(token_path: str = 'token.json', max_results: int = 10) -> list:
    creds = Credentials.from_authorized_user_file(token_path)
    service = build('gmail', 'v1', credentials=creds)
    
    results = service.users().messages().list(
        userId='me',
        q='is:unread newer_than:1d',
        maxResults=max_results
    ).execute()
    
    summaries = []
    for msg in results.get('messages', []):
        detail = service.users().messages().get(
            userId='me',
            id=msg['id'],
            format='metadata',
            metadataHeaders=['From', 'Subject', 'Date']
        ).execute()
        
        headers = {h['name']: h['value'] for h in detail['payload']['headers']}
        summaries.append({
            'from': headers.get('From', ''),
            'subject': headers.get('Subject', 'No Subject'),
            'date': headers.get('Date', '')
        })
    
    return summaries

Busca de manchetes de notícias

Busque manchetes de notícias relevantes usando uma API de notícias. Filtre-as pelos tópicos de interesse configurados pelo usuário para criar uma seção de notícias personalizada.

import httpx
import os

NEWS_API_KEY = os.environ.get('NEWS_API_KEY', 'your-key')

async def get_news_headlines(topics: list, max_per_topic: int = 3) -> list:
    headlines = []
    
    async with httpx.AsyncClient() as client:
        for topic in topics:
            try:
                response = await client.get(
                    'https://newsapi.org/v2/top-headlines',
                    params={
                        'q': topic,
                        'language': 'en',
                        'pageSize': max_per_topic,
                        'apiKey': NEWS_API_KEY
                    },
                    timeout=10.0
                )
                data = response.json()
                for article in data.get('articles', []):
                    headlines.append({
                        'topic': topic,
                        'title': article.get('title', ''),
                        'source': article.get('source', {}).get('name', ''),
                        'url': article.get('url', '')
                    })
            except Exception as e:
                print(f'News fetch failed for {topic}: {e}')
    
    return headlines[:10]  # Cap total

Busca paralela de dados

Busque eventos do calendário, e-mails, notícias e informações meteorológicas ao mesmo tempo. Como são independentes, a busca paralela reduz o tempo total de aproximadamente 4 segundos para aproximadamente 1 segundo.

import asyncio
from datetime import datetime

async def fetch_all_briefing_data(user_prefs: dict) -> 'DailyBriefingData':
    data = DailyBriefingData(date=datetime.now().strftime('%A, %B %d, %Y'))
    
    async def safe_get_calendar():
        try:
            return get_todays_calendar_events()
        except Exception as e:
            print(f'Calendar fetch failed: {e}')
            return []
    
    async def safe_get_emails():
        try:
            return get_email_summaries()
        except Exception as e:
            print(f'Email fetch failed: {e}')
            return []
    
    async def safe_get_news():
        topics = user_prefs.get('news_topics', ['technology', 'business'])
        return await get_news_headlines(topics)
    
    # Run all fetches in parallel
    calendar_events, emails, news = await asyncio.gather(
        safe_get_calendar(),
        safe_get_emails(),
        safe_get_news(),
        return_exceptions=False
    )
    
    data.calendar_events = calendar_events
    data.unread_emails = emails
    data.news_headlines = news
    
    return data

Síntese pelo LLM

Envie todos os dados obtidos ao LLM e peça que ele escreva um resumo natural e personalizado. A estrutura da instrução é importante: organize os dados com clareza para que o LLM produza um resumo bem estruturado.

import openai
import json

client = openai.OpenAI(api_key='sk-...')

def synthesize_briefing(data: 'DailyBriefingData', user_prefs: dict) -> str:
    user_name = user_prefs.get('name', 'there')
    tone = user_prefs.get('briefing_tone', 'professional')  # 'casual', 'professional', 'concise'
    
    calendar_text = json.dumps(data.calendar_events[:5], indent=2) if data.calendar_events else 'No meetings today.'
    email_text = json.dumps(data.unread_emails[:5], indent=2) if data.unread_emails else 'No unread emails.'
    news_text = '\n'.join([f'- [{h["topic"]}] {h["title"]} ({h["source"]})' for h in data.news_headlines[:6]])
    
    prompt = (
        f'Create a {tone} morning briefing for {user_name} for {data.date}.\n\n'
        f'Today\'s calendar:\n{calendar_text}\n\n'
        f'Unread emails:\n{email_text}\n\n'
        f'News headlines:\n{news_text}\n\n'
        'Write a concise, actionable briefing in 3-4 paragraphs. '
        'Start with today\'s schedule, then email highlights, then relevant news. '
        'End with one suggested priority for the day.'
    )
    
    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}],
        temperature=0.3
    )
    return response.choices[0].message.content

Entrega por e-mail

Formate o resumo como um e-mail HTML e envie-o. Uma boa formatação de e-mail HTML facilita a leitura em dispositivos móveis, onde a maioria das pessoas lê seus resumos da manhã.

def format_briefing_email(briefing_text: str, data: 'DailyBriefingData') -> str:
    paragraphs = briefing_text.split('\n\n')
    html_paragraphs = ''.join([f'<p>{p}</p>' for p in paragraphs if p.strip()])
    
    calendar_items = ''.join([
        f'<li><strong>{e["start"][:16]}</strong> - {e["title"]}</li>'
        for e in data.calendar_events[:5]
    ])
    
    return f'''
    <html><body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
    <h2 style="color: #333;">Morning Briefing — {data.date}</h2>
    {html_paragraphs}
    {'<h3>Today\'s Calendar</h3><ul>' + calendar_items + '</ul>' if calendar_items else ''}
    <hr>
    <p style="color: #666; font-size: 12px;">Generated by your Personal AI Assistant</p>
    </body></html>
    '''

def deliver_briefing_email(data: 'DailyBriefingData', user_prefs: dict):
    html = format_briefing_email(data.briefing_text, data)
    to_email = user_prefs.get('email', '')
    send_email_alert(
        to_email=to_email,
        subject=f'Morning Briefing - {data.date}',
        html_body=html
    )

print('Email delivery function defined')

Entrega por DM do Slack

Para usuários que trabalham principalmente no Slack, entregar o resumo como uma DM formatada do Slack costuma ser preferível ao e-mail. Use o Block Kit para obter uma formatação avançada.

from slack_sdk import WebClient
import os

slack_client = WebClient(token=os.environ.get('SLACK_BOT_TOKEN', 'xoxb-...'))

def deliver_briefing_slack(data: 'DailyBriefingData', user_prefs: dict):
    slack_user_id = user_prefs.get('slack_user_id')
    if not slack_user_id:
        print('No Slack user ID configured')
        return
    
    # Split briefing into sections for blocks
    paragraphs = [p for p in data.briefing_text.split('\n\n') if p.strip()]
    
    blocks = [
        {'type': 'header', 'text': {'type': 'plain_text', 'text': f'Morning Briefing - {data.date}'}},
        {'type': 'divider'}
    ]
    
    for para in paragraphs[:4]:  # Max 4 paragraphs
        blocks.append({
            'type': 'section',
            'text': {'type': 'mrkdwn', 'text': para}
        })
    
    if data.calendar_events:
        event_list = '\n'.join([f'• {e["start"][:16]} - {e["title"]}' for e in data.calendar_events[:3]])
        blocks.append({'type': 'section', 'text': {'type': 'mrkdwn', 'text': f'*Meetings*\n{event_list}'}})
    
    slack_client.chat_postMessage(
        channel=slack_user_id,
        text=f'Morning Briefing - {data.date}',
        blocks=blocks
    )
    print(f'Briefing delivered to Slack user {slack_user_id}')

Orquestrador principal do resumo

O orquestrador conecta todas as etapas: busca dados em paralelo, faz a síntese com LLM, entrega o resultado pelo canal preferido e registra o resultado para monitoramento.

import asyncio
from datetime import datetime

async def generate_and_deliver_briefing(user_id: str):
    print(f'Generating briefing for {user_id} at {datetime.now()}')
    
    # Load user preferences
    conn = init_db()
    user_prefs = load_user_preferences(conn, user_id)
    
    # Step 1: Fetch all data in parallel
    data = await fetch_all_briefing_data(user_prefs)
    
    if not data.calendar_events and not data.unread_emails and not data.news_headlines:
        print('No data fetched, skipping briefing')
        return
    
    # Step 2: Synthesize with LLM
    data.briefing_text = synthesize_briefing(data, user_prefs)
    
    # Step 3: Deliver
    delivery_channel = user_prefs.get('delivery_channel', 'email')
    if delivery_channel == 'slack':
        deliver_briefing_slack(data, user_prefs)
    else:
        deliver_briefing_email(data, user_prefs)
    
    data.delivery_status = 'delivered'
    
    # Step 4: Log
    print(f'Briefing delivered via {delivery_channel}')
    print(f'Data: {len(data.calendar_events)} events, {len(data.unread_emails)} emails, {len(data.news_headlines)} headlines')

print('Daily briefing orchestrator defined')

Verificação de compreensão: agente de resumo diário

Verifique sua compreensão sobre como criar um agente de resumo diário.

Resumo do agente de resumo diário

Um agente de resumo diário completo combina: APScheduler para execução de uma tarefa cron às 8h nos dias úteis, busca paralela de dados das APIs de calendário, e-mail e notícias, síntese por LLM para criar um resumo personalizado e coerente, personalização orientada pelas preferências do usuário e entrega multicanal por e-mail ou DM do Slack. Esse é o padrão clássico de um agente pessoal sempre ativo e demonstra todos os conceitos deste curso.

Perguntas Frequentes

A aula “Construindo um agente de briefing diário” é grátis?

Sim — o texto completo de “Construindo um agente de briefing diário” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de AI Agents, atualize para CoddyKit PRO. O curso de AI Agents inclui 4 aulas no total.

O que vou aprender em “Construindo um agente de briefing diário”?

Resumo matinal: notícias + agenda + resumo de e-mails entregues automaticamente. Você pratica AI Agents com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar AI Agents?

Nenhuma experiência prévia é necessária. AI Agents no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Construindo um agente de briefing diário”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de AI Agents?

Sim. Cada aula de AI Agents inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Padrões de projeto para agentes sempre ativos
  2. Sistemas proativos de notificações e alertas
  3. Persistência de contexto entre sessões
  4. Construindo um agente de briefing diário
← Voltar para AI Agents