diff --git a/src/homeagent/agent/gemini.py b/src/homeagent/agent/gemini.py index d71a6fb..3c29d38 100644 --- a/src/homeagent/agent/gemini.py +++ b/src/homeagent/agent/gemini.py @@ -19,154 +19,53 @@ logger = logging.getLogger(__name__) class GeminiAgent(BaseAgent): """Agent orchestrator powered by Google AI Studio (Gemini).""" - def __init__( - self, - settings: Optional[Settings] = None, - registry: Optional[ToolRegistry] = None, - conversation_manager: Optional[ConversationManager] = None, - ) -> None: + def __init__(self, settings=None, registry=None, conversation_manager=None): self.settings = settings or get_settings() self.registry = registry or get_tool_registry() self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR) - api_key = self.settings.GEMINI_API_KEY.get_secret_value() - self._client: Optional[genai.Client] = None - if api_key: - self._client = genai.Client(api_key=api_key) - else: - logger.warning("GEMINI_API_KEY is not set. Agent will return configuration prompts.") + self._client = genai.Client(api_key=api_key) if api_key else None + if not api_key: logger.warning("GEMINI_API_KEY is not set. Agent will return configuration prompts.") def _build_system_instruction(self) -> str: now = datetime.now() 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 = [ - 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]]: + def _get_tools_config(self): declarations = self.registry.get_function_declarations() - if not declarations: - return None - return [types.Tool(function_declarations=declarations)] + return [types.Tool(function_declarations=declarations)] if declarations else None - async def chat( - 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.""" + async def chat(self, chat_id: int, thread_id: Optional[int], user_message: str, max_tool_iterations: int = 8, on_progress=None) -> str: if not self._client: - return ( - "⚠️ **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 + return "⚠️ **Google AI Studio API Key не настроен.**\nПожалуйста, добавьте `GEMINI_API_KEY=your_key` в файл `.env` и перезапустите бота." history = list(self.conversation_manager.get_history(chat_id, thread_id)) - - # 2. Add current user message - user_content = types.Content( - role="user", - parts=[types.Part.from_text(text=user_message)], - ) + user_content = types.Content(role="user", parts=[types.Part.from_text(text=user_message)]) history.append(user_content) - - turn_contents: list[types.Content] = [user_content] - 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, - ) - + turn_contents = [user_content] + config = types.GenerateContentConfig(system_instruction=self._build_system_instruction(), tools=self._get_tools_config(), temperature=0.4) for iteration in range(max_tool_iterations): - logger.debug( - "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})...") - + if on_progress: await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...") try: - response = await self._client.aio.models.generate_content( - model=self.settings.GEMINI_MODEL, - contents=history, - config=config, - ) + response = await self._client.aio.models.generate_content(model=self.settings.GEMINI_MODEL, contents=history, config=config) except Exception as e: logger.exception("Error calling Gemini API: %s", e) return f"⚠️ Ошибка обращения к Google Gemini API: {type(e).__name__}: {str(e)}" - - # Check if model requested function calls - function_calls = response.function_calls - if not function_calls: - # Final response reached + if not response.function_calls: final_text = response.text or "*(Пустой ответ)*" - model_content = types.Content( - role="model", - parts=[types.Part.from_text(text=final_text)], - ) - turn_contents.append(model_content) + turn_contents.append(types.Content(role="model", parts=[types.Part.from_text(text=final_text)])) self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents) return final_text - - # Model produced function calls - # Save the model's message with function calls 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=model_parts) - history.append(model_content) - turn_contents.append(model_content) - - # Execute all function calls requested by the model in this step - response_parts: list[types.Part] = [] - for idx, fc in enumerate(function_calls, 1): - fc_name = fc.name - 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 = "Достигнут лимит последовательных вызовов инструментов для этого запроса." + model_content = types.Content(role="model", parts=candidate.content.parts if candidate and candidate.content else []) + history.append(model_content); turn_contents.append(model_content) + response_parts = [] + for fc in response.function_calls: + result = await self.registry.execute(fc.name, dict(fc.args) if fc.args else {}) + response_parts.append(types.Part.from_function_response(name=fc.name, response={"result": result})) + tool_content = types.Content(role="user", parts=response_parts) + history.append(tool_content); turn_contents.append(tool_content) + warning = "Достигнут лимит последовательных вызовов инструментов для этого запроса." self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents) - return warning_msg - + return warning