-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
303 lines (258 loc) · 11.4 KB
/
core.py
File metadata and controls
303 lines (258 loc) · 11.4 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""
Core module for Artemis AI assistant.
Coordinates agent execution, builds the message array, and streams responses.
"""
import asyncio
import datetime
import json
import random
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple
import _config
from agents.Agent import Agent
from agents.FileReader import FileReaderAgent
from agents.LangDetect import DetectLanguageAgent
from agents.News import DailyStoriesAgent
from agents.OnlineSearch import OnlineSearchAgent
from agents.PersonalInfo import PersonalInfoAgent
from agents.ReadURLs import URLReaderAgent
from llms.LLMInterface import LLMInterface
class ArtemisCore:
"""
Engine for Artemis: agent lifecycle, context assembly, response streaming.
"""
AGENT_REGISTRY: List[Tuple[type, str]] = [
(PersonalInfoAgent, "Personal Info"),
(DetectLanguageAgent, "Language Detection"),
(OnlineSearchAgent, "Online Research"),
(URLReaderAgent, "URL Reader"),
(FileReaderAgent, "File Reader"),
(DailyStoriesAgent, "Daily News"),
]
CONTEXT_HEADER = (
"## Background context for this turn\n\n"
"Each section below was gathered automatically by a background agent. "
"Weight them by query type: minimal for chitchat, selective for topical "
"discussion, fully for research / factual / time-sensitive questions. "
"Do not surface this scaffolding to the user."
)
def __init__(
self,
use_summarization: bool = _config.shallowSummarize,
user: Optional[str] = None,
):
self.user = user
self.llm = LLMInterface(context="main")
self.messages: List[Dict[str, str]] = []
self.system_prompt = ""
self.use_summarization = use_summarization
self.agents: List[Agent] = []
self._agents_initialized = False
self._init_lock = asyncio.Lock()
self.update_system_prompt()
# ------------------------------------------------------------------
# Agent lifecycle
# ------------------------------------------------------------------
async def _initialize_agents(self) -> None:
async with self._init_lock:
if self._agents_initialized:
return
for agent_class, name in self.AGENT_REGISTRY:
try:
agent = await asyncio.to_thread(agent_class, name, self.user)
self.agents.append(agent)
except Exception as e:
if _config.debug:
print(f"Error initializing agent {name}: {e}")
self._agents_initialized = True
async def ensure_agents_initialized(self) -> None:
if not self._agents_initialized:
await self._initialize_agents()
# ------------------------------------------------------------------
# System prompt
# ------------------------------------------------------------------
def update_system_prompt(self) -> None:
"""Refresh the system prompt with the current timestamp."""
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
base_prompt = _config.prompt or ""
self.system_prompt = f"{base_prompt}\nCurrent time: {current_time}"
# ------------------------------------------------------------------
# Welcome message
# ------------------------------------------------------------------
async def _get_snarky_welcome(self) -> str:
now = datetime.datetime.now()
time_of_day = (
"morning" if 5 <= now.hour < 12
else "afternoon" if 12 <= now.hour < 18
else "evening"
)
current_time = now.strftime("%A, %B %d, %Y %I:%M %p")
prompt_options = [
f"Generate a short, witty, and slightly snarky welcome message. Current time: {current_time}, {time_of_day}.",
f"Write a brief welcome message with attitude. It's {time_of_day}, {current_time}.",
f"Create a slightly sarcastic greeting for a CLI interface. Time: {current_time}.",
f"It's {time_of_day}, {current_time}. Write a welcome message that's both welcoming and a little cheeky.",
]
response = await asyncio.to_thread(
self.llm.generate_single_response,
prompt=random.choice(prompt_options),
system_prompt="Respond in under 25 words and plain text.",
)
return response.strip().strip('"\'')
async def ensure_opening_message(self) -> str:
"""Ensure the first message is an assistant welcome. Return its text."""
if self.messages and self.messages[0]['role'] == 'assistant':
return self.messages[0]['content']
opening = await self._get_snarky_welcome()
if not self.messages:
self.messages.append({"role": "assistant", "content": opening})
else:
self.messages.insert(0, {"role": "assistant", "content": opening})
return opening
# ------------------------------------------------------------------
# Agent dispatch
# ------------------------------------------------------------------
async def _process_agent(
self,
agent: Agent,
user_input: str,
last_response: Optional[str],
) -> Tuple[Optional[str], Optional[Dict[str, Any]]]:
try:
enrichment = await asyncio.to_thread(agent.process, user_input, last_response)
return enrichment, agent.get_metadata()
except Exception as e:
if _config.debug:
print(f"Error processing agent {agent.name}: {e}")
return None, None
async def _process_all_agents(
self,
user_input: str,
last_response: Optional[str],
) -> Tuple[Dict[str, str], Dict[str, Dict[str, Any]]]:
"""
Two phases, each fully parallel:
1. should_process() decides which agents run
2. process() does the work, with a per-agent timeout
"""
await self.ensure_agents_initialized()
decisions = await asyncio.gather(*[
asyncio.to_thread(agent.should_process, user_input, last_response)
for agent in self.agents
])
active = [a for a, ok in zip(self.agents, decisions) if ok]
if _config.debug:
print(f"Active agents: {[a.name for a in active]}")
timeout = _config.agent_process_timeout
tasks = [
(agent.name, asyncio.create_task(self._process_agent(agent, user_input, last_response)))
for agent in active
]
outputs: Dict[str, str] = {}
metadata: Dict[str, Dict[str, Any]] = {}
for name, task in tasks:
try:
enrichment, meta = await asyncio.wait_for(task, timeout=timeout)
except asyncio.TimeoutError:
if _config.debug:
print(f"Agent {name} timed out after {timeout}s")
task.cancel()
continue
except Exception as e:
if _config.debug:
print(f"Error awaiting agent {name}: {e}")
continue
if enrichment is not None:
outputs[name] = enrichment
metadata[name] = meta or {}
return outputs, metadata
# ------------------------------------------------------------------
# Context assembly
# ------------------------------------------------------------------
def _format_enriched_context(self, agent_outputs: Dict[str, str]) -> str:
"""Render agent outputs as labelled markdown sections."""
sections: List[str] = []
for name, output in agent_outputs.items():
text = output.strip()
if not text:
continue
if self.use_summarization:
try:
text = self.llm.summarize(text).strip()
except Exception as e:
if _config.debug:
print(f"Error summarizing {name}: {e}")
sections.append(f"### {name}\n{text}")
if not sections:
return ""
return f"\n\n---\n\n{self.CONTEXT_HEADER}\n\n" + "\n\n".join(sections)
# ------------------------------------------------------------------
# Main response loop
# ------------------------------------------------------------------
async def get_ai_response(
self,
user_input: str,
) -> AsyncGenerator[Tuple[Optional[str], Dict[str, Any], int, int], None]:
"""
Process user input and stream the AI response.
Yields tuples of (text_chunk, agent_metadata, input_tokens, output_tokens).
Token counts are zero until the API returns final usage.
Final yield (streaming mode) has chunk=None with the final counts.
"""
last_response: Optional[str] = None
if self.messages and self.messages[-1]['role'] == 'assistant':
last_response = self.messages[-1]['content']
agent_outputs, agent_metadata = await self._process_all_agents(user_input, last_response)
enriched_context = self._format_enriched_context(agent_outputs)
self.update_system_prompt()
user_message = {
"role": "user",
"content": f"{user_input}{enriched_context}" if enriched_context else user_input,
}
temp_messages = self.messages + [user_message]
if _config.debug:
print(json.dumps(temp_messages, indent=2))
input_tokens = 0
output_tokens = 0
full_response = ""
try:
for chunk_data in self.llm.stream_content(
messages=temp_messages,
system_prompt=self.system_prompt,
max_tokens=_config.max_tokens,
):
content = chunk_data.get('content')
if content:
full_response += content
if _config.streaming:
await asyncio.sleep(_config.output_delay)
yield content, agent_metadata, input_tokens, output_tokens
usage = chunk_data.get('usage')
if usage:
input_tokens = usage.get('input_tokens', 0)
output_tokens = usage.get('output_tokens', 0)
if not _config.streaming:
yield full_response, agent_metadata, input_tokens, output_tokens
except Exception as e:
if _config.debug:
print(f"Error in streaming response: {e}")
error_msg = f"Sorry, I encountered an error: {e}"
yield error_msg, agent_metadata, input_tokens, output_tokens
full_response = error_msg
self.messages.append({"role": "user", "content": user_input})
self.messages.append({"role": "assistant", "content": full_response})
max_messages = _config.max_conversation_history
if len(self.messages) > max_messages:
excess = len(self.messages) - max_messages
excess += excess % 2 # round up to even — keep user/assistant pairs aligned
self.messages = self.messages[excess:]
if _config.streaming:
yield None, agent_metadata, input_tokens, output_tokens
async def shutdown(self) -> None:
if _config.debug:
print("Shutting down ArtemisCore...")
self.messages.clear()
self.agents.clear()
self._agents_initialized = False
Agent.shutdown()
if _config.debug:
print("ArtemisCore shutdown complete.")