A comprehensive, educational Rust library for learning prompt engineering concepts and Rust programming patterns, specialized for banking and financial services compliance applications.
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
Perfect for: Anyone who wants to use the compliance prompt templates with any LLM, regardless of programming language.
- Open
COMPLIANCE_PROMPT_TEMPLATES.md - Copy the template for your desired compliance role
- Replace
[PLACEHOLDER]variables with your specific information - 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.
Perfect for: Developers wanting to integrate prompt templates into Rust applications or learn advanced Rust patterns.
- Rust 1.70+ (with Cargo)
- Basic understanding of async Rust programming
git clone <repository-url>
cd fintech-templates
cargo build# 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 amlAll 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
}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();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();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?;The library includes comprehensive templates for 10 key compliance roles:
Know Your Customer/Customer Due Diligence
Handles customer identity verification, document review, and risk assessment.
cargo run -- --role kycKey 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
Anti-Money Laundering Analysis
Detects and investigates suspicious financial activities for money laundering prevention.
cargo run -- --role amlKey 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
Real-time Transaction Screening
Monitors customer transactions to identify unusual or suspicious activities.
cargo run -- --role transactionKey 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
High-Risk Customer Investigation
Conducts in-depth investigations for high-risk customers and complex scenarios.
cargo run -- --role eddKey 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
International Sanctions Compliance
Ensures compliance with international sanctions through comprehensive screening.
cargo run -- --role sanctionsKey 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
Compliance Reporting & Submissions
Prepares and submits regulatory reports for compliance and AML requirements.
cargo run -- --role reportingKey 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
Operational Compliance Management
Oversees day-to-day compliance program implementation and management.
cargo run -- --role managementKey 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
Fraud Detection & Investigation
Specializes in detecting, preventing, and investigating fraudulent activities.
cargo run -- --role fraudKey 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
Control Effectiveness Assessment
Designs and executes testing to assess compliance control effectiveness.
cargo run -- --role monitoringKey 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
Privacy Regulation Compliance
Ensures compliance with data protection regulations like GDPR, CCPA, etc.
cargo run -- --role privacyKey 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
This library exemplifies clean code principles:
- 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
// Robust error handling with Result types
pub async fn generate(&self, prompt: &str) -> Result<String> {
// Implementation with proper error propagation
}/// 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
}Comprehensive test suite with examples:
cargo testTests cover:
- โ Builder pattern functionality
- โ Template system behavior
- โ Mock LLM client responses
- โ Prompt formatting and structure
- โ Error handling scenarios
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();// 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();#[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(())
}This educational library can be extended with:
- Real LLM Integrations: OpenAI, Anthropic, local models
- Caching System: Prompt and response caching for efficiency
- Batch Processing: Handle multiple prompts concurrently
- Web Interface: REST API and web UI for prompt management
- Advanced Templates: Industry-specific and region-specific variations
- Metrics & Analytics: Prompt performance tracking
- Integration Examples: Database connections, file processing
- Multi-language Support: Localized compliance requirements
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
anyhow: Error handlingasync-trait: Async trait supportserde: Serialization supporttokio: Async runtimeclap: CLI argument parsing
This is an educational project demonstrating best practices. Contributions welcome:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
This project is licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.
- 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.