Skip to content

RustSandbox/fintech-prompt-templates

Repository files navigation

Banking & Fintech Prompt Engineering Library ๐Ÿฆ€๐Ÿฆ

Rust MIT/Apache-2.0 Build Status

A comprehensive, educational Rust library for learning prompt engineering concepts and Rust programming patterns, specialized for banking and financial services compliance applications.

๐ŸŽฏ Learning Objectives

This library demonstrates and teaches:

  • ๐Ÿ—๏ธ Builder Pattern: Fluent API design for constructing complex prompts
  • ๐Ÿ”Œ Trait-based Abstraction: Creating interfaces for different LLM implementations
  • โšก Async Programming: Non-blocking operations with async/await
  • ๐Ÿ“‹ Compliance Templates: Pre-built templates for 10 financial compliance roles
  • ๐Ÿ”ง Clean Code: Extensively documented, modular Rust code structure
  • ๐Ÿค– Prompt Engineering: Research-backed prompt structuring techniques

๐Ÿš€ Quick Start

Option 1: Use Standalone Templates (No Rust Required) ๐Ÿ“‹

Perfect for: Anyone who wants to use the compliance prompt templates with any LLM, regardless of programming language.

  1. Open COMPLIANCE_PROMPT_TEMPLATES.md
  2. Copy the template for your desired compliance role
  3. Replace [PLACEHOLDER] variables with your specific information
  4. Use directly with any LLM interface (ChatGPT, Claude, Gemini, etc.)

Example: Copy the KYC template, replace [CUSTOMER_TYPE] with "individual" and [FOCUS_AREA] with "identity verification", then paste into your LLM.

Option 2: Use the Rust Library ๐Ÿฆ€

Perfect for: Developers wanting to integrate prompt templates into Rust applications or learn advanced Rust patterns.

Prerequisites

  • Rust 1.70+ (with Cargo)
  • Basic understanding of async Rust programming

Installation

git clone <repository-url>
cd fintech-templates
cargo build

Basic Usage

# Show all available compliance role examples
cargo run -- --examples

# Show specific role template
cargo run -- --role kyc

# Interactive demo with mock LLM responses
cargo run -- --demo

# Demo specific role with LLM interaction
  cargo run -- --demo --role aml

๐Ÿš€ Getting Started

Prerequisites

Prompt Structure

All prompts are organized into logical sections based on prompt engineering research:

pub enum PromptSection {
    Goal(String),           // What to accomplish
    Context(String),        // Background information  
    Role(String),          // LLM persona/expertise
    Step(String),          // Sequential instructions
    Example { user: String, assistant: String }, // Few-shot learning
    Output(String),        // Expected format
    Guardrail(String),     // Safety constraints
    Rubric(String),        // Success criteria
    Reasoning(String),     // Thinking process
    Style(String),         // Communication tone
    TokenLimit(usize),     // Response constraints
    Meta(String),          // Technical instructions
}

Builder Pattern

Create prompts using fluent, chainable API:

let prompt = PromptBuilder::new()
    .goal("Analyze customer feedback")
    .role("Senior Data Analyst") 
    .step("Load customer feedback data")
    .step("Identify key themes and sentiments")
    .example(
        "Customer says: 'Service was slow but helpful'",
        "Analysis: Mixed sentiment - negative on speed, positive on quality"
    )
    .output("Summary report with sentiment scores")
    .build();

Template System

Pre-built templates for compliance roles:

let template = CompliancePromptTemplate::KycCddAnalyst {
    customer_type: "individual".to_string(),
    focus_area: "identity verification".to_string(),
};

let prompt = template.to_builder()
    .step("Additional verification step")
    .build();

LLM Abstraction

Work with any LLM provider through trait abstraction:

#[async_trait]
pub trait SimpleLLMClient: Send + Sync {
    async fn generate(&self, prompt: &str) -> Result<String>;
}

// Use with any implementation
let client = MockLLMClient;  // or OpenAIClient, AnthropicClient, etc.
let response = client.generate(&prompt.to_string()).await?;

๐Ÿฆ Financial Compliance Templates

The library includes comprehensive templates for 10 key compliance roles:

1. ๐Ÿ” KYC/CDD Analyst

Know Your Customer/Customer Due Diligence

Handles customer identity verification, document review, and risk assessment.

cargo run -- --role kyc

Key Features:

  • Identity document verification workflows
  • Risk assessment methodologies
  • Beneficial ownership analysis
  • Regulatory compliance checks

GenAI Augmentation Potential:

  • Automated document verification & data extraction
  • Intelligent document summarization
  • Preliminary risk scoring assistance
  • Automated adverse media screening

2. ๐Ÿ•ต๏ธ AML Investigator

Anti-Money Laundering Analysis

Detects and investigates suspicious financial activities for money laundering prevention.

cargo run -- --role aml

Key Features:

  • Transaction pattern analysis
  • Suspicious activity investigation
  • Evidence gathering and documentation
  • SAR/STR preparation

GenAI Augmentation Potential:

  • Enhanced alert narrative generation
  • Investigation findings summarization
  • Pattern recognition & anomaly description
  • Automated SAR/STR drafting

3. ๐Ÿ’ณ Transaction Monitoring Analyst

Real-time Transaction Screening

Monitors customer transactions to identify unusual or suspicious activities.

cargo run -- --role transaction

Key Features:

  • Real-time alert review
  • False positive identification
  • Transaction pattern analysis
  • Alert disposition workflows

GenAI Augmentation Potential:

  • Smarter false positive reduction
  • Natural language alert explanations
  • Dynamic threshold tuning suggestions
  • Automated alert prioritization

4. ๐Ÿ”Ž Enhanced Due Diligence (EDD) Investigator

High-Risk Customer Investigation

Conducts in-depth investigations for high-risk customers and complex scenarios.

cargo run -- --role edd

Key Features:

  • Comprehensive background research
  • Ultimate beneficial owner identification
  • Source of wealth/funds verification
  • Complex ownership structure analysis

GenAI Augmentation Potential:

  • Automated OSINT & dark web research
  • Network analysis & UBO identification
  • Source of wealth plausibility assessment
  • Cross-lingual information synthesis

5. ๐Ÿšซ Sanctions Screening Specialist

International Sanctions Compliance

Ensures compliance with international sanctions through comprehensive screening.

cargo run -- --role sanctions

Key Features:

  • Multi-list sanctions screening
  • Name matching and false positive analysis
  • Contextual match investigation
  • Compliance documentation

GenAI Augmentation Potential:

  • Contextual alert adjudication
  • Automated rationale generation
  • Complex sanctions regulation summarization
  • Proactive sanctions risk identification

6. ๐Ÿ“Š Regulatory Reporting Specialist

Compliance Reporting & Submissions

Prepares and submits regulatory reports for compliance and AML requirements.

cargo run -- --role reporting

Key Features:

  • SAR/STR preparation
  • Annual compliance reporting
  • Data accuracy validation
  • Regulatory submission workflows

GenAI Augmentation Potential:

  • Automated data collation & formatting
  • Narrative section drafting
  • Quality control & anomaly detection
  • Regulatory change interpretation

7. ๐Ÿ‘จโ€๐Ÿ’ผ Compliance Officer/Manager

Operational Compliance Management

Oversees day-to-day compliance program implementation and management.

cargo run -- --role management

Key Features:

  • Policy development and updates
  • Training program management
  • Compliance monitoring oversight
  • Business unit coordination

GenAI Augmentation Potential:

  • Policy & procedure generation/updates
  • Training material development
  • Marketing material compliance review
  • Compliance helpdesk automation

8. ๐Ÿšจ Fraud Analyst

Fraud Detection & Investigation

Specializes in detecting, preventing, and investigating fraudulent activities.

cargo run -- --role fraud

Key Features:

  • Payment fraud investigation
  • Internal fraud detection
  • Pattern analysis and evidence gathering
  • Prevention strategy development

GenAI Augmentation Potential:

  • Fraud case summarization
  • Unstructured data analysis for fraud signals
  • Fraud scenario simulation
  • Emerging typology identification

9. ๐Ÿ“‹ Compliance Monitoring & Testing Officer

Control Effectiveness Assessment

Designs and executes testing to assess compliance control effectiveness.

cargo run -- --role monitoring

Key Features:

  • Control testing design
  • Sample selection methodologies
  • Findings analysis and reporting
  • Improvement recommendations

GenAI Augmentation Potential:

  • Automated policy adherence checks
  • Test script generation
  • Results analysis & pattern identification
  • Initial findings report drafting

10. ๐Ÿ”’ Data Protection & Privacy Compliance Specialist

Privacy Regulation Compliance

Ensures compliance with data protection regulations like GDPR, CCPA, etc.

cargo run -- --role privacy

Key Features:

  • Privacy impact assessments
  • Data mapping and classification
  • Privacy policy development
  • Individual rights management

GenAI Augmentation Potential:

  • Privacy notice & policy drafting
  • DSAR fulfillment assistance
  • Contract privacy clause analysis
  • Personal data identification & classification

๐ŸŽจ Code Quality & Best Practices

This library exemplifies clean code principles:

Modular Design

  • Single Responsibility: Each function and struct has a clear, focused purpose
  • Well-Named Components: Descriptive names that indicate purpose and intent
  • Concise Functions: Short, focused functions that are easy to understand

Error Handling

// Robust error handling with Result types
pub async fn generate(&self, prompt: &str) -> Result<String> {
    // Implementation with proper error propagation
}

Documentation Standards

/// Function: sanitize_input
///
/// This function takes a raw string as input and performs sanitization
/// to ensure it's safe and in the expected format for processing.
///
/// Arguments:
///     input_string: A String representing the raw input data
///
/// Returns:
///     A String representing the sanitized input
///
/// Example:
///     Input:  "  HeLlO wOrLd!  "
///     Output: "hello world!"
pub fn sanitize_input(input_string: String) -> String {
    // Implementation with step-by-step comments
}

๐Ÿงช Testing

Comprehensive test suite with examples:

cargo test

Tests cover:

  • โœ… Builder pattern functionality
  • โœ… Template system behavior
  • โœ… Mock LLM client responses
  • โœ… Prompt formatting and structure
  • โœ… Error handling scenarios

๐Ÿ“– Usage Examples

Manual Prompt Building

use fintech_templates::*;

// Build a custom compliance prompt
let prompt = PromptBuilder::new()
    .goal("Assess credit risk for mortgage application")
    .context("30-year fixed rate mortgage, $400k loan amount") 
    .role("Senior Credit Risk Analyst")
    .step("Analyze credit history and FICO score")
    .step("Evaluate debt-to-income ratio")
    .step("Assess employment stability")
    .example(
        "FICO 720, DTI 35%, 3 years employment",
        "Moderate risk - approve with standard terms"
    )
    .output("Risk assessment with approval recommendation")
    .guardrail("Do not approve loans exceeding regulatory DTI limits")
    .rubric("โœ“ Credit analysis complete\nโœ“ Risk factors identified\nโœ“ Regulatory compliance verified")
    .build();

Template-Based Building

// Start with a template and customize
let template = CompliancePromptTemplate::FraudAnalysis {
    fraud_type: "payment fraud".to_string(),
    analysis_scope: "real-time detection".to_string(),
};

let custom_prompt = template.to_builder()
    .step("Check for velocity patterns")
    .step("Validate geographic consistency") 
    .guardrail("Maintain customer privacy during investigation")
    .build();

LLM Integration

#[tokio::main]
async fn main() -> Result<()> {
    let client = MockLLMClient;  // Replace with your LLM client
    
    let template = CompliancePromptTemplate::KycCddAnalyst {
        customer_type: "individual".to_string(),
        focus_area: "identity verification".to_string(),
    };
    
    let prompt = template.to_builder().build();
    let response = client.generate(&prompt.to_string()).await?;
    
    println!("LLM Response: {}", response);
    Ok(())
}

๐Ÿ”ฎ Future Enhancements

This educational library can be extended with:

  1. Real LLM Integrations: OpenAI, Anthropic, local models
  2. Caching System: Prompt and response caching for efficiency
  3. Batch Processing: Handle multiple prompts concurrently
  4. Web Interface: REST API and web UI for prompt management
  5. Advanced Templates: Industry-specific and region-specific variations
  6. Metrics & Analytics: Prompt performance tracking
  7. Integration Examples: Database connections, file processing
  8. Multi-language Support: Localized compliance requirements

๐Ÿ—๏ธ Architecture Details

fintech-templates/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ lib.rs              # Core library implementation
โ”‚   โ””โ”€โ”€ main.rs             # Demo application with CLI
โ”œโ”€โ”€ tests/                  # Integration tests
โ”œโ”€โ”€ examples/               # Usage examples
โ”œโ”€โ”€ docs/                   # Additional documentation
โ””โ”€โ”€ README.md              # This file

Dependencies

  • anyhow: Error handling
  • async-trait: Async trait support
  • serde: Serialization support
  • tokio: Async runtime
  • clap: CLI argument parsing

๐Ÿค Contributing

This is an educational project demonstrating best practices. Contributions welcome:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

๐Ÿ“„ License

This project is licensed under either of:

at your option.

๐Ÿ™ Acknowledgments

  • Inspired by the banking-prompt-lib reference
  • Built with clean code principles and educational focus
  • Incorporates latest prompt engineering research and techniques

Happy Learning! ๐Ÿฆ€โœจ

Built with Rust, designed for education, optimized for financial compliance.

About

A comprehensive, educational Rust library for learning prompt engineering concepts and Rust programming patterns, specialized for banking and financial services compliance applications.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors