tahamajs/Sysmem2_in_AI / ComputerAssignments /CA6_systematic_generalization /config /gemini_config.py
tahamajs/Sysmem2_in_AI / ComputerAssignments /CA6_systematic_generalization /config /gemini_config.py
| """ | |
| پیکربندی Gemini API برای Systematic Generalization | |
| Gemini API Configuration for Systematic Generalization | |
| """ | |
| import os | |
| import google.generativeai as genai | |
| from typing import Dict, List, Optional, Any, Union | |
| import json | |
| import logging | |
| from dataclasses import dataclass | |
| from enum import Enum | |
| # تنظیم لاگینگ | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class ModelType(Enum): | |
| """انواع مدلهای Gemini""" | |
| GEMINI_PRO = "gemini-1.5-pro" | |
| GEMINI_FLASH = "gemini-1.5-flash" | |
| GEMINI_PRO_VISION = "gemini-1.5-pro-vision" | |
| class GeminiConfig: | |
| """پیکربندی Gemini API""" | |
| api_key: str | |
| model_name: str = ModelType.GEMINI_PRO.value | |
| temperature: float = 0.7 | |
| max_tokens: int = 2048 | |
| top_p: float = 0.9 | |
| top_k: int = 40 | |
| safety_settings: Optional[Dict] = None | |
| def __post_init__(self): | |
| """تنظیمات پیشفرض امنیتی""" | |
| if self.safety_settings is None: | |
| self.safety_settings = [ | |
| { | |
| "category": "HARM_CATEGORY_HARASSMENT", | |
| "threshold": "BLOCK_MEDIUM_AND_ABOVE", | |
| }, | |
| { | |
| "category": "HARM_CATEGORY_HATE_SPEECH", | |
| "threshold": "BLOCK_MEDIUM_AND_ABOVE", | |
| }, | |
| { | |
| "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", | |
| "threshold": "BLOCK_MEDIUM_AND_ABOVE", | |
| }, | |
| { | |
| "category": "HARM_CATEGORY_DANGEROUS_CONTENT", | |
| "threshold": "BLOCK_MEDIUM_AND_ABOVE", | |
| }, | |
| ] | |
| class GeminiSystematicGeneralization: | |
| """سیستم Systematic Generalization با Gemini API""" | |
| def __init__(self, config: GeminiConfig): | |
| self.config = config | |
| self._setup_gemini() | |
| self.conversation_history = [] | |
| def _setup_gemini(self): | |
| """تنظیم اولیه Gemini API""" | |
| try: | |
| genai.configure(api_key=self.config.api_key) | |
| # تنظیمات مدل | |
| generation_config = { | |
| "temperature": self.config.temperature, | |
| "top_p": self.config.top_p, | |
| "top_k": self.config.top_k, | |
| "max_output_tokens": self.config.max_tokens, | |
| } | |
| self.model = genai.GenerativeModel( | |
| model_name=self.config.model_name, | |
| generation_config=generation_config, | |
| safety_settings=self.config.safety_settings, | |
| ) | |
| logger.info( | |
| f"✅ Gemini API با موفقیت تنظیم شد - مدل: {self.config.model_name}" | |
| ) | |
| except Exception as e: | |
| logger.error(f"❌ خطا در تنظیم Gemini API: {e}") | |
| raise | |
| def generate_systematic_response( | |
| self, | |
| prompt: str, | |
| context: Optional[str] = None, | |
| examples: Optional[List[Dict]] = None, | |
| ) -> Dict[str, Any]: | |
| """ | |
| تولید پاسخ سیستماتیک با استفاده از Gemini | |
| Args: | |
| prompt: متن ورودی | |
| context: متن زمینه (اختیاری) | |
| examples: مثالهای آموزشی (اختیاری) | |
| Returns: | |
| Dict شامل پاسخ و متادیتا | |
| """ | |
| try: | |
| # ساخت prompt کامل | |
| full_prompt = self._construct_systematic_prompt(prompt, context, examples) | |
| # تولید پاسخ | |
| response = self.model.generate_content(full_prompt) | |
| # ذخیره تاریخچه مکالمه | |
| self.conversation_history.append( | |
| { | |
| "prompt": prompt, | |
| "response": response.text, | |
| "timestamp": self._get_timestamp(), | |
| } | |
| ) | |
| return { | |
| "response": response.text, | |
| "prompt_tokens": len(full_prompt.split()), | |
| "response_tokens": len(response.text.split()), | |
| "model": self.config.model_name, | |
| "success": True, | |
| } | |
| except Exception as e: | |
| logger.error(f"❌ خطا در تولید پاسخ: {e}") | |
| return { | |
| "response": f"خطا در تولید پاسخ: {str(e)}", | |
| "success": False, | |
| "error": str(e), | |
| } | |
| def _construct_systematic_prompt( | |
| self, | |
| prompt: str, | |
| context: Optional[str] = None, | |
| examples: Optional[List[Dict]] = None, | |
| ) -> str: | |
| """ساخت prompt سیستماتیک""" | |
| systematic_instructions = """ | |
| شما یک سیستم هوش مصنوعی پیشرفته هستید که در Systematic Generalization تخصص دارید. | |
| Systematic Generalization به معنای توانایی ترکیب و تعمیم سیستماتیک اجزای یادگرفته شده است. | |
| اصول Systematic Generalization: | |
| 1. ترکیبپذیری (Compositionality): معنی عبارات پیچیده از ترکیب معانی اجزای آنها حاصل میشود | |
| 2. تولیدی بودن (Productivity): توانایی تولید ترکیبات نامحدود از اجزای محدود | |
| 3. سیستماتیک بودن (Systematicity): اگر سیستم بتواند یک ترکیب را پردازش کند، باید ترکیبات مرتبط را نیز پردازش کند | |
| لطفاً پاسخهای خود را بر اساس این اصول ارائه دهید. | |
| """ | |
| full_prompt = systematic_instructions | |
| if context: | |
| full_prompt += f"\n\nزمینه (Context):\n{context}" | |
| if examples: | |
| full_prompt += "\n\nمثالهای آموزشی:\n" | |
| for i, example in enumerate(examples, 1): | |
| full_prompt += f"{i}. ورودی: {example.get('input', '')}\n" | |
| full_prompt += f" خروجی: {example.get('output', '')}\n" | |
| if example.get("explanation"): | |
| full_prompt += f" توضیح: {example['explanation']}\n" | |
| full_prompt += f"\n\nسوال/درخواست:\n{prompt}\n\nپاسخ سیستماتیک:" | |
| return full_prompt | |
| def test_compositional_generalization( | |
| self, training_examples: List[Dict], test_cases: List[Dict] | |
| ) -> Dict[str, Any]: | |
| """ | |
| تست توانایی تعمیم ترکیبی | |
| Args: | |
| training_examples: مثالهای آموزشی | |
| test_cases: موارد تست | |
| Returns: | |
| نتایج تست | |
| """ | |
| results = { | |
| "training_examples": len(training_examples), | |
| "test_cases": len(test_cases), | |
| "correct_predictions": 0, | |
| "total_predictions": len(test_cases), | |
| "detailed_results": [], | |
| } | |
| for test_case in test_cases: | |
| # آموزش با مثالها | |
| response = self.generate_systematic_response( | |
| prompt=test_case["input"], examples=training_examples | |
| ) | |
| # ارزیابی پاسخ | |
| predicted_output = response["response"] | |
| expected_output = test_case["expected_output"] | |
| # مقایسه ساده (میتواند پیچیدهتر شود) | |
| is_correct = self._evaluate_prediction(predicted_output, expected_output) | |
| if is_correct: | |
| results["correct_predictions"] += 1 | |
| results["detailed_results"].append( | |
| { | |
| "input": test_case["input"], | |
| "expected": expected_output, | |
| "predicted": predicted_output, | |
| "correct": is_correct, | |
| } | |
| ) | |
| results["accuracy"] = ( | |
| results["correct_predictions"] / results["total_predictions"] | |
| ) | |
| return results | |
| def _evaluate_prediction(self, predicted: str, expected: str) -> bool: | |
| """ارزیابی ساده پیشبینی""" | |
| # حذف فاصلهها و تبدیل به حروف کوچک برای مقایسه | |
| predicted_clean = predicted.lower().strip() | |
| expected_clean = expected.lower().strip() | |
| # بررسی تطبیق کامل یا جزئی | |
| return expected_clean in predicted_clean or predicted_clean in expected_clean | |
| def _get_timestamp(self) -> str: | |
| """دریافت زمان فعلی""" | |
| from datetime import datetime | |
| return datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| def get_conversation_summary(self) -> Dict[str, Any]: | |
| """خلاصه مکالمات""" | |
| return { | |
| "total_conversations": len(self.conversation_history), | |
| "recent_conversations": ( | |
| self.conversation_history[-5:] if self.conversation_history else [] | |
| ), | |
| "model_used": self.config.model_name, | |
| } | |
| class GeminiRAGSystem: | |
| """سیستم RAG با Gemini API""" | |
| def __init__(self, config: GeminiConfig): | |
| self.config = config | |
| self.gemini_system = GeminiSystematicGeneralization(config) | |
| self.knowledge_base = [] | |
| def add_knowledge( | |
| self, documents: List[str], metadata: Optional[List[Dict]] = None | |
| ): | |
| """افزودن دانش به پایگاه دانش""" | |
| for i, doc in enumerate(documents): | |
| doc_info = { | |
| "content": doc, | |
| "metadata": metadata[i] if metadata and i < len(metadata) else {}, | |
| "id": f"doc_{i}", | |
| } | |
| self.knowledge_base.append(doc_info) | |
| logger.info(f"✅ {len(documents)} سند به پایگاه دانش اضافه شد") | |
| def retrieve_relevant_docs(self, query: str, top_k: int = 3) -> List[Dict]: | |
| """بازیابی اسناد مرتبط (ساده)""" | |
| # در پیادهسازی واقعی، از vector database استفاده میشود | |
| relevant_docs = [] | |
| query_lower = query.lower() | |
| for doc in self.knowledge_base: | |
| content_lower = doc["content"].lower() | |
| # محاسبه شباهت ساده | |
| similarity_score = len( | |
| set(query_lower.split()) & set(content_lower.split()) | |
| ) | |
| if similarity_score > 0: | |
| relevant_docs.append({**doc, "similarity_score": similarity_score}) | |
| # مرتبسازی بر اساس شباهت | |
| relevant_docs.sort(key=lambda x: x["similarity_score"], reverse=True) | |
| return relevant_docs[:top_k] | |
| def generate_rag_response(self, query: str) -> Dict[str, Any]: | |
| """تولید پاسخ با RAG""" | |
| # بازیابی اسناد مرتبط | |
| relevant_docs = self.retrieve_relevant_docs(query) | |
| # ساخت context از اسناد بازیابی شده | |
| context = "\n\n".join([doc["content"] for doc in relevant_docs]) | |
| # تولید پاسخ با Gemini | |
| response = self.gemini_system.generate_systematic_response( | |
| prompt=query, context=context | |
| ) | |
| return { | |
| **response, | |
| "retrieved_documents": relevant_docs, | |
| "context_length": len(context), | |
| } | |
| def create_gemini_config_from_env() -> GeminiConfig: | |
| """ایجاد پیکربندی از متغیرهای محیطی""" | |
| api_key = os.getenv("GEMINI_API_KEY") | |
| if not api_key: | |
| raise ValueError("متغیر محیطی GEMINI_API_KEY تنظیم نشده است") | |
| model_name = os.getenv("GEMINI_MODEL", ModelType.GEMINI_PRO.value) | |
| temperature = float(os.getenv("GEMINI_TEMPERATURE", "0.7")) | |
| return GeminiConfig(api_key=api_key, model_name=model_name, temperature=temperature) | |
| # مثال استفاده | |
| if __name__ == "__main__": | |
| # تنظیم API key (در محیط واقعی از متغیر محیطی استفاده کنید) | |
| config = GeminiConfig( | |
| api_key="your-gemini-api-key-here", | |
| model_name=ModelType.GEMINI_PRO.value, | |
| temperature=0.7, | |
| ) | |
| # ایجاد سیستم | |
| gemini_system = GeminiSystematicGeneralization(config) | |
| # تست ساده | |
| response = gemini_system.generate_systematic_response( | |
| prompt="چگونه میتوانم مفهوم ترکیبپذیری را در هوش مصنوعی پیادهسازی کنم؟" | |
| ) | |
| print("پاسخ Gemini:") | |
| print(response["response"]) | |
Xet Storage Details
- Size:
- 12.6 kB
- Xet hash:
- 84ac93240adf4da852c6a75203a1c3f49d3e03005ebe5d19704a6a13ecfdc861
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.