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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import aiohttp
|
| 4 |
+
import asyncio
|
| 5 |
+
from typing import Dict, List, Optional, Any
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import numpy as np
|
| 8 |
+
from openai import AsyncOpenAI
|
| 9 |
+
from pydantic import BaseModel
|
| 10 |
+
import logging
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
# Configure logging
|
| 14 |
+
logging.basicConfig(level=logging.INFO)
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
class AdvancedMCPTools:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.memory_file = "agent_memory.json"
|
| 20 |
+
self.knowledge_base = {}
|
| 21 |
+
self.load_memory()
|
| 22 |
+
|
| 23 |
+
# Initialize OpenAI client if API key is available
|
| 24 |
+
self.openai_client = None
|
| 25 |
+
if os.getenv('OPENAI_API_KEY'):
|
| 26 |
+
self.openai_client = AsyncOpenAI(api_key=os.getenv('OPENAI_API_KEY'))
|
| 27 |
+
|
| 28 |
+
# ========== Memory Management ==========
|
| 29 |
+
|
| 30 |
+
def load_memory(self):
|
| 31 |
+
"""Load agent's memory from file"""
|
| 32 |
+
try:
|
| 33 |
+
if os.path.exists(self.memory_file):
|
| 34 |
+
with open(self.memory_file, 'r', encoding='utf-8') as f:
|
| 35 |
+
self.knowledge_base = json.load(f)
|
| 36 |
+
logger.info(f"Loaded memory with {len(self.knowledge_base)} entries")
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.error(f"Error loading memory: {e}")
|
| 39 |
+
self.knowledge_base = {}
|
| 40 |
+
|
| 41 |
+
async def save_memory(self):
|
| 42 |
+
"""Save agent's memory to file"""
|
| 43 |
+
try:
|
| 44 |
+
with open(self.memory_file, 'w', encoding='utf-8') as f:
|
| 45 |
+
json.dump(self.knowledge_base, f, ensure_ascii=False, indent=2)
|
| 46 |
+
return {"status": "success", "message": "Memory saved successfully"}
|
| 47 |
+
except Exception as e:
|
| 48 |
+
logger.error(f"Error saving memory: {e}")
|
| 49 |
+
return {"status": "error", "message": str(e)}
|
| 50 |
+
|
| 51 |
+
async def remember(self, key: str, value: Any, metadata: Optional[Dict] = None) -> Dict:
|
| 52 |
+
"""Store information in the agent's memory"""
|
| 53 |
+
try:
|
| 54 |
+
self.knowledge_base[key] = {
|
| 55 |
+
"value": value,
|
| 56 |
+
"timestamp": datetime.now().isoformat(),
|
| 57 |
+
"metadata": metadata or {}
|
| 58 |
+
}
|
| 59 |
+
await self.save_memory()
|
| 60 |
+
return {"status": "success", "message": "Information stored in memory"}
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return {"status": "error", "message": str(e)}
|
| 63 |
+
|
| 64 |
+
async def recall(self, key: str) -> Dict:
|
| 65 |
+
"""Retrieve information from the agent's memory"""
|
| 66 |
+
try:
|
| 67 |
+
if key in self.knowledge_base:
|
| 68 |
+
return {
|
| 69 |
+
"status": "success",
|
| 70 |
+
"key": key,
|
| 71 |
+
"data": self.knowledge_base[key]
|
| 72 |
+
}
|
| 73 |
+
return {"status": "not_found", "message": "Key not found in memory"}
|
| 74 |
+
except Exception as e:
|
| 75 |
+
return {"status": "error", "message": str(e)}
|
| 76 |
+
|
| 77 |
+
# ========== Advanced Tools ==========
|
| 78 |
+
|
| 79 |
+
async def analyze_sentiment(self, text: str) -> Dict:
|
| 80 |
+
"""Analyze sentiment of the given text"""
|
| 81 |
+
if not self.openai_client:
|
| 82 |
+
return {"error": "OpenAI API key not configured"}
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
response = await self.openai_client.chat.completions.create(
|
| 86 |
+
model="gpt-3.5-turbo",
|
| 87 |
+
messages=[
|
| 88 |
+
{"role": "system", "content": "You are a sentiment analysis tool. Respond with a single word: 'positive', 'negative', or 'neutral'."},
|
| 89 |
+
{"role": "user", "content": f"Analyze the sentiment of this text: {text}"}
|
| 90 |
+
],
|
| 91 |
+
max_tokens=10,
|
| 92 |
+
temperature=0
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
sentiment = response.choices[0].message.content.strip().lower()
|
| 96 |
+
return {"sentiment": sentiment, "text": text}
|
| 97 |
+
except Exception as e:
|
| 98 |
+
return {"error": str(e)}
|
| 99 |
+
|
| 100 |
+
async def get_news(self, query: str, language: str = "ar", region: str = "eg", max_results: int = 5) -> List[Dict]:
|
| 101 |
+
"""Get news articles based on a query"""
|
| 102 |
+
try:
|
| 103 |
+
async with aiohttp.ClientSession() as session:
|
| 104 |
+
url = f"https://news.google.com/rss/search"
|
| 105 |
+
params = {
|
| 106 |
+
"q": query,
|
| 107 |
+
"hl": language,
|
| 108 |
+
"gl": region.upper(),
|
| 109 |
+
"ceid": f"{region}:{language}"
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
async with session.get(url, params=params) as response:
|
| 113 |
+
if response.status != 200:
|
| 114 |
+
return [{"error": f"Failed to fetch news: {response.status}"}]
|
| 115 |
+
|
| 116 |
+
from bs4 import BeautifulSoup
|
| 117 |
+
import feedparser
|
| 118 |
+
|
| 119 |
+
feed = feedparser.parse(await response.text())
|
| 120 |
+
articles = []
|
| 121 |
+
|
| 122 |
+
for entry in feed.entries[:max_results]:
|
| 123 |
+
articles.append({
|
| 124 |
+
"title": entry.title,
|
| 125 |
+
"link": entry.link,
|
| 126 |
+
"published": entry.published,
|
| 127 |
+
"source": entry.source.title if hasattr(entry, 'source') else "Unknown"
|
| 128 |
+
})
|
| 129 |
+
|
| 130 |
+
return articles
|
| 131 |
+
except Exception as e:
|
| 132 |
+
return [{"error": str(e)}]
|
| 133 |
+
|
| 134 |
+
async def generate_image(self, prompt: str, size: str = "1024x1024", quality: str = "standard") -> Dict:
|
| 135 |
+
"""Generate an image using DALL-E"""
|
| 136 |
+
if not self.openai_client:
|
| 137 |
+
return {"error": "OpenAI API key not configured"}
|
| 138 |
+
|
| 139 |
+
try:
|
| 140 |
+
response = await self.openai_client.images.generate(
|
| 141 |
+
model="dall-e-3",
|
| 142 |
+
prompt=prompt,
|
| 143 |
+
size=size,
|
| 144 |
+
quality=quality,
|
| 145 |
+
n=1,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
return {
|
| 149 |
+
"status": "success",
|
| 150 |
+
"url": response.data[0].url,
|
| 151 |
+
"revised_prompt": response.data[0].revised_prompt
|
| 152 |
+
}
|
| 153 |
+
except Exception as e:
|
| 154 |
+
return {"error": str(e)}
|
| 155 |
+
|
| 156 |
+
async def analyze_image(self, image_url: str) -> Dict:
|
| 157 |
+
"""Analyze an image (requires GPT-4 Vision)"""
|
| 158 |
+
if not self.openai_client:
|
| 159 |
+
return {"error": "OpenAI API key not configured"}
|
| 160 |
+
|
| 161 |
+
try:
|
| 162 |
+
response = await self.openai_client.chat.completions.create(
|
| 163 |
+
model="gpt-4-vision-preview",
|
| 164 |
+
messages=[
|
| 165 |
+
{
|
| 166 |
+
"role": "user",
|
| 167 |
+
"content": [
|
| 168 |
+
{"type": "text", "text": "Describe this image in detail."},
|
| 169 |
+
{
|
| 170 |
+
"type": "image_url",
|
| 171 |
+
"image_url": {"url": image_url},
|
| 172 |
+
},
|
| 173 |
+
],
|
| 174 |
+
}
|
| 175 |
+
],
|
| 176 |
+
max_tokens=300,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
return {
|
| 180 |
+
"status": "success",
|
| 181 |
+
"analysis": response.choices[0].message.content
|
| 182 |
+
}
|
| 183 |
+
except Exception as e:
|
| 184 |
+
return {"error": str(e)}
|
| 185 |
+
|
| 186 |
+
# ========== Knowledge Graph ==========
|
| 187 |
+
|
| 188 |
+
async def add_to_knowledge_graph(self, entity: str, relation: str, target: str) -> Dict:
|
| 189 |
+
"""Add a relationship to the knowledge graph"""
|
| 190 |
+
try:
|
| 191 |
+
if "knowledge_graph" not in self.knowledge_base:
|
| 192 |
+
self.knowledge_base["knowledge_graph"] = {}
|
| 193 |
+
|
| 194 |
+
if entity not in self.knowledge_base["knowledge_graph"]:
|
| 195 |
+
self.knowledge_base["knowledge_graph"][entity] = {}
|
| 196 |
+
|
| 197 |
+
if relation not in self.knowledge_base["knowledge_graph"][entity]:
|
| 198 |
+
self.knowledge_base["knowledge_graph"][entity][relation] = []
|
| 199 |
+
|
| 200 |
+
self.knowledge_base["knowledge_graph"][entity][relation].append({
|
| 201 |
+
"target": target,
|
| 202 |
+
"timestamp": datetime.now().isoformat()
|
| 203 |
+
})
|
| 204 |
+
|
| 205 |
+
await self.save_memory()
|
| 206 |
+
return {"status": "success", "message": "Added to knowledge graph"}
|
| 207 |
+
except Exception as e:
|
| 208 |
+
return {"status": "error", "message": str(e)}
|
| 209 |
+
|
| 210 |
+
async def query_knowledge_graph(self, entity: str, relation: Optional[str] = None) -> Dict:
|
| 211 |
+
"""Query the knowledge graph"""
|
| 212 |
+
try:
|
| 213 |
+
if "knowledge_graph" not in self.knowledge_base:
|
| 214 |
+
return {"status": "not_found", "message": "Knowledge graph is empty"}
|
| 215 |
+
|
| 216 |
+
if entity not in self.knowledge_base["knowledge_graph"]:
|
| 217 |
+
return {"status": "not_found", "message": f"Entity '{entity}' not found"}
|
| 218 |
+
|
| 219 |
+
if relation:
|
| 220 |
+
if relation in self.knowledge_base["knowledge_graph"][entity]:
|
| 221 |
+
return {
|
| 222 |
+
"status": "success",
|
| 223 |
+
"entity": entity,
|
| 224 |
+
"relation": relation,
|
| 225 |
+
"results": self.knowledge_base["knowledge_graph"][entity][relation]
|
| 226 |
+
}
|
| 227 |
+
else:
|
| 228 |
+
return {"status": "not_found", "message": f"Relation '{relation}' not found for entity '{entity}'"}
|
| 229 |
+
else:
|
| 230 |
+
return {
|
| 231 |
+
"status": "success",
|
| 232 |
+
"entity": entity,
|
| 233 |
+
"relations": self.knowledge_base["knowledge_graph"][entity]
|
| 234 |
+
}
|
| 235 |
+
except Exception as e:
|
| 236 |
+
return {"status": "error", "message": str(e)}
|
| 237 |
+
|
| 238 |
+
# Example usage
|
| 239 |
+
async def example_usage():
|
| 240 |
+
tools = AdvancedMCPTools()
|
| 241 |
+
|
| 242 |
+
# Example: Remember something
|
| 243 |
+
await tools.remember("user_preference", {"theme": "dark", "language": "ar"})
|
| 244 |
+
|
| 245 |
+
# Example: Recall from memory
|
| 246 |
+
memory = await tools.recall("user_preference")
|
| 247 |
+
print("Memory recall:", memory)
|
| 248 |
+
|
| 249 |
+
# Example: Analyze sentiment
|
| 250 |
+
sentiment = await tools.analyze_sentiment("أنا سعيد جداً بهذا الإنجاز ال��ائع!")
|
| 251 |
+
print("Sentiment analysis:", sentiment)
|
| 252 |
+
|
| 253 |
+
# Example: Get news
|
| 254 |
+
news = await tools.get_news("الذكاء الاصطناعي", max_results=3)
|
| 255 |
+
print("Latest AI news:", news)
|
| 256 |
+
|
| 257 |
+
if __name__ == "__main__":
|
| 258 |
+
import asyncio
|
| 259 |
+
asyncio.run(example_usage())
|