Repository navigation
Expand file tree
/
Copy pathapi_compat.py
More file actions
423 lines (348 loc) · 15.9 KB
/
Copy pathapi_compat.py
File metadata and controls
423 lines (348 loc) · 15.9 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
"""API Compatibility Layer — OpenAI, Anthropic, and Gemini-native formats.
All three formats route to the same cloudcode-pa backend using the user's
OAuth token. The user_id acts as the API key in each format:
OpenAI: Authorization: Bearer <user_id>
Anthropic: x-api-key: <user_id>
Gemini: ?key=<user_id> OR Authorization: Bearer <user_id>
"""
import json
import time
import uuid
from flask import Blueprint, Response, jsonify, request, stream_with_context
from auth import get_access_token
from gemini import generate, stream_generate
from prompt_engine import check_input_guardrails
compat_bp = Blueprint("compat", __name__)
SUPPORTED_MODELS = [
"gemini-3-flash-preview",
"gemini-3.1-flash-lite-preview",
"gemini-2.5-flash",
"gemini-2.5-flash-lite",
]
# Map common OpenAI / Anthropic model names to Gemini equivalents
MODEL_MAP = {
# OpenAI — heavy → best model, mini/turbo → lite
"gpt-4o": "gemini-3-flash-preview",
"gpt-4o-mini": "gemini-3.1-flash-lite-preview",
"gpt-4": "gemini-3-flash-preview",
"gpt-4-turbo": "gemini-3-flash-preview",
"gpt-3.5-turbo": "gemini-3.1-flash-lite-preview",
# Anthropic — opus → best, sonnet/haiku → lite
"claude-3-opus": "gemini-3-flash-preview",
"claude-3-sonnet": "gemini-3.1-flash-lite-preview",
"claude-3-haiku": "gemini-3.1-flash-lite-preview",
"claude-3-5-sonnet": "gemini-3-flash-preview",
"claude-opus-4": "gemini-3-flash-preview",
"claude-sonnet-4": "gemini-3.1-flash-lite-preview",
}
# ── Auth helpers ─────────────────────────────────────────────────────────────
def _extract_user_id():
"""Extract user_id from whichever auth header is present."""
# OpenAI / Gemini Bearer
auth = request.headers.get("Authorization", "")
if auth.startswith("Bearer "):
uid = auth[7:].strip()
if uid:
return uid
# Anthropic
uid = request.headers.get("x-api-key", "").strip()
if uid:
return uid
# Gemini ?key= query param
uid = request.args.get("key", "").strip()
if uid:
return uid
# Existing jaika header
uid = request.headers.get("X-User-Id", "").strip()
if uid:
return uid
return None
def _require_user():
"""Return (user_id, None) or (None, error_response)."""
uid = _extract_user_id()
if not uid:
return None, (jsonify({"error": {"message": "Missing API key / user id", "type": "auth_error"}}), 401)
if get_access_token(uid) is None:
return None, (jsonify({"error": {"message": "Token expired — please log in again", "type": "auth_error"}}), 401)
return uid, None
# ── Message converters ───────────────────────────────────────────────────────
def _openai_messages_to_gemini(messages):
"""Convert OpenAI messages list → (gemini_messages, system_instruction)."""
system_parts = []
gemini_msgs = []
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
# content can be a string or a list of parts
if isinstance(content, list):
text = " ".join(p.get("text", "") for p in content if p.get("type") == "text")
else:
text = content
if role == "system":
system_parts.append(text)
elif role == "assistant":
gemini_msgs.append({"role": "model", "text": text})
else:
gemini_msgs.append({"role": "user", "text": text})
system_instruction = "\n".join(system_parts) if system_parts else None
return gemini_msgs, system_instruction
def _anthropic_messages_to_gemini(messages, system=None):
"""Convert Anthropic messages list → (gemini_messages, system_instruction)."""
gemini_msgs = []
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
if isinstance(content, list):
text = " ".join(
b.get("text", "") for b in content if b.get("type") == "text"
)
else:
text = content
gemini_msgs.append({
"role": "model" if role == "assistant" else "user",
"text": text,
})
return gemini_msgs, system or None
def _resolve_model(requested):
"""Map requested model name to a Gemini model name. Always falls back to gemini-3-flash-preview."""
if not requested:
return "gemini-3-flash-preview"
lower = requested.lower()
mapped = MODEL_MAP.get(lower)
if mapped:
return mapped
# Accept known Gemini models as-is
if lower in [m.lower() for m in SUPPORTED_MODELS]:
return lower
# Unknown model → fallback
return "gemini-3-flash-preview"
# ── OpenAI format ─────────────────────────────────────────────────────────────
@compat_bp.route("/v1/models", methods=["GET"])
def openai_list_models():
uid, err = _require_user()
if err:
return err
models = [
{"id": m, "object": "model", "created": 1700000000, "owned_by": "google"}
for m in SUPPORTED_MODELS
]
return jsonify({"object": "list", "data": models})
@compat_bp.route("/v1/chat/completions", methods=["POST"])
def openai_chat_completions():
uid, err = _require_user()
if err:
return err
data = request.get_json(force=True)
messages = data.get("messages", [])
do_stream = data.get("stream", False)
model = _resolve_model(data.get("model", "")) or "gemini-3-flash-preview"
gemini_msgs, system_instruction = _openai_messages_to_gemini(messages)
if not gemini_msgs:
return jsonify({"error": {"message": "No messages provided", "type": "invalid_request_error"}}), 400
# Input guardrails
last_text = gemini_msgs[-1].get("text", "") if gemini_msgs else ""
if last_text:
is_safe, safety_msg = check_input_guardrails(last_text)
if not is_safe:
return jsonify({"error": {"message": safety_msg, "type": "invalid_request_error"}}), 400
grounding = bool(data.get("grounding", False))
if do_stream:
def _gen():
chunk_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
ts = int(time.time())
opening = {
"id": chunk_id, "object": "chat.completion.chunk",
"created": ts, "model": model,
"choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}],
}
yield f"data: {json.dumps(opening)}\n\n"
for raw in stream_generate(uid, gemini_msgs, system_instruction=system_instruction, grounding=grounding):
if not raw.startswith("data: "):
continue
try:
d = json.loads(raw[6:])
except json.JSONDecodeError:
continue
if "text" in d:
chunk = {
"id": chunk_id, "object": "chat.completion.chunk",
"created": ts, "model": model,
"choices": [{"index": 0, "delta": {"content": d["text"]}, "finish_reason": None}],
}
yield f"data: {json.dumps(chunk)}\n\n"
elif d.get("type") == "done":
final = {
"id": chunk_id, "object": "chat.completion.chunk",
"created": ts, "model": model,
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
}
yield f"data: {json.dumps(final)}\n\n"
yield "data: [DONE]\n\n"
return Response(
stream_with_context(_gen()),
mimetype="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
# Non-streaming
result = generate(uid, gemini_msgs, system_instruction=system_instruction, grounding=grounding)
if "error" in result:
return jsonify({"error": {"message": result["error"], "type": "api_error"}}), 502
return jsonify({
"id": f"chatcmpl-{uuid.uuid4().hex[:12]}",
"object": "chat.completion",
"created": int(time.time()),
"model": model,
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": result["text"]},
"finish_reason": "stop",
}],
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
})
# ── Anthropic format ──────────────────────────────────────────────────────────
@compat_bp.route("/v1/messages", methods=["POST"])
def anthropic_messages():
uid, err = _require_user()
if err:
return err
data = request.get_json(force=True)
messages = data.get("messages", [])
system = data.get("system", None)
do_stream = data.get("stream", False)
model = _resolve_model(data.get("model", "")) or "gemini-3-flash-preview"
gemini_msgs, system_instruction = _anthropic_messages_to_gemini(messages, system)
if not gemini_msgs:
return jsonify({"error": {"type": "invalid_request_error", "message": "No messages provided"}}), 400
# Input guardrails
last_text = gemini_msgs[-1].get("text", "") if gemini_msgs else ""
if last_text:
is_safe, safety_msg = check_input_guardrails(last_text)
if not is_safe:
return jsonify({"type": "error", "error": {"type": "invalid_request_error", "message": safety_msg}}), 400
grounding = bool(data.get("grounding", False))
msg_id = f"msg_{uuid.uuid4().hex[:12]}"
if do_stream:
def _gen():
ts = int(time.time())
yield f"event: message_start\ndata: {json.dumps({'type':'message_start','message':{'id':msg_id,'type':'message','role':'assistant','content':[],'model':model,'stop_reason':None,'usage':{'input_tokens':0,'output_tokens':0}}})}\n\n"
yield f"event: content_block_start\ndata: {json.dumps({'type':'content_block_start','index':0,'content_block':{'type':'text','text':''}})}\n\n"
for raw in stream_generate(uid, gemini_msgs, system_instruction=system_instruction, grounding=grounding):
if not raw.startswith("data: "):
continue
try:
d = json.loads(raw[6:])
except json.JSONDecodeError:
continue
if "text" in d:
delta = {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": d["text"]}}
yield f"event: content_block_delta\ndata: {json.dumps(delta)}\n\n"
elif d.get("type") == "done":
yield f"event: content_block_stop\ndata: {json.dumps({'type':'content_block_stop','index':0})}\n\n"
yield f"event: message_delta\ndata: {json.dumps({'type':'message_delta','delta':{'stop_reason':'end_turn','stop_sequence':None},'usage':{'output_tokens':0}})}\n\n"
yield f"event: message_stop\ndata: {json.dumps({'type':'message_stop'})}\n\n"
return Response(
stream_with_context(_gen()),
mimetype="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
result = generate(uid, gemini_msgs, system_instruction=system_instruction, grounding=grounding)
if "error" in result:
return jsonify({"type": "error", "error": {"type": "api_error", "message": result["error"]}}), 502
return jsonify({
"id": msg_id,
"type": "message",
"role": "assistant",
"model": model,
"content": [{"type": "text", "text": result["text"]}],
"stop_reason": "end_turn",
"stop_sequence": None,
"usage": {"input_tokens": 0, "output_tokens": 0},
})
# ── Gemini native format ──────────────────────────────────────────────────────
@compat_bp.route("/v1beta/models", methods=["GET"])
@compat_bp.route("/v1/models/gemini", methods=["GET"])
def gemini_list_models():
uid, err = _require_user()
if err:
return err
models = [
{
"name": f"models/{m}",
"version": m.split("-")[-1],
"displayName": m,
"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],
}
for m in SUPPORTED_MODELS
]
return jsonify({"models": models})
@compat_bp.route("/v1beta/models/<path:model_action>", methods=["POST"])
def gemini_generate(model_action):
"""Handle /v1beta/models/{model}:generateContent and :streamGenerateContent"""
uid, err = _require_user()
if err:
return err
# parse model and action from path e.g. "gemini-2.5-flash:generateContent"
if ":" in model_action:
model_name, action = model_action.rsplit(":", 1)
else:
model_name, action = model_action, "generateContent"
do_stream = "stream" in action.lower()
data = request.get_json(force=True)
contents = data.get("contents", [])
system_instruction = None
si = data.get("systemInstruction", {})
if si:
parts = si.get("parts", [])
system_instruction = " ".join(p.get("text", "") for p in parts)
# Convert Gemini native contents format to internal format
gemini_msgs = []
for c in contents:
role = c.get("role", "user")
parts = c.get("parts", [])
text = " ".join(p.get("text", "") for p in parts if "text" in p)
gemini_msgs.append({"role": role, "text": text})
if not gemini_msgs:
return jsonify({"error": {"message": "No contents provided"}}), 400
# Input guardrails
last_text = gemini_msgs[-1].get("text", "") if gemini_msgs else ""
if last_text:
is_safe, safety_msg = check_input_guardrails(last_text)
if not is_safe:
return jsonify({"error": {"message": safety_msg}}), 400
grounding = bool(data.get("grounding", False))
if do_stream:
def _gen():
for raw in stream_generate(uid, gemini_msgs, system_instruction=system_instruction, grounding=grounding):
if not raw.startswith("data: "):
continue
try:
d = json.loads(raw[6:])
except json.JSONDecodeError:
continue
if "text" in d:
chunk = {
"candidates": [{
"content": {"role": "model", "parts": [{"text": d["text"]}]},
"finishReason": None,
"index": 0,
}]
}
yield f"data: {json.dumps(chunk)}\n\n"
elif d.get("type") == "done":
yield f"data: {json.dumps({'candidates':[{'finishReason':'STOP','index':0}]})}\n\n"
return Response(
stream_with_context(_gen()),
mimetype="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
result = generate(uid, gemini_msgs, system_instruction=system_instruction, grounding=grounding)
if "error" in result:
return jsonify({"error": {"message": result["error"]}}), 502
return jsonify({
"candidates": [{
"content": {"role": "model", "parts": [{"text": result["text"]}]},
"finishReason": "STOP",
"index": 0,
}],
"usageMetadata": {"promptTokenCount": 0, "candidatesTokenCount": 0, "totalTokenCount": 0},
})