-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
279 lines (253 loc) · 9.53 KB
/
Copy pathtools.py
File metadata and controls
279 lines (253 loc) · 9.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
"""
Data-access tools and Claude API tool definitions.
Each function returns a formatted string (not a DataFrame) so the
model gets clean, compact results. The functions are pure — they
operate on in-memory DataFrames generated by data.py (deterministic
synthetic data).
"""
from data import (
AZURE_SUMMARY_DF,
AZURE_DETAILS_DF,
GCP_SUMMARY_DF,
GCP_DETAILS_DF,
)
def get_azure_top_overages(n: int = 5) -> str:
"""Top N Azure subscriptions by estimated 30-day overage cost."""
df = AZURE_SUMMARY_DF.copy()
top = (
df[df["estimated_overage_cost_30d"] > 0]
.nlargest(n, "estimated_overage_cost_30d")[
["subscription_id", "ingested_gb_30d", "overage_gb_30d",
"estimated_overage_cost_30d"]
]
)
if top.empty:
return "No Azure subscriptions with overage found."
return top.to_string(index=False)
def get_gcp_top_projects(n: int = 5) -> str:
"""Top N GCP projects by total logging cost."""
df = GCP_SUMMARY_DF.copy()
top = (
df[df["total_cost"] > 0]
.nlargest(n, "total_cost")[
["project_id", "total_cost", "currency"]
]
)
if top.empty:
return "No GCP projects with costs found."
return top.to_string(index=False)
def get_daily_trend(platform: str, identifier: str) -> str:
"""Day-by-day cost/ingestion for a specific subscription or project."""
platform = platform.lower()
if platform == "azure":
df = AZURE_DETAILS_DF.copy()
sub = df[df["subscription_id"] == identifier]
if sub.empty:
return f"No Azure data found for subscription: {identifier}"
daily = (
sub.groupby("day")[["ingested_gb", "overage_gb",
"estimated_overage_cost"]]
.sum()
.reset_index()
.sort_values("day")
)
header = f"Daily cost trend for Azure subscription {identifier}:\n"
return header + daily.to_string(index=False)
elif platform == "gcp":
df = GCP_DETAILS_DF.copy()
proj = df[df["project_id"] == identifier]
if proj.empty:
return f"No GCP data found for project: {identifier}"
daily = (
proj.groupby("day")[["cost"]]
.sum()
.reset_index()
.sort_values("day")
)
header = f"Daily cost trend for GCP project {identifier}:\n"
return header + daily.to_string(index=False)
else:
return f"Unknown platform '{platform}'. Use 'azure' or 'gcp'."
def find_spikes(threshold_pct: float = 50.0) -> str:
"""Detect days where cost jumped > threshold_pct% vs the previous day."""
results = []
# ── Azure ──────────────────────────────────────────────────────
df_az = AZURE_DETAILS_DF.copy()
daily_az = (
df_az.groupby(["subscription_id", "day"])["estimated_overage_cost"]
.sum()
.reset_index()
.sort_values(["subscription_id", "day"])
)
daily_az["prev"] = daily_az.groupby("subscription_id")[
"estimated_overage_cost"
].shift(1)
daily_az["pct_change"] = (
(daily_az["estimated_overage_cost"] - daily_az["prev"])
/ daily_az["prev"].replace(0, float("nan"))
* 100
)
spikes_az = daily_az[
(daily_az["pct_change"] >= threshold_pct)
& (daily_az["estimated_overage_cost"] > 1)
]
if not spikes_az.empty:
az_lines = (
"[Azure] " + spikes_az["subscription_id"].astype(str)
+ " on " + spikes_az["day"].astype(str)
+ ": +" + spikes_az["pct_change"].round(0).astype(int).astype(str)
+ "% ($" + spikes_az["estimated_overage_cost"].map("{:.2f}".format) + ")"
)
results.extend(az_lines.tolist())
# ── GCP ────────────────────────────────────────────────────────
df_gcp = GCP_DETAILS_DF.copy()
daily_gcp = (
df_gcp.groupby(["project_id", "day"])["cost"]
.sum()
.reset_index()
.sort_values(["project_id", "day"])
)
daily_gcp["prev"] = daily_gcp.groupby("project_id")["cost"].shift(1)
daily_gcp["pct_change"] = (
(daily_gcp["cost"] - daily_gcp["prev"])
/ daily_gcp["prev"].replace(0, float("nan"))
* 100
)
spikes_gcp = daily_gcp[
(daily_gcp["pct_change"] >= threshold_pct)
& (daily_gcp["cost"] > 1)
]
if not spikes_gcp.empty:
gcp_lines = (
"[GCP] " + spikes_gcp["project_id"].astype(str)
+ " on " + spikes_gcp["day"].astype(str)
+ ": +" + spikes_gcp["pct_change"].round(0).astype(int).astype(str)
+ "% ($" + spikes_gcp["cost"].map("{:.2f}".format) + ")"
)
results.extend(gcp_lines.tolist())
if not results:
return f"No spikes above {threshold_pct}% found."
return "\n".join(results)
def compare_cross_cloud() -> str:
"""Compares total costs across Azure and GCP side by side.
Returns a summary of total Azure overage cost, total GCP logging
cost, and the cost split between the two clouds. Useful for
executive-level "what are we spending across both clouds?" questions.
"""
az_total = AZURE_SUMMARY_DF["estimated_overage_cost_30d"].sum()
gcp_total = GCP_SUMMARY_DF["total_cost"].sum()
grand_total = az_total + gcp_total
lines = [
"Cross-Cloud Cost Summary (30 days)",
"=" * 40,
f"Azure total overage cost: ${az_total:,.2f}",
f"GCP total logging cost: ${gcp_total:,.2f}",
f"{'─' * 40}",
f"Grand total: ${grand_total:,.2f}",
"",
"Azure subscription breakdown:",
]
for _, row in AZURE_SUMMARY_DF.sort_values(
"estimated_overage_cost_30d", ascending=False
).iterrows():
lines.append(
f" {row['subscription_id']}: ${row['estimated_overage_cost_30d']:,.2f}"
)
lines.append("")
lines.append("GCP project breakdown:")
for _, row in GCP_SUMMARY_DF.sort_values(
"total_cost", ascending=False
).iterrows():
lines.append(
f" {row['project_id']}: ${row['total_cost']:,.2f}"
)
return "\n".join(lines)
# ── Claude tool definitions ────────────────────────────────────────────
TOOL_DEFINITIONS = [
{
"name": "get_azure_top_overages",
"description": "Returns the top N Azure subscriptions "
"ranked by estimated overage cost over the last 30 days.",
"input_schema": {
"type": "object",
"properties": {
"n": {
"type": "integer",
"description": "Number of top subscriptions to return. Default 5.",
}
},
"required": [],
},
},
{
"name": "get_gcp_top_projects",
"description": "Returns the top N GCP projects "
"ranked by total logging cost.",
"input_schema": {
"type": "object",
"properties": {
"n": {
"type": "integer",
"description": "Number of top projects to return. Default 5.",
}
},
"required": [],
},
},
{
"name": "get_daily_trend",
"description": "Returns day-by-day cost and ingestion data "
"for a specific Azure subscription or GCP project.",
"input_schema": {
"type": "object",
"properties": {
"platform": {
"type": "string",
"enum": ["azure", "gcp"],
"description": "Cloud platform.",
},
"identifier": {
"type": "string",
"description": "Azure subscription_id or GCP project_id.",
},
},
"required": ["platform", "identifier"],
},
},
{
"name": "find_spikes",
"description": "Finds days where daily cost jumped by more than "
"threshold_pct% compared to the previous day, "
"across both Azure and GCP.",
"input_schema": {
"type": "object",
"properties": {
"threshold_pct": {
"type": "number",
"description": "Minimum percentage increase "
"to flag as a spike. Default 50.",
}
},
"required": [],
},
},
{
"name": "compare_cross_cloud",
"description": "Compares total costs across Azure and GCP side by side. "
"Returns total Azure overage cost, total GCP logging cost, "
"and per-subscription / per-project breakdowns. "
"Takes no arguments.",
"input_schema": {
"type": "object",
"properties": {},
"required": [],
},
},
]
TOOL_DISPATCH = {
"get_azure_top_overages": lambda args: get_azure_top_overages(**args),
"get_gcp_top_projects": lambda args: get_gcp_top_projects(**args),
"get_daily_trend": lambda args: get_daily_trend(**args),
"find_spikes": lambda args: find_spikes(**args),
"compare_cross_cloud": lambda args: compare_cross_cloud(),
}