Senior Software Engineer specialized in enterprise-scale distributed systems and cloud architecture Let's Connect →

BOUTOUIL℠

Ask AI-Powered ISO20022 Expert with Spring AI and AWS Bedrock

0
26
Ask AI-Powered ISO20022 Expert with Spring AI and AWS Bedrock

In today’s financial technology landscape, ISO20022 transaction messages are essential for cross-border payments and secure financial communication. However, extracting insights from these XML-based messages can be challenging without the right tools.

This guide introduces an AI-powered ISO20022 Expert using Spring AI and AWS Bedrock. This application allows you to ask natural language questions about ISO20022 messages and receive intelligent, actionable insights directly.

With this boilerplate, you’ll be able to:

✅ Parse ISO20022 XML Messages into Structured Data
✅ Query Message Details Using Natural Language
✅ Leverage AWS Bedrock’s Claude AI for Intelligent Responses
✅ Use an Interactive CLI with Spring Shell for Seamless Interaction

By the end of this guide, you’ll have a robust, scalable backend capable of intelligent ISO20022 message analysis.


📚 1. Overview

1.1 Why Use AWS Bedrock for ISO20022 Messages?

ISO20022 messages are vital but complex XML documents that require careful parsing and interpretation. AWS Bedrock simplifies this process with powerful AI models like Claude 3 Sonnet, enabling:

  • Accurate Data Extraction: Easily interpret transaction details.

  • Scalability: Handle high volumes of messages efficiently.

  • Natural Language Queries: Ask simple questions without technical XML expertise.

1.2 What You’ll Learn

In this guide, you’ll learn how to:

✅ Parse and Analyze ISO20022 Messages ✅ Build Natural Language Query APIs ✅ Use AWS Bedrock for Intelligent Analysis ✅ Create a User-Friendly CLI with Spring Shell

By the end, you’ll have a fully functional backend capable of ISO20022 message querying.


📚 2. Project Setup

2.1 Initialize the Project

Use Spring Initializr with the following dependencies:

  • Spring Web

  • Spring Shell

  • Spring AI for Bedrock

  • Lombok

2.2 Dependencies

Add necessary dependencies for Spring Shell and AWS Bedrock in build.gradle.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.ai:spring-ai-bedrock-ai-spring-boot-starter'
    implementation 'org.springframework.shell:spring-shell-starter'
    // Lombok
    annotationProcessor 'org.projectlombok:lombok'
    compileOnly 'org.projectlombok:lombok'
    // ISO20022
    implementation 'com.prowidesoftware:pw-iso20022:SRU2024-10.2.4'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.shell:spring-shell-dependencies:$springShellVersion"
        mavenBom "org.springframework.ai:spring-ai-bom:$springAiVersion"
    }
}

2.3 Configuration in application.yml

Configuration properties for AWS Bedrock, ISO20022 message handling, and environment settings.

## BEDROCK ENV ##
BEDROCK_ACCESS_KEY_ID: XXXXXXXXXXXXX
BEDROCK_SECRET_ACCESS_KEY: XXXXXXXXXXXXXXXXXXXXXXXXXX
BEDROCK_MODEL_ID: eu.anthropic.claude-3-5-sonnet-20240620-v1:0
BEDROCK_REGION: eu-west-1

spring:
  # AWS Bedrock Configuration
  ai:
    bedrock:
      aws:
        region: ${BEDROCK_REGION:}
        access-key: ${BEDROCK_ACCESS_KEY_ID:}
        secret-key: ${BEDROCK_SECRET_ACCESS_KEY:}
      anthropic3:
        chat:
          enabled: true
          model: ${BEDROCK_MODEL_ID}
          options:
            temperature: 0.1        # Minimize randomness for consistent responses
            top-p: 1.0             # Use all tokens above threshold
            top-k: 40              # Optimal for financial text analysis
            max-tokens: 2048        # Balanced size for message analysis
  # Shell Configuration
  shell:
    command:
      history:
        enabled: true
    interactive:
      enabled: true
    script:
      enabled: false

2.4 Verify Setup

Run the application:

./gradlew bootRun

Ensure the application starts without errors.


📚 3. The Data Model

3.1 ISO20022 Message Entity

Define the core structure for ISO20022 messages. Extract relevant fields such as Transaction AmountSender Bank Beneficiary, and Transaction Date.

public class ISO20022Message {
    // Group Header
    private String messageId;                  // GrpHdr/MsgId
    private String creationDateTime;           // GrpHdr/CreDtTm
    private String numberOfTransactions;       // GrpHdr/NbOfTxs
    private String settlementMethod;           // GrpHdr/SttlmInf/SttlmMtd
    private String clearingSystem;             // GrpHdr/SttlmInf/ClrSys/Cd
    //...
}

Key Fields:

  • transactionId: Unique ID of the transaction.

  • sender: Sender’s bank information.

  • beneficiary: Beneficiary’s bank information.

  • amount: Transaction amount.

  • transactionDate: Date of the transaction.


📚 4. Backend Services

4.1 Bedrock Query Service

  • Use AWS Bedrock AI models to process natural language queries.

  • Provide insights based on ISO20022 transaction details.

Example Queries:

  • “What is the transaction amount?”

  • “Who is the sender?”

  • “List transactions above $10,000.”

private static final String SYSTEM_PROMPT = """
        You are an ISO20022 CBPR+ message analyst. Review the XML message and answer questions about it.
        When responding:
        1. Focus on the specific elements asked about in the question
        2. Present information in a clear format using descriptive labels
        3. If relevant, include the XML path where the information was found
        4. Group related information together
        5. Use bullet points for multiple related items
        
        Message XML: {message}
        """;

@Qualifier("anthropic3ChatModel")
private final ChatModel model;

public String queryMessage(String xmlMessage, String question) {
    try {
        Message userMessage = new UserMessage(question);
        PromptTemplate promptTemplate = new PromptTemplate(SYSTEM_PROMPT, Map.of("message", xmlMessage));

        Prompt prompt = new Prompt(List.of(promptTemplate.createMessage(), userMessage));
        return model.call(prompt).getResult().getOutput().getContent();
    } catch (Exception e) {
        log.error("Error querying Bedrock: {}", e.getMessage());
        throw new RuntimeException("Failed to process query", e);
    }
}

Explanation:

  • SYSTEM_PROMPT: Defines the behavior and focus for the AI model.

  • UserMessage: Captures the user’s natural language query.

  • PromptTemplate: Inserts the XML message into the system prompt dynamically.

  • Model Call: Sends the prompt to AWS Bedrock for processing and returns the AI-generated response.

This approach ensures clarity, flexibility, and reliability when querying ISO20022 messages using natural language.


📚 5. Spring Shell Integration

5.1 Command Setup with Spring Shell

  • Build a Spring Shell interface for querying ISO20022 messages.

  • Accept user input for file path and query.


@ShellMethod(key = "convert", value = "Convert ISO20022 XML message to structured format")
public String convertMessage(
        @ShellOption(help = "Full path to ISO20022 XML file") String file
) {
    try {
        Resource resource = getResource(file);
        System.out.println("\nProcessing ISO20022 message: " + resource.getFile().getName());
        System.out.println("Converting to structured format...\n");

        String input = resource.getContentAsString(StandardCharsets.UTF_8);
        AbstractMX mx = AbstractMX.parse(input);

        ISO20022Message analysis = queryService.analyzeMessage(mx.message());
        return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(analysis) + "\n";
    } catch (Exception e) {
        System.err.println("\nError occurred while converting message:");
        e.printStackTrace(System.err);
        return "\nError: " + e.getMessage() + "\n";
    }
}

@ShellMethod(key = "ask", value = "Ask questions about an ISO20022 message")
public String askQuestion(
        @ShellOption(help = "Full path to ISO20022 XML file") String file,
        @ShellOption(help = "Question about the message") String question
) {
    try {
        Resource resource = getResource(file);
        System.out.println("\nProcessing ISO20022 message: " + resource.getFile().getName());
        System.out.println("Analyzing message with question: \"" + question + "\"\n");

        String input = resource.getContentAsString(StandardCharsets.UTF_8);
        AbstractMX mx = AbstractMX.parse(input);

        String response = queryService.queryMessage(mx.message(), question);
        return "\nAnswer:\n" +
                "----------------------------------------\n" +
                response +
                "\n----------------------------------------\n";
    } catch (Exception e) {
        System.err.println("\nError occurred while processing question:");
        e.printStackTrace(System.err);
        return "\nError: " + e.getMessage() + "\n";
    }
}

5.2 Command Workflow

  1. Load the XML File: Validate and parse the file.

  2. Send Query to Bedrock: Pass extracted details and the natural language query.

  3. Display Response: Show results in a clean format.

Example Output:

ask ./messages/TROK_pacs.002.xml "Is this message a customer credit transfer, account statement, or acknowledgment message?"
#    Answer:
#    This message is an acknowledgment message. Specifically:
#    Message Type:
#    • Financial Institution to Financial Institution Payment Status Report (pacs.002.001.10)
#    
#    The message contains:
#    • Status information for a previous payment message
#    • Reason for rejection (if applicable)
#    • References to the original payment instruction
ask ./messages/TROK_pacs.008.xml "What are the complete details of the beneficiary, including name, address and account?"
#    Answer:
#    Here are the complete details of the beneficiary (creditor) from the message:
#    Creditor Details:
#    • Name: Mr. Creditor
#    • Address:
#      - 125th Street
#      - California
#      - United States

This setup ensures a robust interaction model via Spring Shell, enabling users to query ISO20022 messages seamlessly and receive clear, actionable insights directly from the AWS Bedrock AI model.


📚 6. Workflow Example

1. Start the Application:

Start the application to ensure all configurations and services are correctly loaded:

./gradlew bootRun

2. Run the Query Command:

Full Structure Conversion

Convert an ISO20022 XML message into a structured format:

convert ./messages/TROK_pacs.008.xml

Message Direction and Identification

Identify whether the message represents an incoming or outgoing payment:

ask ./messages/TROK_sender_pacs.008.xml "Is this an incoming or outgoing payment?"
ask ./messages/TROK_pacs.008.xml "Is this payment incoming or outgoing for AABBGB2X?"
ask ./messages/TROK_pacs.002.xml "Is this message a customer credit transfer, account statement, or acknowledgment message?"
ask ./messages/TROK_pacs.008.xml "Is this an outgoing or incoming message for institution AABBGB2X? Analyze the message direction based on the business header's From and To fields, and the instructing/instructed agent information."

Transaction Details

Retrieve detailed transaction information:

ask ./messages/TROK_pacs.008.xml "What is the transaction amount and currency?"
ask ./messages/TROK_pacs.008.xml "What is the settlement date?"
ask ./messages/TROK_pacs.008.xml "What charges and fees are applied?"
ask ./messages/TROK_pacs.008.xml "Is this a domestic or cross-border payment?"

Party Information

Extract information about involved parties:

ask ./messages/TROK_pacs.008.xml "What are the complete details of the beneficiary, including name, address and account?"
ask ./messages/TROK_pacs.008.xml "What are the complete details of the ordering customer, including name, address and account?"
ask ./messages/TROK_pacs.008.xml "What is the beneficiary institution's information including BIC and branch?"
ask ./messages/TROK_pacs.008.xml "What is the ordering institution's information including BIC and branch?"

Intermediary Banks

Identify intermediary institutions involved in the transaction:

ask ./messages/TROK_pacs.008.xml "Is there a correspondent bank involved and what are their details?"
ask ./messages/TROK_pacs.008.xml "Are there any intermediary banks in the payment chain?"

Settlement Information

Understand how the payment is settled:

ask ./messages/TROK_pacs.008.xml "What is the clearing system used for settlement?"
ask ./messages/TROK_pacs.008.xml "What is the settlement method and priority?"

This workflow demonstrates how to interact with the application via Spring Shell, enabling you to query ISO20022 messages intuitively and retrieve valuable insights through natural language queries processed by AWS Bedrock.


📚 7. Resources and References


With this boilerplate, you’re now equipped to build an AI-powered ISO20022 Expert using Spring AIAWS Bedrock, and an intuitive Spring Shell CLI.

Happy Coding! 🚀✨


Mohammed AmineM
WRITTEN BY

Mohammed Amine

I’m a Senior Software Engineer and Technical Lead with over 5 years of experience designing and scalable financial systems, specializing in Java, Spring Boot, AWS, and cross-payment platforms like SWIFT and Mastercard APIs. Experienced in leading teams, optimizing system performance, and delivering secure, high-availability solutions. Passionate about solving complex challenges and driving innovation in financial technology.

Responses (0 )