🚀 Мультиагентные системы: как решить проблему изоляции LLM с помощью инструментов ADK

🤔 Зачем агентам нужны инструменты?

Проблема:

Без инструментов знания агента ограничены данными обучения — он не знает свежих новостей, инвентаря компании или внешних API. LLM изолирован и не может выполнять действия.

Решение:

Инструменты превращают LLM в функционального агента. В этой статье вы узнаете:

  • Как превратить функции Python в инструменты агента
  • Как создать агента и использовать его как инструмент в другом агенте
  • Как построить мультиинструментального агента
  • Обзор всех типов инструментов в Agent Development Kit (ADK)

📖 Начало работы с Python и ADK

1. Установите зависимости

pip install google-adk

2. Получите ключ API Gemini

  • Перейдите в Google AI Studio
  • Создайте API-ключ
  • Сохраните его в переменной окружения:

import os os.environ["GOOGLE_API_KEY"] = "ваш_ключ"

3. Проверка аутентификации

import os try: api_key = os.environ["GOOGLE_API_KEY"] print("API key loaded successfully.") except KeyError: print("Error: Set GOOGLE_API_KEY environment variable.")

⚙ Раздел 1: Настройка среды

1.1 Импорт компонентов ADK

from google.genaiimport types from google.adk.agentsimportLlmAgentfrom google.adk.models.google_llmimportGeminifrom google.adk.runnersimportInMemoryRunnerfrom google.adk.sessionsimportInMemorySessionServicefrom google.adk.toolsimport google_search, AgentTool, ToolContextfrom google.adk.code_executorsimportBuiltInCodeExecutorprint("ADK components imported successfully.")

1.2 Параметры повторных попыток

Для обработки временных ошибок (429, 500, 503, 504):

retry_config = types.HttpRetryOptions( attempts=5, # Maximum retry attempts exp_base=7, # Delay multiplier initial_delay=1, http_status_codes=[429, 500, 503, 504], # Retry on these HTTP errors )

🤖 Раздел 2: Пользовательские инструменты

Пользовательские инструменты — это ваш код и бизнес-логика. Встроенные (как Google Search) универсальны, но не покрывают уникальные нужды компании.

2.1 Пример: Агент конвертации валют

Два инструмента:

  • Поиск комиссии
  • Курс обменаЗатем — точный расчёт

Рекомендации ADK для создания инструментов

  1. Возврат: {"status": "success", "data": ...} или {"status": "error", "error_message": ...}
  2. Чёткие docstrings — LLM использует их для понимания инструмента
  3. Type hints — для корректной генерации схем
  4. Обработка ошибок — структурированные ответы

Инструмент 1: Комиссия за платёж

# Pay attention to the docstring, type hints, and return value. def get_fee_for_payment_method(method: str) -> dict: """Looks up the transaction fee percentage for a given payment method. This tool simulates looking up a company's internal fee structure based on the name of the payment method provided by the user. Args: method: The name of the payment method. It should be descriptive, e.g., "platinum credit card" or "bank transfer". Returns: Dictionary with status and fee information. Success: {"status": "success", "fee_percentage": 0.02} Error: {"status": "error", "error_message": "Payment method not found"} """ # This simulates looking up a company's internal fee structure. fee_database = { "platinum credit card": 0.02, # 2% "gold debit card": 0.035, # 3.5% "bank transfer": 0.01, # 1% } fee = fee_database.get(method.lower()) if fee is not None: return {"status": "success", "fee_percentage": fee} else: return { "status": "error", "error_message": f"Payment method '{method}' not found", }

Инструмент 2: Курс обмена

def get_exchange_rate(base_currency: str, target_currency: str) -> dict: """Looks up and returns the exchange rate between two currencies. Args: base_currency: The ISO 4217 currency code of the currency you are converting from (e.g., "USD"). target_currency: The ISO 4217 currency code of the currency you are converting to (e.g., "EUR"). Returns: Dictionary with status and rate information. Success: {"status": "success", "rate": 0.93} Error: {"status": "error", "error_message": "Unsupported currency pair"} """ # Static data simulating a live exchange rate API # In production, this would call something like: requests.get("api.exchangerates.com") rate_database = { "usd": { "eur": 0.93, # Euro "jpy": 157.50, # Japanese Yen "inr": 83.58, # Indian Rupee } } # Input validation and processing base = base_currency.lower() target = target_currency.lower() # Return structured result with status rate = rate_database.get(base, {}).get(target) if rate is not None: return {"status": "success", "rate": rate} else: return { "status": "error", "error_message": f"Unsupported currency pair: {base_currency}/{target_currency}", }

Создание валютного агента

# Currency agent with custom function tools currency_agent = LlmAgent( name="currency_agent", model=Gemini(model="gemini-2.5-flash-lite", retry_options=retry_config), instruction="""You are a smart currency conversion assistant. For currency conversion requests: 1. Use `get_fee_for_payment_method()` to find transaction fees 2. Use `get_exchange_rate()` to get currency conversion rates 3. Check the "status" field in each tool's response for errors 4. Calculate the final amount after fees based on the output from `get_fee_for_payment_method` and `get_exchange_rate` methods and provide a clear breakdown. 5. First, state the final converted amount. Then, explain how you got that result by showing the intermediate amounts. Your explanation must include: the fee percentage and its value in the original currency, the amount remaining after the fee, and the exchange rate used for the final conversion. If any tool returns status "error", explain the issue to the user clearly. """, tools=[get_fee_for_payment_method, get_exchange_rate], )

⚙ Как выглядит архитектура агента ADK

🚀 Мультиагентные системы: как решить проблему изоляции LLM с помощью инструментов ADK

Повышение надёжности с помощью кода

LLM ошибается в математике. Даже простые расчёты могут быть неточными.

Решение: Делегировать вычисления коду, а не полагаться на LLM.

3.1 Агент-калькулятор с BuiltInCodeExecutor

calculation_agent = LlmAgent( name="CalculationAgent", model=Gemini(model="gemini-2.5-flash-lite", retry_options=retry_config), instruction="""You are a specialized calculator that ONLY responds with Python code. You are forbidden from providing any text, explanations, or conversational responses. Your task is to take a request for a calculation and translate it into a single block of Python code that calculates the answer. **RULES:** 1. Your output MUST be ONLY a Python code block. 2. Do NOT write any text before or after the code block. 3. The Python code MUST calculate the result. 4. The Python code MUST print the final result to stdout. 5. You are PROHIBITED from performing the calculation yourself. Your only job is to generate the code that will perform the calculation. Failure to follow these rules will result in an error. """, code_executor=BuiltInCodeExecutor(), # Use the built-in Code Executor Tool. This gives the agent code execution capabilities )

3.2 Улучшенный валютный агент

enhanced_currency_agent = LlmAgent( name="enhanced_currency_agent", model=Gemini(model="gemini-2.5-flash-lite", retry_options=retry_config), # Updated instruction instruction="""You are a smart currency conversion assistant. You must strictly follow these steps and use the available tools. For any currency conversion request: 1. Get Transaction Fee: Use the get_fee_for_payment_method() tool to determine the transaction fee. 2. Get Exchange Rate: Use the get_exchange_rate() tool to get the currency conversion rate. 3. Error Check: After each tool call, you must check the "status" field in the response. If the status is "error", you must stop and clearly explain the issue to the user. 4. Calculate Final Amount (CRITICAL): You are strictly prohibited from performing any arithmetic calculations yourself. You must use the calculation_agent tool to generate Python code that calculates the final converted amount. This code will use the fee information from step 1 and the exchange rate from step 2. 5. Provide Detailed Breakdown: In your summary, you must: * State the final converted amount. * Explain how the result was calculated, including: * The fee percentage and the fee amount in the original currency. * The amount remaining after deducting the fee. * The exchange rate applied. """, tools=[ get_fee_for_payment_method, get_exchange_rate, AgentTool(agent=calculation_agent), # Using another agent as a tool! ], )

Результат: Код генерируется → выполняется в sandbox → точный ответ.

🧩 Интерактивная схема взаимодействия агентов

🚀 Мультиагентные системы: как решить проблему изоляции LLM с помощью инструментов ADK

Инструменты vs Субагенты

🚀 Мультиагентные системы: как решить проблему изоляции LLM с помощью инструментов ADK

В нашем случае — инструмент, потому что нужен контроль.

Раздел 4: Полное руководство по типам инструментов ADK

1. Пользовательские инструменты

🚀 Мультиагентные системы: как решить проблему изоляции LLM с помощью инструментов ADK

2. Встроенные инструменты

🚀 Мультиагентные системы: как решить проблему изоляции LLM с помощью инструментов ADK

🧭 Пример архитектуры с несколькими агентами

🚀 Мультиагентные системы: как решить проблему изоляции LLM с помощью инструментов ADK

✅ Итоги

ADK позволяет создавать агентов, которые:

  • 🔧 используют Python-функции как инструменты;
  • 🧠 делегируют задачи другим агентам;
  • 💻 выполняют код для точных расчетов;
  • 🌐 подключаются к API и внешним сервисам.

📘 Где почитать подробнее

Начать дискуссию