-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
183 lines (153 loc) ยท 6.74 KB
/
agent.py
File metadata and controls
183 lines (153 loc) ยท 6.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
from datetime import datetime, timezone
from uuid import uuid4
from typing import Any, Dict
import json
import os
import shutil
import asyncio
from dotenv import load_dotenv
from uagents import Context, Model, Protocol, Agent
from hyperon import MeTTa
env_path = os.path.join(os.path.dirname(__file__), '.env')
env_loaded = load_dotenv(env_path)
from uagents_core.contrib.protocols.chat import (
ChatAcknowledgement,
ChatMessage,
EndSessionContent,
StartSessionContent,
TextContent,
chat_protocol_spec,
)
from metta.investment_rag import InvestmentRAG
from metta.knowledge import initialize_investment_knowledge
from metta.utils import LLM, process_query
from metta.scheduler import ScheduledTaskManager
from metta.email_service import email_service
from metta.stock_monitor import stock_monitor
agent = Agent(name="Semiconductor Market Intelligence Agent", port=8008, mailbox=True, publish_agent_details=True, readme_path = "README.md")
class InvestmentQuery(Model):
query: str
intent: str
keyword: str
def create_text_chat(text: str, end_session: bool = False) -> ChatMessage:
content = [TextContent(type="text", text=text)]
if end_session:
content.append(EndSessionContent(type="end-session"))
return ChatMessage(
timestamp=datetime.now(timezone.utc),
msg_id=uuid4(),
content=content,
)
# Initialize core components
metta = MeTTa()
initialize_investment_knowledge(metta)
rag = InvestmentRAG(metta)
llm = LLM(api_key=os.getenv("ASI_ONE_API_KEY"))
# Initialize scheduled task manager
task_manager = ScheduledTaskManager(rag, llm)
chat_proto = Protocol(spec=chat_protocol_spec)
@chat_proto.on_message(ChatMessage)
async def handle_message(ctx: Context, sender: str, msg: ChatMessage):
ctx.storage.set(str(ctx.session), sender)
await ctx.send(
sender,
ChatAcknowledgement(timestamp=datetime.now(timezone.utc), acknowledged_msg_id=msg.msg_id),
)
terminal_width = shutil.get_terminal_size().columns
separator = "=" * terminal_width
dash_line = "-" * terminal_width
for item in msg.content:
if isinstance(item, StartSessionContent):
ctx.logger.info(f"Got a start session message from {sender}")
print(f"\n{separator}")
print("๐ NEW SESSION STARTED")
print(f"๐ง From: {sender}")
print(f"{separator}\n")
continue
elif isinstance(item, TextContent):
user_query = item.text.strip()
ctx.logger.info(f"Got a semiconductor market query from {sender}: {user_query}")
print(f"\n{separator}")
print("๐ฉ NEW REQUEST RECEIVED")
print(separator)
print(f"๐ค From: {sender}")
print(f"โ Query: {user_query}")
print(f"โฐ Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(dash_line)
try:
print("๐ Processing query...")
response = process_query(user_query, rag, llm)
print("\nโ
RESPONSE GENERATED")
print(dash_line)
if isinstance(response, dict):
selected_q = response.get('selected_question', user_query)
answer = response.get('humanized_answer', 'I apologize, but I could not process your query.')
print(f"๐ Question: {selected_q}")
print(f"\n๐ก Answer:\n{answer}")
# Use raw response directly without formatting
answer_text = f"๐น {selected_q}\n\n{answer}"
else:
# Use raw response directly without formatting
answer_text = str(response)
print(f"๐ก Response:\n{answer_text}")
print(dash_line)
print("โ๏ธ Sending response to user...")
await ctx.send(sender, create_text_chat(answer_text))
print("โ
Response sent successfully!")
print(f"{separator}\n")
except Exception as e:
ctx.logger.error(f"Error processing semiconductor market query: {e}")
print("\nโ ERROR OCCURRED")
print(dash_line)
print(f"โ ๏ธ Error: {str(e)}")
print(dash_line)
await ctx.send(
sender,
create_text_chat("I apologize, but I encountered an error processing your semiconductor market query. Please try again.")
)
print("โ๏ธ Error message sent to user")
print(f"{separator}\n")
else:
ctx.logger.info(f"Got unexpected content from {sender}")
print(f"โ ๏ธ Unexpected content type from {sender}")
@chat_proto.on_message(ChatAcknowledgement)
async def handle_ack(ctx: Context, sender: str, msg: ChatAcknowledgement):
ctx.logger.info(f"Got an acknowledgement from {sender} for {msg.acknowledged_msg_id}")
@agent.on_event("startup")
async def startup(ctx: Context):
"""Initialization when the agent starts"""
print("\n" + "="*60)
print("๐ SEMICONDUCTOR MARKET INTELLIGENCE AGENT")
print("="*60)
print(f"๐ค Agent Name: {agent.name}")
print(f"๐ Agent Address: {agent.address}")
print("="*60)
# Check email configuration
if email_service.email_user and email_service.email_password and email_service.recipient_email:
print("๐ง Email service: โ
Configured")
print(f"๐จ Reports will be sent to: {email_service.recipient_email}")
# Send startup notification email
print("๐ฎ Sending startup notification email...")
startup_success = email_service.send_startup_notification()
if startup_success:
print("โ
Startup notification email sent successfully!")
else:
print("โ Failed to send startup notification email")
else:
print("๐ง Email service: โ ๏ธ Not configured")
print(" Set EMAIL_USER, EMAIL_PASSWORD, RECIPIENT_EMAIL in .env file")
# Start scheduled task manager
print("\n๐
Starting scheduled task manager...")
task_manager.start()
print("\nโ
Agent startup complete!")
print("๐ฌ Ready to receive queries via Agentverse chat interface")
print("="*60 + "\n")
@agent.on_event("shutdown")
async def shutdown(ctx: Context):
"""Cleanup when the agent shuts down"""
print("\nโธ๏ธ Shutting down Semiconductor Market Intelligence Agent...")
task_manager.stop()
print("โ
Shutdown complete")
agent.include(chat_proto, publish_manifest=True)
if __name__ == "__main__":
agent.run()