techprotrade commited on
Commit
366ff00
·
verified ·
1 Parent(s): 569a3e5

Add loan-advisor-agent

Browse files
loan-advisor-agent/app/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .agent import app
16
+
17
+ __all__ = ["app"]
loan-advisor-agent/app/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (221 Bytes). View file
 
loan-advisor-agent/app/__pycache__/agent.cpython-312.pyc ADDED
Binary file (6.88 kB). View file
 
loan-advisor-agent/app/agent.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ruff: noqa
2
+ # Copyright 2026 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # https://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ from typing import Optional
18
+
19
+ from google.adk.agents import Agent
20
+ from google.adk.apps import App
21
+ from google.adk.models import Gemini
22
+ from google.genai import types
23
+
24
+ import os
25
+ import google.auth
26
+
27
+ _, project_id = google.auth.default()
28
+ os.environ["GOOGLE_CLOUD_PROJECT"] = project_id
29
+ os.environ["GOOGLE_CLOUD_LOCATION"] = "global"
30
+ os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
31
+
32
+
33
+ def get_loan_products(
34
+ use_case: Optional[str] = None,
35
+ amount_range: Optional[str] = None,
36
+ ) -> str:
37
+ """Retrieve available loan products and their terms.
38
+
39
+ Args:
40
+ use_case: The intended use (e.g., 'startup', 'expansion', 'working_capital').
41
+ amount_range: The loan amount range as 'min-max' in euros.
42
+
43
+ Returns:
44
+ A JSON string containing available loan products with terms.
45
+ """
46
+ loans_db = [
47
+ {
48
+ "id": "startup_basic",
49
+ "name": "Startup Growth Loan",
50
+ "min_amount": 10000,
51
+ "max_amount": 250000,
52
+ "interest_rate": 6.5,
53
+ "term_years": [3, 5, 7],
54
+ "use_case": ["startup"],
55
+ "description": "For new businesses and startups",
56
+ },
57
+ {
58
+ "id": "business_expansion",
59
+ "name": "Business Expansion Credit",
60
+ "min_amount": 50000,
61
+ "max_amount": 1000000,
62
+ "interest_rate": 5.2,
63
+ "term_years": [5, 7, 10],
64
+ "use_case": ["expansion", "growth"],
65
+ "description": "For established businesses expanding operations",
66
+ },
67
+ {
68
+ "id": "working_capital",
69
+ "name": "Working Capital Loan",
70
+ "min_amount": 25000,
71
+ "max_amount": 500000,
72
+ "interest_rate": 7.1,
73
+ "term_years": [2, 3, 5],
74
+ "use_case": ["working_capital", "cash_flow"],
75
+ "description": "Short-term financing for operational needs",
76
+ },
77
+ {
78
+ "id": "equipment_finance",
79
+ "name": "Equipment Financing",
80
+ "min_amount": 20000,
81
+ "max_amount": 750000,
82
+ "interest_rate": 4.8,
83
+ "term_years": [5, 7, 10, 12],
84
+ "use_case": ["equipment", "infrastructure"],
85
+ "description": "Asset-backed financing for equipment purchases",
86
+ },
87
+ ]
88
+
89
+ filtered = loans_db
90
+
91
+ if use_case:
92
+ filtered = [
93
+ loan
94
+ for loan in filtered
95
+ if any(use in loan["use_case"] for use in use_case.lower().split(","))
96
+ ]
97
+
98
+ return json.dumps(filtered, indent=2)
99
+
100
+
101
+ def calculate_loan_payment(
102
+ principal: float, annual_interest_rate: float, years: int
103
+ ) -> str:
104
+ """Calculate monthly payment and total cost for a loan.
105
+
106
+ Args:
107
+ principal: Loan amount in euros.
108
+ annual_interest_rate: Annual interest rate as a percentage (e.g., 5.5).
109
+ years: Loan term in years.
110
+
111
+ Returns:
112
+ A JSON string with monthly payment, total interest, and total cost.
113
+ """
114
+ monthly_rate = annual_interest_rate / 100 / 12
115
+ num_payments = years * 12
116
+
117
+ if monthly_rate == 0:
118
+ monthly_payment = principal / num_payments
119
+ else:
120
+ monthly_payment = principal * (
121
+ monthly_rate * (1 + monthly_rate) ** num_payments
122
+ ) / ((1 + monthly_rate) ** num_payments - 1)
123
+
124
+ total_paid = monthly_payment * num_payments
125
+ total_interest = total_paid - principal
126
+
127
+ return json.dumps(
128
+ {
129
+ "principal": principal,
130
+ "annual_interest_rate": annual_interest_rate,
131
+ "term_years": years,
132
+ "monthly_payment": round(monthly_payment, 2),
133
+ "total_interest": round(total_interest, 2),
134
+ "total_cost": round(total_paid, 2),
135
+ }
136
+ )
137
+
138
+
139
+ def compare_loan_scenarios(scenarios_json: str) -> str:
140
+ """Compare multiple loan scenarios side-by-side.
141
+
142
+ Args:
143
+ scenarios_json: JSON string with array of {loan_id, amount, years} objects.
144
+
145
+ Returns:
146
+ A comparison table as JSON with all scenarios and their calculations.
147
+ """
148
+ try:
149
+ scenarios = json.loads(scenarios_json)
150
+ except json.JSONDecodeError:
151
+ return json.dumps({"error": "Invalid JSON format for scenarios"})
152
+
153
+ loans_db = {
154
+ "startup_basic": {"name": "Startup Growth Loan", "rate": 6.5},
155
+ "business_expansion": {"name": "Business Expansion Credit", "rate": 5.2},
156
+ "working_capital": {"name": "Working Capital Loan", "rate": 7.1},
157
+ "equipment_finance": {"name": "Equipment Financing", "rate": 4.8},
158
+ }
159
+
160
+ comparison = []
161
+ for i, scenario in enumerate(scenarios):
162
+ loan_id = scenario.get("loan_id")
163
+ amount = scenario.get("amount", 0)
164
+ years = scenario.get("years", 5)
165
+
166
+ if loan_id not in loans_db:
167
+ comparison.append(
168
+ {
169
+ "scenario": i + 1,
170
+ "error": f"Unknown loan_id: {loan_id}",
171
+ }
172
+ )
173
+ continue
174
+
175
+ loan_info = loans_db[loan_id]
176
+ monthly_rate = loan_info["rate"] / 100 / 12
177
+ num_payments = years * 12
178
+
179
+ if monthly_rate == 0:
180
+ monthly_payment = amount / num_payments
181
+ else:
182
+ monthly_payment = amount * (
183
+ monthly_rate * (1 + monthly_rate) ** num_payments
184
+ ) / ((1 + monthly_rate) ** num_payments - 1)
185
+
186
+ total_paid = monthly_payment * num_payments
187
+ total_interest = total_paid - amount
188
+
189
+ comparison.append(
190
+ {
191
+ "scenario": i + 1,
192
+ "loan_name": loan_info["name"],
193
+ "amount": amount,
194
+ "years": years,
195
+ "rate": loan_info["rate"],
196
+ "monthly_payment": round(monthly_payment, 2),
197
+ "total_interest": round(total_interest, 2),
198
+ "total_cost": round(total_paid, 2),
199
+ }
200
+ )
201
+
202
+ return json.dumps(comparison, indent=2)
203
+
204
+
205
+ root_agent = Agent(
206
+ name="root_agent",
207
+ model=Gemini(
208
+ model="gemini-flash-latest",
209
+ retry_options=types.HttpRetryOptions(attempts=3),
210
+ ),
211
+ instruction="""You are an expert loan advisor helping customers find the right loan for their financial needs.
212
+ You have access to loan products, calculation tools, and comparison features.
213
+
214
+ When a user asks about loans:
215
+ 1. First understand their needs (use case, amount, timeline)
216
+ 2. Retrieve relevant loan products using get_loan_products
217
+ 3. If they want calculations, use calculate_loan_payment or compare_loan_scenarios
218
+ 4. Provide clear, actionable recommendations with pros/cons
219
+ 5. Always explain terms, rates, and monthly costs clearly
220
+
221
+ Be proactive in asking clarifying questions about their business needs and financial situation.""",
222
+ tools=[get_loan_products, calculate_loan_payment, compare_loan_scenarios],
223
+ )
224
+
225
+ app = App(
226
+ root_agent=root_agent,
227
+ name="app",
228
+ )
loan-advisor-agent/app/agent_runtime_app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import logging
15
+ import os
16
+ from typing import Any
17
+
18
+ import vertexai
19
+ from dotenv import load_dotenv
20
+ from google.adk.artifacts import GcsArtifactService, InMemoryArtifactService
21
+ from google.cloud import logging as google_cloud_logging
22
+ from vertexai.agent_engines.templates.adk import AdkApp
23
+
24
+ from app.agent import app as adk_app
25
+ from app.app_utils.telemetry import setup_telemetry
26
+ from app.app_utils.typing import Feedback
27
+
28
+ # Load environment variables from .env file at runtime
29
+ load_dotenv()
30
+
31
+
32
+ class AgentEngineApp(AdkApp):
33
+ def set_up(self) -> None:
34
+ """Initialize the agent engine app with logging and telemetry."""
35
+ vertexai.init()
36
+ setup_telemetry()
37
+ super().set_up()
38
+ logging.basicConfig(level=logging.INFO)
39
+ logging_client = google_cloud_logging.Client()
40
+ self.logger = logging_client.logger(__name__)
41
+ if gemini_location:
42
+ os.environ["GOOGLE_CLOUD_LOCATION"] = gemini_location
43
+
44
+ def register_feedback(self, feedback: dict[str, Any]) -> None:
45
+ """Collect and log feedback."""
46
+ feedback_obj = Feedback.model_validate(feedback)
47
+ self.logger.log_struct(feedback_obj.model_dump(), severity="INFO")
48
+
49
+ def register_operations(self) -> dict[str, list[str]]:
50
+ """Registers the operations of the Agent."""
51
+ operations = super().register_operations()
52
+ operations[""] = [*operations.get("", []), "register_feedback"]
53
+ return operations
54
+
55
+
56
+ gemini_location = os.environ.get("GOOGLE_CLOUD_LOCATION")
57
+ logs_bucket_name = os.environ.get("LOGS_BUCKET_NAME")
58
+ agent_runtime = AgentEngineApp(
59
+ app=adk_app,
60
+ artifact_service_builder=lambda: (
61
+ GcsArtifactService(bucket_name=logs_bucket_name)
62
+ if logs_bucket_name
63
+ else InMemoryArtifactService()
64
+ ),
65
+ )
loan-advisor-agent/app/app_utils/telemetry.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ import os
17
+
18
+
19
+ def setup_telemetry() -> str | None:
20
+ """Configure OpenTelemetry and GenAI telemetry with GCS upload."""
21
+ os.environ.setdefault("GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY", "true")
22
+
23
+ bucket = os.environ.get("LOGS_BUCKET_NAME")
24
+ capture_content = os.environ.get(
25
+ "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "false"
26
+ )
27
+ if bucket and capture_content != "false":
28
+ logging.info(
29
+ "Prompt-response logging enabled - mode: NO_CONTENT (metadata only, no prompts/responses)"
30
+ )
31
+ os.environ["OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"] = "NO_CONTENT"
32
+ os.environ.setdefault("OTEL_INSTRUMENTATION_GENAI_UPLOAD_FORMAT", "jsonl")
33
+ os.environ.setdefault("OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK", "upload")
34
+ os.environ.setdefault(
35
+ "OTEL_SEMCONV_STABILITY_OPT_IN", "gen_ai_latest_experimental"
36
+ )
37
+ commit_sha = os.environ.get("COMMIT_SHA", "dev")
38
+ os.environ.setdefault(
39
+ "OTEL_RESOURCE_ATTRIBUTES",
40
+ f"service.namespace=loan-advisor-agent,service.version={commit_sha}",
41
+ )
42
+ path = os.environ.get("GENAI_TELEMETRY_PATH", "completions")
43
+ os.environ.setdefault(
44
+ "OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH",
45
+ f"gs://{bucket}/{path}",
46
+ )
47
+ else:
48
+ logging.info(
49
+ "Prompt-response logging disabled (set LOGS_BUCKET_NAME=gs://your-bucket and OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=NO_CONTENT to enable)"
50
+ )
51
+
52
+ return bucket
loan-advisor-agent/app/app_utils/typing.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import uuid
15
+ from typing import (
16
+ Literal,
17
+ )
18
+
19
+ from pydantic import (
20
+ BaseModel,
21
+ Field,
22
+ )
23
+
24
+
25
+ class Feedback(BaseModel):
26
+ """Represents feedback for a conversation."""
27
+
28
+ score: int | float
29
+ text: str | None = ""
30
+ log_type: Literal["feedback"] = "feedback"
31
+ service_name: Literal["loan-advisor-agent"] = "loan-advisor-agent"
32
+ user_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
33
+ session_id: str = Field(default_factory=lambda: str(uuid.uuid4()))