Skip to main content

AI Agent with Claude Haiku to Generate Blog Articles from the Terminal

Rogelio Guerra Riverón
Author
Rogelio Guerra Riverón
Building my own web infrastructure from scratch. Here I document each step: servers, networks, containers and everything that comes along.

Why Automate Content Generation
#

Writing technical articles takes time. Between server configuration, troubleshooting, and documentation, I find little time to write. So I decided to create an AI agent to help me structure and generate drafts from the terminal.

Claude Haiku is perfect for this: it’s fast, cheap, and works well for text generation tasks. It doesn’t require powerful GPUs. I simply run a script and have an article ready to edit.

Requirements
#

  • Anthropic account with access to Claude API
  • API token configured in an environment variable
  • Python 3.10+
  • anthropic library installed
pip install anthropic

The Agent in Practice
#

I created a script that receives as input:

  • A topic or concept to document
  • The desired number of sections
  • The tone (technical, educational, etc.)

And it generates a Markdown article ready to publish.

Implementation
#

Here’s the base script I use:

#!/usr/bin/env python3

import anthropic
import sys
from datetime import datetime

def generate_article(topic: str, sections: int = 5, tone: str = "técnico") -> str:
    """
    Genera un artículo de blog usando Claude Haiku
    """
    
    client = anthropic.Anthropic()
    
    prompt = f"""Eres un escritor técnico especializado en servidores, Docker y automatización.
    
Genera un artículo de blog sobre: {topic}

Requisitos:
- Número de secciones principales: {sections}
- Tono: {tone}
- Incluye ejemplos de código cuando sea relevante
- Usa formato Markdown
- Longitud: 600-800 palabras
- Sé práctico y directo, sin florituras
- Primera persona cuando sea apropiado

Estructura recomendada:
1. Introducción (por qué es importante)
2. Requisitos previos
3. Pasos o explicación principal (puede dividirse en subsecciones)
4. Configuración o ejemplo práctico
5. Conclusión

Genera el artículo completo en Markdown, listo para publicar."""

    message = client.messages.create(
        model="claude-3-5-haiku-20241022",
        max_tokens=2000,
        messages=[
            {"role": "user", "content": prompt}
        ]
    )
    
    return message.content[0].text

def save_article(content: str, filename: str) -> None:
    """
    Guarda el artículo en un archivo con frontmatter
    """
    
    frontmatter = f"""---
title: "{filename.replace('-', ' ').title()}"
date: {datetime.now().strftime('%Y-%m-%d')}
draft: false
tags: ["técnica", "servidor", "automatización"]
description: "Artículo generado con asistencia de IA"
---

"""
    
    with open(f"{filename}.md", "w", encoding="utf-8") as f:
        f.write(frontmatter + content)
    
    print(f"✓ Artículo guardado en {filename}.md")

def main():
    if len(sys.argv) < 2:
        print("Uso: python blog_agent.py '<tema>' [secciones] [tono]")
        print("Ejemplo: python blog_agent.py 'Docker en producción' 5 técnico")
        sys.exit(1)
    
    topic = sys.argv[1]
    sections = int(sys.argv[2]) if len(sys.argv) > 2 else 5
    tone = sys.argv[3] if len(sys.argv) > 3 else "técnico"
    
    print(f"Generando artículo sobre: {topic}...")
    print("Esto puede tomar 30-60 segundos...\n")
    
    content = generate_article(topic, sections, tone)
    
    filename = topic.lower().replace(" ", "-").replace("'", "")
    save_article(content, filename)
    
    print("\nPrimeras líneas del artículo:")
    print("-" * 50)
    print(content[:300] + "...\n")

if __name__ == "__main__":
    main()

Using it in Practice
#

I run the script like this:

python blog_agent.py 'Configurar Nginx con SSL en Docker' 5 técnico

In less than a minute I have a .md file with a complete draft. Then I review it, correct specific details, and publish it.

Real Advantages
#

  • Speed: From topic to draft in 1-2 minutes
  • Consistency: The format is always coherent
  • Starting point: I don’t start from a blank page
  • Economical: Haiku is very cheap compared to other models

Limitations
#

The agent generates generic content. I always need to add:

  • Specific details from my actual configurations
  • Exact commands I used
  • Errors I faced and how I resolved them
  • My personal perspective

It’s an assistant, not a replacement. But it saves a lot of time on structure and initial writing.

Conclusion
#

Using AI to automate technical writing makes sense if you combine it with human editing. This agent allows me to document experiences faster without sacrificing quality. If you write frequently on a technical blog, it’s worth experimenting.


Recommended Equipment#

Affiliate links. No extra cost to you.