Skip to content

Commit 5eb09fb

Browse files
authored
add agent module for AI-DATA (#4373)
1 parent faaa3f3 commit 5eb09fb

File tree

6 files changed

+586
-0
lines changed

6 files changed

+586
-0
lines changed

.DS_Store

0 Bytes
Binary file not shown.

Agent_module/Agent_Demo.python

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
async def demo_single_agents():
2+
"""Demo individual agents"""
3+
print("=== Single Agent Demo ===\n")
4+
5+
# Create agents
6+
echo_agent = EchoAgent()
7+
calculator_agent = CalculatorAgent()
8+
weather_agent = WeatherAgent()
9+
translator_agent = TranslatorAgent()
10+
chat_agent = ChatAgent()
11+
12+
# Test echo agent
13+
print("1. Testing Echo Agent:")
14+
response = await echo_agent.process(AgentMessage(
15+
content="Hello, world!",
16+
sender="User",
17+
timestamp=time.time()
18+
))
19+
print(f"Input: Hello, world!")
20+
print(f"Output: {response.content}\n")
21+
22+
# Test calculator agent
23+
print("2. Testing Calculator Agent:")
24+
response = await calculator_agent.process(AgentMessage(
25+
content="(15 + 25) * 2",
26+
sender="User",
27+
timestamp=time.time()
28+
))
29+
print(f"Input: (15 + 25) * 2")
30+
print(f"Output: {response.content}\n")
31+
32+
# Test weather agent
33+
print("3. Testing Weather Agent:")
34+
response = await weather_agent.process(AgentMessage(
35+
content="Tokyo",
36+
sender="User",
37+
timestamp=time.time()
38+
))
39+
print(f"Input: Tokyo")
40+
print(f"Output: {response.content}\n")
41+
42+
# Test translator agent
43+
print("4. Testing Translator Agent:")
44+
response = await translator_agent.process(AgentMessage(
45+
content="Hello, how are you?",
46+
sender="User",
47+
timestamp=time.time(),
48+
metadata={"target_language": "french"}
49+
))
50+
print(f"Input: Hello, how are you? (to French)")
51+
print(f"Output: {response.content}\n")
52+
53+
# Test chat agent
54+
print("5. Testing Chat Agent:")
55+
response = await chat_agent.process(AgentMessage(
56+
content="Hello! What can you do?",
57+
sender="User",
58+
timestamp=time.time()
59+
))
60+
print(f"Input: Hello! What can you do?")
61+
print(f"Output: {response.content}\n")
62+
63+
async def demo_agent_system():
64+
"""Demo the complete agent system"""
65+
print("\n=== Agent System Demo ===\n")
66+
67+
# Create agent manager and register agents
68+
manager = AgentManager()
69+
70+
manager.register_agent(EchoAgent())
71+
manager.register_agent(CalculatorAgent())
72+
manager.register_agent(WeatherAgent())
73+
manager.register_agent(TranslatorAgent())
74+
manager.register_agent(ChatAgent())
75+
76+
print(f"Registered {len(manager.agents)} agents:")
77+
for agent_name in manager.agents.keys():
78+
print(f" - {agent_name}")
79+
80+
# Test individual agent communication
81+
print("\n1. Testing Calculator Agent through Manager:")
82+
response = await manager.send_message("CalculatorAgent", "45 + 17 * 3")
83+
print(f"Response: {response.content}")
84+
85+
print("\n2. Testing Weather Agent through Manager:")
86+
response = await manager.send_message("WeatherAgent", "London")
87+
print(f"Response: {response.content}")
88+
89+
print("\n3. Testing Broadcast Message:")
90+
responses = await manager.broadcast_message("Hello everyone!")
91+
print("Broadcast responses:")
92+
for agent_name, response in responses.items():
93+
print(f" {agent_name}: {response.content[:50]}...")
94+
95+
# Demonstrate agent discovery
96+
print("\n4. Agent Discovery:")
97+
math_agents = manager.find_agent_by_capability("calculation")
98+
print(f"Agents for calculations: {math_agents}")
99+
100+
weather_agents = manager.find_agent_by_capability("weather")
101+
print(f"Agents for weather: {weather_agents}")
102+
103+
# Show system statistics
104+
print("\n5. System Statistics:")
105+
stats = manager.get_system_stats()
106+
for key, value in stats.items():
107+
print(f" {key}: {value}")
108+
109+
async def interactive_demo():
110+
"""Interactive demo where users can talk to agents"""
111+
print("\n=== Interactive Demo ===\n")
112+
113+
manager = AgentManager()
114+
manager.register_agent(ChatAgent())
115+
manager.register_agent(CalculatorAgent())
116+
manager.register_agent(WeatherAgent())
117+
manager.register_agent(TranslatorAgent())
118+
119+
print("Available agents: ChatAgent, CalculatorAgent, WeatherAgent, TranslatorAgent")
120+
print("Type 'quit' to exit, 'help' for commands, 'agents' to list agents\n")
121+
122+
while True:
123+
try:
124+
user_input = input("You: ").strip()
125+
126+
if user_input.lower() in ['quit', 'exit']:
127+
break
128+
elif user_input.lower() == 'help':
129+
print("\nAvailable commands:")
130+
print(" 'calc [expression]' - Use calculator")
131+
print(" 'weather [city]' - Get weather")
132+
print(" 'translate [text] to [language]' - Translate text")
133+
print(" 'agents' - List all agents")
134+
print(" 'stats' - Show system statistics")
135+
print(" 'quit' - Exit\n")
136+
continue
137+
elif user_input.lower() == 'agents':
138+
print("\nRegistered agents:")
139+
for name, agent in manager.agents.items():
140+
print(f" {name}: {agent.description}")
141+
print()
142+
continue
143+
elif user_input.lower() == 'stats':
144+
stats = manager.get_system_stats()
145+
print("\nSystem Statistics:")
146+
for key, value in stats.items():
147+
print(f" {key}: {value}")
148+
print()
149+
continue
150+
151+
# Route to appropriate agent based on input
152+
if user_input.startswith('calc '):
153+
expression = user_input[5:]
154+
response = await manager.send_message("CalculatorAgent", expression)
155+
print(f"Calculator: {response.content}\n")
156+
157+
elif user_input.startswith('weather '):
158+
city = user_input[8:]
159+
response = await manager.send_message("WeatherAgent", city)
160+
print(f"Weather: {response.content}\n")
161+
162+
elif user_input.startswith('translate '):
163+
# Simple parsing for translation commands
164+
parts = user_input[10:].split(' to ')
165+
if len(parts) == 2:
166+
text, language = parts
167+
response = await manager.send_message(
168+
"TranslatorAgent",
169+
text,
170+
{"target_language": language.strip()}
171+
)
172+
print(f"Translator: {response.content}\n")
173+
else:
174+
print("Usage: translate [text] to [language]\n")
175+
176+
else:
177+
# Default to chat agent
178+
response = await manager.send_message("ChatAgent", user_input)
179+
print(f"ChatAgent: {response.content}\n")
180+
181+
except KeyboardInterrupt:
182+
break
183+
except Exception as e:
184+
print(f"Error: {e}\n")
185+
186+
if __name__ == "__main__":
187+
# Run demos
188+
asyncio.run(demo_single_agents())
189+
asyncio.run(demo_agent_system())

Agent_module/Chat_Agent.python

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
class ChatAgent(BaseAgent):
2+
"""Intelligent chat agent with context awareness"""
3+
4+
def __init__(self, name: str = "ChatAgent"):
5+
super().__init__(name, "Intelligent conversational agent")
6+
self.context = {}
7+
self.personality_traits = [
8+
"friendly", "helpful", "knowledgeable", "enthusiastic"
9+
]
10+
11+
async def _process_impl(self, message: AgentMessage) -> AgentMessage:
12+
user_input = str(message.content).lower()
13+
user_id = message.metadata.get("user_id", "unknown")
14+
15+
# Update context
16+
if user_id not in self.context:
17+
self.context[user_id] = {
18+
"conversation_count": 0,
19+
"last_interaction": time.time(),
20+
"topics": set()
21+
}
22+
23+
self.context[user_id]["conversation_count"] += 1
24+
self.context[user_id]["last_interaction"] = time.time()
25+
26+
# Simple intent recognition
27+
response = await self._generate_response(user_input, user_id)
28+
29+
return AgentMessage(
30+
content=response,
31+
sender=self.name,
32+
timestamp=time.time(),
33+
message_type="chat_response",
34+
metadata={"user_context": self.context[user_id]}
35+
)
36+
37+
async def _generate_response(self, user_input: str, user_id: str) -> str:
38+
"""Generate context-aware responses"""
39+
40+
# Greeting detection
41+
if any(word in user_input for word in ["hello", "hi", "hey", "greetings"]):
42+
return random.choice([
43+
"Hello! How can I assist you today?",
44+
"Hi there! What can I help you with?",
45+
"Greetings! I'm here to help.",
46+
"Hello! Nice to meet you."
47+
])
48+
49+
# Question detection
50+
elif "?" in user_input or any(word in user_input for word in ["what", "how", "when", "where", "why"]):
51+
return await self._answer_question(user_input)
52+
53+
# Weather inquiry
54+
elif "weather" in user_input:
55+
return "I can help with weather information! Please use the WeatherAgent for accurate weather data."
56+
57+
# Calculation request
58+
elif any(word in user_input for word in ["calculate", "math", "equation"]):
59+
return "I can help with calculations! Try using the CalculatorAgent for mathematical operations."
60+
61+
# Translation request
62+
elif any(word in user_input for word in ["translate", "translation"]):
63+
return "I can assist with translations! The TranslatorAgent specializes in language translation."
64+
65+
# Default response
66+
else:
67+
return random.choice([
68+
"That's interesting! Can you tell me more?",
69+
"I understand. How can I help you with that?",
70+
"Thanks for sharing! Is there anything specific you'd like to know?",
71+
"I see. What would you like to do next?"
72+
])
73+
74+
async def _answer_question(self, question: str) -> str:
75+
"""Answer general knowledge questions"""
76+
question_lower = question.lower()
77+
78+
if "time" in question_lower:
79+
return f"The current time is {time.strftime('%H:%M:%S')}"
80+
81+
elif "date" in question_lower:
82+
return f"Today's date is {time.strftime('%Y-%m-%d')}"
83+
84+
elif "name" in question_lower:
85+
return "I'm ChatAgent, your friendly AI assistant!"
86+
87+
elif "purpose" in question_lower or "what can you do" in question_lower:
88+
return "I can chat with you, answer questions, and coordinate with other specialized agents for weather, calculations, translations, and more!"
89+
90+
else:
91+
responses = [
92+
"That's a good question! Let me think about it...",
93+
"I'm not entirely sure about that, but I'd be happy to help you find out!",
94+
"Interesting question! Here's what I know about that topic...",
95+
"I understand your curiosity about that subject."
96+
]
97+
return random.choice(responses)

Agent_module/Framework.python

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import asyncio
2+
import time
3+
from abc import ABC, abstractmethod
4+
from typing import Any, Dict, List, Optional, Callable
5+
from dataclasses import dataclass
6+
from enum import Enum
7+
import random
8+
import json
9+
10+
class AgentStatus(Enum):
11+
IDLE = "idle"
12+
PROCESSING = "processing"
13+
ERROR = "error"
14+
STOPPED = "stopped"
15+
16+
@dataclass
17+
class AgentMessage:
18+
content: Any
19+
sender: str
20+
timestamp: float
21+
message_type: str = "text"
22+
metadata: Dict[str, Any] = None
23+
24+
def __post_init__(self):
25+
if self.metadata is None:
26+
self.metadata = {}
27+
self.timestamp = self.timestamp or time.time()
28+
29+
class BaseAgent(ABC):
30+
"""Base class for all agents"""
31+
32+
def __init__(self, name: str, description: str = ""):
33+
self.name = name
34+
self.description = description
35+
self.status = AgentStatus.IDLE
36+
self.message_history: List[AgentMessage] = []
37+
self._callbacks: List[Callable] = []
38+
39+
async def process(self, message: AgentMessage) -> AgentMessage:
40+
"""Process a message and return response"""
41+
self.status = AgentStatus.PROCESSING
42+
self.message_history.append(message)
43+
44+
try:
45+
result = await self._process_impl(message)
46+
self.status = AgentStatus.IDLE
47+
self._notify_callbacks(message, result)
48+
return result
49+
except Exception as e:
50+
self.status = AgentStatus.ERROR
51+
error_msg = AgentMessage(
52+
content=f"Error: {str(e)}",
53+
sender=self.name,
54+
timestamp=time.time(),
55+
message_type="error"
56+
)
57+
return error_msg
58+
59+
@abstractmethod
60+
async def _process_impl(self, message: AgentMessage) -> AgentMessage:
61+
"""Agent-specific processing logic"""
62+
pass
63+
64+
def add_callback(self, callback: Callable):
65+
"""Add callback for message processing events"""
66+
self._callbacks.append(callback)
67+
68+
def _notify_callbacks(self, input_msg: AgentMessage, output_msg: AgentMessage):
69+
"""Notify all callbacks"""
70+
for callback in self._callbacks:
71+
try:
72+
callback(input_msg, output_msg)
73+
except Exception:
74+
pass # Don't break agent if callback fails
75+
76+
def get_recent_messages(self, count: int = 10) -> List[AgentMessage]:
77+
"""Get recent message history"""
78+
return self.message_history[-count:]

0 commit comments

Comments
 (0)