File size: 10,484 Bytes
2f5416d
 
 
 
 
 
 
 
 
 
 
 
 
 
98d3509
 
 
53ddae0
98d3509
53ddae0
98d3509
786a4bd
c956f2e
39a3de5
786a4bd
 
c956f2e
a9d1ee5
 
 
 
2f5416d
 
 
 
 
9c808b3
 
2f5416d
9c808b3
2f5416d
 
 
 
9c808b3
2f5416d
9c808b3
 
 
 
 
 
a9d1ee5
9c808b3
 
 
 
a9d1ee5
39a3de5
 
 
 
 
 
a9d1ee5
9c808b3
 
 
 
 
 
c956f2e
9c808b3
c956f2e
 
786a4bd
 
 
9c808b3
786a4bd
c956f2e
 
a9d1ee5
53ddae0
33b84e4
 
53ddae0
 
 
 
 
 
39a3de5
53ddae0
 
c956f2e
cd5342c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9d1ee5
cd5342c
 
 
 
 
 
 
 
53ddae0
cd5342c
53ddae0
c956f2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ddae0
39a3de5
 
 
cd5342c
53ddae0
39a3de5
c956f2e
53ddae0
39a3de5
362b9e1
 
39a3de5
 
 
 
 
 
362b9e1
 
 
39a3de5
 
 
53ddae0
c956f2e
 
 
 
786a4bd
39a3de5
 
 
 
33b84e4
98d3509
 
 
 
 
 
33b84e4
 
 
98d3509
c956f2e
2f5416d
 
 
98d3509
 
 
 
 
 
39a3de5
cd5342c
c956f2e
 
 
 
 
 
 
8ee1ea0
2f5416d
 
 
8ee1ea0
2f5416d
8ee1ea0
2f5416d
8ee1ea0
 
 
cd5342c
98d3509
2f5416d
98d3509
53ddae0
98d3509
 
 
 
 
 
 
 
 
 
 
 
 
2f5416d
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
"""Patch backend: OpenRouter routing + DeepSeek V4 Flash 0731 + FIX DeepSeek routing.

FIX: GLM_52_MODEL_ID was set to "openai/deepseek/deepseek-v4-flash" which routes
to OpenRouter via the openai/ prefix catch-all. However, OpenRouter's model ID
is "deepseek/deepseek-v4-flash" (without the openai/ prefix). When LiteLLM
sends the full "openai/deepseek/deepseek-v4-flash" as the model name to
OpenRouter's API, it gets a 404 because OpenRouter doesn't recognize the
"openai/" prefix.

Solution:
1. GLM_52_MODEL_ID -> "deepseek-ai/DeepSeek-V4-Flash:deepinfra" (HF Router path, model exists there, cheapest provider)
2. OpenRouter routing strips the "openai/" prefix before sending to OpenRouter
3. Add :novita tag to DeepSeek V4 Pro for deterministic routing via HF Router
"""

import ast
import os
import re

AGENT_FILE = "/app/backend/routes/agent.py"
LLM_PARAMS_FILE = "/app/agent/core/llm_params.py"
IDS_FILE = "/app/agent/core/model_ids.py"

with open(IDS_FILE) as f:
    content = f.read()

# Remove NO_TOOLS_MODELS if present from previous patches
if "NO_TOOLS_MODELS" in content:
    content = re.sub(r'NO_TOOLS_MODELS\s*=\s*\{[^}]*\}\n?', '', content)
    print("OK: Removed old NO_TOOLS_MODELS")

# FIX: Set GLM_52_MODEL_ID to HF Router path with provider tag.
# "deepseek-ai/DeepSeek-V4-Flash:deepinfra" IS available on HF Router
# (5 providers for -0731 variant, 3 for standard). All support tools, 1M context.
# Using :deepinfra for better pricing ($0.09/0.18 per 1M tokens)
# KIMI_K27_CODE_MODEL_ID -> DeepSeek V4 Pro via HF Router with :novita tag
replacements = [
    ('KIMI_K27_CODE_MODEL_ID = "moonshotai/Kimi-K2.7-Code:novita"',
     'KIMI_K27_CODE_MODEL_ID = "deepseek-ai/DeepSeek-V4-Pro:novita"'),
    ('MINIMAX_M3_MODEL_ID = "MiniMaxAI/MiniMax-M3:novita"',
     'MINIMAX_M3_MODEL_ID = "deepseek-ai/DeepSeek-V4-Flash:deepinfra"'),
    # FIX: Was "openai/deepseek/deepseek-v4-flash" which routes to OpenRouter but
    # OpenRouter model IDs don't include the "openai/" prefix, causing 404.
    # Change to HF Router path with :deepinfra provider tag for cheaper pricing.
    ('GLM_52_MODEL_ID = "zai-org/GLM-5.2:novita"',
     'GLM_52_MODEL_ID = "deepseek-ai/DeepSeek-V4-Flash:deepinfra"'),
    ('DEEPSEEK_V4_PRO_MODEL_ID = "deepseek-ai/DeepSeek-V4-Pro:novita"',
     'DEEPSEEK_V4_PRO_MODEL_ID = "nvidia/nemotron-3-super-120b-a12b:free"'),
]
for old, new in replacements:
    content = content.replace(old, new)
print("OK: Model ID replacements applied")

# Add missing constants BEFORE the specific line DEEPSEEK_V4_PRO_MODEL_ID = "..."
if "TENCENT_HY3_FREE_MODEL_ID" not in content:
    target_line = 'DEEPSEEK_V4_PRO_MODEL_ID = "nvidia/nemotron-3-super-120b-a12b:free"'
    insert_block = '''TENCENT_HY3_FREE_MODEL_ID = "openai/tencent/hy3:free"
GEMMA_4_31B_FREE_MODEL_ID = "openai/google/gemma-4-31b-it:free"
LLAMA_3_3_70B_FREE_MODEL_ID = "openai/meta-llama/llama-3.3-70b-instruct:free"
LLAMA_3_1_8B_MODEL_ID = "openai/meta-llama/llama-3.1-8b-instruct"
LAGUNA_M1_FREE_MODEL_ID = "openai/poolside/laguna-m.1:free"
LAGUNA_S21_FREE_MODEL_ID = "openai/poolside/laguna-s-2.1:free"
NEX_N2_MINI_MODEL_ID = "openai/nex-agi/nex-n2-mini"
LING_3_0_FLASH_FREE_MODEL_ID = "openai/inclusionai/ling-3.0-flash:free"
'''
    # Only replace the first occurrence (the variable definition)
    if target_line in content:
        content = content.replace(target_line, insert_block + target_line)
        print("OK: Added missing constants")
    else:
        print("WARN: Could not find target line")

# Replace all references to ~deepseek deepseek models with 0731 version (quoted strings only)
content = content.replace('"~deepseek/deepseek-v4-flash-latest"', '"deepseek/deepseek-v4-flash-0731"')
content = content.replace('"~deepseek/deepseek-v4-flash-0731"', '"deepseek/deepseek-v4-flash-0731"')

with open(IDS_FILE, "w") as f:
    f.write(content)
print("OK: model_ids.py written")

ast.parse(content)  # validate syntax
print("OK: model_ids.py syntax OK")

with open(AGENT_FILE) as f:
    content = f.read()

content = content.replace(
    "DEFAULT_MODEL_ID = GLM_52_MODEL_ID",
    'DEFAULT_MODEL_ID = "openai/tencent/hy3:free"'
)
content = content.replace(
    "DEFAULT_GPT_MODEL_ID = GPT_55_MODEL_ID",
    "DEFAULT_GPT_MODEL_ID = LAGUNA_S21_FREE_MODEL_ID"
)

# Update imports
old_import = (
    "from agent.core.model_ids import (\n"
    "    CLAUDE_OPUS_48_MODEL_ID,\n"
    "    DEEPSEEK_V4_PRO_MODEL_ID,\n"
    "    GLM_52_MODEL_ID,\n"
    "    GPT_55_MODEL_ID,\n"
    "    KIMI_K27_CODE_MODEL_ID,\n"
    "    MINIMAX_M3_MODEL_ID,\n"
    "    strip_huggingface_model_prefix,\n"
    ")"
)
new_import = (
    "from agent.core.model_ids import (\n"
    "    DEEPSEEK_V4_PRO_MODEL_ID,\n"
    "    GLM_52_MODEL_ID,\n"
    "    GPT_55_MODEL_ID,\n"
    "    KIMI_K27_CODE_MODEL_ID,\n"
    "    MINIMAX_M3_MODEL_ID,\n"
    "    TENCENT_HY3_FREE_MODEL_ID,\n"
    "    GEMMA_4_31B_FREE_MODEL_ID,\n"
    "    LLAMA_3_3_70B_FREE_MODEL_ID,\n"
    "    LLAMA_3_1_8B_MODEL_ID,\n"
    "    LAGUNA_M1_FREE_MODEL_ID,\n"
    "    LAGUNA_S21_FREE_MODEL_ID,\n"
    "    NEX_N2_MINI_MODEL_ID,\n"
    "    LING_3_0_FLASH_FREE_MODEL_ID,\n"
    "    strip_huggingface_model_prefix,\n"
    ")"
)
content = content.replace(old_import, new_import)

# Update _available_models to include DeepSeek V4 Flash 0731
new_func = '''def _available_models() -> list[dict[str, Any]]:
    models = [
        {"id": TENCENT_HY3_FREE_MODEL_ID, "label": "Tencent HY3:free", "recommended": True},
        {"id": GEMMA_4_31B_FREE_MODEL_ID, "label": "Gemma 4 31B:free", "recommended": True},
        {"id": LLAMA_3_3_70B_FREE_MODEL_ID, "label": "Llama 3.3 70B:free", "recommended": True},
        {"id": LAGUNA_M1_FREE_MODEL_ID, "label": "Laguna M.1:free", "recommended": True},
        {"id": DEFAULT_GPT_MODEL_ID, "label": "Laguna S 2.1:free", "recommended": True},
        {"id": NEX_N2_MINI_MODEL_ID, "label": "nex-agi/nex-n2-mini", "recommended": True},
        {"id": LING_3_0_FLASH_FREE_MODEL_ID, "label": "inclusionai/ling-3.0-flash:free", "recommended": True},
        {"id": LLAMA_3_1_8B_MODEL_ID, "label": "Llama 3.1 8B"},
        {"id": KIMI_K27_CODE_MODEL_ID, "label": "DeepSeek V4 Pro"},
        {"id": MINIMAX_M3_MODEL_ID, "label": "DeepSeek V4 Flash"},
        {"id": DEFAULT_MODEL_ID, "label": "DeepSeek V4 Flash"},
        {"id": DEEPSEEK_V4_PRO_MODEL_ID, "label": "Nemotron 3 Super 120B"},
        {"id": "deepseek/deepseek-v4-flash-0731", "label": "DeepSeek V4 Flash 0731", "recommended": True},
    ]
    return models'''

func_match = re.search(
    r"def _available_models\(\)\s*->\s*list\[dict\[str,\s*Any\]\]:.*?return models",
    content, re.DOTALL
)
if func_match:
    content = content[:func_match.start()] + new_func + content[func_match.end():]
    print("OK: Replaced _available_models() with DeepSeek V4 Flash 0731")
else:
    old_func = (
        "def _available_models() -> list[dict[str, Any]]:\n"
        "    models = [\n"
        '        {"id": CLAUDE_OPUS_48_MODEL_ID, "label": "Claude Opus 4.8"},\n'
        '        {"id": DEFAULT_GPT_MODEL_ID, "label": "GPT-5.5"},\n'
        '        {"id": KIMI_K27_CODE_MODEL_ID, "label": "Kimi K2.7 Code"},\n'
        '        {"id": MINIMAX_M3_MODEL_ID, "label": "MiniMax M3"},\n'
        '        {"id": DEFAULT_MODEL_ID, "label": "GLM 5.2", "recommended": True},\n'
        '        {"id": DEEPSEEK_V4_PRO_MODEL_ID, "label": "DeepSeek V4 Pro"},\n'
        "    ]\n"
        "    return models"
    )
    if old_func in content:
        content = content.replace(old_func, new_func)
        print("OK: String replace of _available_models()")
    else:
        print("WARN: Could not find _available_models() pattern, searching...")
        idx = content.find("def _available_models")
        if idx >= 0:
            print(f"Found at index {idx}, context: {content[idx:idx+400]}")

content = content.replace(
    '"openai/gpt-oss-120b:cerebras",',
    '"huggingface/deepseek-ai/DeepSeek-V4-Pro",'
)

try:
    ast.parse(content)
    print("OK: agent.py syntax OK")
except SyntaxError as e:
    print(f"FAIL: agent.py syntax error: {e}")
    raise

with open(AGENT_FILE, "w") as f:
    f.write(content)

# Patch llm_params for OpenRouter routing
# FIX: Strip the "openai/" prefix before sending model name to OpenRouter
# OpenRouter model IDs do not include the "openai/" prefix.
# e.g. "openai/tencent/hy3:free" -> "tencent/hy3:free"
with open(LLM_PARAMS_FILE) as f:
    llm_content = f.read()

if "normalized_model.startswith" not in llm_content:
    api_key_find = "api_key = _resolve_hf_router_token(session_hf_token)"
    if api_key_find in llm_content:
        line_end = llm_content.find("\n", llm_content.find(api_key_find) + len(api_key_find)) + 1
        routing_insert = (
            '    # Route deepseek/ models to OpenRouter\n'
            '    if normalized_model.startswith("deepseek/"):\n'
            '        return {\n'
            '            "model": normalized_model,\n'
            '            "api_base": "https://openrouter.ai/api/v1",\n'
            '            "api_key": os.environ.get("OPENROUTER_API_KEY") or api_key or "",\n'
            '        }\n\n'
            '    # Route openai/-prefixed models to OpenRouter\n'
            '    # FIX: Strip the "openai/" prefix - OpenRouter model IDs do not include it.\n'
            '    # e.g. "openai/deepseek/deepseek-v4-flash" -> "deepseek/deepseek-v4-flash"\n'
            '    # e.g. "openai/tencent/hy3:free" -> "tencent/hy3:free"\n'
            '    if normalized_model.startswith("openai/"):\n'
            '        or_model = normalized_model[len("openai/"):]\n'
            '        return {\n'
            '            "model": or_model,\n'
            '            "api_base": "https://openrouter.ai/api/v1",\n'
            '            "api_key": os.environ.get("OPENROUTER_API_KEY") or api_key or "",\n'
            '        }\n\n'
        )
        llm_content = llm_content[:line_end] + routing_insert + llm_content[line_end:]
        print("OK: Patched _resolve_llm_params with deepseek/ + fixed openai/ routing")
    else:
        print("WARN: Could not find api_key line")
else:
    print("OK: llm_params.py already patched")

try:
    ast.parse(llm_content)
    print("OK: llm_params.py syntax OK")
except SyntaxError as e:
    print(f"FAIL: llm_params.py syntax error: {e}")
    raise

with open(LLM_PARAMS_FILE, "w") as f:
    f.write(llm_content)

print("OK: ALL BACKEND PATCHES APPLIED (including DeepSeek V4 Flash routing fix)")