Spaces:
Paused
Paused
Update backend/model_router.py
Browse files- backend/model_router.py +57 -14
backend/model_router.py
CHANGED
|
@@ -1,14 +1,19 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from typing import List, Dict, AsyncGenerator
|
| 3 |
from openai import AsyncOpenAI
|
| 4 |
import httpx
|
| 5 |
|
| 6 |
-
groq_keys = os.environ.get("GROQ_API_KEYS", "").split(",")
|
| 7 |
-
openrouter_keys = os.environ.get("OPENROUTER_KEYS", "").split(",")
|
| 8 |
ollama_base = os.environ.get("OLLAMA_BASE_URL", "http://host.docker.internal:11434")
|
| 9 |
|
| 10 |
POLLINATIONS_URL = "https://text.pollinations.ai/openai"
|
| 11 |
|
|
|
|
| 12 |
def _make_client(base_url: str, api_key: str) -> AsyncOpenAI:
|
| 13 |
http_client = httpx.AsyncClient(trust_env=False)
|
| 14 |
return AsyncOpenAI(
|
|
@@ -17,17 +22,25 @@ def _make_client(base_url: str, api_key: str) -> AsyncOpenAI:
|
|
| 17 |
http_client=http_client
|
| 18 |
)
|
| 19 |
|
|
|
|
| 20 |
def get_groq_client():
|
|
|
|
|
|
|
| 21 |
key = random.choice(groq_keys)
|
| 22 |
return _make_client("https://api.groq.com/openai/v1", key)
|
| 23 |
|
|
|
|
| 24 |
def get_openrouter_client():
|
|
|
|
|
|
|
| 25 |
key = random.choice(openrouter_keys)
|
| 26 |
return _make_client("https://openrouter.ai/api/v1", key)
|
| 27 |
|
|
|
|
| 28 |
def get_ollama_client():
|
| 29 |
return _make_client(f"{ollama_base}/v1", "ollama")
|
| 30 |
|
|
|
|
| 31 |
async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, None]:
|
| 32 |
if model.startswith("groq-"):
|
| 33 |
client = get_groq_client()
|
|
@@ -40,6 +53,7 @@ async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, No
|
|
| 40 |
async for chunk in stream:
|
| 41 |
if chunk.choices[0].delta.content:
|
| 42 |
yield chunk.choices[0].delta.content
|
|
|
|
| 43 |
elif model.startswith("openrouter-"):
|
| 44 |
client = get_openrouter_client()
|
| 45 |
model_id = model[11:]
|
|
@@ -51,6 +65,7 @@ async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, No
|
|
| 51 |
async for chunk in stream:
|
| 52 |
if chunk.choices[0].delta.content:
|
| 53 |
yield chunk.choices[0].delta.content
|
|
|
|
| 54 |
elif model.startswith("ollama-"):
|
| 55 |
client = get_ollama_client()
|
| 56 |
model_id = model[7:]
|
|
@@ -62,6 +77,7 @@ async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, No
|
|
| 62 |
async for chunk in stream:
|
| 63 |
if chunk.choices[0].delta.content:
|
| 64 |
yield chunk.choices[0].delta.content
|
|
|
|
| 65 |
elif model == "free-pollinations":
|
| 66 |
async with aiohttp.ClientSession() as session:
|
| 67 |
async with session.post(
|
|
@@ -74,20 +90,33 @@ async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, No
|
|
| 74 |
raise Exception(f"Pollinations error {resp.status}: {text}")
|
| 75 |
data = await resp.json()
|
| 76 |
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
| 78 |
else:
|
| 79 |
raise ValueError(f"Unknown model: {model}")
|
| 80 |
|
|
|
|
| 81 |
async def route_autocomplete(model: str, prefix: str, suffix: str, max_tokens: int) -> str:
|
| 82 |
if model.startswith("ollama-"):
|
| 83 |
client = get_ollama_client()
|
| 84 |
model_id = model[7:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
else:
|
|
|
|
| 86 |
client = get_groq_client()
|
| 87 |
model_id = "llama-3.1-8b-instant"
|
| 88 |
-
|
|
|
|
| 89 |
if suffix:
|
| 90 |
-
prompt += f"\nThe code should continue until before: {suffix}"
|
|
|
|
| 91 |
response = await client.chat.completions.create(
|
| 92 |
model=model_id,
|
| 93 |
messages=[{"role": "user", "content": prompt}],
|
|
@@ -96,7 +125,8 @@ async def route_autocomplete(model: str, prefix: str, suffix: str, max_tokens: i
|
|
| 96 |
)
|
| 97 |
return response.choices[0].message.content
|
| 98 |
|
| 99 |
-
|
|
|
|
| 100 |
models = [
|
| 101 |
{"id": "groq-llama-3.3-70b-versatile", "name": "Groq Llama 3.3 70B", "free": False},
|
| 102 |
{"id": "groq-llama-3.1-8b-instant", "name": "Groq Llama 3.1 8B (Instant)", "free": False},
|
|
@@ -107,12 +137,25 @@ def get_available_models():
|
|
| 107 |
{"id": "openrouter-google/gemma-2-9b-it", "name": "Gemma 2 9B (OpenRouter)", "free": False},
|
| 108 |
{"id": "free-pollinations", "name": "Free Pollinations (GPT-4o-mini)", "free": True},
|
| 109 |
]
|
|
|
|
|
|
|
| 110 |
try:
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
pass
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Fixed model_router.py
|
| 3 |
+
model_router_py = '''import os
|
| 4 |
+
import random
|
| 5 |
+
import aiohttp
|
| 6 |
from typing import List, Dict, AsyncGenerator
|
| 7 |
from openai import AsyncOpenAI
|
| 8 |
import httpx
|
| 9 |
|
| 10 |
+
groq_keys = [k.strip() for k in os.environ.get("GROQ_API_KEYS", "").split(",") if k.strip()]
|
| 11 |
+
openrouter_keys = [k.strip() for k in os.environ.get("OPENROUTER_KEYS", "").split(",") if k.strip()]
|
| 12 |
ollama_base = os.environ.get("OLLAMA_BASE_URL", "http://host.docker.internal:11434")
|
| 13 |
|
| 14 |
POLLINATIONS_URL = "https://text.pollinations.ai/openai"
|
| 15 |
|
| 16 |
+
|
| 17 |
def _make_client(base_url: str, api_key: str) -> AsyncOpenAI:
|
| 18 |
http_client = httpx.AsyncClient(trust_env=False)
|
| 19 |
return AsyncOpenAI(
|
|
|
|
| 22 |
http_client=http_client
|
| 23 |
)
|
| 24 |
|
| 25 |
+
|
| 26 |
def get_groq_client():
|
| 27 |
+
if not groq_keys:
|
| 28 |
+
raise ValueError("No Groq API keys configured. Set GROQ_API_KEYS env var.")
|
| 29 |
key = random.choice(groq_keys)
|
| 30 |
return _make_client("https://api.groq.com/openai/v1", key)
|
| 31 |
|
| 32 |
+
|
| 33 |
def get_openrouter_client():
|
| 34 |
+
if not openrouter_keys:
|
| 35 |
+
raise ValueError("No OpenRouter API keys configured. Set OPENROUTER_KEYS env var.")
|
| 36 |
key = random.choice(openrouter_keys)
|
| 37 |
return _make_client("https://openrouter.ai/api/v1", key)
|
| 38 |
|
| 39 |
+
|
| 40 |
def get_ollama_client():
|
| 41 |
return _make_client(f"{ollama_base}/v1", "ollama")
|
| 42 |
|
| 43 |
+
|
| 44 |
async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, None]:
|
| 45 |
if model.startswith("groq-"):
|
| 46 |
client = get_groq_client()
|
|
|
|
| 53 |
async for chunk in stream:
|
| 54 |
if chunk.choices[0].delta.content:
|
| 55 |
yield chunk.choices[0].delta.content
|
| 56 |
+
|
| 57 |
elif model.startswith("openrouter-"):
|
| 58 |
client = get_openrouter_client()
|
| 59 |
model_id = model[11:]
|
|
|
|
| 65 |
async for chunk in stream:
|
| 66 |
if chunk.choices[0].delta.content:
|
| 67 |
yield chunk.choices[0].delta.content
|
| 68 |
+
|
| 69 |
elif model.startswith("ollama-"):
|
| 70 |
client = get_ollama_client()
|
| 71 |
model_id = model[7:]
|
|
|
|
| 77 |
async for chunk in stream:
|
| 78 |
if chunk.choices[0].delta.content:
|
| 79 |
yield chunk.choices[0].delta.content
|
| 80 |
+
|
| 81 |
elif model == "free-pollinations":
|
| 82 |
async with aiohttp.ClientSession() as session:
|
| 83 |
async with session.post(
|
|
|
|
| 90 |
raise Exception(f"Pollinations error {resp.status}: {text}")
|
| 91 |
data = await resp.json()
|
| 92 |
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
| 93 |
+
# Yield word by word to simulate streaming
|
| 94 |
+
words = content.split(" ")
|
| 95 |
+
for word in words:
|
| 96 |
+
yield word + " "
|
| 97 |
else:
|
| 98 |
raise ValueError(f"Unknown model: {model}")
|
| 99 |
|
| 100 |
+
|
| 101 |
async def route_autocomplete(model: str, prefix: str, suffix: str, max_tokens: int) -> str:
|
| 102 |
if model.startswith("ollama-"):
|
| 103 |
client = get_ollama_client()
|
| 104 |
model_id = model[7:]
|
| 105 |
+
elif model.startswith("groq-"):
|
| 106 |
+
client = get_groq_client()
|
| 107 |
+
model_id = model[5:]
|
| 108 |
+
elif model.startswith("openrouter-"):
|
| 109 |
+
client = get_openrouter_client()
|
| 110 |
+
model_id = model[11:]
|
| 111 |
else:
|
| 112 |
+
# Default to Groq for autocomplete
|
| 113 |
client = get_groq_client()
|
| 114 |
model_id = "llama-3.1-8b-instant"
|
| 115 |
+
|
| 116 |
+
prompt = f"Complete the following code:\\n```\\n{prefix}\\n```"
|
| 117 |
if suffix:
|
| 118 |
+
prompt += f"\\nThe code should continue until before: {suffix}"
|
| 119 |
+
|
| 120 |
response = await client.chat.completions.create(
|
| 121 |
model=model_id,
|
| 122 |
messages=[{"role": "user", "content": prompt}],
|
|
|
|
| 125 |
)
|
| 126 |
return response.choices[0].message.content
|
| 127 |
|
| 128 |
+
|
| 129 |
+
async def get_available_models():
|
| 130 |
models = [
|
| 131 |
{"id": "groq-llama-3.3-70b-versatile", "name": "Groq Llama 3.3 70B", "free": False},
|
| 132 |
{"id": "groq-llama-3.1-8b-instant", "name": "Groq Llama 3.1 8B (Instant)", "free": False},
|
|
|
|
| 137 |
{"id": "openrouter-google/gemma-2-9b-it", "name": "Gemma 2 9B (OpenRouter)", "free": False},
|
| 138 |
{"id": "free-pollinations", "name": "Free Pollinations (GPT-4o-mini)", "free": True},
|
| 139 |
]
|
| 140 |
+
|
| 141 |
+
# Try to fetch Ollama models asynchronously
|
| 142 |
try:
|
| 143 |
+
async with aiohttp.ClientSession() as session:
|
| 144 |
+
async with session.get(f"{ollama_base}/api/tags", timeout=aiohttp.ClientTimeout(total=2)) as resp:
|
| 145 |
+
if resp.status == 200:
|
| 146 |
+
data = await resp.json()
|
| 147 |
+
for model in data.get("models", []):
|
| 148 |
+
models.append({
|
| 149 |
+
"id": f"ollama-{model['name']}",
|
| 150 |
+
"name": f"Ollama {model['name']}",
|
| 151 |
+
"free": True
|
| 152 |
+
})
|
| 153 |
+
except Exception:
|
| 154 |
pass
|
| 155 |
+
|
| 156 |
+
return models
|
| 157 |
+
'''
|
| 158 |
+
|
| 159 |
+
with open('/mnt/agents/output/model_router.py', 'w') as f:
|
| 160 |
+
f.write(model_router_py)
|
| 161 |
+
print("model_router.py written successfully")
|