ES: chapter 09 translated
This commit is contained in:
@@ -1,191 +1,177 @@
|
||||
Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation.
|
||||
Los formatos de datos estructurados como JSON y YAML son esenciales para construir aplicaciones que consumen salidas de IA programáticamente. Este capítulo cubre técnicas para generación confiable de salidas estructuradas.
|
||||
|
||||
<Callout type="info" title="From Text to Data">
|
||||
JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly.
|
||||
<Callout type="info" title="De Texto a Datos">
|
||||
JSON y YAML transforman las salidas de IA de texto libre en datos estructurados y con tipos seguros que el código puede consumir directamente.
|
||||
</Callout>
|
||||
|
||||
## Why Structured Formats?
|
||||
## ¿Por Qué Formatos Estructurados?
|
||||
|
||||
<JsonYamlDemo />
|
||||
|
||||
## JSON Prompting Basics
|
||||
## Fundamentos de Prompting con JSON
|
||||
|
||||
JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline.
|
||||
JSON (JavaScript Object Notation) es el formato más común para salidas programáticas de IA. Su sintaxis estricta lo hace fácil de parsear, pero también significa que pequeños errores pueden romper toda tu pipeline.
|
||||
|
||||
### Do's and Don'ts: Requesting JSON
|
||||
### Do's y Don'ts: Solicitar JSON
|
||||
|
||||
<Compare
|
||||
before={{ label: "❌ Don't: Vague request", content: "Give me the user info as JSON." }}
|
||||
after={{ label: "✓ Do: Show the schema", content: "Extract user info as JSON matching this schema:\n\n{\n \"name\": \"string\",\n \"age\": number,\n \"email\": \"string\"\n}\n\nReturn ONLY valid JSON, no markdown." }}
|
||||
before={{ label: "❌ No: Solicitud vaga", content: "Dame la info del usuario como JSON." }}
|
||||
after={{ label: "✓ Sí: Muestra el esquema", content: "Extrae la info del usuario como JSON siguiendo este esquema:\n\n{\n \"nombre\": \"string\",\n \"edad\": number,\n \"email\": \"string\"\n}\n\nDevuelve SOLO JSON válido, sin markdown." }}
|
||||
/>
|
||||
|
||||
### Simple JSON Output
|
||||
### Salida JSON Simple
|
||||
|
||||
Start with a schema showing the expected structure. The model will fill in values based on the input text.
|
||||
Comienza con un esquema que muestre la estructura esperada. El modelo llenará los valores basándose en el texto de entrada.
|
||||
|
||||
```
|
||||
Extract the following information as JSON:
|
||||
Extrae la siguiente información como JSON:
|
||||
|
||||
{
|
||||
"name": "string",
|
||||
"age": number,
|
||||
"nombre": "string",
|
||||
"edad": number,
|
||||
"email": "string"
|
||||
}
|
||||
|
||||
Text: "Contact John Smith, 34 years old, at john@example.com"
|
||||
Texto: "Contactar a Juan García, 34 años, en juan@example.com"
|
||||
```
|
||||
|
||||
Output:
|
||||
Salida:
|
||||
```json
|
||||
{
|
||||
"name": "John Smith",
|
||||
"age": 34,
|
||||
"email": "john@example.com"
|
||||
"nombre": "Juan García",
|
||||
"edad": 34,
|
||||
"email": "juan@example.com"
|
||||
}
|
||||
```
|
||||
|
||||
### Nested JSON Structures
|
||||
### Estructuras JSON Anidadas
|
||||
|
||||
Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects.
|
||||
Los datos del mundo real a menudo tienen relaciones anidadas. Define cada nivel de tu esquema claramente, especialmente para arrays de objetos.
|
||||
|
||||
```
|
||||
Parse this order into JSON:
|
||||
Parsea este pedido en JSON:
|
||||
|
||||
{
|
||||
"order_id": "string",
|
||||
"customer": {
|
||||
"name": "string",
|
||||
"numero_pedido": "string",
|
||||
"cliente": {
|
||||
"nombre": "string",
|
||||
"email": "string"
|
||||
},
|
||||
"items": [
|
||||
"articulos": [
|
||||
{
|
||||
"product": "string",
|
||||
"quantity": number,
|
||||
"price": number
|
||||
"producto": "string",
|
||||
"cantidad": number,
|
||||
"precio": number
|
||||
}
|
||||
],
|
||||
"total": number
|
||||
}
|
||||
|
||||
Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each),
|
||||
1x Gadget ($25). Total: $45"
|
||||
Pedido: "Pedido #12345 para María López (maria@email.com): 2x Widget (10€ cada uno),
|
||||
1x Gadget (25€). Total: 45€"
|
||||
```
|
||||
|
||||
### Ensuring Valid JSON
|
||||
### Asegurar JSON Válido
|
||||
|
||||
<Callout type="warning" title="Common Failure Point">
|
||||
Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only.
|
||||
<Callout type="warning" title="Punto de Fallo Común">
|
||||
Los modelos a menudo envuelven JSON en bloques de código markdown o agregan texto explicativo. Sé explícito sobre querer solo JSON crudo.
|
||||
</Callout>
|
||||
|
||||
Add explicit instructions:
|
||||
Agrega instrucciones explícitas:
|
||||
|
||||
```
|
||||
CRITICAL: Return ONLY valid JSON. No markdown, no explanation,
|
||||
no additional text before or after the JSON object.
|
||||
CRÍTICO: Devuelve SOLO JSON válido. Sin markdown, sin explicación,
|
||||
sin texto adicional antes o después del objeto JSON.
|
||||
|
||||
If a field cannot be determined, use null.
|
||||
Ensure all strings are properly quoted and escaped.
|
||||
Numbers should not be quoted.
|
||||
Si un campo no puede determinarse, usa null.
|
||||
Asegúrate de que todos los strings estén correctamente citados y escapados.
|
||||
Los números no deben estar citados.
|
||||
```
|
||||
|
||||
## YAML Prompting Basics
|
||||
## Fundamentos de Prompting con YAML
|
||||
|
||||
YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions).
|
||||
YAML es más legible para humanos que JSON y soporta comentarios. Es el estándar para archivos de configuración, especialmente en DevOps (Docker, Kubernetes, GitHub Actions).
|
||||
|
||||
### Simple YAML Output
|
||||
### Salida YAML Simple
|
||||
|
||||
YAML uses indentation instead of braces. Provide a template showing the expected structure.
|
||||
YAML usa indentación en lugar de llaves. Proporciona una plantilla mostrando la estructura esperada.
|
||||
|
||||
```
|
||||
Generate a configuration file in YAML format:
|
||||
Genera un archivo de configuración en formato YAML:
|
||||
|
||||
server:
|
||||
servidor:
|
||||
host: string
|
||||
port: number
|
||||
puerto: number
|
||||
ssl: boolean
|
||||
database:
|
||||
type: string
|
||||
connection_string: string
|
||||
base_datos:
|
||||
tipo: string
|
||||
cadena_conexion: string
|
||||
|
||||
Requirements: Production server on port 443 with SSL, PostgreSQL database
|
||||
Requisitos: Servidor de producción en puerto 443 con SSL, base de datos PostgreSQL
|
||||
```
|
||||
|
||||
Output:
|
||||
Salida:
|
||||
```yaml
|
||||
server:
|
||||
servidor:
|
||||
host: "0.0.0.0"
|
||||
port: 443
|
||||
puerto: 443
|
||||
ssl: true
|
||||
database:
|
||||
type: "postgresql"
|
||||
connection_string: "postgresql://user:pass@localhost:5432/prod"
|
||||
base_datos:
|
||||
tipo: "postgresql"
|
||||
cadena_conexion: "postgresql://user:pass@localhost:5432/prod"
|
||||
```
|
||||
|
||||
### Complex YAML Structures
|
||||
## Definiciones de Tipos en Prompts
|
||||
|
||||
For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes.
|
||||
Las definiciones de tipos le dan al modelo un contrato preciso para la estructura de salida. Son más explícitas que los ejemplos y más fáciles de validar programáticamente.
|
||||
|
||||
```
|
||||
Generate a GitHub Actions workflow in YAML:
|
||||
### Usar Tipos Estilo TypeScript
|
||||
|
||||
Requirements:
|
||||
- Trigger on push to main and pull requests
|
||||
- Run on Ubuntu latest
|
||||
- Steps: checkout, setup Node 18, install dependencies, run tests
|
||||
- Cache npm dependencies
|
||||
```
|
||||
|
||||
## Type Definitions in Prompts
|
||||
|
||||
Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically.
|
||||
|
||||
### Using TypeScript-like Types
|
||||
|
||||
TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts.
|
||||
Las interfaces de TypeScript son familiares para desarrolladores y describen precisamente campos opcionales, tipos union y arrays.
|
||||
|
||||
<TryIt
|
||||
title="TypeScript Interface Extraction"
|
||||
description="Use a TypeScript interface to extract structured data."
|
||||
prompt={`Extract data according to this type definition:
|
||||
title="Extracción con Interface TypeScript"
|
||||
description="Usa una interface TypeScript para extraer datos estructurados."
|
||||
prompt={`Extrae datos según esta definición de tipo:
|
||||
|
||||
interface ChatPersona {
|
||||
name?: string;
|
||||
role?: string;
|
||||
tone?: "professional" | "casual" | "friendly" | "technical";
|
||||
interface PersonaChat {
|
||||
nombre?: string;
|
||||
rol?: string;
|
||||
tono?: "profesional" | "casual" | "amigable" | "tecnico";
|
||||
expertise?: string[];
|
||||
personality?: string[];
|
||||
background?: string;
|
||||
personalidad?: string[];
|
||||
trasfondo?: string;
|
||||
}
|
||||
|
||||
Return as JSON matching this interface.
|
||||
Devuelve como JSON que coincida con esta interface.
|
||||
|
||||
Description: "A senior software engineer named Alex who reviews code. They're analytical and thorough, with expertise in backend systems and databases. Professional but approachable tone."`}
|
||||
Descripción: "Un ingeniero de software senior llamado Alex que revisa código. Es analítico y minucioso, con expertise en sistemas backend y bases de datos. Tono profesional pero accesible."`}
|
||||
/>
|
||||
|
||||
### JSON Schema Definition
|
||||
### Definición con JSON Schema
|
||||
|
||||
<Callout type="info" title="Industry Standard">
|
||||
JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools.
|
||||
<Callout type="info" title="Estándar de la Industria">
|
||||
JSON Schema es una especificación formal para describir estructura JSON. Es soportado por muchas bibliotecas de validación y herramientas de API.
|
||||
</Callout>
|
||||
|
||||
JSON Schema provides constraints like min/max values, required fields, and regex patterns:
|
||||
JSON Schema proporciona restricciones como valores min/max, campos requeridos y patrones regex:
|
||||
|
||||
```
|
||||
Extract data according to this JSON Schema:
|
||||
Extrae datos según este JSON Schema:
|
||||
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"required": ["title", "author", "year"],
|
||||
"required": ["titulo", "autor", "anio"],
|
||||
"properties": {
|
||||
"title": { "type": "string" },
|
||||
"author": { "type": "string" },
|
||||
"year": { "type": "integer", "minimum": 1000, "maximum": 2100 },
|
||||
"genres": {
|
||||
"titulo": { "type": "string" },
|
||||
"autor": { "type": "string" },
|
||||
"anio": { "type": "integer", "minimum": 1000, "maximum": 2100 },
|
||||
"generos": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" }
|
||||
},
|
||||
"rating": {
|
||||
"calificacion": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 5
|
||||
@@ -193,394 +179,242 @@ Extract data according to this JSON Schema:
|
||||
}
|
||||
}
|
||||
|
||||
Book: "1984 by George Orwell (1949) - A dystopian masterpiece.
|
||||
Genres: Science Fiction, Political Fiction. Rated 4.8/5"
|
||||
Libro: "1984 de George Orwell (1949) - Una obra maestra distópica.
|
||||
Géneros: Ciencia Ficción, Ficción Política. Calificado 4.8/5"
|
||||
```
|
||||
|
||||
## Handling Arrays
|
||||
## Manejar Arrays
|
||||
|
||||
Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases.
|
||||
Los arrays requieren atención especial. Especifica si necesitas un número fijo de elementos o una lista de longitud variable, y cómo manejar casos vacíos.
|
||||
|
||||
### Fixed-Length Arrays
|
||||
### Arrays de Longitud Fija
|
||||
|
||||
When you need exactly N items, state it explicitly. The model will ensure the array has the right length.
|
||||
Cuando necesitas exactamente N elementos, dilo explícitamente.
|
||||
|
||||
```
|
||||
Extract exactly 3 key points as JSON:
|
||||
Extrae exactamente 3 puntos clave como JSON:
|
||||
|
||||
{
|
||||
"key_points": [
|
||||
"string (first point)",
|
||||
"string (second point)",
|
||||
"string (third point)"
|
||||
"puntos_clave": [
|
||||
"string (primer punto)",
|
||||
"string (segundo punto)",
|
||||
"string (tercer punto)"
|
||||
]
|
||||
}
|
||||
|
||||
Article: [article text]
|
||||
Artículo: [texto del artículo]
|
||||
```
|
||||
|
||||
### Variable-Length Arrays
|
||||
### Arrays de Longitud Variable
|
||||
|
||||
For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness.
|
||||
Para arrays de longitud variable, especifica qué hacer cuando hay cero elementos.
|
||||
|
||||
```
|
||||
Extract all mentioned people as JSON:
|
||||
Extrae todas las personas mencionadas como JSON:
|
||||
|
||||
{
|
||||
"people": [
|
||||
"personas": [
|
||||
{
|
||||
"name": "string",
|
||||
"role": "string or null if not mentioned"
|
||||
"nombre": "string",
|
||||
"rol": "string o null si no se menciona"
|
||||
}
|
||||
],
|
||||
"count": number
|
||||
"cantidad": number
|
||||
}
|
||||
|
||||
If no people are mentioned, return empty array.
|
||||
Si no se mencionan personas, devuelve array vacío.
|
||||
|
||||
Text: [text]
|
||||
Texto: [texto]
|
||||
```
|
||||
|
||||
## Enum Values and Constraints
|
||||
## Valores Enum y Restricciones
|
||||
|
||||
Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs.
|
||||
Los enums restringen valores a un conjunto predefinido. Esto es crucial para tareas de clasificación.
|
||||
|
||||
### Do's and Don'ts: Enum Values
|
||||
### Do's y Don'ts: Valores Enum
|
||||
|
||||
<Compare
|
||||
before={{ label: "❌ Don't: Open-ended categories", content: "Classify this text into a category.\n\n{\n \"category\": \"string\"\n}" }}
|
||||
after={{ label: "✓ Do: Restrict to valid values", content: "Classify this text. Category MUST be exactly one of:\n- \"technical\"\n- \"business\"\n- \"creative\"\n- \"personal\"\n\n{\n \"category\": \"one of the values above\"\n}" }}
|
||||
before={{ label: "❌ No: Categorías abiertas", content: "Clasifica este texto en una categoría.\n\n{\n \"categoria\": \"string\"\n}" }}
|
||||
after={{ label: "✓ Sí: Restringir a valores válidos", content: "Clasifica este texto. La categoría DEBE ser exactamente una de:\n- \"tecnico\"\n- \"negocios\"\n- \"creativo\"\n- \"personal\"\n\n{\n \"categoria\": \"uno de los valores anteriores\"\n}" }}
|
||||
/>
|
||||
|
||||
### String Enums
|
||||
## Manejar Datos Faltantes
|
||||
|
||||
List allowed values explicitly. Use "MUST be one of" language to enforce strict matching.
|
||||
Los textos del mundo real a menudo no contienen toda la información. Define cómo el modelo debe manejar datos faltantes para evitar valores inventados.
|
||||
|
||||
```
|
||||
Classify this text. The category MUST be one of these exact values:
|
||||
- "technical"
|
||||
- "business"
|
||||
- "creative"
|
||||
- "personal"
|
||||
|
||||
Return JSON:
|
||||
{
|
||||
"text": "original text (truncated to 50 chars)",
|
||||
"category": "one of the enum values above",
|
||||
"confidence": number between 0 and 1
|
||||
}
|
||||
|
||||
Text: [text to classify]
|
||||
```
|
||||
|
||||
### Validated Numbers
|
||||
|
||||
Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range.
|
||||
|
||||
```
|
||||
Rate these aspects. Each score MUST be an integer from 1 to 5.
|
||||
|
||||
{
|
||||
"quality": 1-5,
|
||||
"value": 1-5,
|
||||
"service": 1-5,
|
||||
"overall": 1-5
|
||||
}
|
||||
|
||||
Review: [review text]
|
||||
```
|
||||
|
||||
## Handling Missing Data
|
||||
|
||||
Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values.
|
||||
|
||||
### Do's and Don'ts: Missing Information
|
||||
### Do's y Don'ts: Información Faltante
|
||||
|
||||
<Compare
|
||||
before={{ label: "❌ Don't: Let AI guess", content: "Extract all company details as JSON:\n{\n \"revenue\": number,\n \"employees\": number\n}" }}
|
||||
after={{ label: "✓ Do: Explicitly allow null", content: "Extract company details. Use null for any field NOT explicitly mentioned. Do NOT invent or estimate values.\n\n{\n \"revenue\": \"number or null\",\n \"employees\": \"number or null\"\n}" }}
|
||||
before={{ label: "❌ No: Dejar que la IA adivine", content: "Extrae todos los detalles de la empresa como JSON:\n{\n \"ingresos\": number,\n \"empleados\": number\n}" }}
|
||||
after={{ label: "✓ Sí: Permitir null explícitamente", content: "Extrae detalles de la empresa. Usa null para cualquier campo que NO se mencione explícitamente. NO inventes ni estimes valores.\n\n{\n \"ingresos\": \"number o null\",\n \"empleados\": \"number o null\"\n}" }}
|
||||
/>
|
||||
|
||||
### Null Values
|
||||
### Valores Null
|
||||
|
||||
Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess.
|
||||
Permite null explícitamente e instruye al modelo a no inventar información.
|
||||
|
||||
```
|
||||
Extract information. Use null for any field that cannot be
|
||||
determined from the text. Do NOT invent information.
|
||||
Extrae información. Usa null para cualquier campo que no pueda
|
||||
determinarse del texto. NO inventes información.
|
||||
|
||||
{
|
||||
"company": "string or null",
|
||||
"revenue": "number or null",
|
||||
"employees": "number or null",
|
||||
"founded": "number (year) or null",
|
||||
"headquarters": "string or null"
|
||||
"empresa": "string o null",
|
||||
"ingresos": "number o null",
|
||||
"empleados": "number o null",
|
||||
"fundada": "number (año) o null",
|
||||
"sede": "string o null"
|
||||
}
|
||||
|
||||
Text: "Apple, headquartered in Cupertino, was founded in 1976."
|
||||
Texto: "Apple, con sede en Cupertino, fue fundada en 1976."
|
||||
```
|
||||
|
||||
Output:
|
||||
Salida:
|
||||
```json
|
||||
{
|
||||
"company": "Apple",
|
||||
"revenue": null,
|
||||
"employees": null,
|
||||
"founded": 1976,
|
||||
"headquarters": "Cupertino"
|
||||
"empresa": "Apple",
|
||||
"ingresos": null,
|
||||
"empleados": null,
|
||||
"fundada": 1976,
|
||||
"sede": "Cupertino"
|
||||
}
|
||||
```
|
||||
|
||||
### Default Values
|
||||
## YAML para Generación de Configuración
|
||||
|
||||
When defaults make sense, specify them in the schema. This is common for configuration extraction.
|
||||
YAML brilla en configuraciones DevOps. El modelo conoce patrones estándar para herramientas comunes.
|
||||
|
||||
```
|
||||
Extract settings with these defaults if not specified:
|
||||
|
||||
{
|
||||
"theme": "light" (default) | "dark",
|
||||
"language": "en" (default) | other ISO code,
|
||||
"notifications": true (default) | false,
|
||||
"fontSize": 14 (default) | number
|
||||
}
|
||||
|
||||
User preferences: "I want dark mode and larger text (18px)"
|
||||
```
|
||||
|
||||
## Multi-Object Responses
|
||||
|
||||
Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements.
|
||||
|
||||
### Array of Objects
|
||||
|
||||
For lists of similar items, define the object schema once and specify it's an array.
|
||||
|
||||
```
|
||||
Parse this list into JSON array:
|
||||
|
||||
[
|
||||
{
|
||||
"task": "string",
|
||||
"priority": "high" | "medium" | "low",
|
||||
"due": "ISO date string or null"
|
||||
}
|
||||
]
|
||||
|
||||
Todo list:
|
||||
- Finish report (urgent, due tomorrow)
|
||||
- Call dentist (low priority)
|
||||
- Review PR #123 (medium, due Friday)
|
||||
```
|
||||
|
||||
### Grouped Objects
|
||||
|
||||
Grouping tasks require categorization logic. The model will sort items into the categories you define.
|
||||
|
||||
```
|
||||
Categorize these items into JSON:
|
||||
|
||||
{
|
||||
"fruits": ["string array"],
|
||||
"vegetables": ["string array"],
|
||||
"other": ["string array"]
|
||||
}
|
||||
|
||||
Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach
|
||||
```
|
||||
|
||||
## YAML for Configuration Generation
|
||||
|
||||
YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs.
|
||||
|
||||
### Do's and Don'ts: YAML Configs
|
||||
### Do's y Don'ts: Configuraciones YAML
|
||||
|
||||
<Compare
|
||||
before={{ label: "❌ Don't: Vague requirements", content: "Generate a docker-compose file for my app." }}
|
||||
after={{ label: "✓ Do: Specify components and needs", content: "Generate docker-compose.yml for:\n- Node.js app (port 3000)\n- PostgreSQL database\n- Redis cache\n\nInclude: health checks, volume persistence, environment from .env file" }}
|
||||
before={{ label: "❌ No: Requisitos vagos", content: "Genera un archivo docker-compose para mi app." }}
|
||||
after={{ label: "✓ Sí: Especificar componentes y necesidades", content: "Genera docker-compose.yml para:\n- App Node.js (puerto 3000)\n- Base de datos PostgreSQL\n- Cache Redis\n\nIncluir: Health checks, persistencia de volúmenes, environment desde archivo .env" }}
|
||||
/>
|
||||
|
||||
### Docker Compose
|
||||
|
||||
Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices.
|
||||
Especifica los servicios que necesitas y cualquier requisito especial.
|
||||
|
||||
```
|
||||
Generate a docker-compose.yml for:
|
||||
- Node.js app on port 3000
|
||||
- PostgreSQL database
|
||||
- Redis cache
|
||||
- Nginx reverse proxy
|
||||
Genera docker-compose.yml para:
|
||||
- App Node.js en puerto 3000
|
||||
- Base de datos PostgreSQL
|
||||
- Cache Redis
|
||||
- Reverse proxy Nginx
|
||||
|
||||
Include:
|
||||
Incluir:
|
||||
- Health checks
|
||||
- Volume persistence
|
||||
- Environment variables from .env file
|
||||
- Network isolation
|
||||
- Persistencia de volúmenes
|
||||
- Variables de entorno desde archivo .env
|
||||
- Aislamiento de red
|
||||
```
|
||||
|
||||
### Kubernetes Manifests
|
||||
## Validación y Manejo de Errores
|
||||
|
||||
Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML.
|
||||
Para sistemas de producción, incluye validación en tus prompts.
|
||||
|
||||
### Prompt de Auto-Validación
|
||||
|
||||
Pide al modelo que valide su propia salida contra reglas que especifiques.
|
||||
|
||||
```
|
||||
Generate Kubernetes deployment YAML:
|
||||
|
||||
Deployment:
|
||||
- Name: api-server
|
||||
- Image: myapp:v1.2.3
|
||||
- Replicas: 3
|
||||
- Resources: 256Mi memory, 250m CPU (requests)
|
||||
- Health checks: /health endpoint
|
||||
- Environment from ConfigMap: api-config
|
||||
|
||||
Also generate matching Service (ClusterIP, port 8080)
|
||||
```
|
||||
|
||||
## Validation and Error Handling
|
||||
|
||||
For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline.
|
||||
|
||||
### Self-Validation Prompt
|
||||
|
||||
Ask the model to validate its own output against rules you specify. This catches format errors and invalid values.
|
||||
|
||||
```
|
||||
Extract data as JSON, then validate your output.
|
||||
Extrae datos como JSON, luego valida tu salida.
|
||||
|
||||
Schema:
|
||||
{
|
||||
"email": "valid email format",
|
||||
"phone": "E.164 format (+1234567890)",
|
||||
"date": "ISO 8601 format (YYYY-MM-DD)"
|
||||
"email": "formato email válido",
|
||||
"telefono": "formato E.164 (+34612345678)",
|
||||
"fecha": "formato ISO 8601 (YYYY-MM-DD)"
|
||||
}
|
||||
|
||||
After generating JSON, check:
|
||||
1. Email contains @ and valid domain
|
||||
2. Phone starts with + and contains only digits
|
||||
3. Date is valid and parseable
|
||||
Después de generar JSON, verifica:
|
||||
1. Email contiene @ y dominio válido
|
||||
2. Teléfono comienza con + y contiene solo dígitos
|
||||
3. Fecha es válida y parseable
|
||||
|
||||
If validation fails, fix the issues before responding.
|
||||
Si la validación falla, corrige los problemas antes de responder.
|
||||
|
||||
Text: [contact information]
|
||||
Texto: [información de contacto]
|
||||
```
|
||||
|
||||
### Error Response Format
|
||||
|
||||
Define separate success and error formats. This makes programmatic handling much easier.
|
||||
|
||||
```
|
||||
Attempt to extract data. If extraction fails, return error format:
|
||||
|
||||
Success format:
|
||||
{
|
||||
"success": true,
|
||||
"data": { ... extracted data ... }
|
||||
}
|
||||
|
||||
Error format:
|
||||
{
|
||||
"success": false,
|
||||
"error": "description of what went wrong",
|
||||
"partial_data": { ... any data that could be extracted ... }
|
||||
}
|
||||
```
|
||||
|
||||
## JSON vs YAML: When to Use Which
|
||||
## JSON vs YAML: Cuándo Usar Cada Uno
|
||||
|
||||
<div className="my-4 grid md:grid-cols-2 gap-4">
|
||||
<div className="p-4 bg-amber-50 dark:bg-amber-950/30 rounded-lg border border-amber-200 dark:border-amber-800">
|
||||
<div className="font-semibold text-amber-700 dark:text-amber-300 mb-2">Use JSON When</div>
|
||||
<div className="font-semibold text-amber-700 dark:text-amber-300 mb-2">Usa JSON cuando</div>
|
||||
<div className="text-sm space-y-1">
|
||||
<p className="m-0!">Programmatic parsing needed</p>
|
||||
<p className="m-0!">API responses</p>
|
||||
<p className="m-0!">Strict type requirements</p>
|
||||
<p className="m-0!">JavaScript/Web integration</p>
|
||||
<p className="m-0!">Compact representation</p>
|
||||
<p className="m-0!">Necesitas parsing programático</p>
|
||||
<p className="m-0!">Respuestas de API</p>
|
||||
<p className="m-0!">Requisitos de tipos estrictos</p>
|
||||
<p className="m-0!">Integración JavaScript/Web</p>
|
||||
<p className="m-0!">Representación compacta</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4 bg-purple-50 dark:bg-purple-950/30 rounded-lg border border-purple-200 dark:border-purple-800">
|
||||
<div className="font-semibold text-purple-700 dark:text-purple-300 mb-2">Use YAML When</div>
|
||||
<div className="font-semibold text-purple-700 dark:text-purple-300 mb-2">Usa YAML cuando</div>
|
||||
<div className="text-sm space-y-1">
|
||||
<p className="m-0!">Human readability matters</p>
|
||||
<p className="m-0!">Configuration files</p>
|
||||
<p className="m-0!">Comments are needed</p>
|
||||
<p className="m-0!">DevOps/Infrastructure</p>
|
||||
<p className="m-0!">Deep nested structures</p>
|
||||
<p className="m-0!">La legibilidad humana importa</p>
|
||||
<p className="m-0!">Archivos de configuración</p>
|
||||
<p className="m-0!">Necesitas comentarios</p>
|
||||
<p className="m-0!">DevOps/Infraestructura</p>
|
||||
<p className="m-0!">Estructuras muy anidadas</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
## Prompts.chat Structured Prompts
|
||||
## Errores Comunes
|
||||
|
||||
On prompts.chat, you can create prompts with structured output formats:
|
||||
|
||||
```
|
||||
When creating a prompt on prompts.chat, you can specify:
|
||||
|
||||
Type: STRUCTURED
|
||||
Format: JSON or YAML
|
||||
|
||||
The platform will:
|
||||
- Validate outputs against your schema
|
||||
- Provide syntax highlighting
|
||||
- Enable easy copying of structured output
|
||||
- Support template variables in your schema
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
<Callout type="warning" title="Debug These First">
|
||||
These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output.
|
||||
<Callout type="warning" title="Depura estos primero">
|
||||
Estos tres problemas causan la mayoría de errores de parsing JSON. Revísalos si tu código no puede parsear salidas de IA.
|
||||
</Callout>
|
||||
|
||||
### 1. Markdown Code Blocks
|
||||
### 1. Bloques de Código Markdown
|
||||
|
||||
**Problem:** Model wraps JSON in ```json blocks
|
||||
**Problema:** El modelo envuelve JSON con bloques ```json
|
||||
|
||||
**Solution:**
|
||||
**Solución:**
|
||||
```
|
||||
Return ONLY the JSON object. Do not wrap in markdown code blocks.
|
||||
Do not include ```json or ``` markers.
|
||||
Devuelve SOLO el objeto JSON. No lo envuelvas con bloques de código markdown.
|
||||
No incluyas marcadores ```json o ```.
|
||||
```
|
||||
|
||||
### 2. Trailing Commas
|
||||
### 2. Comas Finales
|
||||
|
||||
**Problem:** Invalid JSON due to trailing commas
|
||||
**Problema:** JSON inválido por comas finales
|
||||
|
||||
**Solution:**
|
||||
**Solución:**
|
||||
```
|
||||
Ensure valid JSON syntax. No trailing commas after the last
|
||||
element in arrays or objects.
|
||||
Asegura sintaxis JSON válida. Sin comas finales después del
|
||||
último elemento en arrays u objetos.
|
||||
```
|
||||
|
||||
### 3. Unescaped Strings
|
||||
### 3. Strings Sin Escapar
|
||||
|
||||
**Problem:** Quotes or special characters break JSON
|
||||
**Problema:** Comillas o caracteres especiales rompen JSON
|
||||
|
||||
**Solution:**
|
||||
**Solución:**
|
||||
```
|
||||
Properly escape special characters in strings:
|
||||
- \" for quotes
|
||||
- \\ for backslashes
|
||||
- \n for newlines
|
||||
Escapa caracteres especiales en strings correctamente:
|
||||
- \" para comillas
|
||||
- \\ para backslashes
|
||||
- \n para saltos de línea
|
||||
```
|
||||
|
||||
## Summary
|
||||
## Resumen
|
||||
|
||||
<Callout type="tip" title="Key Techniques">
|
||||
Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case.
|
||||
<Callout type="tip" title="Técnicas Clave">
|
||||
Define esquemas explícitamente con interfaces TypeScript o JSON Schema. Especifica tipos y restricciones, maneja nulls y valores por defecto, solicita auto-validación, y elige el formato correcto para tu caso de uso.
|
||||
</Callout>
|
||||
|
||||
<Quiz
|
||||
question="When should you prefer YAML over JSON for AI outputs?"
|
||||
question="¿Cuándo deberías preferir YAML sobre JSON para salidas de IA?"
|
||||
options={[
|
||||
"When building REST APIs",
|
||||
"When the output needs to be human-readable and may include comments",
|
||||
"When working with JavaScript applications",
|
||||
"When you need the most compact representation"
|
||||
"Al construir APIs REST",
|
||||
"Cuando la salida necesita ser legible por humanos y puede contener comentarios",
|
||||
"Al trabajar con aplicaciones JavaScript",
|
||||
"Cuando necesitas la representación más compacta"
|
||||
]}
|
||||
correctIndex={1}
|
||||
explanation="YAML is preferred when human readability matters, such as configuration files, DevOps manifests, and documentation. It also supports comments, unlike JSON."
|
||||
explanation="YAML se prefiere cuando la legibilidad humana importa, como en archivos de configuración, manifiestos DevOps y documentación. También soporta comentarios a diferencia de JSON."
|
||||
/>
|
||||
|
||||
This completes Part II on techniques. In Part III, we'll explore practical applications across different domains.
|
||||
Esto completa la Parte II sobre Técnicas. En la Parte III, exploraremos aplicaciones prácticas en varios dominios.
|
||||
|
||||
Reference in New Issue
Block a user