-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_insights.py
More file actions
104 lines (83 loc) · 3.67 KB
/
Copy pathget_insights.py
File metadata and controls
104 lines (83 loc) · 3.67 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
import os
import requests
import json
from dotenv import load_dotenv
from typing import Any
# Load environment variables
load_dotenv()
def get_insights_rest(api_key: str, customer_context: str) -> dict[str, Any]:
"""
Attempt to fetch insights from the DoiT Insights API results endpoint.
Note: As of March 2026, this endpoint may return 404 if not enabled for the account.
"""
url = f"https://api.doit.com/insights/v1/results?customerContext={customer_context}&category=FinOps"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
print(f"Checking DoiT Insights REST API at {url}...")
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
elif response.status_code == 404:
print(
"Rest API endpoint /insights/v1/results returned 404. Falling back to Ava..."
)
return None
else:
print(f"Rest API error: {response.status_code}")
print("Response body omitted to avoid JSON output.")
return None
def get_insights_via_ava(api_key: str, customer_context: str) -> dict[str, Any]:
"""
Fallback method: Use DoiT's Ava API to list the same FinOps insights.
"""
url = f"https://api.doit.com/ava/v1/askSync?customerContext={customer_context}"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
# We ask Ava for the structured JSON of the insights
question = (
"Ada, please list all current actionable FinOps insights for this customer. "
"Output the result as a valid JSON object with a 'results' key containing a list of objects. "
"Each object should have: 'key', 'title', 'status', 'provider', 'potentialDailySavings'. "
"Format the potentialDailySavings as a number. Round to nearest dollar. "
"Note that potentialDailySavings is for a day, not a month. "
"Only include actionable insights."
)
payload = {"question": question, "ephemeral": True}
print("Asking Ava for the Insights list...")
response = requests.post(url, headers=headers, json=payload)
if response.status_code != 200:
print(f"Ava API error: {response.status_code}")
return None
ava_data = response.json()
answer_text = ava_data.get("answer", "")
# Parse the JSON from Ava's response
try:
if "```json" in answer_text:
json_str = answer_text.split("```json")[1].split("```")[0].strip()
elif "```" in answer_text:
json_str = answer_text.split("```")[1].strip()
else:
json_str = answer_text.strip()
return json.loads(json_str)
except Exception as e:
print(f"Failed to parse Ava response as JSON: {e}")
print("Ava response body omitted to avoid JSON output.")
return None
if __name__ == "__main__":
api_key = os.getenv("DOIT_API_KEY")
customer_context = os.getenv("CUSTOMER_CONTEXT")
if not api_key or not customer_context:
print("Error: DOIT_API_KEY and CUSTOMER_CONTEXT must be set in .env")
exit(1)
# 1. Try the REST API first
insights = get_insights_rest(api_key, customer_context)
# 2. Fall back to Ava if needed
if insights is None:
insights = get_insights_via_ava(api_key, customer_context)
if insights:
print("\nSuccessfully retrieved FinOps Insights:")
print(json.dumps(insights, indent=2))
# Save to file
with open("existing_insights.json", "w") as f:
json.dump(insights, f, indent=2)
print("\nInsights saved to existing_insights.json")
else:
print("\nFailed to retrieve insights via both REST and Ava.")