File size: 9,540 Bytes
87c0663 0445c27 87c0663 0445c27 87c0663 0445c27 87c0663 0445c27 87c0663 0445c27 87c0663 0445c27 87c0663 0445c27 87c0663 0445c27 87c0663 0445c27 87c0663 | 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 | import json
import logging
from typing import Any
import litellm
from app.models.domain import AIProviderResponse, ToolCall
from app.tools.registry import ToolRegistry
logger = logging.getLogger(__name__)
class LiteLLMOrchestration:
"""Provides AI orchestration using LiteLLM Router for automatic API management"""
def __init__(
self,
groq_api_key: str,
groq_model: str,
openrouter_api_key: str | None = None,
openrouter_model: str | None = None,
groq_api_key_2: str | None = None,
groq_model_2: str | None = None,
google_ai_api_key: str | None = None,
google_ai_model: str | None = None,
max_tool_iterations: int = 3,
temperature: float = 0.2,
) -> None:
self.name = "litellm-orchestration"
self.groq_api_key = groq_api_key
self.groq_model = groq_model
self.groq_api_key_2 = groq_api_key_2
self.groq_model_2 = groq_model_2
self.google_ai_api_key = google_ai_api_key
self.google_ai_model = google_ai_model
self.openrouter_api_key = openrouter_api_key
self.openrouter_model = openrouter_model
self.max_tool_iterations = max_tool_iterations
self.temperature = temperature
self._initialized = False
@staticmethod
def _litellm_model(model: str, provider: str) -> str:
"""Ensure model name has the litellm provider prefix.
litellm strips the provider prefix before sending to the API,
so 'groq/openai/gpt-oss-120b' sends 'openai/gpt-oss-120b' to Groq.
Also strips non-litellm prefixes (e.g. 'google/' from OpenRouter
model IDs) before applying the correct litellm provider prefix.
"""
for prefix in ("google",):
if model.startswith(f"{prefix}/"):
model = model[len(prefix) + 1 :]
break
if model.startswith(f"{provider}/"):
return model
return f"{provider}/{model}"
async def _ensure_initialized(self):
if not self._initialized:
self.router = litellm.Router(
model_list=[
{
"model_name": "groq",
"litellm_params": {
"model": self._litellm_model(self.groq_model, "groq"),
"api_key": self.groq_api_key,
"api_base": "https://api.groq.com/openai/v1",
},
},
{
"model_name": "groq_2",
"litellm_params": {
"model": self._litellm_model(self.groq_model_2 or self.groq_model, "groq"),
"api_key": self.groq_api_key_2 or self.groq_api_key,
"api_base": "https://api.groq.com/openai/v1",
},
},
{
"model_name": "google_ai_studio",
"litellm_params": {
"model": self._litellm_model(self.google_ai_model or self.openrouter_model, "gemini"),
"api_key": self.google_ai_api_key or self.openrouter_api_key,
"api_base": "https://generativelanguage.googleapis.com/v1beta",
},
},
{
"model_name": "openrouter",
"litellm_params": {
"model": self._litellm_model(self.openrouter_model, "openrouter"),
"api_key": self.openrouter_api_key,
"api_base": "https://openrouter.ai/api/v1",
},
},
],
fallbacks=[{"groq": ["groq_2", "google_ai_studio", "openrouter"]},],
num_retries=0,
retry_policy={
"TimeoutErrorRetries": 0,
"RateLimitErrorRetries": 0,
"InternalServerErrorRetries": 0,
},
routing_strategy="latency-based-routing",
set_verbose=False,
)
self._initialized = True
async def chat(
self,
*,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None = None,
temperature: float | None = None,
tool_choice: str | None = "auto",
) -> AIProviderResponse:
if temperature is None:
temperature = self.temperature
await self._ensure_initialized()
kwargs = {
"messages": messages,
"model": "groq",
"temperature": temperature,
}
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = tool_choice
try:
response = await self.router.acompletion(**kwargs)
return self._adapt_response(response)
except Exception as exc:
logger.error("LiteLLM Router error: %s", exc)
raise RuntimeError(f"AI request failed: {exc}") from exc
async def generate_reply(
self,
*,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]],
registry: ToolRegistry,
) -> str:
working_messages = [dict(msg) for msg in messages]
for _ in range(self.max_tool_iterations + 1):
response = await self.chat(
messages=working_messages,
tools=tools,
temperature=self.temperature,
)
if not response.tool_calls:
content = (response.content or "").strip()
if content:
return content
continue
working_messages.append(self._assistant_tool_message(response))
for tool_call in response.tool_calls:
result = await self._execute_tool_call(registry, tool_call)
if result.suppress_llm_reply:
return result.error or ""
working_messages.append(
{
"role": "tool",
"tool_call_id": tool_call.id,
"name": tool_call.name,
"content": json.dumps(result.to_payload(), ensure_ascii=False),
}
)
return (
"I found that this request needs extra checking. "
"A support team member will follow up with you shortly."
)
def _adapt_response(self, response: Any) -> AIProviderResponse:
raw_message: dict[str, Any] = {}
if hasattr(response, "choices") and response.choices:
choice = response.choices[0]
if hasattr(choice, "message") and choice.message:
if hasattr(choice.message, "model_dump"):
raw_message = choice.message.model_dump(exclude_none=True)
elif isinstance(choice.message, dict):
raw_message = choice.message
else:
raw_message = {
"content": getattr(choice.message, "content", None),
"tool_calls": getattr(choice.message, "tool_calls", None),
}
tool_calls = []
for tool_call in raw_message.get("tool_calls") or []:
if hasattr(tool_call, "function"):
function = tool_call.function
name = function.name
arguments = function.arguments or "{}"
id_val = getattr(tool_call, "id", None) or f"tool-call-{name}"
else:
function = tool_call.get("function") or {}
name = function.get("name", "")
arguments = function.get("arguments") or "{}"
id_val = tool_call.get("id") or f"tool-call-{name}"
tool_calls.append(
ToolCall(
id=id_val,
name=name,
arguments=arguments,
)
)
return AIProviderResponse(
content=raw_message.get("content"),
tool_calls=tool_calls,
raw_message=raw_message,
)
@staticmethod
def _assistant_tool_message(response: AIProviderResponse) -> dict[str, Any]:
if response.raw_message:
return response.raw_message
return {
"role": "assistant",
"content": response.content,
"tool_calls": [
{
"id": tool_call.id,
"type": "function",
"function": {"name": tool_call.name, "arguments": tool_call.arguments},
}
for tool_call in response.tool_calls
],
}
@staticmethod
async def _execute_tool_call(
registry: ToolRegistry, tool_call: ToolCall
) -> Any:
try:
arguments = json.loads(tool_call.arguments or "{}")
if not isinstance(arguments, dict):
raise ValueError("Tool arguments must be a JSON object")
except (json.JSONDecodeError, ValueError) as exc:
from app.models.domain import ToolResult
return ToolResult(
ok=False, data={}, error=f"Invalid tool arguments: {exc}"
)
return await registry.execute(tool_call.name, arguments)
|