# Build an AI agent system to automate banking workflows

[AI agents](https://www.infobip.com/docs/ai-agents) are modular AI systems that can perform specific tasks. This tutorial explains how to create an AI agent system that checks end users' eligibility for loans and mortgages and helps them book appointments.

After completing this tutorial, you will have a chatbot that routes end user requests to the correct AI agent.

This tutorial uses the WhatsApp channel. You can customize the instructions in the tutorial to use other channels.

## Products and channels [#products-channels]

Use the following Infobip products to build and deploy your AI agent system:

| Feature | Description |
| --- | --- |
| [AI agents](https://www.infobip.com/docs/ai-agents) | Create and manage AI agents. |
| [Answers](https://www.infobip.com/docs/answers) | Create components to use as tools in AI agents.Create a chatbot that calls the AI agent. |
| [WhatsApp](https://www.infobip.com/docs/whatsapp) | The channel over which the end user communicates with the chatbot. |

## Prerequisites [#prerequisites]

Infobip account with the following enabled:

- [AI agents](https://www.infobip.com/docs/ai-agents). Contact your Infobip account manager to enable this.
- [Answers](https://www.infobip.com/docs/answers)
- [WhatsApp](https://www.infobip.com/docs/whatsapp)

## Technical specifications [#technical-specifications]

The system consists of the following:

- Specialist AI agents to book appointments and calculate loan and mortgage eligibility.
- An orchestrator that coordinates these AI agents.
- A chatbot that uses these AI agents. End users interact with the chatbot to get support.
- Tools that perform specific tasks and are used in the AI agents.

## Process overview [#process-overview]

1. In Answers, create components that perform specific tasks. These are used as tools by the AI agents.
2. Create and publish the specialist AI agents.
    - Include the tools in the agents.
3. Create and publish the orchestrator.
    - Include the specialist AI agents in the orchestrator.
4. In your Answers chatbot, use the **Agent connector** element to call the orchestrator.

## Implementation steps [#implementation-steps]

### Create tools for the AI agents

The **tools** used in AI agents are created as **components** in Answers.

#### Components to create in Answers

This tutorial creates the following components:

| Component | Agent in which it is used |
| --- | --- |
| bank_calculate_loans | Loan & Mortgage Recommender - Banks |
| bank_calculate_mortgage | Loan & Mortgage Recommender - Banks |
| bank_book_slot | Appointment Organizer - Banks |
| bank_find_slot | Appointment Organizer - Banks |
| bank_send_email | Appointment Organizer - Banks |

#### Create the bank_calculate_loans component

##### Create the component in Answers

1. [Create](https://www.infobip.com/docs/answers/chatbot-structure/components#create-the-component) a new component.
2. Configure the fields in the component.
3. Configure the input and output attributes.
4. Add and configure the [**Code**](https://www.infobip.com/docs/answers/chatbot-elements/core-elements#code) element.
5. Add the **Return result** element.

##### Configure the component

Component name: bank_calculate_loans

Component description: This component is used to calculate loans based on the end user's monthly net income and the duration of the loan term.

Input attributes:

| Attribute name | Data type | Description |
| --- | --- | --- |
| loanAmount | Number | The amount of the loan that the end user wants to borrow. |
| propertyValue | Number | The number of years the end user wants to repay the mortgage. |
| monthlyNetIncome | Number | The end user's monthly net income in Euros. |

Output attribute:

Name | Data type  
---|---  
result | Text

##### Configure the Code element

Use the following code:

```javascript showLineNumbers copy
function loanCalculator(loanAmount, annualInterestRate, durationYears, monthlyNetIncome) {
  // Convert annual percent rate (e.g., 7 for 7%) to decimal (0.07)
  const annualRateDecimal = annualInterestRate / 100;
  const monthlyInterestRate = annualRateDecimal / 12;
  const numberOfPayments = durationYears * 12;
  let monthlyPayment;
  
  if (monthlyInterestRate === 0) {
    monthlyPayment = loanAmount / numberOfPayments;
  } else {
    const pow = Math.pow(1 + monthlyInterestRate, numberOfPayments);
    monthlyPayment = loanAmount * (monthlyInterestRate * pow) / (pow - 1);
  }

  const totalPayback = monthlyPayment * numberOfPayments;

  // Guardrail: max allowed payment is 40% of net income
  const maxAffordablePayment = monthlyNetIncome * 0.4;

  // Format as currency
  const formatter = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });

  // Build result object
  const result = {
    eligible: monthlyPayment <= maxAffordablePayment,
    loanAmount: Number(loanAmount),
    durationYears: Number(durationYears),
    annualInterestRate: Number(annualInterestRate),
    monthlyPayment: Number(monthlyPayment.toFixed(2)),
    totalPayback: Number(totalPayback.toFixed(2)),
    maxAffordablePayment: Number(maxAffordablePayment.toFixed(2)),
    message: ""
  };

  if (monthlyPayment > maxAffordablePayment) {
    result.message = `Not eligible based on your income. The estimated monthly payment of ${formatter.format(monthlyPayment)} exceeds your allowable maximum of ${formatter.format(maxAffordablePayment)}.`;
  } else {
    result.message =
      `For a loan amount of ${formatter.format(loanAmount)} over a ${durationYears}-year term at an interest rate of ${annualInterestRate.toFixed(2)}%, your estimated monthly payment would be ${formatter.format(monthlyPayment)}.\n` +
      `Total amount to pay back (including interest): ${formatter.format(totalPayback)}.`;
  }

  return result;
}

// Example usage:
const loanAmount = Number(attributeApi.get('loanAmount'));
const durationYears = Number(attributeApi.get('durationYears'));
const monthlyNetIncome = Number(attributeApi.get('monthlyNetIncome'));
const annualInterestRate = 8; // or get from attributeApi if variable

const result = loanCalculator(loanAmount, annualInterestRate, durationYears, monthlyNetIncome);

console.log(result.message);
console.log("Annual Interest Rate:", result.annualInterestRate + "%");

attributeApi.set('result', result);
```

#### Create the bank_calculate_mortgage component [#create-bank-calculate-mortgage-]

##### Create the component in Answers

1. [Create](https://www.infobip.com/docs/answers/chatbot-structure/components#create-the-component) a new component.
2. Configure the fields in the component.
3. Configure the input and output attributes.
4. Add and configure the [**Code**](https://www.infobip.com/docs/answers/chatbot-elements/core-elements#code) element.
5. Add the **Return result** element.

##### Configure the component

Component name: bank_calculate_mortgage

Component description: This component is used to calculate eligibility and terms of mortgage for an end user.

Input attributes:

Name | Data type | Description  
---|---|---  
durationYears | Number | The number of years for which the end user wants to get a mortgage.  
propertyValue | Number | The value of the property in Euros.  
monthlyNetIncome | Number | The end user's monthly net income in Euros.

Output attribute:

Name | Data type  
---|---  
result | Text

##### Configure the Code element

Use the following code:

```javascript showLineNumbers copy
function mortgageCalculator(propertyValue, monthlyNetIncome, durationYears) {
  const annualInterestRate = 0.03;
  const monthlyInterestRate = annualInterestRate / 12;
  const maxDurationYears = 30;
  let eligible = false;
  let monthlyPayment, validDuration, totalDebt;

  function calcPayment(principal, monthlyRate, years) {
    const n = years * 12;
    if (monthlyRate === 0) return principal / n;
    const pow = Math.pow(1 + monthlyRate, n);
    return principal * (monthlyRate * pow) / (pow - 1);
  }

  propertyValue = Number(propertyValue);
  monthlyNetIncome = Number(monthlyNetIncome);
  durationYears = Number(durationYears);

  const maxAffordablePayment = monthlyNetIncome * 0.4;

  monthlyPayment = calcPayment(propertyValue, monthlyInterestRate, durationYears);
  totalDebt = monthlyPayment * durationYears * 12;

  if (monthlyPayment <= maxAffordablePayment) {
    eligible = true;
    return {
      eligible: true,
      message: `Eligible! Your estimated monthly payment would be €${monthlyPayment.toFixed(2)} over ${durationYears} years.`,
      monthlyPayment: monthlyPayment.toFixed(2),
      durationNeeded: durationYears,
      annualInterestRate: (annualInterestRate * 100).toFixed(2) + '%',
      totalDebt: totalDebt.toFixed(2)
    };
  }

  for (let yrs = durationYears + 1; yrs <= maxDurationYears; yrs++) {
    const payment = calcPayment(propertyValue, monthlyInterestRate, yrs);
    if (payment <= maxAffordablePayment) {
      eligible = true;
      validDuration = yrs;
      monthlyPayment = payment;
      totalDebt = monthlyPayment * yrs * 12;
      break;
    }
  }

  if (eligible) {
    return {
      eligible: false,
      message: `Not eligible for ${durationYears} years. To become eligible, extend the duration to ${validDuration} years (monthly payment: €${monthlyPayment.toFixed(2)}).`,
      monthlyPayment: monthlyPayment.toFixed(2),
      durationNeeded: validDuration,
      annualInterestRate: (annualInterestRate * 100).toFixed(2) + '%',
      totalDebt: totalDebt.toFixed(2)
    };
  } else {
    return {
      eligible: false,
      message: `Not eligible for ${durationYears} years or any duration up to ${maxDurationYears} years. The property value is too high for your income.`,
      monthlyPayment: null,
      durationNeeded: null,
      annualInterestRate: (annualInterestRate * 100).toFixed(2) + '%',
      totalDebt: null
    };
  }
}

const propertyValue = Number(attributeApi.get('propertyValue'));
const monthlyNetIncome = Number(attributeApi.get('monthlyNetIncome'));
const durationYears = Number(attributeApi.get('durationYears'));
const result = mortgageCalculator(propertyValue, monthlyNetIncome, durationYears);

console.log(result.message);
if (result.durationNeeded) {
  console.log(`Needed duration: ${result.durationNeeded} years`);
}
console.log(`Annual Interest Rate: ${result.annualInterestRate}`);
if (result.totalDebt) {
  console.log(`Total Debt: $${result.totalDebt}`);
}

attributeApi.set('result', result);
```

#### Create the bank_book_slot component

##### Create the component in Answers

1. [Create](https://www.infobip.com/docs/answers/chatbot-structure/components#create-the-component) a new component.
2. Configure the fields in the component.
3. Configure the input attributes.
4. Add and configure the [**API**](https://www.infobip.com/docs/answers/chatbot-elements/core-elements#api) element.
5. Add the **Return result** element.

##### Configure the component

Component name: bank_book_slot

Component description: This component is used to book an appointment in the bank.

Input attributes:

Name | Data type | Description  
---|---|---  
booked_from | Date | From date in the format 2025-06-30T15:00:00  
booked_to | Date | To date in the format 2025-06-30T15:00:00  
notes | Text | Additional notes  
username | Text | The name of the end user  
topic | Text | Topic for which the appointment is booked. Example: Mortgage

##### Configure the API element

In the Request section, configure the following:

- Method: POST  
- URL: https://demobanking1.makeplans.com/api/v1/bookings  
- Content type: JSON (application/json)

- Headers:

  | Key | Value |
  | --- | --- |
  | Authorization | <your-api-key> |

- Body:

  ```json showLineNumbers copy
  {
  "booked_from": "{{booked_from}}",
  "booked_to": "{{booked_to}}",
  "resource_id": 17600,
  "title": "Meeting with {{username}}: {{topic}}",
  "notes": "{{notes}}",
  "external_id": "...todo...",
  "booking_type": "appointment"
  }
  ```

#### Create the bank_find_slot component

##### Create the component in Answers

1. [Create](https://www.infobip.com/docs/answers/chatbot-structure/components#create-the-component) a new component.
2. Configure the fields in the component.
3. Configure the input and output attributes.
4. Add and configure the [**API**](https://www.infobip.com/docs/answers/chatbot-elements/core-elements#api) element.
5. Add the **Return result** element.

##### Configure the component

Component name: bank_find_slot

Component description: This component is used to find available slots in the bank's calendar for an appointment.

Input attributes:

Name | Data type | Description  
---|---|---  
date_from | Text | From date in the format 2025-06-28T08:00:00  
date_to | Text | To date in the format 2025-06-28T08:00:00

Output attribute:

Name | Data type  
---|---  
response | Text

##### Configure the API element

Request

In the Request section, configure the following:

- Method: GET
- URL: https://demobanking1.makeplans.com/api/v1/services/28783/slots?from={{date_from}}&to={{date_to}}
- Content type: JSON (application/json)

- Headers:

  | Key | Value |
  | --- | --- |
  | Authorization | <your-api-key> |

Response

In the Response section, configure the Response body attributes.

  | Attribute | Path |
  | --- | --- |
  | response | $ |

#### Create the bank_send_email component

##### Create the component in Answers

1. [Create](https://www.infobip.com/docs/answers/chatbot-structure/components#create-the-component) a new component.
2. Configure the fields in the component.
3. Configure the input attributes.
4. Add and configure the [**API**](https://www.infobip.com/docs/answers/chatbot-elements/core-elements#api) element.
5. Add the **Return result** element.

##### Configure the component

Component name: bank_send_email

Component description: This component is used to send verification e-mail to the end user with the details of their appointment in the html_body.

Input attributes:

Name | Data type | Default value | Description  
---|---|---|---  
email | Email | — | Email address of the end user  
html_body | Text | <h1>Html body</h1><p>Rich HTML message body</p> | The body of the email in rich text format sent to the end user

##### Configure the API element

In the Request section, configure the following:

- Method: POST  
- URL: https://api.infobip.com/email/3/send  
- Content type: Form Data (multipart/form-data)
- Headers:

  | Key | Value |
  | --- | --- |
  | Authorization | <your-api-key> |

- Body:

  | Key | Value |
  | --- | --- |
  | from | <your address email> |
  | to | {{email}} |
  | replyTo | <your address email> |
  | subject | Confirmation |
  | html | {{html_body}} |

### Create AI agents

#### AI agents to create

This tutorial creates the following AI agents:

| AI agent | Role | Collaborators used |
| --- | --- | --- |
| Banks | Orchestrator | Appointment Organizer - BanksLoan & Mortgage Recommender - Banks |
| Appointment Organizer - Banks | Specialist AI agent | N/A |
| Loan & Mortgage Recommender - Banks | Specialist AI agent | N/A |

##### Banks (Orchestrator)

This routes end user requests to the most relevant specialist AI agent.

It uses the following specialist AI agents as collaborators:

- Appointment Organizer - Banks
- Loan & Mortgage Recommender - Banks

##### Appointment Organizer - Banks (Specialist AI agent)

This AI agent helps end users book an appointment for banking services such as short-term loans, mortgages, opening a new bank account, and financial advice.

It does the following:

- Collects the necessary information from the end user.
- Provides real-time available time slots and confirms bookings.
- Sends confirmation emails with detailed appointment summary.

It uses the following tools:

- Tool to look at free slots in the calendar (bank_find_slot)
- Tool to book the free slot (bank_book_slot)
- Tool to send an email (bank_send_email)

##### Loan & Mortgage Recommender - Banks (Specialist AI agent)

This AI agent assesses the eligibility of end users for personal loans and mortgages.

It does the following:

- Collects financial information, which is required to do loan/mortgage calculation, from the end user. Example: Income, property price/desired loan amount, and desired loan term.
- Computes eligibility by using banking rules.
- If the end user is eligible, the AI agent communicates the estimated repayments, rates, and total debt. It also seamlessly offers an appointment link for further in-branch actions.

It uses the following tools:

- Tool to calculate loan eligibility (bank_calculate_loans)
- Tool to calculate mortgage eligibility (bank_calculate_mortgage)

#### Create the Appointment Organizer - Banks AI agent

1. On the [Infobip web interface](https://portal.infobip.com/login), go to AI agents > Create agent.
2. Rename the agent as Appointment Organizer - Banks.
3. In the Agent setup section, configure the following fields:

    - Description: Add a description for the agent so that you can identify it.

      You are a friendly agent who helps end users book an appointment for a banking session.

    - Instructions: Specify the instructions or prompts for the LLM.

        ```javaScript showLineNumbers copy
        - You are a helpful **appointment booker** agent.

        **Initial Contact & Appointment Purpose**  
        - When end user first contacts you, analyze their message to determine the appointment purpose.  
        - If the message is unclear, respond:  
          "I am here to help you schedule a bank appointment for short-term loans, mortgages, opening a new bank account, or financial advice. What would you like to schedule today?"

        **Appointment Types**  
        - Supported appointment types: Short-term loans, Mortgages, Opening a new bank account, Financial Advice.  
        - If an unsupported type is requested, categorize it as Other.

        **Date Selection & Slot Availability**  
        - ALWAYS ask for preferred date(s).  
        - When you have the preferred dates, use the bank_find_slot tool from {{tools}} to show available slots.  
          Example:  
          "Available slots on [date]: [list slots]. Which one works for you?"  
        - Do not select a timeslot for the end user.

        **Name Collection**  
        - After a date and timeslot are chosen, ask for the end user's name.  
        - When recognizing the name pay attention that it is a real name, not something random.

        **Handling Date Modifications**  
        - If the end user at any point asks for another date including 'check today', 'tomorrow', look at your previous conversation.  
        - If you think they want to modify the day they want to book the appointment, use the tool again to check availability.

        **Data Storage**  
        - Store the customer's name, appointment type, date, and timeslot.

        **Booking Confirmation**  
        - Before booking, confirm the information you have.  
        - If confirmed, use the bank_book_slot tool from {{tools}}.  
        - If not, clarify or adjust.

        **Post-Booking Message**  
        - After booking, verify:  
          "Your appointment for [appointment type] on [date] at [time] is booked! Anything else?"

        **Email Confirmation**  
        - If bank_send_email tool is available in {{tools}}, ask if the end user wants an e-mail confirmation.  
        - If yes, request their e-mail address.  
        - Create an HTML email and send it.

        **Error Handling**  
        - For invalid input, say:  
        "Sorry — that [date/timeslot] isn't available. Here are the slots: [list slots]. Please choose one!"  
        - If tools fail, respond:  
        "I'm having trouble checking slots. It might be that there aren't any slots available for the day you selected. Please try again or pick another date!"

        **Tone & Presentation**  
        - Use Emojis where appropriate.
        ```

4. Specify the tools that the agent uses to complete tasks. In the Agent actions section, add the following tools:

    - bank_book_slot
    - bank_find_slot
    - bank_send_email

5. Save the agent.

The agent is now listed in AI agents > My agents page.

#### Create the Loan & Mortgage Recommender - Banks AI agent

1. On the [Infobip web interface](https://portal.infobip.com/login), go to AI agents > Create agent.
2. Rename the agent as Loan and Mortgage Recommender - Banks.
3. In the Agent setup section, configure the following fields:

    - Description: Add a description for the agent so that you can identify it. You are a friendly agent who guides end users regarding loan and mortgage options.

    - Instructions: Specify the instructions or prompts for the LLM.

        ```javaScript showLineNumbers copy
        - You are an agent that provides guidance on **loan and mortgage options**.

      **Initial Contact**  
      - On first contact, ask:  
        "Are you interested in exploring options for a loan or a mortgage?"

      **Required Information Collection**  
      - Based on the response, collect the required information:  
        - **For loans:**
          — Monthly net income  
          — Desired loan term (up to 10 years)  
          — Desired loan amount  
        - **For mortgages:**
          — Monthly net income  
          — Price of the property  
          — Desired loan term (15–30 years)  
      - Do not make any assumptions. The end user must provide all the information needed for the calculations.

      **Tool Usage**
      - After all information is collected, use the appropriate tool:  
        - **For loans:** bank_calculate_loans from {{tools}}  
        - **For mortgages:** bank_calculate_mortgage from {{tools}}

      **Eligibility & Response**  
      - Based on the results, inform the end user of their eligibility and provide:  
        — Estimated monthly payment  
        — Loan interest rate  
        — Total debt amount  
        — Duration of the loan  
      - If the end user is not eligible, respond:  
        "Unfortunately, based on your income and the property price, you are not eligible at this time. To explore further financing options, please schedule an appointment."  
      - If the end user is eligible for a loan, ask:  
        "Would you like to schedule an appointment to further discuss the terms?"

      **Conversation Boundaries**  
      - Do not answer questions unrelated to loans or mortgages or outside these instructions.

      **Error Handling**  
      - If tools fail or input is invalid, respond:  
        "I'm having trouble processing your request — please verify your details or try again."

      **Dynamic Updates**  
      - The end user might change some of the information previously provided.  
        — When this happens, use the new information for the calculations.

      **Tone & Presentation**  
      - Use emojis where appropriate.
      ```

4. Specify the tools that the agent uses to complete tasks. In the Agent actions section, add the following tools:

    - bank_calculate_loans
    - bank_calculate_mortgage

5. Save the agent.

The agent is now listed in AI agents > My agents page.

##### Create the Banks orchestrator

1. On the Infobip web interface, go to AI agents > Create agent.
2. Rename the agent as Bank Orchestrator Agent.
3. In the Agent setup section, configure the following fields:

    - Description: Add a description for the agent so that you can identify it. You are an AI Orchestrator Agent for Banking.
    - Instructions: Specify the instructions or prompts for the LLM.

        ```javaScript showLineNumbers copy
        - You are a friendly assistant.

      **Initial Interaction**  
      - When the end user asks for help or greets you for the first time  
        - Introduce yourself warmly  
        - Explain what you can assist with based on {{system.collaborators}}  
        - Highlight the areas of expertise available through your collaborators

      **Request Handling**  
      - For every end user request  
        - Identify the most suitable agent from {{system.collaborators}}  
        - Delegate the task clearly and directly — do not answer the question yourself  
        - Clarify which collaborator will assist the end user

      **Tone & Presentation**
      - Maintain a friendly and helpful tone  
      - Use emojis where appropriate
        ```

4. Enable Orchestrator agent.
5. Select Add agent and add each of the following AI agents (collaborators).
    - Loan & Mortgage Recommender - Banks
    - Appointment Organizer - Banks

6. Save the agent.

The agent is now listed in AI agents > My agents page.

### Use the AI agent in an Answers chatbot

1. Create a chatbot for the banking use case.
2. Add the required dialogs.
3. Create the following attributes to save data obtained from the AI agents:

    | Attribute | Data type |
    | --- | --- |
    | agentHistory | Text |
    | agentName | Text |
    | executedTools | Text |
    | agentResponse | Text |
    | agentContext | JSON |

4. To add the AI agent to your chatbot, add the [Agent connector](https://www.infobip.com/docs/ai-agents#use-ai-agents-answers-agent-connector-element) element to the relevant dialog.
5. In the Agent connector element > Request tab, configure the following fields:

    - Agent ID: Enter the ID of the orchestrator.
    - User message: Use the predefined attribute lastReceivedTextMessage.
    - Session ID: Use the predefined attribute session_id.
    - End user destination (Optional): Use the predefined attribute endUserDestination.
    - Agent context: Add the attribute agentContext.
6. To save the results from the AI agent in attributes, configure the following Response body attributes in the Response tab:

    | Attribute | Path |
    | --- | --- |
    | agentResponse | $.content |
    | executedTools | $.debug.executedTools |
    | agentName | $.debug.agentName |
    | agentHistory | $.history |

7. Add a [Text](https://www.infobip.com/docs/answers/chatbot-elements/channels#text-whatsapp) element to return the result to the end user.

## Additional resources [#additional-resources]

- [AI agents](https://www.infobip.com/docs/ai-agents) documentation
- [Answers](https://www.infobip.com/docs/answers/create-chatbot/create-chatbot-from-scratch) documentation to create, test, and activate a chatbot
- Answers on the Infobip web interface
- AI agents on the Infobip web interface