165 lines
5.9 KiB
Python
165 lines
5.9 KiB
Python
from dataclasses import dataclass
|
||
from typing import Optional
|
||
from django.conf import settings
|
||
import os
|
||
import logging
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
@dataclass
|
||
class AIConfig:
|
||
"""
|
||
Конфигурация для интеграции с ИИ-сервисами
|
||
"""
|
||
api_key: str
|
||
api_url: str
|
||
model_name: str
|
||
temperature: float
|
||
is_coding_endpoint: bool = False
|
||
max_tokens: int = 1000
|
||
timeout: int = 30
|
||
|
||
@classmethod
|
||
def from_integration_model(cls, integration_model):
|
||
"""
|
||
Создать конфигурацию из модели интеграции
|
||
"""
|
||
logger.info(f"=== Создание конфигурации из модели интеграции ===")
|
||
logger.info(f"Тип модели: {type(integration_model)}")
|
||
logger.info(f"Атрибуты модели: {dir(integration_model)}")
|
||
|
||
try:
|
||
api_key = integration_model.api_key
|
||
logger.info(f"API key (первые 10 символов): {api_key[:10] if api_key else 'None'}...")
|
||
except AttributeError as e:
|
||
logger.error(f"Ошибка при получении api_key: {str(e)}")
|
||
raise
|
||
|
||
# Всегда используем общий эндпоинт
|
||
api_url = "https://api.z.ai/api/paas/v4"
|
||
logger.info(f"Используем общий endpoint: {api_url}")
|
||
|
||
try:
|
||
model_name = integration_model.model_name
|
||
logger.info(f"Model name: {model_name}")
|
||
except AttributeError as e:
|
||
logger.error(f"Ошибка при получении model_name: {str(e)}")
|
||
raise
|
||
|
||
try:
|
||
temperature = float(integration_model.temperature)
|
||
logger.info(f"Temperature: {temperature}")
|
||
except AttributeError as e:
|
||
logger.error(f"Ошибка при получении temperature: {str(e)}")
|
||
raise
|
||
|
||
return cls(
|
||
api_key=api_key,
|
||
api_url=api_url,
|
||
model_name=model_name,
|
||
temperature=temperature,
|
||
is_coding_endpoint=False, # Всегда False, так как используем общий endpoint
|
||
)
|
||
|
||
@classmethod
|
||
def from_env(cls):
|
||
"""
|
||
Создать конфигурацию из переменных окружения
|
||
"""
|
||
return cls(
|
||
api_key=os.getenv('ZAI_API_KEY', ''),
|
||
api_url=os.getenv('ZAI_API_URL', 'https://api.z.ai/api/paas/v4'),
|
||
model_name=os.getenv('ZAI_MODEL_NAME', 'glm-4.7'),
|
||
temperature=float(os.getenv('ZAI_TEMPERATURE', '0.7')),
|
||
is_coding_endpoint=os.getenv('ZAI_CODING_ENDPOINT', 'false').lower() == 'true',
|
||
)
|
||
|
||
|
||
def get_glm_config(integration_model=None):
|
||
"""
|
||
Получить конфигурацию GLM из модели интеграции или из .env
|
||
"""
|
||
if integration_model:
|
||
return AIConfig.from_integration_model(integration_model)
|
||
else:
|
||
return AIConfig.from_env()
|
||
|
||
|
||
@dataclass
|
||
class OpenRouterConfig:
|
||
"""
|
||
Конфигурация для интеграции с OpenRouter
|
||
"""
|
||
api_key: str
|
||
api_url: str
|
||
model_name: str
|
||
temperature: float
|
||
max_tokens: int = 1000
|
||
timeout: int = 30
|
||
|
||
@classmethod
|
||
def from_integration_model(cls, integration_model):
|
||
"""
|
||
Создать конфигурацию из модели интеграции
|
||
"""
|
||
logger.info(f"=== Создание конфигурации OpenRouter из модели интеграции ===")
|
||
logger.info(f"Тип модели: {type(integration_model)}")
|
||
|
||
try:
|
||
api_key = integration_model.api_key
|
||
logger.info(f"API key (первые 10 символов): {api_key[:10] if api_key else 'None'}...")
|
||
except AttributeError as e:
|
||
logger.error(f"Ошибка при получении api_key: {str(e)}")
|
||
raise
|
||
|
||
api_url = getattr(integration_model, 'api_url', 'https://openrouter.ai/api/v1')
|
||
logger.info(f"API URL: {api_url}")
|
||
|
||
try:
|
||
model_name = integration_model.model_name
|
||
logger.info(f"Model name: {model_name}")
|
||
except AttributeError as e:
|
||
logger.error(f"Ошибка при получении model_name: {str(e)}")
|
||
raise
|
||
|
||
try:
|
||
temperature = float(integration_model.temperature)
|
||
logger.info(f"Temperature: {temperature}")
|
||
except AttributeError as e:
|
||
logger.error(f"Ошибка при получении temperature: {str(e)}")
|
||
raise
|
||
|
||
max_tokens = getattr(integration_model, 'max_tokens', 1000)
|
||
logger.info(f"Max tokens: {max_tokens}")
|
||
|
||
return cls(
|
||
api_key=api_key,
|
||
api_url=api_url,
|
||
model_name=model_name,
|
||
temperature=temperature,
|
||
max_tokens=max_tokens,
|
||
)
|
||
|
||
@classmethod
|
||
def from_env(cls):
|
||
"""
|
||
Создать конфигурацию из переменных окружения
|
||
"""
|
||
return cls(
|
||
api_key=os.getenv('OPENROUTER_API_KEY', ''),
|
||
api_url=os.getenv('OPENROUTER_API_URL', 'https://openrouter.ai/api/v1'),
|
||
model_name=os.getenv('OPENROUTER_MODEL_NAME', 'xiaomi/mimo-v2-flash:free'),
|
||
temperature=float(os.getenv('OPENROUTER_TEMPERATURE', '0.7')),
|
||
max_tokens=int(os.getenv('OPENROUTER_MAX_TOKENS', '1000')),
|
||
)
|
||
|
||
|
||
def get_openrouter_config(integration_model=None):
|
||
"""
|
||
Получить конфигурацию OpenRouter из модели интеграции или из .env
|
||
"""
|
||
if integration_model:
|
||
return OpenRouterConfig.from_integration_model(integration_model)
|
||
else:
|
||
return OpenRouterConfig.from_env() |