-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaetherflow_api.py
More file actions
205 lines (173 loc) · 6.4 KB
/
aetherflow_api.py
File metadata and controls
205 lines (173 loc) · 6.4 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
from flask import Flask, request, jsonify
import traceback
# Import core credit management helpers
from aetherflow_core import (
register_agent,
deduct_credits,
add_credits,
get_balance,
authorize_agent,
analytics_summary,
analytics_agents,
save_policy,
get_policy,
list_policies,
update_policy,
)
app = Flask(__name__)
"""AetherFlow Credits API — pay-as-you-go credit metering for AI agents"""
# ---------------------------------------------------------------------------
# Auth helper — returns (agent_id, None) on success or (None, error_response)
# ---------------------------------------------------------------------------
def _require_auth():
api_key = request.headers.get('X-API-KEY') or request.headers.get('Authorization', '').replace('Bearer ', '')
if not api_key:
return None, (jsonify({"error": "missing_api_key", "hint": "Include X-API-KEY header"}), 401)
agent_id = authorize_agent(api_key)
if not agent_id:
return None, (jsonify({"error": "invalid_api_key"}), 403)
return agent_id, None
# ---------------------------------------------------------------------------
# Public endpoints
# ---------------------------------------------------------------------------
@app.route('/health', methods=['GET'])
def health():
return jsonify({"status": "ok", "service": "aetherflow-credits"})
@app.route('/agents/register', methods=['POST'])
def register():
"""Register a new agent — returns agent_id + api_key. Public endpoint."""
data = request.get_json(force=True) or {}
agent_id = data.get('agent_id')
initial_credits = data.get('initial_credits', 1000)
if not agent_id:
return jsonify({"error": "agent_id is required"}), 400
try:
result = register_agent(agent_id, initial_credits)
return jsonify(result)
except Exception:
traceback.print_exc()
return jsonify({"error": "internal_error"}), 500
# ---------------------------------------------------------------------------
# Protected agent endpoints — require X-API-KEY
# ---------------------------------------------------------------------------
@app.route('/agents/deduct', methods=['POST'])
def deduct():
agent_id, err = _require_auth()
if err:
return err
data = request.get_json(force=True) or {}
# Allow body agent_id override; fall back to authenticated agent
target_id = data.get('agent_id', agent_id)
amount = data.get('amount')
description = data.get('description', '')
if amount is None:
return jsonify({"error": "amount is required"}), 400
try:
policy_id = data.get('policy_id')
msg = deduct_credits(target_id, amount, description, policy_id)
balance = get_balance(target_id)
return jsonify({"message": msg, "balance": balance})
except Exception:
traceback.print_exc()
return jsonify({"error": "internal_error"}), 500
@app.route('/agents/add', methods=['POST'])
def add():
agent_id, err = _require_auth()
if err:
return err
data = request.get_json(force=True) or {}
target_id = data.get('agent_id', agent_id)
amount = data.get('amount')
description = data.get('description', '')
if amount is None:
return jsonify({"error": "amount is required"}), 400
try:
msg = add_credits(target_id, amount, description)
balance = get_balance(target_id)
return jsonify({"message": msg, "balance": balance})
except Exception:
traceback.print_exc()
return jsonify({"error": "internal_error"}), 500
@app.route('/agents/balance', methods=['GET'])
def balance():
agent_id, err = _require_auth()
if err:
return err
target_id = request.args.get('agent_id', agent_id)
try:
bal = get_balance(target_id)
return jsonify(bal)
except Exception:
traceback.print_exc()
return jsonify({"error": "internal_error"}), 500
# ---------------------------------------------------------------------------
# Policy endpoints — protected
# ---------------------------------------------------------------------------
@app.route('/policies/create', methods=['POST'])
def policies_create():
_, err = _require_auth()
if err:
return err
policy = request.get_json(force=True) or {}
result = save_policy(policy)
return jsonify(result)
@app.route('/policies/<policy_id>', methods=['GET'])
def policies_get(policy_id):
_, err = _require_auth()
if err:
return err
policy = get_policy(policy_id)
if not policy:
return jsonify({"error": "policy_not_found"}), 404
return jsonify({"policy": policy})
@app.route('/policies', methods=['GET'])
def policies_list():
_, err = _require_auth()
if err:
return err
return jsonify({"policies": list_policies()})
@app.route('/policies/<policy_id>', methods=['PATCH'])
def policies_patch(policy_id):
_, err = _require_auth()
if err:
return err
patch = request.get_json(force=True) or {}
result = update_policy(policy_id, patch)
return jsonify(result)
@app.route('/policies/<policy_id>/enable-auto-topup', methods=['POST'])
def policies_enable_autotop(policy_id):
_, err = _require_auth()
if err:
return err
policy = get_policy(policy_id)
if not policy:
return jsonify({"error": "policy_not_found"}), 404
patch = {"auto_topup": {"enabled": True}}
return jsonify(update_policy(policy_id, patch))
@app.route('/policies/<policy_id>/disable-auto-topup', methods=['POST'])
def policies_disable_autotop(policy_id):
_, err = _require_auth()
if err:
return err
policy = get_policy(policy_id)
if not policy:
return jsonify({"error": "policy_not_found"}), 404
patch = {"auto_topup": {"enabled": False}}
return jsonify(update_policy(policy_id, patch))
# ---------------------------------------------------------------------------
# Analytics endpoints — protected
# ---------------------------------------------------------------------------
@app.route('/analytics/summary', methods=['GET'])
def analytics_sum():
_, err = _require_auth()
if err:
return err
return jsonify(analytics_summary())
@app.route('/analytics/agents', methods=['GET'])
def analytics_agents_route():
_, err = _require_auth()
if err:
return err
return jsonify(analytics_agents())
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=False)