# -*- coding: utf-8 -*- """AI Loan Officer Assistant.ipynb Automatically generated by Colab. Original file is located at https://colab.research.google.com/drive/1Om043ogOg3FZB4mkhCZY2gcOapGFM-5q """ import os import time import pandas as pd import gradio as gr from google import genai from google.genai import types from google.api_core import exceptions # 1. Initialize Client WITHOUT api_version # This specifically fixes the 'INVALID_ARGUMENT' error you received # Initialize the client with explicit API version 'v1' import os import time import pandas as pd import gradio as gr from google import genai from google.genai import types from google.api_core import exceptions # SECURE FIX: Use os.environ for Hugging Face Spaces # The SDK will automatically use 'GOOGLE_API_KEY' if it exists in environment client = genai.Client(api_key=os.environ.get('GOOGLE_API_KEY')) # Use gemini-1.5-flash for the best free-tier stability STABLE_MODEL = "gemini-flash-latest" # 2. Data Preparation (Structured Systems) df_credit = pd.DataFrame({'ID': [1111, 2222, 3333, 4444, 5555], 'Credit_Score': [455, 685, 825, 840, 350]}) df_account = pd.DataFrame({ 'ID': [1111, 2222, 3333, 4444, 5555], 'Name': ['Loren', 'Matt', 'Hilda', 'Andy', 'Kit'], 'Email': ['loren@gmail.com', 'matt@yahoo.com', 'halida@gmail.com', 'andy@gmail.com', 'kit@yahho.com'], 'Status': ['Good-standing', 'Closed', 'Delinquent', 'Good-standing', 'Delinquent'], 'Nationality': ['Singaporean', 'NonSingaporean', 'Singaporean', 'NonSingaporean', 'Singaporean'] }) df_gov = pd.DataFrame({'ID': [2222, 4444], 'PR_Status': [True, False]}) df_merged = df_account.merge(df_credit, on="ID").merge(df_gov, on="ID", how="left").fillna(False) # 3. Upload Policy Files once on startup risk_policy_file = client.files.upload(file="Bank Loan Overall Risk Policy.pdf") interest_policy_file = client.files.upload(file="Bank Loan Interest Rate Policy.pdf") # 4. Standardized Assessment Logic def process_loan_request(applicant_id, customer_name_optional): try: # Retrieve data from the structured systems row = df_merged[df_merged['ID'] == int(applicant_id)] if row.empty: return "Error: Applicant ID not found." applicant = row.iloc[0] # THE STANDARDIZED PROMPT: Ensuring strict adherence to provided tables prompt = f""" You are a Senior Loan Officer. Assess the application for the individual provided. Stick strictly to the information and tables provided in the attached PDF policies. APPLICANT DATA: Name: {applicant['Name']} ID: {applicant_id} Email: {applicant['Email']} Credit Score: {applicant['Credit_Score']} Account Status: {applicant['Status']} Nationality: {applicant['Nationality']} PR Status: {applicant['PR_Status']} REQUIRED OUTPUT PATTERN: # Loan Assessment Report: {applicant['Name']} (ID: {applicant_id}, Email: {applicant['Email']}) ### **1. Info Retrieval** | Applicant Detail | Value | | :--- | :--- | | Name (ID) | {applicant['Name']} ({applicant_id}) | | Credit Score | {applicant['Credit_Score']} | | Account Status | {applicant['Status']} | | Nationality | {applicant['Nationality']} | | PR Status | {applicant['PR_Status']} | ### **2. PR Status Check** - For Non-Singaporean applicants: State result as "PR Status -> [True/False]". - For Singaporean applicants: State "Check not required for Singaporean". ### **3. Overall Risk Assessment** - Reference 'Bank Loan Overall Risk Policy.pdf'. - Calculation: Credit Score [{applicant['Credit_Score']}] + Account Status [{applicant['Status']}] -> Overall Risk: [Value from Table] ### **4. Interest Rate Determination** - Reference 'Bank Loan Interest Rate Policy.pdf'. - Calculation: Overall Risk [Value from Table] -> [Rate from Table] - Apply conservative rule if risk falls between categories. ### **5. Final Report & Recommendation** - Recommend the loan interest rate OR Not recommend. - Rationale: Based on risk profile and compliance (PR false for Non-Singaporean leads to 'Not recommend'). """ # Generate content using the multimodal input response = client.models.generate_content( model=STABLE_MODEL, contents=[risk_policy_file, interest_policy_file, prompt] ) return response.text except exceptions.ResourceExhausted: return "Error: Quota reached. Please wait 60 seconds." except Exception as e: return f"System Error: {str(e)}" # 5. Launch Gradio Interface demo = gr.Interface( fn=process_loan_request, inputs=[gr.Textbox(label="Applicant ID"), gr.Textbox(label="Name (Optional)")], outputs=gr.Markdown(), title="🏦 Enterprise AI Loan Risk Assessment Tool" ) if __name__ == "__main__": demo.launch()