fix: read agent memory from its configured data directory
This commit is contained in:
1 parent
a588bec86f
commit
264095255d
1 file changed
+26
-127
+26
-127
@@ -19,154 +19,53 @@ logger = logging.getLogger(__name__)
|
|||||||
class GeminiAgent(BaseAgent):
|
class GeminiAgent(BaseAgent):
|
||||||
"""Agent orchestrator powered by Google AI Studio (Gemini)."""
|
"""Agent orchestrator powered by Google AI Studio (Gemini)."""
|
||||||
|
|
||||||
def __init__(
|
def __init__(self, settings=None, registry=None, conversation_manager=None):
|
||||||
self,
|
|
||||||
settings: Optional[Settings] = None,
|
|
||||||
registry: Optional[ToolRegistry] = None,
|
|
||||||
conversation_manager: Optional[ConversationManager] = None,
|
|
||||||
) -> None:
|
|
||||||
self.settings = settings or get_settings()
|
self.settings = settings or get_settings()
|
||||||
self.registry = registry or get_tool_registry()
|
self.registry = registry or get_tool_registry()
|
||||||
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
||||||
|
|
||||||
api_key = self.settings.GEMINI_API_KEY.get_secret_value()
|
api_key = self.settings.GEMINI_API_KEY.get_secret_value()
|
||||||
self._client: Optional[genai.Client] = None
|
self._client = genai.Client(api_key=api_key) if api_key else None
|
||||||
if api_key:
|
if not api_key: logger.warning("GEMINI_API_KEY is not set. Agent will return configuration prompts.")
|
||||||
self._client = genai.Client(api_key=api_key)
|
|
||||||
else:
|
|
||||||
logger.warning("GEMINI_API_KEY is not set. Agent will return configuration prompts.")
|
|
||||||
|
|
||||||
def _build_system_instruction(self) -> str:
|
def _build_system_instruction(self) -> str:
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
dt_context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
dt_context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
||||||
memory_summary = get_global_memory().get_memory_summary()
|
memory = get_global_memory(self.settings.DATA_DIR / "global_memory.json").get_memory_summary()
|
||||||
|
return "\n\n".join(filter(None, [self.settings.SYSTEM_INSTRUCTION, dt_context, memory]))
|
||||||
|
|
||||||
parts = [
|
def _get_tools_config(self):
|
||||||
self.settings.SYSTEM_INSTRUCTION,
|
|
||||||
dt_context,
|
|
||||||
]
|
|
||||||
if memory_summary:
|
|
||||||
parts.append(memory_summary)
|
|
||||||
|
|
||||||
return "\n\n".join(parts)
|
|
||||||
|
|
||||||
def _get_tools_config(self) -> Optional[list[types.Tool]]:
|
|
||||||
declarations = self.registry.get_function_declarations()
|
declarations = self.registry.get_function_declarations()
|
||||||
if not declarations:
|
return [types.Tool(function_declarations=declarations)] if declarations else None
|
||||||
return None
|
|
||||||
return [types.Tool(function_declarations=declarations)]
|
|
||||||
|
|
||||||
async def chat(
|
async def chat(self, chat_id: int, thread_id: Optional[int], user_message: str, max_tool_iterations: int = 8, on_progress=None) -> str:
|
||||||
self,
|
|
||||||
chat_id: int,
|
|
||||||
thread_id: Optional[int],
|
|
||||||
user_message: str,
|
|
||||||
max_tool_iterations: int = 8,
|
|
||||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
|
||||||
) -> str:
|
|
||||||
"""Process a user message within the topic context, running tools as requested by Gemini."""
|
|
||||||
if not self._client:
|
if not self._client:
|
||||||
return (
|
return "⚠️ **Google AI Studio API Key не настроен.**\nПожалуйста, добавьте `GEMINI_API_KEY=your_key` в файл `.env` и перезапустите бота."
|
||||||
"⚠️ **Google AI Studio API Key не настроен.**\n"
|
|
||||||
"Пожалуйста, добавьте `GEMINI_API_KEY=your_key` в файл `.env` и перезапустите бота.\n"
|
|
||||||
"Получить ключ можно бесплатно в [Google AI Studio](https://aistudio.google.com/)."
|
|
||||||
)
|
|
||||||
|
|
||||||
# 1. Fetch current conversation history
|
|
||||||
history = list(self.conversation_manager.get_history(chat_id, thread_id))
|
history = list(self.conversation_manager.get_history(chat_id, thread_id))
|
||||||
|
user_content = types.Content(role="user", parts=[types.Part.from_text(text=user_message)])
|
||||||
# 2. Add current user message
|
|
||||||
user_content = types.Content(
|
|
||||||
role="user",
|
|
||||||
parts=[types.Part.from_text(text=user_message)],
|
|
||||||
)
|
|
||||||
history.append(user_content)
|
history.append(user_content)
|
||||||
|
turn_contents = [user_content]
|
||||||
turn_contents: list[types.Content] = [user_content]
|
config = types.GenerateContentConfig(system_instruction=self._build_system_instruction(), tools=self._get_tools_config(), temperature=0.4)
|
||||||
system_instruction = self._build_system_instruction()
|
|
||||||
tools_config = self._get_tools_config()
|
|
||||||
|
|
||||||
config = types.GenerateContentConfig(
|
|
||||||
system_instruction=system_instruction,
|
|
||||||
tools=tools_config,
|
|
||||||
temperature=0.4,
|
|
||||||
)
|
|
||||||
|
|
||||||
for iteration in range(max_tool_iterations):
|
for iteration in range(max_tool_iterations):
|
||||||
logger.debug(
|
if on_progress: await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
||||||
"Gemini request turn: chat=%d, thread=%s, iteration=%d, history_len=%d",
|
|
||||||
chat_id,
|
|
||||||
thread_id,
|
|
||||||
iteration,
|
|
||||||
len(history),
|
|
||||||
)
|
|
||||||
|
|
||||||
if on_progress:
|
|
||||||
if iteration == 0:
|
|
||||||
await on_progress("🤔 Формирую ответ...")
|
|
||||||
else:
|
|
||||||
await on_progress(f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = await self._client.aio.models.generate_content(
|
response = await self._client.aio.models.generate_content(model=self.settings.GEMINI_MODEL, contents=history, config=config)
|
||||||
model=self.settings.GEMINI_MODEL,
|
|
||||||
contents=history,
|
|
||||||
config=config,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception("Error calling Gemini API: %s", e)
|
logger.exception("Error calling Gemini API: %s", e)
|
||||||
return f"⚠️ Ошибка обращения к Google Gemini API: {type(e).__name__}: {str(e)}"
|
return f"⚠️ Ошибка обращения к Google Gemini API: {type(e).__name__}: {str(e)}"
|
||||||
|
if not response.function_calls:
|
||||||
# Check if model requested function calls
|
|
||||||
function_calls = response.function_calls
|
|
||||||
if not function_calls:
|
|
||||||
# Final response reached
|
|
||||||
final_text = response.text or "*(Пустой ответ)*"
|
final_text = response.text or "*(Пустой ответ)*"
|
||||||
model_content = types.Content(
|
turn_contents.append(types.Content(role="model", parts=[types.Part.from_text(text=final_text)]))
|
||||||
role="model",
|
|
||||||
parts=[types.Part.from_text(text=final_text)],
|
|
||||||
)
|
|
||||||
turn_contents.append(model_content)
|
|
||||||
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
||||||
return final_text
|
return final_text
|
||||||
|
|
||||||
# Model produced function calls
|
|
||||||
# Save the model's message with function calls
|
|
||||||
candidate = response.candidates[0] if response.candidates else None
|
candidate = response.candidates[0] if response.candidates else None
|
||||||
model_parts = candidate.content.parts if (candidate and candidate.content) else []
|
model_content = types.Content(role="model", parts=candidate.content.parts if candidate and candidate.content else [])
|
||||||
model_content = types.Content(role="model", parts=model_parts)
|
history.append(model_content); turn_contents.append(model_content)
|
||||||
history.append(model_content)
|
response_parts = []
|
||||||
turn_contents.append(model_content)
|
for fc in response.function_calls:
|
||||||
|
result = await self.registry.execute(fc.name, dict(fc.args) if fc.args else {})
|
||||||
# Execute all function calls requested by the model in this step
|
response_parts.append(types.Part.from_function_response(name=fc.name, response={"result": result}))
|
||||||
response_parts: list[types.Part] = []
|
tool_content = types.Content(role="user", parts=response_parts)
|
||||||
for idx, fc in enumerate(function_calls, 1):
|
history.append(tool_content); turn_contents.append(tool_content)
|
||||||
fc_name = fc.name
|
warning = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
||||||
fc_args = dict(fc.args) if fc.args else {}
|
|
||||||
|
|
||||||
if on_progress:
|
|
||||||
from homeagent.bot.progress import format_tool_progress
|
|
||||||
|
|
||||||
step_info = f"[{idx}/{len(function_calls)}] " if len(function_calls) > 1 else ""
|
|
||||||
desc = format_tool_progress(fc_name, fc_args)
|
|
||||||
await on_progress(f"⏳ {step_info}{desc}")
|
|
||||||
|
|
||||||
logger.info("Executing function call: %s(%s)", fc_name, fc_args)
|
|
||||||
tool_result = await self.registry.execute(fc_name, fc_args)
|
|
||||||
|
|
||||||
response_parts.append(
|
|
||||||
types.Part.from_function_response(
|
|
||||||
name=fc_name,
|
|
||||||
response={"result": tool_result},
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
tool_response_content = types.Content(role="user", parts=response_parts)
|
|
||||||
history.append(tool_response_content)
|
|
||||||
turn_contents.append(tool_response_content)
|
|
||||||
|
|
||||||
# If exceeded max iterations, return warning
|
|
||||||
warning_msg = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
|
||||||
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
||||||
return warning_msg
|
return warning
|
||||||
|
|
||||||
Reference in new issue
Block a user