{
  "name": "AgenteIA",
  "nodes": [
    {
      "parameters": {
        "promptType": "define",
        "text": "=Eres un asistente de conversaci\u00f3n experto y debes mantener el contexto de la conversaci\u00f3n previa.\n\nREGLAS DE FORMATO CR\u00cdTICAS:\n1.  Tu respuesta debe estar SIEMPRE en formato JSON ESTRICTO.\n2.  Todas las CLAVES (\"reply\", \"videos\", etc.) DEBEN usar comillas dobles.\n3.  NO incluyas bloques de c\u00f3digo Markdown (ej., ```json).\n4.  SOLO devuelve el objeto JSON, sin texto adicional.\n\nHISTORIAL COMPLETO DE CONVERSACI\u00d3N (\u00dasalo como contexto):\n{{ JSON.stringify($json.body.history) }}\n\nInstrucci\u00f3n: Utiliza el historial de conversaci\u00f3n anterior para responder a la \u00faltima pregunta planteada en ese historial. Aseg\u00farate de que el array 'videos' contenga contenido relevante si aplica, o un array vac\u00edo si no lo es.",
        "batching": {}
      },
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.7,
      "position": [
        -48,
        112
      ],
      "id": "72a1ad3d-5e24-4923-b3a2-2f02b8c50074",
      "name": "Basic LLM Chain"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatDeepSeek",
      "typeVersion": 1,
      "position": [
        -48,
        -336
      ],
      "id": "57100a22-65fb-43c6-bfa8-4cb34dd8b186",
      "name": "DeepSeek Chat Model",
      "credentials": {
        "deepSeekApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ $json }}",
        "options": {}
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        1312,
        112
      ],
      "id": "4e72873f-743c-48ec-8c12-a31779675c39",
      "name": "Respond to Webhook"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.body.history[$json.body.history.length - 1].content }}",
                    "rightValue": "formato",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    },
                    "id": "a753bbb0-9315-45f3-af38-5ec7de9fb390"
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "108fdc4e-501a-4473-a3ce-1a1bf06ed4aa",
                    "leftValue": "={{ $json.body.history[$json.body.history.length - 1].content }}",
                    "rightValue": "genera",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    }
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "28ad394f-5ff0-4ce3-8946-19b160ab8856",
                    "leftValue": "={{ $json.body.history[$json.body.history.length - 1].content }}",
                    "rightValue": "investigaci\u00f3n",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    }
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "69e63266-51d2-4add-90ef-493bf1f9e4ee",
                    "leftValue": "={{ $json.body.history[$json.body.history.length - 1].content }}",
                    "rightValue": "",
                    "operator": {
                      "type": "string",
                      "operation": "notEmpty",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "and"
              }
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.3,
      "position": [
        -400,
        -560
      ],
      "id": "672daf75-cb82-4684-bf32-c6f686f4c974",
      "name": "Switch"
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Eres un asistente de investigaci\u00f3n experto. Tu \u00fanica tarea es analizar la solicitud del usuario y generar un documento de investigaci\u00f3n completo y detallado.\n\nREGLAS DE FORMATO CR\u00cdTICAS:\n1. NO incluyas ninguna explicaci\u00f3n, saludo o texto antes del JSON.\n2. SIEMPRE devuelve la respuesta en formato JSON estricto.\n3. NO uses bloques de c\u00f3digo Markdown (```json) ni saltos de l\u00ednea fuera del campo \"content\".\n4. El JSON debe tener EXACTAMENTE DOS campos: \"title\" (t\u00edtulo del documento) y \"content\" (el cuerpo del documento).\n5. REGLA CR\u00cdTICA DE ESTRUCTURA: El campo \"content\" debe estar dividido en las siguientes secciones obligatorias, utilizando t\u00edtulos en negrita y doble salto de l\u00ednea para separarlos:\n    - **Introducci\u00f3n**\n    - **Desarrollo del Tema**\n    - **Conclusiones**\n    - **Referencias/Bibliograf\u00eda**\n\nESTRUCTURA DE RESPUESTA REQUERIDA (JSON):\n{\n\u00a0 \u00a0 \"title\": \"[Genera un t\u00edtulo formal y conciso basado en la solicitud]\",\n\u00a0 \u00a0 \"content\": \"[Genera el documento completo. Utiliza saltos de l\u00ednea (\\n\\n) para separar p\u00e1rrafos y doble asterisco (**) para encabezados de secci\u00f3n y negritas. Aseg\u00farate de incluir y formatear las secciones Introducci\u00f3n, Desarrollo, Conclusiones y Bibliograf\u00eda.]\"\n}\n\nTema de la investigaci\u00f3n: {{ $json.final_prompt }}",
        "batching": {}
      },
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.7,
      "position": [
        -48,
        -544
      ],
      "id": "968cb3ed-6927-4974-bba7-98334f168faf",
      "name": "GenerarInvestigacion",
      "alwaysOutputData": false
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "98ed43f3-8588-49dc-8df4-98722d72ac44",
              "name": "plantilla_caratula",
              "value": "UNIVERSIDAD SAN PABLO DE GUATEMALA Facultad de Ciencias Empresariales Escuela de Ingenier\u00eda en Ciencias y Sistemas de la Computaci\u00f3n.  [IMAGEN DEL ESCUDO]  <<TITULO_INVESTIGACION>> en el curso de Sistemas Expertos Impartido por el ingeniero Marco Alfredo Orozco de Paz ALUMNO Henry Morales  --- [INICIO_CONTENIDO]",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -640,
        -160
      ],
      "id": "5a5e7a88-7c58-4590-b5cb-253fe30f5f90",
      "name": "generaFormato"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "/chat",
        "responseMode": "responseNode",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -880,
        -160
      ],
      "id": "f16ef7cc-b159-409e-afab-f83d578f47e8",
      "name": "Webhook"
    },
    {
      "parameters": {
        "mode": "combine",
        "combineBy": "combineByPosition",
        "options": {}
      },
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3.2,
      "position": [
        240,
        -176
      ],
      "id": "0205045f-4665-4824-b738-befb9e4d86d5",
      "name": "Merge"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "f2472787-50c4-44f2-8eb7-0b381fab47bb",
              "name": "reply",
              "value": "={{ JSON.parse($json.text).reply }}",
              "type": "string"
            },
            {
              "id": "d80c0ec1-2187-4401-95f2-ace756bd5872",
              "name": "videos",
              "value": "={{ JSON.parse($json.text).videos }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        320,
        112
      ],
      "id": "69d5e8ab-9f7c-4c5e-b822-95ecb493cbac",
      "name": "FormatoChat"
    },
    {
      "parameters": {
        "jsCode": "for (const item of items) {\n    // 1. Obtener la \u00faltima solicitud del historial\n    const history = item.json.body.history;\n    const fullPrompt = history[history.length - 1].content;\n    \n    // 2. Usar RegEx para encontrar el texto exacto entre comillas despu\u00e9s de \"genera investigaci\u00f3n sobre \"\n    const match = fullPrompt.match(/genera investigaci\u00f3n sobre \"(.*)\"/i);\n    \n    // 3. Si encuentra la coincidencia, usa solo el tema (match[1]). Si no, usa el prompt completo.\n    const final_prompt = match && match[1] ? match[1] : fullPrompt;\n\n    // 4. Agregar el campo de salida limpio al \u00edtem\n    item.json.final_prompt = final_prompt;\n}\n\nreturn items;"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -208,
        -544
      ],
      "id": "e7a6b2b7-fe7a-42a0-8251-eeaaa89a2fba",
      "name": "Code in JavaScript"
    },
    {
      "parameters": {
        "operation": "copy",
        "fileId": {
          "__rl": true,
          "value": "1pMtYHJZyLGWgS9BoOdSLMEu0cO37tcKrxx1XkEgpsjw",
          "mode": "id"
        },
        "name": "={{ $json.llm_data.title }}",
        "options": {
          "copyRequiresWriterPermission": false,
          "description": ""
        }
      },
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        624,
        -176
      ],
      "id": "a693ac5d-380e-494f-9709-14d8b9274710",
      "name": "Copy file",
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "authentication": "serviceAccount",
        "operation": "update",
        "documentURL": "={{ $json.id }}",
        "simple": false,
        "actionsUi": {
          "actionFields": [
            {
              "action": "replaceAll",
              "text": "{{titulo}}",
              "replaceText": "={{ $json.llm_data.title }}"
            },
            {
              "action": "replaceAll",
              "text": "{{introduccion}}",
              "replaceText": "={{ $json.llm_data.introduccion }}"
            },
            {
              "action": "replaceAll",
              "text": "{{desarrollo}}",
              "replaceText": "={{ $json.llm_data.desarrollo }}"
            },
            {
              "action": "replaceAll",
              "text": "{{conclusiones}}",
              "replaceText": "={{ $json.llm_data.conclusiones }}"
            },
            {
              "action": "replaceAll",
              "text": "{{referencias}}",
              "replaceText": "={{ $json.llm_data.referencias }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.googleDocs",
      "typeVersion": 2,
      "position": [
        1104,
        -352
      ],
      "id": "4b6afaf0-39c1-4bc5-897b-ff35ca742d8b",
      "name": "Update a document",
      "credentials": {
        "googleApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "for (const item of $input.all()) {\n  try {\n    // 1. PASO DE PARSEO y CLAVE\n    const jsonString = item.json.text;\n    item.json.llm_data = JSON.parse(jsonString);\n    item.json.mergeKey = 1; \n    \n    // 2. PASO DE SEGMENTACI\u00d3N (\u00a1SOLO CONTENIDO!)\n    const content = item.json.llm_data.content;\n\n    // A. Extraer Introducci\u00f3n (Contenido puro entre los encabezados)\n    const introMatch = content.match(/\\*\\*Introducci\u00f3n\\*\\*\\s*\\n*(.*?)\\n*\\*\\*Desarrollo del Tema\\*\\*/s);\n    let introduccion = introMatch && introMatch[1] ? introMatch[1].trim() : '';\n    // YA NO A\u00d1ADE EL T\u00cdTULO \"Introducci\u00f3n\\n\\n\"\n\n    // B. Extraer Desarrollo del Tema\n    const desarrolloMatch = content.match(/\\*\\*Desarrollo del Tema\\*\\*\\s*\\n*(.*?)\\n*\\*\\*Conclusiones\\*\\*/s);\n    let desarrollo = desarrolloMatch && desarrolloMatch[1] ? desarrolloMatch[1].trim() : '';\n    // YA NO A\u00d1ADE EL T\u00cdTULO\n\n    // C. Extraer Conclusiones\n    const concMatch = content.match(/\\*\\*Conclusiones\\*\\*\\s*\\n*(.*?)\\n*\\*\\*Referencias\\/Bibliograf\u00eda\\*\\*/s);\n    let conclusiones = concMatch && concMatch[1] ? concMatch[1].trim() : '';\n    // YA NO A\u00d1ADE EL T\u00cdTULO\n\n    // D. Extraer Referencias/Bibliograf\u00eda\n    const refMatch = content.match(/\\*\\*Referencias\\/Bibliograf\u00eda\\*\\*\\s*\\n*(.*)$/s);\n    let referencias = refMatch && refMatch[1] ? refMatch[1].trim() : '';\n    // YA NO A\u00d1ADE EL T\u00cdTULO\n\n    // 3. Crear el nuevo objeto llm_data con campos segmentados\n    item.json.llm_data = {\n      ...item.json.llm_data,\n      introduccion: introduccion,\n      desarrollo: desarrollo,\n      conclusiones: conclusiones,\n      referencias: referencias,\n    };\n    \n    // Eliminamos el campo 'content' original\n    delete item.json.llm_data.content;\n\n  } catch (error) {\n    console.error('Error al analizar o segmentar el JSON:', error);\n  }\n}\nreturn $input.all();"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        400,
        -176
      ],
      "id": "3fc2d705-c78a-4661-9555-2f2744c6550c",
      "name": "Code in JavaScript1"
    },
    {
      "parameters": {
        "mode": "combine",
        "fieldsToMatchString": "mergeKey",
        "options": {}
      },
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3.2,
      "position": [
        928,
        -352
      ],
      "id": "0fffd1ff-0a65-4a45-a6aa-f26b13ca7aa8",
      "name": "Merge1"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "491d2d3e-6e94-4669-b72c-9855bd3ad6c8",
              "name": "mergeKey",
              "value": 1,
              "type": "number"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        784,
        -176
      ],
      "id": "c65412dc-e24d-4247-9606-3e1a1a95264b",
      "name": "SetMergeKey"
    }
  ],
  "connections": {
    "DeepSeek Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Basic LLM Chain",
            "type": "ai_languageModel",
            "index": 0
          },
          {
            "node": "GenerarInvestigacion",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Basic LLM Chain": {
      "main": [
        [
          {
            "node": "FormatoChat",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Code in JavaScript",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Code in JavaScript",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Code in JavaScript",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Basic LLM Chain",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GenerarInvestigacion": {
      "main": [
        [
          {
            "node": "Merge",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "generaFormato": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          },
          {
            "node": "Merge",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Webhook": {
      "main": [
        [
          {
            "node": "generaFormato",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge": {
      "main": [
        [
          {
            "node": "Code in JavaScript1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "FormatoChat": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code in JavaScript": {
      "main": [
        [
          {
            "node": "GenerarInvestigacion",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Copy file": {
      "main": [
        [
          {
            "node": "SetMergeKey",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update a document": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code in JavaScript1": {
      "main": [
        [
          {
            "node": "Copy file",
            "type": "main",
            "index": 0
          },
          {
            "node": "Merge1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge1": {
      "main": [
        [
          {
            "node": "Update a document",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SetMergeKey": {
      "main": [
        [
          {
            "node": "Merge1",
            "type": "main",
            "index": 1
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "3521d091-97b2-4dab-8c65-02afebdf85ea",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "id": "sTYK22OQWGCd5Fxx",
  "tags": []
}