{
  "id": "6LeAm5UyENgTdwkv",
  "meta": {
    "instanceId": "6d46e25379ef430a7067964d1096b885c773564549240cb3ad4c087f6cf94bd3",
    "templateCredsSetupCompleted": true
  },
  "name": "agente",
  "tags": [],
  "nodes": [
    {
      "id": "84ce6905-4416-4721-8627-f8c303730a4f",
      "name": "OpenAI Chat Model1",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        8260,
        2260
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-nano-2025-04-14",
          "cachedResultName": "gpt-4.1-nano-2025-04-14"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "id": "zUnIUrOWA279vAoC",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "a6e9358a-a873-49f3-af38-21ca545b2bfc",
      "name": "Assistente clinica interno",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        8380,
        2020
      ],
      "parameters": {
        "text": "={{ $json.message.text }}",
        "options": {
          "systemMessage": "=Hoje u00e9 {{$now}}nPAPEL:  nVocu00ea u00e9 um assistente interno de reagendamento na clu00ednica, acionado diretamente por um profissional via Telegram para gerenciar situau00e7u00f5es de remarcau00e7u00e3o de consultas ou incluir lembretes na lista de compras.nnOBJETIVO GERAL:  n1. Reagendar consultas a pedido do profissional.  n2. Adicionar lembretes na lista de compras quando solicitado.  nnRESUMO DE RESPONSABILIDADES:  n1. Reagendamento de pacientes  n   - Acesse o Google Calendar por meio da ferramenta "MCP Google Calendar" para identificar as consultas afetadas.  n   - Extraia o nu00famero de telefone na descriu00e7u00e3o do evento.  n   - Use a ferramenta "Reagendar no WhatsApp" para enviar mensagens de reagendamento aos pacientes.  n   - Lembre-se de que vocu00ea apenas envia a mensagem; a resposta do paciente u00e9 tratada por outro agente.  nn2. Lista de compras da clu00ednica  n   - Se o profissional solicitar pelo Telegram a inclusu00e3o de um item na lista de compras, utilize a ferramenta "Google Tasks" para adicionar o lembrete.  nnORIENTAu00c7u00d5ES DE LINGUAGEM E PROCEDIMENTO:  n- Use uma abordagem empu00e1tica, profissional e acolhedora.  n- Nunca envie mensagens para pacientes sem autorizau00e7u00e3o explu00edcita do profissional.  n- Quando listar eventos ou tarefas, seja objetivo e organizado.  n- Mantenha clareza e concisu00e3o em todas as interau00e7u00f5es.  nnFERRAMENTAS DISPONu00cdVEIS:  n- Reagendar no WhatsApp  n- Google Tasks  n- MCP Google Calendar  nnINSTRUu00c7u00d5ES FINAIS:  n- Atenda exclusivamente u00e0s solicitau00e7u00f5es de reagendamento e inclusu00e3o de lembretes.  n- A remarcau00e7u00e3o de consultas ocorre somente quando o profissional pede, utilizando o MCP Google Calendar para identificar os pacientes e o "Reagendar no WhatsApp" para enviar a mensagem.  n- Para a lista de compras, sempre registre no "Google Tasks".  n"
        },
        "promptType": "define"
      },
      "typeVersion": 1.8
    },
    {
      "id": "d674fb31-cf45-47ac-b33b-4abe1920e352",
      "name": "Google Tasks",
      "type": "n8n-nodes-base.googleTasksTool",
      "position": [
        8720,
        2320
      ],
      "parameters": {
        "task": "bDQ5ZlNVV2lPQ3pYT3NsNA",
        "title": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Title', ``, 'string') }}",
        "additionalFields": {
          "notes": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Notes', ``, 'string') }}",
          "status": "needsAction"
        }
      },
      "credentials": {
        "googleTasksOAuth2Api": {
          "id": "3SQEwHb0AR81JO8y",
          "name": "Google Tasks account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "dff00a3c-6496-4104-afc4-a0556f3cabfa",
      "name": "MCP Google Calendar",
      "type": "@n8n/n8n-nodes-langchain.mcpClientTool",
      "position": [
        8560,
        2320
      ],
      "parameters": {
        "sseEndpoint": "https://engaging-seahorse-19.rshare.io/mcp/ceb17fa5-1937-405f-8000-ea3be7d2b032/mcp/:tool/calendar/sse"
      },
      "typeVersion": 1
    },
    {
      "id": "10a0bda3-94b3-487a-98a1-1e7badcc8775",
      "name": "Receber Mensagem Telegram",
      "type": "n8n-nodes-base.telegramTrigger",
      "position": [
        8100,
        2020
      ],
      "webhookId": "f2b29356-d5d3-4f5d-9ef1-273001c0a820",
      "parameters": {
        "updates": [
          "message"
        ],
        "additionalFields": {}
      },
      "credentials": {
        "telegramApi": {
          "id": "TAVUHrFXuDIMInWe",
          "name": "Telegram account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "46cfa6be-f896-4e33-be3d-b4ef676c043b",
      "name": "Postgres Chat Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryPostgresChat",
      "position": [
        8420,
        2300
      ],
      "parameters": {
        "sessionKey": "100",
        "sessionIdType": "customKey",
        "contextWindowLength": 10
      },
      "credentials": {
        "postgres": {
          "id": "t8gw5Kie6Oxy5TcK",
          "name": "Postgres account"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "c79c44f6-94fa-4e56-9d94-49185f83bfb4",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        5860,
        3980
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini-2025-04-14",
          "cachedResultName": "gpt-4.1-mini-2025-04-14"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "id": "zUnIUrOWA279vAoC",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "5e7ac239-6ba1-414c-b11d-d637361e8f77",
      "name": "Assistente Clu00ednica",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        5960,
        3760
      ],
      "parameters": {
        "text": "={{ $json.text }}{{ $json.output}}",
        "options": {
          "systemMessage": "=HOJE u00c9: {{ $now }}nCONTATO DA CLu00cdNICA: n{ coloque o seu contato aqui }nnINSTRUu00c7u00c3O IMPORTANTE:nnAo criar ou editar qualquer evento via MCP_CALENDAR, inclua na descriu00e7u00e3o do agendamento:nnTelefone do pacientennNome completonnData de nascimentonnInformau00e7u00f5es adicionais (convu00eanio, condiu00e7u00e3o de sau00fade etc.)nnPAPEL:nVocu00ea u00e9 uma atendente do WhatsApp da Clu00ednica Moreira, especializada em atendimento humanizado. Sua missu00e3o:nnAtender pacientes de forma u00e1gil e eficientennResponder du00favidas sobre clu00ednica e serviu00e7osnnAgendar, remarcar e cancelar consultas pelo MCP_CALENDARnnPERSONALIDADE E TOM DE VOZ:nnSimpu00e1tica, acolhedora e respeitosannFormal, sem emojis ou gu00edriasnnFERRAMENTAS DISPONu00cdVEIS:nnMCP_CALENDAR (trigger /mcp/:tool/calendar)nnAVALIABILITY_CALENDAR: verifica horu00e1rios livres entre Start_Time e End_TimennGET_ALL_CALENDAR: lista todos os eventos entre After e BeforennCREATE_CALENDAR: cria novo evento com start, end e Description (inclua sempre telefone, nome e data de nascimento)nnUPDATE_CALENDAR: atualiza campos de um evento existente (Event_ID)nnDELETE_CALENDAR: remove evento (Event_ID)nnGET_CALENDAR: obtu00e9m detalhes de um evento especu00edfico (Event_ID)nnCallToHuman (workflow id A95kslcW4H82nJuR)nnEncaminha atendimento humano via EvolutionAPI em n8nnnDisparar IMEDIATAMENTE quando:nnUrgu00eancia ou mal-estar gravennPedido de diagnu00f3stico/opiniu00e3o mu00e9dicannInsatisfau00e7u00e3o expressa do pacientennAssuntos fora do escopo da clu00ednicannExemplo de chamada:nn{n  "tool": "CallToHuman",n  "telefone": "",n  "nome": "",n  "ultima_mensagem": ""n}nnEnviar telegram cancelamentonnApu00f3s DELETE_CALENDAR, envie ao gestor via Telegram: nome, data, horannSOP (Fluxo de Atendimento):nnInu00edcio e coleta de dadosnnCumprimente e informe o link da agenda: https://calendar.google.com/calendar/embed?src=a57a3781407f42b1ad7fe24ce76f558dc6c86fea5f349b7fd39747a2294c1654%40group.calendar.google.com&ctz=America%2FArgentina%2FBuenos_AiresnnPeu00e7a: nome completo, data de nascimento e confirme o telefonen number: {{ $('Webhook1').item.json.body.data.key.remoteJid.replaceAll("@s.whatsapp.net","") }}nnVerificau00e7u00e3o de disponibilidadennPergunte data e turno preferidosnnChame AVALIABILITY_CALENDAR com Start_Time 08:00 e End_Time 19:00 (ou turno)nnInforme horu00e1rios livresnnAgendamentonnApu00f3s escolha do paciente, use CREATE_CALENDAR com start, end e DescriptionnnAguarde retorno para confirmar criau00e7u00e3o antes de respondernnRemarcau00e7u00e3onnSolicite dados e nova preferu00eancia de data/turnonnLocalize evento antigo via GET_ALL_CALENDARnnUse DELETE_CALENDAR no Event_ID antigonnCrie novo com CREATE_CALENDARnnConfirme apu00f3s sucessonnCancelamentonnSolicite dados do pacientennIdentifique Event_ID via GET_ALL_CALENDAR ou GET_CALENDARnnExecute DELETE_CALENDARnnUse Enviar telegram cancelamentonnConfirme cancelamento ao pacientennConfirmau00e7u00e3o de consulta (follow-up)nnSe paciente responder u201cConfirmar, IDu201d: use UPDATE_CALENDAR para prefixar tu00edtulo com [Confirmado]nnSe u201cReagendar, IDu201d: DELETE_CALENDAR e oriente para usar link da agendannREGRAS DE ESCALONAMENTO:nnUse CallToHuman IMEDIATAMENTE em situau00e7u00f5es de:nnUrgu00eancia/mal-estarnnPedidos de diagnu00f3stico/opiniu00e3o mu00e9dicannInsatisfau00e7u00e3o ou reclamau00e7u00f5esnnAssuntos fora do escoponnMANTENHA SEMPRE:nnTom profissional e respeitosonnLinguagem clara e objetivannAgendamentos apenas em datas futurasnnNunca confirmar sem retorno do MCP_CALENDARnnHORu00c1RIOS DE FUNCIONAMENTO:nnSegu2013Su00e1b: 08hu201319h | Dom e feriados: fechadonnLOCALIZAu00c7u00c3O:nRua Rio Casca, 417 u2013 Belo Horizonte, MGnnLINK DA AGENDA:nhttps://calendar.google.com/calendar/embed?src=a57a3781407f42b1ad7fe24ce76f558dc6c86fea5f349b7fd39747a2294c1654%40group.calendar.google.com&ctz=America%2FArgentina%2FBuenos_Airesnn"
        },
        "promptType": "define"
      },
      "retryOnFail": true,
      "typeVersion": 1.8,
      "waitBetweenTries": 1000
    },
    {
      "id": "2f0a6ea1-7654-4ae7-884e-d5b8ff47d4f9",
      "name": "Enviar alerta de cancelamento",
      "type": "n8n-nodes-base.telegramTool",
      "position": [
        6400,
        3980
      ],
      "webhookId": "d045a8c1-ec1b-4d20-8226-457aa18934af",
      "parameters": {
        "text": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Text', ``, 'string') }}",
        "chatId": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Chat_ID', ``, 'string') }}",
        "additionalFields": {}
      },
      "credentials": {
        "telegramApi": {
          "id": "TAVUHrFXuDIMInWe",
          "name": "Telegram account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "8ddaa14f-7d2f-4364-8ff7-f87e0a428e37",
      "name": "Gatilho diu00e1rio",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        8060,
        2780
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 8 * * 1-5"
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "0784753d-123d-4259-abcc-8abf39e7fc07",
      "name": "Assistente de confirmau00e7u00e3o",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        8280,
        2680
      ],
      "parameters": {
        "text": "=Hoje u00e9 {{ $now }}. Vocu00ea u00e9 um agente especializado em **confirmau00e7u00e3o de consultas** para a clu00ednica. Sua funu00e7u00e3o principal u00e9:nn1. **Listar os eventos** agendados para o pru00f3ximo dia no MCP Calendar.n2. **Obter o numero** na descriu00e7u00e3o de cada evento.n3. **Enviar uma mensagem de confirmau00e7u00e3o** usando a ferramenta u201crelembraAGENDAMENTOu201d, perguntando se o paciente confirma a consulta ou prefere reagendar.nnImportante:n- Vocu00ea **nu00e3o recebe respostas** diretamente; o retorno do paciente u00e9 tratado por outro agente.nn",
        "options": {
          "systemMessage": ""
        },
        "promptType": "define"
      },
      "typeVersion": 1.8
    },
    {
      "id": "afa90e86-0f44-4069-976b-ca302b0d828a",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        5840,
        4460
      ],
      "parameters": {
        "text": "={{ $json.output }}",
        "options": {
          "systemMessage": "=Vocu00ea u00e9 especialista em formatau00e7u00e3o de mensagem para whataspp, trabalhando somente na formatau00e7u00e3o e nu00e3o alterando o conteu00fado da menssagem.nn- Substitua ** por *n- Remova #"
        },
        "promptType": "define"
      },
      "typeVersion": 1.8
    },
    {
      "id": "13179a70-85b6-4e18-8736-eb2cdd252591",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        6960,
        2580
      ],
      "parameters": {
        "color": 5,
        "width": 1940,
        "height": 600,
        "content": "# "Appointment Confirmation Assistant"nDescription:nnPurpose:nThis section contains the configuration for the Appointment Confirmation Assistant, an agent specialized in confirming scheduled appointments with patients.nnInstructions for Use:nnIt is triggered automatically every weekday (Monday to Friday) at 08:00 AM via the Daily Trigger (Gatilho diu00e1rio).nnThe agent retrieves all appointments scheduled for the next day using MCP Google Calendar.nnIt extracts each patient's phone number from the event description field.nnA confirmation message is sent to each patient using the relembraAGENDAMENTO tool, asking for confirmation or rescheduling.nnImportant: This agent does not handle responses from patients; another agent or workflow is responsible for follow-ups.nnMake sure event descriptions in Google Calendar are correctly filled to avoid errors.nn"
      },
      "typeVersion": 1
    },
    {
      "id": "4111432b-2ddc-4e96-ba6d-d25e003e2688",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4760,
        3620
      ],
      "parameters": {
        "color": 3,
        "width": 1780,
        "height": 640,
        "content": "# "Agent Core Components (Tools, MCP, Memory, LLM Model)"nDescription:nnPurpose:nnThis sticky note represents the essential structure of any intelligent agent: it includes access to external tools,n persistent memory, the MCP system for calendar management, and a Language Model (LLM) to process natural language tasks.nnInstructions for Use:nnLanguage Model nodes (OpenAI, OpenRouter) are responsible for natural language understanding and generation.nnMemory nodes (Postgres Chat Memory) maintain conversation context over multiple interactions.nnMCP Tools interact with Google Calendar and other services to perform real-world actions.nnAlways ensure memory synchronization between the agent's context and actions performed.nnIf new tools are added, they must be connected both to the agent and properly described in the system message.nn"
      },
      "typeVersion": 1
    },
    {
      "id": "4b59f903-07c2-4e66-9ea1-0727beb0d85c",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4640,
        4300
      ],
      "parameters": {
        "color": 4,
        "width": 1800,
        "height": 640,
        "content": "# "Processing and Sending WhatsApp Responses"nDescription:nnPurpose:nThis section is responsible for processing, formatting, and sending outbound WhatsApp messages to patients through the Evolution API.nnInstructions for Use:nnMessages received from the assistant agent are first reformatted by the AI Agent node to comply with WhatsApp markdown syntax (e.g., replacing **bold** with *bold*).nnOnce formatted, the messages are forwarded to WhatsApp using the Evolution API2 node.nnEnsure proper formatting before sending to maintain a professional communication tone and avoid delivery errors.nnAny future text-processing improvements should be implemented here."
      },
      "typeVersion": 1
    },
    {
      "id": "274f7f66-7613-4e9e-868d-a5705156dde6",
      "name": "Postgres Chat Memory1",
      "type": "@n8n/n8n-nodes-langchain.memoryPostgresChat",
      "position": [
        6000,
        3980
      ],
      "parameters": {
        "sessionKey": "= {{ $('Webhook1').item.json.body.data.key.id }}",
        "sessionIdType": "customKey",
        "contextWindowLength": 50
      },
      "credentials": {
        "postgres": {
          "id": "t8gw5Kie6Oxy5TcK",
          "name": "Postgres account"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "654ed617-df1a-48db-b9bc-833b2c1ecb80",
      "name": "MCP Google Calendar2",
      "type": "@n8n/n8n-nodes-langchain.mcpClientTool",
      "position": [
        6120,
        3980
      ],
      "parameters": {
        "sseEndpoint": "https://engaging-seahorse-19.rshare.io/mcp/ceb17fa5-1937-405f-8000-ea3be7d2b032/mcp/:tool/calendar/sse"
      },
      "typeVersion": 1
    },
    {
      "id": "b11aeec6-b446-4c02-a0b0-7f9239628df3",
      "name": "MCP GMAIL",
      "type": "@n8n/n8n-nodes-langchain.mcpClientTool",
      "position": [
        8540,
        3000
      ],
      "parameters": {
        "sseEndpoint": "https://engaging-seahorse-19.rshare.io/mcp/82a7a338-618c-44f5-a1c3-f2e32b6b4833/mcp/:tool/gmail/sse"
      },
      "typeVersion": 1
    },
    {
      "id": "f5a38b34-499e-4bbc-9282-ce5f4a3b85a3",
      "name": "MCP CALENDAR",
      "type": "@n8n/n8n-nodes-langchain.mcpClientTool",
      "position": [
        8380,
        3000
      ],
      "parameters": {
        "sseEndpoint": "https://engaging-seahorse-19.rshare.io/mcp/ceb17fa5-1937-405f-8000-ea3be7d2b032/mcp/:tool/calendar/sse"
      },
      "typeVersion": 1
    },
    {
      "id": "cd6a6147-fd18-4cd4-8aab-fcb454ab76b7",
      "name": "Telegram",
      "type": "n8n-nodes-base.telegram",
      "position": [
        8740,
        2020
      ],
      "webhookId": "5bba05fc-2859-4225-aa85-7c4bc5ff532d",
      "parameters": {
        "text": "={{ $json.output }}",
        "chatId": "={{ $('Receber Mensagem Telegram').item.json.message.chat.id }}",
        "additionalFields": {}
      },
      "credentials": {
        "telegramApi": {
          "id": "TAVUHrFXuDIMInWe",
          "name": "Telegram account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "900b8c1a-f987-4898-9fc1-bfc673773e06",
      "name": "OpenRouter Chat Model1",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "position": [
        5760,
        4680
      ],
      "parameters": {
        "model": "google/gemini-2.0-flash-exp:free",
        "options": {}
      },
      "credentials": {
        "openRouterApi": {
          "id": "eGPA8rbskZCfFPBn",
          "name": "OpenRouter account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "1584b448-d8f5-4bab-ad9a-9b07edb8e102",
      "name": "Webhook1",
      "type": "n8n-nodes-base.webhook",
      "position": [
        5760,
        2100
      ],
      "webhookId": "405dab7c-a0ea-4f5b-a6cc-ede9d5ba78a0",
      "parameters": {
        "path": "evolutionAPIKORE",
        "options": {},
        "httpMethod": "POST"
      },
      "typeVersion": 2
    },
    {
      "id": "74b5179f-502c-45d6-88e9-2c2d492603cd",
      "name": "Edit Fields1",
      "type": "n8n-nodes-base.set",
      "position": [
        6000,
        2100
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "3e6335ae-74c3-4655-b68f-cdf0c68b864f",
              "name": "number",
              "type": "string",
              "value": "={{ $json.body.data.key.remoteJid }}"
            },
            {
              "id": "15f399cf-a98e-45e7-91ce-61b4fad340fd",
              "name": "name",
              "type": "string",
              "value": "={{ $json.body.data.pushName }}"
            },
            {
              "id": "b1943003-1f47-40e1-b418-6a52557ec44e",
              "name": "key_id",
              "type": "string",
              "value": "={{ $json.body.data.key.id }}"
            },
            {
              "id": "ed23194b-22ca-455b-a085-7dae706d0569",
              "name": "text",
              "type": "string",
              "value": "={{ $json.body.data.message.conversation }}"
            },
            {
              "id": "b35f8b61-da15-42e3-a078-4cd901e1f273",
              "name": "type",
              "type": "string",
              "value": "={{ $json.body.data.message.imageMessage.mimetype }}"
            },
            {
              "id": "a62bf96a-51aa-44c3-9e5d-f592e32a31d6",
              "name": "image.url",
              "type": "string",
              "value": "={{ $json.body.data.message.imageMessage.url }}"
            },
            {
              "id": "b004987d-3527-4040-a5e6-5fe06b25c9b9",
              "name": "audio.url",
              "type": "string",
              "value": "={{ $json.body.data.message.audioMessage.url }}"
            },
            {
              "id": "4c2cc03a-c104-4a87-9d31-6a7c256890ad",
              "name": "document.url",
              "type": "string",
              "value": "={{ $json.body.data.message.documentMessage.url }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "ce22f5bc-f0e1-463d-9b9a-5112f8d91f00",
      "name": "Switch",
      "type": "n8n-nodes-base.switch",
      "position": [
        6240,
        2080
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "text",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "2f9854ac-26b3-446c-9d0d-ae25157c61bb",
                    "operator": {
                      "type": "string",
                      "operation": "notEmpty",
                      "singleValue": true
                    },
                    "leftValue": "={{ $json.text }}",
                    "rightValue": "="
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "image",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "73b7d93a-928e-42ec-9c8e-ae8e9b97a867",
                    "operator": {
                      "type": "string",
                      "operation": "notEmpty",
                      "singleValue": true
                    },
                    "leftValue": "={{ $json.image.url }}",
                    "rightValue": "="
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "audio",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "2f9915b9-e2b4-4528-ad36-515a848ab1be",
                    "operator": {
                      "type": "string",
                      "operation": "notEmpty",
                      "singleValue": true
                    },
                    "leftValue": "={{ $json.audio.url }}",
                    "rightValue": "[null]"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "document",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "9fcbe89a-c9d7-4dc6-bb6f-27c1cacbfddc",
                    "operator": {
                      "type": "string",
                      "operation": "notEmpty",
                      "singleValue": true
                    },
                    "leftValue": "={{ $json.document.url }}",
                    "rightValue": "[null]"
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.2
    },
    {
      "id": "c78ee758-fb71-4a4f-9450-0ffcd67a2af2",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4960,
        1840
      ],
      "parameters": {
        "color": 6,
        "width": 1580,
        "height": 640,
        "content": "# Incoming WhatsApp Webhook and Message Type Handling"nDescription:nnPurpose:nManages the initial reception and classification of incoming WhatsApp messages from patients via the webhook system.nnInstructions for Use:nnThe Webhook1 node captures incoming messages.nnEdit Fields1 extracts structured fields such as text, image URL, audio URL, and document URL.nnSwitch node analyzes which type of content was received and directs the flow accordingly:nnText u2192 Forwarded to the assistant for handling.nnImage u2192 Sent for OCR analysis.nnAudio u2192 Sent for transcription.nnDocument u2192 (Currently unused, but ready for future workflows).nnKeep webhook credentials updated to ensure system reliability.nn"
      },
      "typeVersion": 1
    },
    {
      "id": "83abbf61-91e2-4d1c-a42a-4f05b18583e7",
      "name": "OpenAI",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        6380,
        3260
      ],
      "parameters": {
        "options": {},
        "resource": "audio",
        "operation": "transcribe",
        "binaryPropertyName": "=data"
      },
      "credentials": {
        "openAiApi": {
          "id": "zUnIUrOWA279vAoC",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.8
    },
    {
      "id": "4c2dcefc-fb65-42ca-8c63-8636f2906654",
      "name": "Evolution API",
      "type": "n8n-nodes-evolution-api.evolutionApi",
      "position": [
        5860,
        3260
      ],
      "parameters": {
        "resource": "chat-api",
        "messageId": "={{ $json.key_id }}",
        "operation": "get-media-base64",
        "convertToMp4": true,
        "instanceName": "={{ $('Webhook1').item.json.body.instance }}"
      },
      "credentials": {
        "evolutionApi": {
          "id": "fPKdX0EITLV8HI89",
          "name": "Evolution account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "85909834-7564-478b-bce8-0c3fe7bf4159",
      "name": "Convert to File",
      "type": "n8n-nodes-base.convertToFile",
      "position": [
        6100,
        3260
      ],
      "parameters": {
        "options": {},
        "operation": "toBinary",
        "sourceProperty": "data.base64"
      },
      "typeVersion": 1.1
    },
    {
      "id": "3e200157-fbcc-4225-b982-2dfaea54cc23",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4980,
        3100
      ],
      "parameters": {
        "width": 1760,
        "height": 480,
        "content": "## "Download Audio and Convert to MP4"nDescription:nnPurpose:nHandles retrieval, conversion, and transcription of audio files sent by patients via WhatsApp.nnInstructions for Use:nnEvolution API downloads the audio in base64 format.nnConvert to File transforms base64 into a binary file compatible with transcription engines.nnOpenAI Whisper API (via OpenAI node) transcribes the audio into text, preparing it for natural language processing.nnEnsure audio formats are correctly handled (e.g., MP4/MP3) to avoid conversion or transcription failures.nnMonitor for potential heavy file size issues (>25MB) which may impact performance."
      },
      "typeVersion": 1
    },
    {
      "id": "5862d5f1-2df4-40ee-881f-a6d6e302602f",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4920,
        2540
      ],
      "parameters": {
        "width": 1820,
        "height": 480,
        "content": "# "Extract Text from Images"nDescription:nnPurpose:nProcesses images received via WhatsApp to extract text (OCR) and describe their visual content for further contextual analysis.nnInstructions for Use:nnThe OpenAI1 node uses a Vision model to transcribe and describe any text or scene from incoming images.nnThe resulting data is interpreted by the AI Agent2, which prepares insights and recommends appropriate responses.nnImage-to-text extraction is especially useful for handling prescriptions, notes, or medical documents sent by patients.nnMaintain quality standards: images must be clear and high-resolution for best transcription results."
      },
      "typeVersion": 1
    },
    {
      "id": "8dbd4e6d-8b38-44d8-ba45-5cac2713f6ca",
      "name": "OpenAI1",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        5980,
        2620
      ],
      "parameters": {
        "text": "TRANSCRIBE OS TEXTOS e describe a imagem",
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "chatgpt-4o-latest",
          "cachedResultName": "CHATGPT-4O-LATEST"
        },
        "options": {},
        "resource": "image",
        "imageUrls": "={{ $json.image }}",
        "operation": "analyze"
      },
      "credentials": {
        "openAiApi": {
          "id": "zUnIUrOWA279vAoC",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.8
    },
    {
      "id": "19e8d50d-4f87-408e-96f0-236932c1d120",
      "name": "AI Agent2",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        6200,
        2620
      ],
      "parameters": {
        "text": "={{$json.output}}",
        "options": {
          "systemMessage": "voce e encarregado de analizar o texto proveniente do analisis de uma iamgem ela pode conter texto, a ideia e que voce explique ao proximo agente como debe responder as mensagens"
        },
        "promptType": "define"
      },
      "typeVersion": 1.9
    },
    {
      "id": "0d2f9842-b011-49f5-9594-24a917dee60e",
      "name": "OpenRouter Chat Model2",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "position": [
        6100,
        2860
      ],
      "parameters": {
        "model": "google/gemini-2.5-pro-exp-03-25:free",
        "options": {}
      },
      "credentials": {
        "openRouterApi": {
          "id": "eGPA8rbskZCfFPBn",
          "name": "OpenRouter account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "58f7f9c7-6f86-40ff-bfad-5467e5b3a9e4",
      "name": "Evolution API2",
      "type": "n8n-nodes-evolution-api.evolutionApi",
      "position": [
        6200,
        4460
      ],
      "parameters": {
        "resource": "messages-api",
        "remoteJid": "={{ $('Webhook1').item.json.body.data.key.remoteJid }}",
        "messageText": "={{$json.output}}",
        "instanceName": "={{ $('Webhook1').item.json.body.instance }}",
        "options_message": {}
      },
      "credentials": {
        "evolutionApi": {
          "id": "fPKdX0EITLV8HI89",
          "name": "Evolution account"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "2b529ab1-2a7e-44e0-b7c8-ed05e07c6def",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        6960,
        1840
      ],
      "parameters": {
        "width": 1960,
        "height": 680,
        "content": "## "Internal Clinic Assistant"nDescription:nnPurpose:nRepresents the Internal Assistant for the clinic, used exclusively by the internal team via Telegram to manage patient rescheduling and manage a purchasing reminder list.nnInstructions for Use:nnTriggered by staff messages sent via Telegram.nnRescheduling tasks:nnAccess the MCP Google Calendar to locate and manage appointments.nnExtract patient contact from the event description.nnSend rescheduling messages through WhatsApp using the dedicated tool.nnShopping list tasks:nnInsert shopping list reminders into Google Tasks based on the staff's instructions.nnAlways maintain professional and empathetic tone when interacting with patients, even if the communication is indirect.nnAvoid unauthorized direct patient contact without staff permission."
      },
      "typeVersion": 1
    },
    {
      "id": "a4a51bd1-48a6-4e32-b696-0ae77a0e05fe",
      "name": "CallToHuman",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "position": [
        6240,
        4000
      ],
      "parameters": {
        "name": "escalar_humano",
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "A95kslcW4H82nJuR",
          "cachedResultName": "callToHuman"
        },
        "description": "=Use essa ferramenta ao perceber que o paciente fala de:n- Situau00e7u00f5es urgentes (sentindo-se mal, etc.)n- Assuntos nu00e3o relacionados u00e0 clu00ednican- Insatisfau00e7u00e3o extrema ou pedidos de falar com um humanon",
        "workflowInputs": {
          "value": {
            "nome": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('nome', ``, 'string') }}",
            "telefone": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('telefone', ``, 'string') }}",
            "ultima_mensagem": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('ultima_mensagem', ``, 'string') }}"
          },
          "schema": [
            {
              "id": "telefone",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "telefone",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "nome",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "nome",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "ultima_mensagem",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "ultima_mensagem",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "674c5c75-a954-4306-8a02-71bdda89293c",
      "name": "OpenAI Chat Model2",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        8260,
        2840
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "gpt-4.1-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "id": "zUnIUrOWA279vAoC",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "b398627e-2fbe-44e4-ac2f-523b03871eda",
      "name": "REMINDER",
      "type": "n8n-nodes-evolution-api.evolutionApi",
      "position": [
        8640,
        2700
      ],
      "parameters": {
        "resource": "messages-api",
        "remoteJid": "5511111111111@s.whatsapp.net",
        "messageText": "={{$fromAI("reminder")}}",
        "instanceName": "instance name",
        "options_message": {}
      },
      "credentials": {
        "evolutionApi": {
          "id": "fPKdX0EITLV8HI89",
          "name": "Evolution account"
        }
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "pinData": {
    "Webhook1": [
      {
        "json": {
          "body": {
            "data": {
              "key": {
                "id": "05D218BDE5BFC8378B5AA50BA87FDAFE",
                "fromMe": false,
                "remoteJid": "5491169701682@s.whatsapp.net"
              },
              "source": "android",
              "status": "DELIVERY_ACK",
              "message": {
                "conversation": "Sim",
                "messageContextInfo": {
                  "messageSecret": "RdahuRio1gbaHLsCeV24k8yFFyJWGpAJ5zHYRc2QysU=",
                  "deviceListMetadata": {
                    "recipientKeyHash": "KgcEIs2I9kXQgQ==",
                    "recipientTimestamp": "1745501413"
                  },
                  "deviceListMetadataVersion": 2
                }
              },
              "pushName": "Luciano",
              "instanceId": "317a031e-567d-4c2e-9bc4-146616fe4db7",
              "messageType": "conversation",
              "messageTimestamp": 1745501855
            },
            "event": "messages.upsert",
            "apikey": "59BA76B6BD78-403B-A0CC-8735B6A7ED3A",
            "sender": "553191282843@s.whatsapp.net",
            "instance": "kore",
            "date_time": "2025-04-24T10:37:35.514Z",
            "server_url": "http://localhost:8080",
            "destination": "https://engaging-seahorse-19.rshare.io/webhook/evolutionAPIKORE"
          },
          "query": {},
          "params": {},
          "headers": {
            "host": "host.docker.internal:5678",
            "x-scheme": "https",
            "forwarded": "by=_exposr;for=179.0.72.34;host=engaging-seahorse-19.rshare.io;proto=https",
            "x-real-ip": "179.0.72.34",
            "connection": "keep-alive",
            "exposr-via": "b9e7ef031eb8fe005896193e59b1d6f6d8743b1e",
            "user-agent": "axios/1.7.9",
            "content-type": "application/json",
            "x-request-id": "91360975101096aa10d12cb5b8925b55",
            "content-length": "821",
            "accept-encoding": "gzip, compress, deflate, br",
            "x-forwarded-for": "179.0.72.34",
            "x-forwarded-host": "engaging-seahorse-19.rshare.io",
            "x-forwarded-port": "443",
            "x-forwarded-proto": "https",
            "x-forwarded-scheme": "https"
          },
          "webhookUrl": "https://engaging-seahorse-19.rshare.io/webhook/evolutionAPIKORE",
          "executionMode": "production"
        }
      }
    ],
    "Gatilho diu00e1rio": [
      {
        "json": {
          "Hour": "10",
          "Year": "2025",
          "Month": "April",
          "Minute": "13",
          "Second": "11",
          "Timezone": "America/New_York (UTC-04:00)",
          "timestamp": "2025-04-24T10:13:11.035-04:00",
          "Day of week": "Thursday",
          "Day of month": "24",
          "Readable date": "April 24th 2025, 10:13:11 am",
          "Readable time": "10:13:11 am"
        }
      }
    ]
  },
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "3044ad5c-d14e-4562-a454-0ad87f26dc68",
  "connections": {
    "OpenAI": {
      "main": [
        [
          {
            "node": "Assistente Clu00ednica",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Assistente Clu00ednica",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "OpenAI1",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Evolution API",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "OpenAI1": {
      "main": [
        [
          {
            "node": "AI Agent2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "Evolution API2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook1": {
      "main": [
        [
          {
            "node": "Edit Fields1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent2": {
      "main": [
        [
          {
            "node": "Assistente Clu00ednica",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "MCP GMAIL": {
      "ai_tool": [
        [
          {
            "node": "Assistente de confirmau00e7u00e3o",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "CallToHuman": {
      "ai_tool": [
        [
          {
            "node": "Assistente Clu00ednica",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Edit Fields1": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Tasks": {
      "ai_tool": [
        [
          {
            "node": "Assistente clinica interno",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "MCP CALENDAR": {
      "ai_tool": [
        [
          {
            "node": "Assistente de confirmau00e7u00e3o",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Evolution API": {
      "main": [
        [
          {
            "node": "Convert to File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Convert to File": {
      "main": [
        [
          {
            "node": "OpenAI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gatilho diu00e1rio": {
      "main": [
        [
          {
            "node": "Assistente de confirmau00e7u00e3o",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Assistente Clu00ednica",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model1": {
      "ai_languageModel": [
        [
          {
            "node": "Assistente clinica interno",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model2": {
      "ai_languageModel": [
        [
          {
            "node": "Assistente de confirmau00e7u00e3o",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Assistente Clu00ednica": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "MCP Google Calendar": {
      "ai_tool": [
        [
          {
            "node": "Assistente clinica interno",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "MCP Google Calendar2": {
      "ai_tool": [
        [
          {
            "node": "Assistente Clu00ednica",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Postgres Chat Memory": {
      "ai_memory": [
        [
          {
            "node": "Assistente clinica interno",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Postgres Chat Memory1": {
      "ai_memory": [
        [
          {
            "node": "Assistente Clu00ednica",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter Chat Model1": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter Chat Model2": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent2",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Receber Mensagem Telegram": {
      "main": [
        [
          {
            "node": "Assistente clinica interno",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Assistente clinica interno": {
      "main": [
        [
          {
            "node": "Telegram",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Assistente de confirmau00e7u00e3o": {
      "main": [
        [
          {
            "node": "REMINDER",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Enviar alerta de cancelamento": {
      "ai_tool": [
        [
          {
            "node": "Assistente Clu00ednica",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    }
  }
}