AI Provider Integrations
Relevant source files
The following files were used as context for generating this wiki page:
- app/src/main/java/io/github/mojri/hesabyar/api/AiProvider.kt
- app/src/main/java/io/github/mojri/hesabyar/api/AiProviderConfig.kt
- app/src/main/java/io/github/mojri/hesabyar/domain/usecase/ManageAiConfigUseCase.kt
- app/src/main/java/io/github/mojri/hesabyar/ui/AiAssistantViewModel.kt
- rust/hesabyar-core/src/ai_validation.rs
- app/src/main/java/io/github/mojri/hesabyar/di/AiModule.kt
The AI Provider Integration system in Hesabyar enables smart financial assistance through natural language processing (NLP) and intelligent insights. The system is designed as an optional enhancement to the core offline functionality, allowing users to connect to various Large Language Model (LLM) providers such as Google Gemini and OpenRouter. It facilitates features like smart transaction parsing, budget forecasting, and personalized financial advice while maintaining a strict validation layer for security and accuracy.
Architecture and Components
The AI integration follows a multi-layered architecture spanning from the UI layer to a native Rust core for validation. It abstracts specific API implementations behind a unified provider interface, ensuring the business logic remains decoupled from specific AI vendors.
Core Architecture Flow
The following diagram illustrates the data flow from a user prompt to the AI provider and back through the validation layer.
The flow involves UI interaction, ViewModel management, provider-specific API calls, and a final validation step in the Rust core.
Sources: app/src/main/java/io/github/mojri/hesabyar/api/AiProvider.kt:50-80, app/src/main/java/io/github/mojri/hesabyar/ui/AiAssistantViewModel.kt:180-210
Key Classes and Responsibilities
| Class/Module | Responsibility |
|---|---|
AiProvider | Singleton object managing network calls to Gemini, OpenRouter, and Custom endpoints. |
AiConfigManager | Manages persistence and migration of AI configurations using EncryptedSharedPreferences. |
AiAssistantViewModel | Orchestrates state for AI features, including model fetching, parsing, and caching. |
AiProviderConfig | Data class defining provider type, API keys, model IDs, and base URLs. |
AiParsedTransaction | (Rust) Data structure for validated and repaired AI-generated transactions. |
Sources: app/src/main/java/io/github/mojri/hesabyar/api/AiProvider.kt:16, app/src/main/java/io/github/mojri/hesabyar/api/AiProviderConfig.kt:76, rust/hesabyar-core/src/ai_validation.rs:13
Configuration and Security
Configurations are stored securely using EncryptedSharedPreferences. The system supports multiple provider profiles, allowing users to switch between different models or API keys easily.
AI Provider Types
The system categorizes providers into three primary types via the AiProviderType enum:
- GEMINI: Direct integration with Google's Generative Language API.
- OPENROUTER: Uses an OpenAI-compatible format to access a wide range of models (Mistral, Llama, Claude).
- CUSTOM: Allows users to specify their own OpenAI-compatible base URL.
Sources: app/src/main/java/io/github/mojri/hesabyar/api/AiProviderConfig.kt:14-20
Configuration Data Model
data class AiProviderConfig(
val id: String = UUID.randomUUID().toString(),
val providerType: AiProviderType = AiProviderType.GEMINI,
val apiKey: String = "",
val model: String = "",
val baseUrl: String = "",
val label: String = ""
)
Sources: app/src/main/java/io/github/mojri/hesabyar/api/AiProviderConfig.kt:47-54
AI Validation Layer (Rust Core)
A critical component of the system is the ai_validation.rs module in the Rust core. This layer ensures that AI-generated responses (often in JSON format for transaction parsing) conform to the application's strict data requirements.
Transaction Repair Logic
When an AI returns a transaction, the Rust core validates fields and performs "repairs" to maintain data integrity:
- Type Mapping: Unknown transaction types are coerced to
EXPENSE. - Category Normalization: Maps extended categories (e.g., "Personal Care") to the 8 core database categories (e.g., "Shopping").
- Clamping: Ensures values like
hour(0-23),minute(0-59), andconfidence(0.0-1.0) are within valid ranges. - Currency Conversion: Automatically converts AI-extracted Toman amounts to the internal Rial representation (multiplication by 10).
The Rust validation process ensures data safety before the transaction is presented to the user for confirmation.
Sources: rust/hesabyar-core/src/ai_validation.rs:55-150, rust/hesabyar-core/src/ai_validation.rs:155-180
Service Integration Details
API Request Handling
The AiProvider uses OkHttpClient to execute requests. It specifically handles different payload formats for Gemini vs. OpenAI-compatible providers (OpenRouter/Custom).
| Provider | API Endpoint Pattern | Format |
|---|---|---|
| Gemini | /v1beta/models/{model}:generateContent?key={key} | Gemini contents/parts JSON |
| OpenAI-Compatible | {baseUrl}/chat/completions | OpenAI messages/role/content JSON |
Sources: app/src/main/java/io/github/mojri/hesabyar/api/AiProvider.kt:174-250
Model Fetching and Caching
To improve user experience, the system can fetch available models from providers. These results are cached for 24 hours to reduce unnecessary network calls.
- Cache Duration: 24 hours.
- Cache Storage: Managed by
AiConfigManagerin JSON format within encrypted preferences.
Sources: app/src/main/java/io/github/mojri/hesabyar/api/AiProviderConfig.kt:66-74, app/src/main/java/io/github/mojri/hesabyar/domain/usecase/ManageAiConfigUseCase.kt:44-60
Summary
The AI Provider Integration module provides a robust and secure bridge between the Hesabyar financial app and external LLMs. By combining a flexible Kotlin-based provider abstraction with a strict Rust-based validation core, the system delivers intelligent features like transaction parsing and budget advice without compromising data accuracy or security. The use of encrypted storage and automated data "repair" logic ensures that even imperfect AI outputs are safely integrated into the user's financial records.