Skip to main content

Overview

The AIAnalyzer class provides integration with OpenAI’s GPT models to generate structured summaries of job postings. It analyzes extracted skills and requirements to produce professional insights about the role.

AIAnalyzer

Class Definition

from openai import OpenAI
from typing import List

class AIAnalyzer:
    """Clase responsable de la comunicación con modelos de Inteligencia Artificial (OpenAI)."""

Constructor

def __init__(self):
    api_key = os.getenv("OPENAI_API_KEY")
    
    if api_key:
        self.client = OpenAI(api_key=api_key)
    else:
        self.client = None
Initialization Process:
  1. Loads environment variables from .env file using dotenv
  2. Retrieves OPENAI_API_KEY from environment variables
  3. Initializes OpenAI client if API key is found
  4. Sets self.client to None if no API key is configured
The constructor will print a warning message if OPENAI_API_KEY is not found in environment variables, but will not raise an exception. Methods will fail gracefully when called.
Example:
# Create .env file first
# OPENAI_API_KEY=sk-your-api-key-here

from inteligencia_artificial.gpt_analyzer import AIAnalyzer

analyzer = AIAnalyzer()
# Prints warning if OPENAI_API_KEY not configured

Methods

generar_resumen()

Generates a structured professional summary of a job posting by analyzing the title and extracted skills using GPT.
def generar_resumen(self, titulo: str, habilidades: List[str]) -> str:
titulo
str
required
The job posting title (e.g., “Senior Python Developer”)
habilidades
List[str]
required
List of cleaned skills and requirements extracted from the job description. Should be pre-cleaned using TextCleaner.limpiar_habilidades().
return
str
Markdown-formatted summary containing:
  • Objetivo del Rol: One-sentence description of what the role seeks
  • Stack Tecnológico Principal: Top 5 most important technologies mentioned
  • Skills Blandas: Soft skills and personal attributes required
  • Nivel de Experiencia: Inferred seniority level (Junior, Mid, Senior)
Returns an error message string if:
  • OpenAI API key is not configured
  • Skills list is empty
  • API call fails (network error, quota exceeded, etc.)
Configuration:
  • Model: gpt-3.5-turbo (can be changed to gpt-4o-mini or gpt-4)
  • Temperature: 0.7 (balanced creativity)
  • Max Tokens: 500 (concise responses)
  • Token Optimization: Only the first 30 skills are sent to the API to reduce costs
Example Usage:
from inteligencia_artificial.gpt_analyzer import AIAnalyzer

analyzer = AIAnalyzer()

titulo = "Senior Full Stack Developer"
habilidades = [
    "React, TypeScript, Node.js",
    "5+ years of experience",
    "Strong communication skills",
    "AWS cloud infrastructure",
    "CI/CD pipelines"
]

resumen = analyzer.generar_resumen(titulo, habilidades)
print(resumen)
Output Example:
**Objetivo del Rol**: Desarrollar y mantener aplicaciones full stack escalables con tecnologías modernas.

**Stack Tecnológico Principal**:
1. React
2. TypeScript
3. Node.js
4. AWS
5. CI/CD

**Skills Blandas**: Comunicación efectiva, trabajo en equipo, resolución de problemas.

**Nivel de Experiencia**: Senior (5+ años)

Prompt Engineering

The analyzer uses a carefully crafted prompt that instructs GPT to act as an expert technical recruiter. The prompt structure:
prompt = f"""
Actúa como un reclutador experto en tecnología. Analiza la siguiente oferta de trabajo.

Título del puesto: {titulo}

Fragmentos extraídos de la descripción:
{lista_texto}

Por favor, genera un resumen estructurado en Markdown que incluya:
1. **Objetivo del Rol**: En una frase, ¿qué buscan?
2. **Stack Tecnológico Principal**: Las 5 herramientas más importantes mencionadas.
3. **Skills Blandas**: ¿Qué aptitudes personales buscan?
4. **Nivel de Experiencia**: ¿Parece Junior, Mid o Senior? (Deduce basado en el texto).

Sé conciso y profesional.
"""

System Message

{"role": "system", "content": "Eres un asistente experto en RRHH y tecnología."}
The system message establishes the AI’s role as an HR and technology expert.

Error Handling

The class implements graceful error handling for common scenarios:
Returns: "⚠️ No se ha configurado la API Key de OpenAI. Crea un archivo .env con OPENAI_API_KEY=..."
Returns: "⚠️ No se encontraron habilidades para analizar."
Returns: "❌ Error al consultar ChatGPT: {error_details}"Common causes:
  • Network connectivity issues
  • Rate limit exceeded
  • Insufficient API credits
  • Invalid API key

Dependencies

import os
from typing import List
from openai import OpenAI
from dotenv import load_dotenv
Requires openai and python-dotenv packages. Install with:
pip install openai python-dotenv

Best Practices

API Key Security

Never hardcode API keys. Always use environment variables stored in .env files that are excluded from version control.

Cost Optimization

The analyzer limits skills to the first 30 items to reduce token usage and API costs while maintaining analysis quality.

Pre-clean Data

Always clean skills with TextCleaner before passing to generar_resumen() to improve GPT analysis quality.

Model Selection

Use gpt-3.5-turbo for speed and cost-effectiveness. Upgrade to gpt-4 for higher quality analysis if needed.

Build docs developers (and LLMs) love