diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..d2027d99d48bd37cb1b0588bbb47e105006f807f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +src/db/finova.db filter=lfs diff=lfs merge=lfs -text diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/__pycache__/__init__.cpython-313.pyc b/src/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb64aa1c701c860fcec3a550ba333c1e72c828c4 Binary files /dev/null and b/src/__pycache__/__init__.cpython-313.pyc differ diff --git a/src/__pycache__/logging.cpython-313.pyc b/src/__pycache__/logging.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20e268aea190a5cf7c4721d319902c1d2025b27c Binary files /dev/null and b/src/__pycache__/logging.cpython-313.pyc differ diff --git a/src/__pycache__/main.cpython-313.pyc b/src/__pycache__/main.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87b444d6087367718b71dbcdafa554af7d22c994 Binary files /dev/null and b/src/__pycache__/main.cpython-313.pyc differ diff --git a/src/__pycache__/utils.cpython-313.pyc b/src/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9ac0f49db25a98f3bcfbf4fa6e90c7f24dd74cf Binary files /dev/null and b/src/__pycache__/utils.cpython-313.pyc differ diff --git a/src/agents/__init__.py b/src/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63bd45e6d2440a43a4e0cb2fdeffc292129ea1a2 --- /dev/null +++ b/src/agents/__init__.py @@ -0,0 +1 @@ +from . import agent \ No newline at end of file diff --git a/src/agents/__pycache__/__init__.cpython-313.pyc b/src/agents/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7409fc4ab3e8f28c2263331530b6379334a26f4f Binary files /dev/null and b/src/agents/__pycache__/__init__.cpython-313.pyc differ diff --git a/src/agents/__pycache__/agent.cpython-313.pyc b/src/agents/__pycache__/agent.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81e08e0be0601da74b76639dd30fc9c238ba9baa Binary files /dev/null and b/src/agents/__pycache__/agent.cpython-313.pyc differ diff --git a/src/agents/agent.py b/src/agents/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..3e84675c66c1e700a48ecac09162a6f3e7dfbb29 --- /dev/null +++ b/src/agents/agent.py @@ -0,0 +1,23 @@ +from google.adk.agents import Agent +from google.adk.tools.agent_tool import AgentTool + +from src.prompts import FINOVA +from src.tools import add_financial_goals, update_balance, check_balance, update_user_profile + +from .sub_agents.financial_advisor import financial_advisor +from .sub_agents.read_agent import read_agent +from .sub_agents.write_agent import write_agent + +finova = Agent( + name="finova", + model=FINOVA.config.model, + description="Main Personal financial assistant agent", + instruction=FINOVA.prompt, + sub_agents=[write_agent, read_agent], + tools=[ + AgentTool(financial_advisor), + add_financial_goals, + check_balance, + update_user_profile + ], +) \ No newline at end of file diff --git a/src/agents/sub_agents/financial_advisor/__init__.py b/src/agents/sub_agents/financial_advisor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c4adec9c96e71b9a4aae0c1d6539b062f187844b --- /dev/null +++ b/src/agents/sub_agents/financial_advisor/__init__.py @@ -0,0 +1 @@ +from .agent import financial_advisor \ No newline at end of file diff --git a/src/agents/sub_agents/financial_advisor/__pycache__/__init__.cpython-313.pyc b/src/agents/sub_agents/financial_advisor/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c99f7bbca45f2fd70353fb772eee1fb4f98c698 Binary files /dev/null and b/src/agents/sub_agents/financial_advisor/__pycache__/__init__.cpython-313.pyc differ diff --git a/src/agents/sub_agents/financial_advisor/__pycache__/agent.cpython-313.pyc b/src/agents/sub_agents/financial_advisor/__pycache__/agent.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..488e30d1861c9e83a7117b762cd2f3471ac89e99 Binary files /dev/null and b/src/agents/sub_agents/financial_advisor/__pycache__/agent.cpython-313.pyc differ diff --git a/src/agents/sub_agents/financial_advisor/agent.py b/src/agents/sub_agents/financial_advisor/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..80e4581f6179b6c97d584d26cb5be768457aa9c4 --- /dev/null +++ b/src/agents/sub_agents/financial_advisor/agent.py @@ -0,0 +1,10 @@ +from google.adk.agents import Agent, SequentialAgent, ParallelAgent + +from src.prompts import ADVISOR + +financial_advisor = Agent( + name="financial_advisor", + model=ADVISOR.config.model, + description="Specialized Agent for answering financial related topic", + instruction=ADVISOR.prompt, +) \ No newline at end of file diff --git a/src/agents/sub_agents/preference_agent/__init__.py b/src/agents/sub_agents/preference_agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/agents/sub_agents/preference_agent/agent.py b/src/agents/sub_agents/preference_agent/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..c45c0438d72b61ba5bdb6c81bcc00d74be437a0a --- /dev/null +++ b/src/agents/sub_agents/preference_agent/agent.py @@ -0,0 +1,8 @@ +from google.adk.agents import Agent + + +preference_agent = Agent( + name="preference_agent", + model="gemini-2.5-flash", + description="Agent that help notes user preference" +) \ No newline at end of file diff --git a/src/agents/sub_agents/read_agent/__init__.py b/src/agents/sub_agents/read_agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9d4bbf03374a08fa341c6a817d1fb4c6600e1222 --- /dev/null +++ b/src/agents/sub_agents/read_agent/__init__.py @@ -0,0 +1 @@ +from .agent import read_agent \ No newline at end of file diff --git a/src/agents/sub_agents/read_agent/__pycache__/__init__.cpython-313.pyc b/src/agents/sub_agents/read_agent/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f26ce552fe00cd1944cd1a3389fab4a138526e72 Binary files /dev/null and b/src/agents/sub_agents/read_agent/__pycache__/__init__.cpython-313.pyc differ diff --git a/src/agents/sub_agents/read_agent/__pycache__/agent.cpython-313.pyc b/src/agents/sub_agents/read_agent/__pycache__/agent.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3a4798722932eeb725c1719e8020676eefbd6d4 Binary files /dev/null and b/src/agents/sub_agents/read_agent/__pycache__/agent.cpython-313.pyc differ diff --git a/src/agents/sub_agents/read_agent/agent.py b/src/agents/sub_agents/read_agent/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..d921deab23d979cce860005dcdc7360b2913d984 --- /dev/null +++ b/src/agents/sub_agents/read_agent/agent.py @@ -0,0 +1,30 @@ +from google.adk.agents import Agent +from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset +from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams +from mcp import StdioServerParameters + +from src.tools import get_current_time +from src.prompts import READ_AGENT +from src.db import DB_PATH + + +read_agent = Agent( + name="read_agent", + model=READ_AGENT.config.model, + description="Agent that specialized in reading transaction", + instruction=READ_AGENT.prompt, + tools=[ + MCPToolset( + connection_params=StdioConnectionParams( + server_params=StdioServerParameters( + command="npx", + args= [ + "-y", + "@executeautomation/database-server", + f"{DB_PATH}" + ] + ) + ) + ) + ] +) diff --git a/src/agents/sub_agents/write_agent/__init__.py b/src/agents/sub_agents/write_agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac233430916ef19c7289659d93c4e1d0c389116f --- /dev/null +++ b/src/agents/sub_agents/write_agent/__init__.py @@ -0,0 +1 @@ +from .agent import write_agent \ No newline at end of file diff --git a/src/agents/sub_agents/write_agent/__pycache__/__init__.cpython-313.pyc b/src/agents/sub_agents/write_agent/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa2c07c9967dd0027ddb082ff44c2a74918c1157 Binary files /dev/null and b/src/agents/sub_agents/write_agent/__pycache__/__init__.cpython-313.pyc differ diff --git a/src/agents/sub_agents/write_agent/__pycache__/agent.cpython-313.pyc b/src/agents/sub_agents/write_agent/__pycache__/agent.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c05bdfa45851ae4788543f8e60df7b46de67635c Binary files /dev/null and b/src/agents/sub_agents/write_agent/__pycache__/agent.cpython-313.pyc differ diff --git a/src/agents/sub_agents/write_agent/agent.py b/src/agents/sub_agents/write_agent/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..77c4972faa31d5530b210fc7f3ffbacabf151823 --- /dev/null +++ b/src/agents/sub_agents/write_agent/agent.py @@ -0,0 +1,13 @@ +from google.adk.agents import Agent + +from src.prompts import WRITE_AGENT +from src.tools import get_current_time, insert_transaction_tool +from src.tools.user_tool import update_balance + +write_agent = Agent( + name="write_agent", + model=WRITE_AGENT.config.model, + description="An agent that specialized in writing transaction", + instruction=WRITE_AGENT.prompt, + tools=[get_current_time, insert_transaction_tool, update_balance] +) \ No newline at end of file diff --git a/src/db/__init__.py b/src/db/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b6592fd21c88bf97404f376fad890b6d2552ca3c --- /dev/null +++ b/src/db/__init__.py @@ -0,0 +1 @@ +from .database import DB_PATH, DB_URL, engine, Session, Transaction, initialize_db \ No newline at end of file diff --git a/src/db/__pycache__/__init__.cpython-313.pyc b/src/db/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..450b86cd1f6aaacba72099e07805dcbb5744011f Binary files /dev/null and b/src/db/__pycache__/__init__.cpython-313.pyc differ diff --git a/src/db/__pycache__/database.cpython-313.pyc b/src/db/__pycache__/database.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45f56afcc76c696f45d9b01e6cab0162bc8a0bc0 Binary files /dev/null and b/src/db/__pycache__/database.cpython-313.pyc differ diff --git a/src/db/__pycache__/sql_db.cpython-313.pyc b/src/db/__pycache__/sql_db.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1de9c167de661239f9882cce65cd9309f604172d Binary files /dev/null and b/src/db/__pycache__/sql_db.cpython-313.pyc differ diff --git a/src/db/database.py b/src/db/database.py new file mode 100644 index 0000000000000000000000000000000000000000..501290b483660ee16cc86b34283adc2a11023ce9 --- /dev/null +++ b/src/db/database.py @@ -0,0 +1,34 @@ +import os +import logging +from datetime import datetime +from sqlalchemy.engine import Engine, create_engine +from typing_extensions import Optional +from sqlalchemy.orm import declarative_base, Mapped, mapped_column, sessionmaker +from sqlalchemy.types import DECIMAL, TIMESTAMP, String + +logger = logging.getLogger(__name__) + +script_dir = os.path.dirname(os.path.abspath(__file__)) +DB_PATH = f"{script_dir}/finova.db" +DB_URL = f"sqlite:///{DB_PATH}" + +logger.info(f"Database URL configured: {DB_URL}") +engine = create_engine(DB_URL, connect_args={"check_same_thread": False}) +Session = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +Base = declarative_base() + +class Transaction(Base): + __tablename__ = "transactions" + id: Mapped[int] = mapped_column(primary_key=True, index=True) + timestamp: Mapped[datetime] = mapped_column(TIMESTAMP(), nullable=False) + amount: Mapped[DECIMAL] = mapped_column(DECIMAL(10, 2), nullable=False) + type: Mapped[str] = mapped_column(String(8), nullable=False) + description: Mapped[str] = mapped_column(String(500), nullable=False) + category: Mapped[str] = mapped_column(String(50), nullable=False) + subcategory: Mapped[Optional[str]] = mapped_column(String(50), nullable=True) + notes: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + +def initialize_db(engine: Engine) -> None: + """Crete all the database tables""" + Base.metadata.create_all(engine) diff --git a/src/db/finova.db b/src/db/finova.db new file mode 100644 index 0000000000000000000000000000000000000000..7a82d801af5cdbb50e43c84d34ff5f1c2c953575 --- /dev/null +++ b/src/db/finova.db @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84eed56133bfbceb53c5af268b908244b7ab7f40c8dde23b6ba28dbdaf7139cc +size 110592 diff --git a/src/db/vector.py b/src/db/vector.py new file mode 100644 index 0000000000000000000000000000000000000000..e358cd98214dc267910cee3754969fc0b373fcf1 --- /dev/null +++ b/src/db/vector.py @@ -0,0 +1,3 @@ +from qdrant_client import models, QdrantClient + +client = QdrantClient(":memory:") diff --git a/src/logging.py b/src/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..1d043fafc060596892a264a544745b4b8149dd4e --- /dev/null +++ b/src/logging.py @@ -0,0 +1,30 @@ +import os +import sys +import logging + +def setup_logging(): + """Configures the root logger for the application""" + + log_format = "%(asctime)s [%(levelname)s] %(message)s" + + log_dir = os.path.join(os.path.dirname(__file__), '..', 'logs') + os.makedirs(log_dir, exist_ok=True) + log_file_path = os.path.join(log_dir, 'app.log') + + logger = logging.getLogger() + logger.setLevel(logging.INFO) + + if logger.hasHandlers(): + logger.handlers.clear() + + # Handler for the console + stdout_handler = logging.StreamHandler(sys.stdout) + stdout_handler.setFormatter(logging.Formatter(log_format)) + logger.addHandler(stdout_handler) + + # Handler for the 'logs/app.log' file + file_handler = logging.FileHandler(log_file_path) + file_handler.setFormatter(logging.Formatter(log_format)) + logger.addHandler(file_handler) + + logging.info("Logging configured successfully.") \ No newline at end of file diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000000000000000000000000000000000000..58fcba2c3a39b2c32e77bff6f82562a94e7392f6 --- /dev/null +++ b/src/main.py @@ -0,0 +1,263 @@ +import gradio as gr +import asyncio +import os +import logging +from dotenv import load_dotenv +from google.adk.sessions import DatabaseSessionService +from google.adk.runners import Runner +from google.genai import types +from huggingface_hub import HfApi, HfApiHTTPError + +# Asumsi struktur proyek Anda dipertahankan +from src.logging import setup_logging +from src.db import DB_PATH, DB_URL, engine, initialize_db +from src.agents.agent import finova # Impor agen utama +from src.utils import display_state, process_agent_response + +# --- Inisialisasi --- +load_dotenv() +setup_logging() +logger = logging.getLogger(__name__) + +# Setup Langfuse (Opsional) +def setup_tracing(): + """Setup tracing for observability""" + if os.getenv("LANGFUSE_PUBLIC_KEY") and os.getenv("LANGFUSE_SECRET_KEY"): + try: + from langfuse import get_client + langfuse = get_client() + if langfuse.auth_check(): + logger.info("Langfuse client authenticated. Observability ENABLED.") + from openinference.instrumentation.google_adk import GoogleADKInstrumentor + GoogleADKInstrumentor().instrument() + else: + logger.warning("Langfuse client authentication failed") + except ImportError: + logger.warning("Langfuse not installed. pip install langfuse openinference-instrumentation-google-adk") + except Exception as e: + logger.error(f"Error setting up Langfuse: {e}") + else: + logger.warning("Langfuse observability is DISABLED. Set LANGFUSE keys to enable.") + +# Setup Database +def setup_database(): + """Periksa database dan inisialisasi jika tidak ditemukan""" + if not os.path.exists(DB_PATH): + logger.warning("Database not found. Initializing...") + try: + initialize_db(engine) + logger.info(f"Database created successfully at: {DB_PATH}") + except Exception as e: + logger.critical(f"Error initializing database: {e}") + raise + else: + logger.info("Database already exists. Skipping initialization.") + +logger.info("==================== GRADIO APP START ====================") +setup_tracing() # Opsional +setup_database() + +# Setup Session Service dan Runner +session_service = DatabaseSessionService(db_url=DB_URL) +APP_NAME = "FinovaGradio" # Nama aplikasi yang konsisten + +# State Awal +initial_state = { + "user:name": "User", + "user:balance": 0, + "user:language": "eng", + "user:currency": "USD", + "user:financial_goals": [] +} + +runner = Runner( + app_name=APP_NAME, + agent=finova, + session_service=session_service, +) + +# --- Logika Antarmuka Gradio --- + +async def get_user_id( + hf_token: gr.OAuthToken | None, + request: gr.Request +) -> str: + """ + Mendapatkan user_id yang unik. + Prioritas: Login HF > Session Hash Anonim. + """ + user_id = None + if hf_token: + try: + # Gunakan token untuk mendapatkan info pengguna + user_info = await asyncio.to_thread( + HfApi().whoami, token=hf_token.token + ) + user_id = user_info['name'] # 'name' adalah username HF + logger.info(f"Using Hugging Face user ID: {user_id}") + except HfApiHTTPError as e: + logger.warning(f"Failed to get HF user info with token: {e}. Using session hash.") + user_id = request.session_hash # Fallback + except Exception as e: + logger.error(f"Error during HF whoami check: {e}. Using session hash.") + user_id = request.session_hash # Fallback + else: + # Pengguna tidak login + logger.info("No HF token. Using Gradio session hash for anonymous user.") + user_id = request.session_hash + + return user_id + +async def get_or_create_adk_session( + user_id: str, + adk_session_state: str | None +) -> str: + """ + Mendapatkan atau membuat sesi ADK untuk user_id yang diberikan. + """ + adk_session_id = adk_session_state + + if adk_session_id is None: + logger.info(f"No existing ADK session state. Checking DB for user: {user_id}") + + # Periksa apakah sesi SUDAH ADA untuk user_id ini di DB + # (Berguna untuk pengguna HF yang login me-refresh browser) + existing_sessions = [] + try: + session_list = await session_service.list_sessions( + app_name=APP_NAME, user_id=user_id + ) + existing_sessions = session_list.sessions + except Exception as e: + logger.warning(f"Could not list existing sessions for user {user_id}: {e}") + + if existing_sessions: + # Gunakan kembali sesi terbaru + adk_session_id = existing_sessions[-1].id + logger.info(f"Reusing existing ADK session {adk_session_id} from DB for user {user_id}") + else: + # Buat sesi yang benar-benar baru + logger.info(f"Creating new ADK session for user: {user_id}") + new_session = await session_service.create_session( + app_name=APP_NAME, + user_id=user_id, + state=initial_state, + ) + adk_session_id = new_session.id + logger.info(f"Created new ADK session: {adk_session_id} for user: {user_id}") + else: + logger.info(f"Using existing ADK session from state: {adk_session_id} for user: {user_id}") + + return adk_session_id + +async def chat_interface( + message: str, + history: list, + adk_session_state: str | None, # Dari additional_inputs + request: gr.Request, # Input implisit + hf_token: gr.OAuthToken | None # Input implisit dari login +): + """ + Menangani interaksi chat dengan agen Finova melalui Gradio. + Mengelola sesi pengguna berdasarkan login HF atau session hash. + + Args: + message: Pesan input dari pengguna. + history: Riwayat percakapan. + adk_session_state: State dari Gradio, menyimpan ADK session_id. + request: Objek Gradio Request untuk session hash (fallback). + hf_token: Objek Gradio OAuthToken (jika pengguna login). + + Returns: + Tuple: (respons_teks_final, adk_session_state_baru) + """ + + try: + # 1. Dapatkan User ID (dari HF Login atau Session Hash) + user_id = await get_user_id(hf_token, request) + + # 2. Dapatkan atau Buat Sesi ADK + adk_session_id = await get_or_create_adk_session(user_id, adk_session_state) + + # 3. Jalankan agent + logger.info(f"User query: {message}") + content = types.Content(role="user", parts=[types.Part(text=message)]) + final_response_text = "Sorry, I couldn't process that." + + async for event in runner.run_async( + user_id=user_id, session_id=adk_session_id, new_message=content + ): + response = await process_agent_response(event) + if response: + final_response_text = response + logger.info(f"Agent response: {final_response_text}") + + # 4. Kembalikan respons dan state yang diperbarui + return final_response_text, adk_session_id + + except Exception as e: + logger.error(f"Error during chat interaction for user {user_id}: {e}", exc_info=True) + # Jika terjadi error, laporkan error dan reset state ke None. + return f"An error occurred: {e}", None + +# --- Luncurkan Gradio --- +if __name__ == "__main__": + + with gr.Blocks( + theme=gr.themes.Default(primary_hue="blue", secondary_hue="neutral") + ) as demo: + + # State untuk menyimpan ID Sesi ADK di seluruh giliran + adk_session_state = gr.State(None) + + with gr.Sidebar(): + gr.Markdown("## Login") + gr.Markdown( + "Login dengan akun Hugging Face Anda untuk menyimpan riwayat percakapan Anda." + ) + gr.LoginButton() # Tombol Login OAuth + gr.Markdown("---") + gr.Markdown("### Tentang Finova") + gr.Markdown( + "Finova adalah asisten keuangan pribadi Anda, " + "diberdayakan oleh Google ADK dan model Gemini." + ) + + with gr.Column(): + chatbot = gr.ChatInterface( + fn=chat_interface, + # 'fn' akan menerima argumen implisit 'request' dan 'hf_token' + # 'adk_session_state' harus didefinisikan secara eksplisit + additional_inputs=[adk_session_state], + additional_outputs=[adk_session_state], + title="Finova Chatbot", + description="Your Agentic Financial Assistant. Interact using natural language.", + examples=[ + "Hello", + "I bought groceries for 50 dollars", + "I received my salary of 2000", + "What's my current balance?", + "Add a goal: Save for a vacation", + "What is a good way to start investing?" + ], + retry_btn=None, + undo_btn="Delete Previous", + clear_btn="Clear Chat", + ) + + # Saat "Clear Chat" diklik, kita juga harus me-reset state sesi ADK + def clear_session_state(): + logger.info("Chat cleared by user. Resetting ADK session state.") + return None # Kembalikan None untuk me-reset state + + chatbot.clear_btn.click( + fn=clear_session_state, + inputs=[], + outputs=[adk_session_state], + queue=False # Jalankan ini dengan cepat tanpa antrian + ) + + # Metode launch Gradio menangani event loop + demo.launch() + + logger.info("==================== GRADIO APP END ====================") \ No newline at end of file diff --git a/src/prompts/__init__.py b/src/prompts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85986559b7c4b1c7ad420f442a6b5b63169552b3 --- /dev/null +++ b/src/prompts/__init__.py @@ -0,0 +1,5 @@ +from .base import Prompt, PromptConfig +from .write_agent import WRITE_AGENT +from .finova import FINOVA +from .advisor import ADVISOR +from .read_agent import READ_AGENT \ No newline at end of file diff --git a/src/prompts/__pycache__/__init__.cpython-313.pyc b/src/prompts/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cf8af6fbf13909979efe580a8202b7d7c9b6da0 Binary files /dev/null and b/src/prompts/__pycache__/__init__.cpython-313.pyc differ diff --git a/src/prompts/__pycache__/advisor.cpython-313.pyc b/src/prompts/__pycache__/advisor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee0daf7d63cd2ab97ec1ac4a1af9c494cf5bec64 Binary files /dev/null and b/src/prompts/__pycache__/advisor.cpython-313.pyc differ diff --git a/src/prompts/__pycache__/base.cpython-313.pyc b/src/prompts/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b2f57c818e9c22e868ac70e691f7b3bf8fbc0d0 Binary files /dev/null and b/src/prompts/__pycache__/base.cpython-313.pyc differ diff --git a/src/prompts/__pycache__/finova.cpython-313.pyc b/src/prompts/__pycache__/finova.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fde0dad4bf94b28fb3af803eaa466bd6e2b5a35 Binary files /dev/null and b/src/prompts/__pycache__/finova.cpython-313.pyc differ diff --git a/src/prompts/__pycache__/read_agent.cpython-313.pyc b/src/prompts/__pycache__/read_agent.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..404cae93990751c54e5d5fc4c2e69bc60344865f Binary files /dev/null and b/src/prompts/__pycache__/read_agent.cpython-313.pyc differ diff --git a/src/prompts/__pycache__/write_agent.cpython-313.pyc b/src/prompts/__pycache__/write_agent.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cb2b4b0cbbc1e9cf1b97a5b7f4f186052495958 Binary files /dev/null and b/src/prompts/__pycache__/write_agent.cpython-313.pyc differ diff --git a/src/prompts/advisor.py b/src/prompts/advisor.py new file mode 100644 index 0000000000000000000000000000000000000000..4b7ef9c954e96a32253ea4d64dacdb1b88e33d25 --- /dev/null +++ b/src/prompts/advisor.py @@ -0,0 +1,26 @@ +from src.prompts import Prompt, PromptConfig + +ADVISOR_INSTRUCTION = """ +You are a Financial Advisor that takes an user question about finance. + +Before providing some advise, always write this disclaimer: + +"Important Disclaimer: For Educational and Informational Purposes Only. +The information outlines provided by this tool, including any analysis, +commentary, or potential scenarios, are generated by an AI model and are for educational and informational purposes only. +They do not constitute, and should not be interpreted as, financial advice, investment recommendations, endorsements, +or offers to buy or sell any financial instruments." + + +""" + + +ADVISOR = Prompt( + name="advisor-instruction", + prompt=ADVISOR_INSTRUCTION, + type="text", + config=PromptConfig( + model="gemini-2.5-flash", + orchestrator="Google ADK" + ) +) \ No newline at end of file diff --git a/src/prompts/base.py b/src/prompts/base.py new file mode 100644 index 0000000000000000000000000000000000000000..3aa70effbd3c62d3bba9b789ddc0959604d080a4 --- /dev/null +++ b/src/prompts/base.py @@ -0,0 +1,14 @@ +from typing_extensions import Optional +from pydantic import BaseModel, Field + +class PromptConfig(BaseModel): + model: str = Field(default="gemini-2.5-flash") + temperature: Optional[float] = Field(default=0.5) + orchestrator: Optional[str] = Field(default=None) + +class Prompt(BaseModel): + name: str = Field(description="Prompt name or title") + prompt: str = Field(description="Prompt string", default="You are a helpful assistant") + type: str = Field(description="Prompt Type (text or chat)", default="text") + config: PromptConfig + diff --git a/src/prompts/finova.py b/src/prompts/finova.py new file mode 100644 index 0000000000000000000000000000000000000000..129f88392c4338584490955408bcb1cdf0294aab --- /dev/null +++ b/src/prompts/finova.py @@ -0,0 +1,91 @@ +from src.prompts import Prompt, PromptConfig + +FINOVA_INSTRUCTION = """ +You are the primary financial assistant agent for a user, your name is Finova. +Your role is to help user answer some question that related to the financial terms and direct writing or reading transaction to the appropriate specialized agent. + +Uses a warm, conversational tone to be helpful and approachable. Don't be too formal, just be relax. You can use slang but don't use too much. +DON'T USE MARKDOWN FORMAT TO WRITE YOUR RESPONSE + +**Core Capabilities:** + +1. Query Understanding & Routing + - Understand user queries either asking to write and read transaction or asking financial advice. + - Direct users to the appropriate specialized agent + - Maintain conversation context using state + - Reject anything unrelated to the finance subject + +2. State Management + - Track user interactions in state['interaction_history'] + - Monitor user's financial goals in state['user:financial_goals'] + - Track user balance in state['user:balance'] + - Use state to provide personalized response + +**User Information:** + +Name: {user:name} +Balance: {user:balance} +Goals: {user:financial_goals} + + +**User Preference** + +Language: {user:language} +Currency: {user:currency} + + + +**IMPORTANT** + +New User Introduction Guidance: + +If the displayed name is "User" (default user name), you must ask user to fill their profile first + +First, ask their name +Second, ask their Language +Third, ask their currency preference + +Finally, introduce your name and your capability. + +**Capability** + +You have access to the following specialized agents: + +1. Write Agent + - When user want to write some transaction, either income or expense. Direct to this agent + +2. Read Agent + - When user want to check a specific transaction, either income or expense. Direct to this agent + +You are also have access to the following tools: + +1. Financial advisor + - Use when user wan't to ask guidance or advise about finance + - Don't use when user want to write or read a specific transaction. + +2. Update User Profile + - Use to update user's name, language, and currency. + +3. Check Balance + - Use when user want to check their balance + +4. Add financial goals + - Use for adding new user goals. + - Summarize the user goals with short and clear statement + - IT CAN NOT BE USED TO ADD TWO GOALS AT THE SAME TIME. + - THIS TOOLS CAN BE USED JUST ONCE. IF USER WANT TO ADD TWO GOALS YOU NEED TO USE IT TWICE. + +**REMEMBER** +- If user tell you about their current financial status, WRITE as INCOME with Description "User Deposit". + - For example, if user tell you amount of his money, and you found that it differ from their balance in state['user:balance'] write that transaction. +""" + +FINOVA = Prompt( + name= "finova-instruction", + prompt= FINOVA_INSTRUCTION, + type= "text", + config= PromptConfig( + model= "gemini-2.5-flash", + orchestrator= "Google ADK" + ), +) \ No newline at end of file diff --git a/src/prompts/read_agent.py b/src/prompts/read_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..7725bd57e9fddad04d2f1eec44d0f1aaf657021f --- /dev/null +++ b/src/prompts/read_agent.py @@ -0,0 +1,25 @@ +from src.prompts import Prompt, PromptConfig + + +READ_AGENT_INSTRUCTION = """ +You are a financial agent that specialized in reading user transaction. +You will take an instruction either from user or another agent and use appropriate tools to provide relevant answer. + +If the request isn't clear, you can ask back to gather more or specific information. +Wrap your response into short, clear, and well formatted summary. + +**REMEMBER** +You are NOT PROHIBITED to use tool to write to database. You are ONLY PROHIBITED to READ data. +Hand back to the main agent (finova) after finish providing information. + +""" + +READ_AGENT = Prompt( + name="read-agent-instruction", + prompt=READ_AGENT_INSTRUCTION, + type="text", + config=PromptConfig( + model="gemini-2.5-flash", + orchestrator="Google ADK" + ) +) \ No newline at end of file diff --git a/src/prompts/write_agent.py b/src/prompts/write_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..4e00163ae1286eb1183f7b6adf915f4a45bd5b59 --- /dev/null +++ b/src/prompts/write_agent.py @@ -0,0 +1,102 @@ +from enum import Enum +from src.prompts import Prompt, PromptConfig + + +class IncomeCategory(Enum): + SALARY = "Salary" + BONUS = "Bonus" + GIFTS = "Gifts" + INVESTMENTS = "Investments" + + @classmethod + def get_all_categories(cls): + return [category.value for category in cls] + +class ExpenseCategory(Enum): + FOOD_DRINK = "Food & Drink" + TRANSPORTATION = "Transportation" + SHOPPING = "Shopping" + BILLS_UTILITIES = "Bills & Utilities" + ENTERTAINMENT = "Entertainment" + HEALTH = "Health" + OTHER = "Other" + + @classmethod + def get_all_categories(cls): + return [category.value for category in cls] + + +WRITE_AGENT_INSTRUCTION = """ +You are a part of Financial Assistant Agent that specialized in writing transaction. +You are taking a query and write a transaction based on the provided information from the query + +**User Preference** + +Language: {user:language} +Currency: {user:currency} + + +Always act cheerful and responsive +- For example: + Query: I just bought some meals + Response: Woww, it sound delicious. Let me help you write that transaction + +Look for the user preference, you must always speak user preference language + +**Required Data** + - timestamp (str): When the transaction happen? (Write in YYYY-MM-DD hh:mm:ss format) + - amount (int): How much money related to the transaction? + - type (str): What is the transaction type (Income or Expense) + - description (str): The description of the transaction or context of the transaction (use Title style) + - category (str): Transaction category (you should be smart enough to choose one of the category below based on the information provided) + - Income Category: {IncomeCategory.get_all_categories()} + - Expense Category: {ExpenseCategory.get_all_categories()} + - subcategory (str): A Sub-Category if it necessary, you should provide this yourself + - For example Food & Drink Category could be break into Food Sub Category or Drink Sub Category alone. + - Just fill with 'None' if you unsure, never ask the user it will annoy them. + - notes (str): Optional notes, specified by the user + +Before writing the transaction, make sure all the necessary information is provided, then use write_formatter tool to format the data. +You should check current datetime for accurate timestamp. + +After you got all the necessary information, re-confirm and then ask if they're want an optional notes. +If they don't specify an optional notes, you can leave it with 'None'. +- For example: + ``` + Timestamp: [timestamp] + Amount: [amount] + type: [type] + description: [description] + category: [category] + subcategory: [subcategory] + + Do you want to add an additional notes? + ``` + +After success writing the transaction, you should update user balance with 'update_balance' tool. + +You have access to these tools: + +- get_current_time +Use this to check current time + +- insert_transaction +Use this to insert the transaction + +- update_balance +Use this to update user balance after success insert transaction to the database + +After success inserting the transaction and updating the balance, you must handover back to the Main Agent (finova). + +REMEMBER TO ALWAYS ACT CHEERFUL +""" + +WRITE_AGENT = Prompt( + name= "write-agent-instruction", + type= "text", + prompt= WRITE_AGENT_INSTRUCTION, + config= PromptConfig( + model= "gemini-2.5-flash", + orchestrator= "Google ADK" + ), +) \ No newline at end of file diff --git a/src/tools/__init__.py b/src/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e58b73ed31e3de6fe07a91285bfe657d41915815 --- /dev/null +++ b/src/tools/__init__.py @@ -0,0 +1,3 @@ +from .user_tool import * +from .insert_transaction import insert_transaction_tool +from .time_tool import get_current_time \ No newline at end of file diff --git a/src/tools/__pycache__/__init__.cpython-313.pyc b/src/tools/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a61d1440959fbcfc0352058f1564e4baa882f29a Binary files /dev/null and b/src/tools/__pycache__/__init__.cpython-313.pyc differ diff --git a/src/tools/__pycache__/insert_transaction.cpython-313.pyc b/src/tools/__pycache__/insert_transaction.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25d53e735db5494771fc801402150f0b8b9f7d2d Binary files /dev/null and b/src/tools/__pycache__/insert_transaction.cpython-313.pyc differ diff --git a/src/tools/__pycache__/preference_tool.cpython-313.pyc b/src/tools/__pycache__/preference_tool.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f2c11d3992a4d1afe3988abec3d9a2023974a48 Binary files /dev/null and b/src/tools/__pycache__/preference_tool.cpython-313.pyc differ diff --git a/src/tools/__pycache__/time_tool.cpython-313.pyc b/src/tools/__pycache__/time_tool.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dff7be60ad959bef056ccbcaf5299a701bda8f0e Binary files /dev/null and b/src/tools/__pycache__/time_tool.cpython-313.pyc differ diff --git a/src/tools/__pycache__/user_tool.cpython-313.pyc b/src/tools/__pycache__/user_tool.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f415b4f8e55b57ae810aed72886bd9ddc69ae66c Binary files /dev/null and b/src/tools/__pycache__/user_tool.cpython-313.pyc differ diff --git a/src/tools/insert_transaction.py b/src/tools/insert_transaction.py new file mode 100644 index 0000000000000000000000000000000000000000..ce885878cb05e2bc59be0bacebf72d24c24f185a --- /dev/null +++ b/src/tools/insert_transaction.py @@ -0,0 +1,68 @@ +from datetime import datetime +from decimal import Decimal +from typing_extensions import Optional + +from sqlalchemy.orm import Session + +from src.db import Session, Transaction + +def insert_transaction_tool( + timestamp: str, + amount: int, + type: str, + description: str, + category: str, + subcategory: Optional[str], + notes: Optional[str], +) -> dict: + """Insert a transaction into the database + + Args: + timestamp (str): Transaction date + amount (str): Amount of the transaction + type (str): Transaction type (income or expense) + description (str): The transaction description + category (str): Transaction category + subcategory (str): Optional sub-category based on the transaction category + notes (str): Optional notes specified by the user + + Returns: + dict: A dictionary containing the transaction record. + Includes a 'status' key ('success' or 'error'). + If 'success', includes a 'summary' key with weather details. + If 'error', includes an 'error_message' key. + """ + + timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") + amount = Decimal(amount) + session = Session() + + new_transaction = Transaction( + timestamp=timestamp, + amount=amount, + type=type.lower(), + description=description, + category=category.lower(), + subcategory=subcategory.lower(), + notes=notes, + ) + session.add(new_transaction) + session.commit() + session.close() + + return { + "status": "success", + "summary": ( + "Transaction recorded successfully..\n" + f"Type: {type}\n" + f"Amount: {amount}\n" + f"Timestamp: {timestamp}\n" + f"Description: {description}\n" + f"Category: {category}\n" + f"Sub Category: {subcategory}\n" + f"Notes: {notes}" + ) + } + +def read_transaction_tool(): + pass \ No newline at end of file diff --git a/src/tools/time_tool.py b/src/tools/time_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..0fd2961c7080e9469666e136838e9491763fa119 --- /dev/null +++ b/src/tools/time_tool.py @@ -0,0 +1,9 @@ +from datetime import datetime + +def get_current_time() -> dict: + """Get current time + + Returns: + dict: A dictionary containing current timestamp. + """ + return({"Current Time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}) \ No newline at end of file diff --git a/src/tools/user_tool.py b/src/tools/user_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..aac3f4d3d2ecd63b37a196faeaeee82dff422d05 --- /dev/null +++ b/src/tools/user_tool.py @@ -0,0 +1,104 @@ +from google.adk.tools.tool_context import ToolContext + +def update_user_profile(name: str, language: str, currency: str, tool_context: ToolContext) -> dict: + """ + Udate current user name + Use only when user name is not provided. + + Args: + name (str): User name + + Returns: + dict: A dictionary confirming the action was successful and report updated balance + """ + + tool_context.state["user:name"] = name + tool_context.state["user:language"] = language + tool_context.state["user:currency"] = currency + + return { + "status": "success", + "message": "User Profile Successfully Created" + } + + +def add_financial_goals(goals: str, tool_context: ToolContext) -> dict: + """ + Add new user financial goals + + Args: + goals (str): String of user defined financial goals + + Returns: + dict: A dictionary confirming the action was successful + """ + user_goals = tool_context.state.get("user:financial_goals", []) + user_goals.append(goals) + tool_context.state["user:financial_goals"] = user_goals + + return { + "status": "success", + "message": f"New user financial goals added: {goals}" + } + +def update_balance(transaction_amount: int, tool_context: ToolContext) -> dict: + """ + Udate current user balance based on incoming transaction + + Args: + transaction_amount (int): Amount of recent user transaction. + Positive (plus) if an income, negative (minus) if an expense + + Returns: + dict: A dictionary confirming the action was successful and report updated balance + """ + + balance = tool_context.state.get("user:balance", 0) + balance += transaction_amount + tool_context.state["user:balance"] = balance + + return { + "status": "success", + "message": f"Current user balance: {balance}" + } + + +def check_balance(tool_context: ToolContext) -> dict: + """ + Check current user balance + + Returns: + dics: A dictionary contains status and report of current user balance + """ + + balance = tool_context.state.get("user:balance", 0) + if balance >= 0: + return { + "status": "success", + "report": f"Current user balance: {balance}" + } + else: + return { + "status": "ValueError", + "report": "There is an error in user balance value" + } + + +def set_budget(salary: int, tool_context: ToolContext, **kwargs): + + tool_context.state["user:budget"] = { + "salary": salary, + **kwargs + } + + + +def insert_liabilites(new_liability: dict, tool_context: ToolContext) -> dict: + """ + Insert some liabilities + + """ + + liabilities = tool_context.state.get("user:liabilites", []) + pass + diff --git a/src/utils.py b/src/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..349f8617435170b46024e66c3143277232b3ea7d --- /dev/null +++ b/src/utils.py @@ -0,0 +1,84 @@ +from google.genai import types + +async def display_state( + session_service, app_name, user_id, session_id, label="Current State" +): + """Display the current session state in a formatted way.""" + try: + session = await session_service.get_session( + app_name=app_name, user_id=user_id, session_id=session_id + ) + + # Format the output with clear sections + print(f"\n{'-' * 10} {label} {'-' * 10}") + + # Handle the user name + user_name = session.state.get("user:name", "Unknown") + print(f"User: {user_name}") + + balance = session.state.get("user:balance", 0) + print(f"Balance: {balance}") + + language = session.state.get("user:language", 0) + print(f"Language: {language}") + + currency = session.state.get("user:currency", 0) + print(f"Currency: {currency}") + + # Handle reminders + goals = session.state.get("user:financial_goals", []) + if goals: + print("Goals :") + for idx, goal in enumerate(goals, 1): + print(f" {idx}. {goal}") + else: + print("Goals: None") + + print("-" * (22 + len(label))) + except Exception as e: + print(f"Error displaying state: {e}") + +async def process_agent_response(event): + + print(f"Event ID: {event.id}, Author: {event.author}") + + final_response = None + if event.is_final_response(): + if ( + event.content and event.content.parts + ): + final_response = event.content.parts[0].text + + return final_response + +async def call_agent_async(query: str, runner, user_id, session_id): + + content = types.Content(role="user", parts=[types.Part(text=query)]) + + final_response_text = None + + # Display state before processing + await display_state( + runner.session_service, + runner.app_name, + user_id, + session_id, + "State BEFORE processing", + ) + + async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=content): + + response = await process_agent_response(event) + if response: + final_response_text = response + + # Display state after processing + await display_state( + runner.session_service, + runner.app_name, + user_id, + session_id, + "State AFTER processing", + ) + + return final_response_text \ No newline at end of file