File size: 8,247 Bytes
cf6e451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import StreamingResponse
import random
import asyncio
import aiohttp
import uvicorn

from src.config import get_api_keys
from src.model_tester import ModelTester
from src.scheduler import Scheduler


model_tester = ModelTester()
scheduler = Scheduler(task_callback=lambda: model_tester.scan_all_models())

fastapi_app = FastAPI(title="OpenRouter Free API")


@fastapi_app.on_event("startup")
async def startup_event():
    scheduler.start()


@fastapi_app.get("/v1/models")
async def list_models():
    available = model_tester.get_available_models(free_only=False)
    available_free = model_tester.get_available_models(free_only=True)

    models = []
    for model_id in available:
        is_free = model_id in available_free
        models.append({
            "id": model_id,
            "object": "model",
            "created": 1677610602,
            "owned_by": "openrouter",
            "free": is_free
        })

    return {"object": "list", "data": models}


async def _select_candidates(model_hint: str) -> list[str]:
    """获取候选模型列表(带排序:free 优先)"""
    await model_tester.refresh_model_list_async()
    all_free = model_tester.get_all_free_models()
    all_models = model_tester._all_models

    if not model_hint:
        return all_free[:10]

    hint = model_hint.lower()

    # free 候选(精确优先)
    free_exact = []
    free_fuzzy = []
    for m in all_free:
        name = m.replace(":free", "").split("/")[-1].lower()
        if name == hint:
            free_exact.append(m)
        elif name.startswith(hint) or hint in name:
            free_fuzzy.append(m)

    # 付费候选
    free_set = set(all_free)
    paid_fuzzy = []
    for m in all_models:
        if m in free_set:
            continue
        name = m.replace(":free", "").split("/")[-1].lower()
        if name == hint or hint in name or hint in m.lower():
            paid_fuzzy.append(m)

    return (free_exact + free_fuzzy + paid_fuzzy)[:15]


def _is_definitive_error(error: str) -> bool:
    """不可重试的错误(模型不存在/无权访问)"""
    keywords = ("HTTP 400", "HTTP 403", "HTTP 404",
                "model_not_found", "not found", "not_found")
    return any(k in error for k in keywords)


async def _proxy_with_retry(body: dict, candidates: list[str]) -> dict:
    """

    带重试的代理请求。



    遍历候选模型,对每个模型:

    - 遇到限流/超时/5xx → 换 key + 退避重试

    - 遇到 400/403/404 → 跳到下一个候选

    - 所有候选全失败 → 返回 400

    """
    api_keys = get_api_keys()
    max_retries = 3          # 每个模型最多重试次数
    retry_delay = 5          # 退避基数(秒)

    for candidate in candidates:
        failed_keys: set = set()

        for attempt in range(max_retries):
            # 从可用 key 中选一个
            available = [k for k in api_keys if k not in failed_keys]
            if not available:
                print(f"[proxy] All keys exhausted for {candidate}")
                break
            api_key = random.choice(available)

            body["model"] = candidate

            url = "https://openrouter.ai/api/v1/chat/completions"
            headers = {
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json"
            }

            try:
                async with aiohttp.ClientSession() as session:
                    async with session.post(url, json=body, headers=headers,
                                            timeout=aiohttp.ClientTimeout(total=120)) as response:
                        data = await response.json()

                        if "error" in data:
                            error_detail = str(data["error"])
                            print(f"[proxy] {candidate} → {error_detail[:100]}")

                            # 不可重试 → 跳下一个候选
                            if _is_definitive_error(error_detail):
                                break

                            # 401 → 换 key
                            if "401" in error_detail or "unauthorized" in error_detail.lower():
                                failed_keys.add(api_key)
                                continue

                            # 429 / 5xx / 其他 → 退避重试
                            sleep_s = retry_delay * (attempt + 1)
                            print(f"[proxy] {candidate} retry {attempt + 1}/{max_retries} in {sleep_s}s")
                            await asyncio.sleep(sleep_s)
                            continue

                        return data

            except (asyncio.TimeoutError, aiohttp.ClientError) as e:
                print(f"[proxy] {candidate} error: {e}")
                sleep_s = retry_delay * (attempt + 1)
                await asyncio.sleep(sleep_s)
                continue

            except Exception as e:
                print(f"[proxy] {candidate} unexpected error: {e}")
                sleep_s = retry_delay * (attempt + 1)
                await asyncio.sleep(sleep_s)
                continue

        # 当前候选所有重试用完,换下一个

    raise HTTPException(status_code=400, detail="No available model responded")


async def _proxy_streaming(body: dict, candidates: list[str]):
    """流式代理 — 逐个尝试候选模型"""
    api_keys = get_api_keys()

    url = "https://openrouter.ai/api/v1/chat/completions"
    body["stream"] = True

    for candidate in candidates:
        api_key = random.choice(api_keys)
        body["model"] = candidate

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }

        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(url, json=body, headers=headers,
                                        timeout=aiohttp.ClientTimeout(total=120)) as response:
                    if response.status != 200:
                        print(f"[proxy:stream] {candidate} → HTTP {response.status}, trying next")
                        continue

                    async for chunk in response.content:
                        yield chunk
                    return
        except Exception as e:
            print(f"[proxy:stream] {candidate} error: {e}, trying next")
            continue

    raise HTTPException(status_code=400, detail="No available model for streaming")


@fastapi_app.post("/v1/chat/completions")
async def chat_completions(request: Request):
    body = await request.json()
    model_hint = body.get("model")

    candidates = await _select_candidates(model_hint)
    if not candidates:
        raise HTTPException(status_code=400, detail="No available model")

    if body.get("stream"):
        return StreamingResponse(
            _proxy_streaming(body, candidates),
            media_type="text/event-stream"
        )

    return await _proxy_with_retry(body, candidates)


@fastapi_app.get("/health")
async def health():
    return {"status": "ok"}


def get_scan_status():
    scan_result = model_tester.scan_result
    total = scan_result.get("total_available", 0)
    free = scan_result.get("free_available", 0)
    return f"Free: {free} | Total: {total}"


def format_model_list(models):
    return "\n".join(models) if models else "No models available"


with gr.Blocks(title="OpenRouter Free API") as demo:
    gr.Markdown("# OpenRouter Free API")
    gr.Markdown("Standard OpenAI-compatible API with free model support")
    gr.Markdown(f"**Status: {get_scan_status()}**")
    gr.Markdown("## Available Free Models")
    gr.Textbox(value=format_model_list(model_tester.get_available_models(free_only=True)), lines=15, interactive=False)


app = gr.mount_gradio_app(fastapi_app, demo, path="/")


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)