Mayank2027 commited on
Commit
62b5eb1
·
verified ·
1 Parent(s): 0f00000

Update backend/model_router.py

Browse files
Files changed (1) hide show
  1. backend/model_router.py +9 -12
backend/model_router.py CHANGED
@@ -1,19 +1,20 @@
1
- import os, asyncio, random
2
  from typing import List, Dict, AsyncGenerator
3
- from groq import Groq
 
 
4
  from openai import AsyncOpenAI
5
 
6
  groq_keys = os.environ.get("GROQ_API_KEYS", "").split(",")
7
  openrouter_keys = os.environ.get("OPENROUTER_KEYS", "").split(",")
8
 
9
- # Free models via Pollinations (no key needed)
10
  POLLINATIONS_URL = "https://text.pollinations.ai/"
11
 
12
  async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, None]:
13
- if model.startswith("groq"):
14
  key = random.choice(groq_keys)
15
  client = Groq(api_key=key)
16
- model_id = model.split("-",1)[1] # e.g., "groq-mixtral-8x7b-32768"
17
  stream = client.chat.completions.create(
18
  messages=messages,
19
  model=model_id,
@@ -22,13 +23,13 @@ async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, No
22
  for chunk in stream:
23
  if chunk.choices[0].delta.content:
24
  yield chunk.choices[0].delta.content
25
- elif model.startswith("openrouter"):
26
  key = random.choice(openrouter_keys)
27
  client = AsyncOpenAI(
28
  base_url="https://openrouter.ai/api/v1",
29
  api_key=key,
30
  )
31
- model_id = model.split("-",1)[1] # e.g., "openrouter-anthropic/claude-3-opus"
32
  stream = await client.chat.completions.create(
33
  messages=messages,
34
  model=model_id,
@@ -38,9 +39,7 @@ async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, No
38
  if chunk.choices[0].delta.content:
39
  yield chunk.choices[0].delta.content
40
  elif model == "free-pollinations":
41
- # Free text generation via Pollinations
42
  prompt = "\n".join([f"{m['role']}: {m['content']}" for m in messages])
43
- import aiohttp
44
  async with aiohttp.ClientSession() as session:
45
  async with session.post(POLLINATIONS_URL, json={"prompt": prompt, "model": "openai"}, params={"stream": "true"}) as resp:
46
  async for line in resp.content:
@@ -50,13 +49,11 @@ async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, No
50
  raise ValueError(f"Unknown model: {model}")
51
 
52
  async def route_autocomplete(model: str, prefix: str, suffix: str, max_tokens: int) -> str:
53
- # For autocomplete, use Groq with FIM (fill-in-middle) if supported, else just completion.
54
  key = random.choice(groq_keys)
55
  client = Groq(api_key=key)
56
- # Format for code completion
57
  prompt = f"<fim_prefix>{prefix}<fim_suffix>{suffix}<fim_middle>"
58
  response = client.completions.create(
59
- model="codellama-70b", # or "llama3-8b"
60
  prompt=prompt,
61
  max_tokens=max_tokens,
62
  temperature=0.1,
 
1
+ import os, random, aiohttp
2
  from typing import List, Dict, AsyncGenerator
3
+
4
+ # Correct imports for groq 0.3.0+
5
+ from groq import Client as Groq
6
  from openai import AsyncOpenAI
7
 
8
  groq_keys = os.environ.get("GROQ_API_KEYS", "").split(",")
9
  openrouter_keys = os.environ.get("OPENROUTER_KEYS", "").split(",")
10
 
 
11
  POLLINATIONS_URL = "https://text.pollinations.ai/"
12
 
13
  async def route_chat(model: str, messages: List[Dict]) -> AsyncGenerator[str, None]:
14
+ if model.startswith("groq-"):
15
  key = random.choice(groq_keys)
16
  client = Groq(api_key=key)
17
+ model_id = model[5:] # strip "groq-"
18
  stream = client.chat.completions.create(
19
  messages=messages,
20
  model=model_id,
 
23
  for chunk in stream:
24
  if chunk.choices[0].delta.content:
25
  yield chunk.choices[0].delta.content
26
+ elif model.startswith("openrouter-"):
27
  key = random.choice(openrouter_keys)
28
  client = AsyncOpenAI(
29
  base_url="https://openrouter.ai/api/v1",
30
  api_key=key,
31
  )
32
+ model_id = model[11:] # strip "openrouter-"
33
  stream = await client.chat.completions.create(
34
  messages=messages,
35
  model=model_id,
 
39
  if chunk.choices[0].delta.content:
40
  yield chunk.choices[0].delta.content
41
  elif model == "free-pollinations":
 
42
  prompt = "\n".join([f"{m['role']}: {m['content']}" for m in messages])
 
43
  async with aiohttp.ClientSession() as session:
44
  async with session.post(POLLINATIONS_URL, json={"prompt": prompt, "model": "openai"}, params={"stream": "true"}) as resp:
45
  async for line in resp.content:
 
49
  raise ValueError(f"Unknown model: {model}")
50
 
51
  async def route_autocomplete(model: str, prefix: str, suffix: str, max_tokens: int) -> str:
 
52
  key = random.choice(groq_keys)
53
  client = Groq(api_key=key)
 
54
  prompt = f"<fim_prefix>{prefix}<fim_suffix>{suffix}<fim_middle>"
55
  response = client.completions.create(
56
+ model="codellama-70b",
57
  prompt=prompt,
58
  max_tokens=max_tokens,
59
  temperature=0.1,