Genisi / backend /services.py
AnesKAM's picture
Create services.py
87ebc19 verified
import os
from google import genai
from google.genai import types
class GeminiService:
def __init__(self, api_key: str):
self.client = genai.Client(api_key=api_key)
self.model = "gemma-4-31b-it"
def generate_stream(self, message: str, context: list, language: str = 'en') -> str:
"""توليد الرد مع الستريمينج"""
# بناء السياق
contents = self._build_contents(message, context)
# تحديد اللغة في التعليمات
system_instruction = self._get_system_instruction(language)
try:
full_response = ""
for chunk in self.client.models.generate_content_stream(
model=self.model,
contents=contents,
config=types.GenerateContentConfig(
temperature=1.0,
thinking_config=types.ThinkingConfig(
thinking_level="MINIMAL",
),
media_resolution="MEDIA_RESOLUTION_HIGH",
tools=[
types.Tool(googleSearch=types.GoogleSearch())
],
system_instruction=[
types.Part.from_text(text=system_instruction),
],
),
):
if text := chunk.text:
full_response += text
return full_response
except Exception as e:
raise Exception(f"خطأ في توليد الرد: {str(e)}")
def _build_contents(self, message: str, context: list) -> list:
"""بناء محتوى الرسائل مع السياق"""
contents = []
# إضافة الرسائل السابقة كسياق
for msg in context:
contents.append(
types.Content(
role="user" if msg['role'] == 'user' else "model",
parts=[types.Part.from_text(text=msg['content'])],
)
)
# إضافة الرسالة الحالية
contents.append(
types.Content(
role="user",
parts=[types.Part.from_text(text=message)],
)
)
return contents
def _get_system_instruction(self, language: str) -> str:
"""الحصول على تعليمات النظام بناءً على اللغة"""
instructions = {
'en': """You are Genisi, an advanced AI model developed by AnesNT.
AnesNT is an Algerian initiative from the city of Batna created by Anes Kameche. It is currently the only member of this technological initiative.
Be helpful and friendly to the user. Always respond in the user's language. Provide clear, concise, and accurate information.""",
'ar': """أنت Genisi نموذج ذكاء اصطناعي متطور من قبل AnesNT.
AnesNT مبادرة جزائرية من ولاية باتنة صاحبها انس كامش. وهو حاليا العضو الوحيد في هذي المبادرة وهي مبادرة ت��نولوجية.
كن مفيدا وصديقا للمستخدم. تحدث باللغة التي يتحدثها المستخدم. قدم معلومات واضحة ودقيقة.""",
'fr': """Vous êtes Genisi, un modèle d'IA avancé développé par AnesNT.
AnesNT est une initiative algérienne de la ville de Batna créée par Anes Kameche. C'est actuellement le seul membre de cette initiative technologique.
Soyez utile et amical envers l'utilisateur. Répondez toujours dans la langue de l'utilisateur. Fournissez des informations claires et précises.""",
'es': """Eres Genisi, un modelo de IA avanzado desarrollado por AnesNT.
AnesNT es una iniciativa argelina de la ciudad de Batna creada por Anes Kameche. Actualmente es el único miembro de esta iniciativa tecnológica.
Sea útil y amable con el usuario. Responda siempre en el idioma del usuario. Proporcione información clara y precisa.""",
'de': """Sie sind Genisi, ein fortschrittliches KI-Modell, das von AnesNT entwickelt wurde.
AnesNT ist eine algerische Initiative aus der Stadt Batna, die von Anes Kameche ins Leben gerufen wurde. Es ist derzeit das einzige Mitglied dieser technologischen Initiative.
Seien Sie hilfreich und freundlich zum Benutzer. Antworten Sie immer in der Sprache des Benutzers. Geben Sie klare und genaue Informationen."""
}
return instructions.get(language, instructions['en'])