import os import requests import json from typing import List, Generator class ModelRegistry: """سجل النماذج المتاحة للوصول السريع""" def __init__(self): # النماذج الأساسية التي طلبتها للبرمجة والذكاء العام self.models_db = { "qwen-coder": "Qwen/Qwen2.5-Coder-32B-Instruct", "deepseek-v3": "deepseek-ai/DeepSeek-V3" } class HFAdapter: """المحول المسؤول عن الاتصال بـ Hugging Face Router الجديد""" def __init__(self, model_id: str, base_url: str): self.model_id = model_id self.base_url = base_url # جلب التوكن من إعدادات البيئة (Secrets) للأمان self.api_key = os.getenv("HF_TOKEN") def generate_stream(self, messages: List[dict]) -> Generator[str, None, None]: """توليد الرد بنظام التدفق (Streaming) لضمان سرعة الاستجابة""" if not self.api_key: yield "❌ خطأ: لم يتم العثور على HF_TOKEN. تأكد من إضافته في الإعدادات." return headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } payload = { "model": self.model_id, "messages": messages, "stream": True, "max_tokens": 4096, "temperature": 0.7 } try: # استخدام الرابط الجديد router.huggingface.co لتفادي خطأ 410 response = requests.post( f"{self.base_url}/chat/completions", headers=headers, json=payload, stream=True, timeout=120 ) if response.status_code != 200: error_msg = response.json().get('error', 'Unknown Error') yield f"❌ خطأ من الخادم ({response.status_code}): {error_msg}" return for line in response.iter_lines(): if line: # فك تشفير البيانات القادمة من Hugging Face decoded_line = line.decode('utf-8').lstrip('data: ') if decoded_line == '[DONE]': break try: json_data = json.loads(decoded_line) content = json_data['choices'][0]['delta'].get('content', '') if content: yield content except json.JSONDecodeError: continue except requests.exceptions.RequestException as e: yield f"❌ خطأ في الاتصال: {str(e)}"