跳转到内容

用于 ADK 的自定义工具

在 ADK 中得到支持。Python v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.1.0Kotlin v0.1.0

在 ADK 代理的工作流程中,工具(Tools)是一些具有结构化输入和输出功能的编程模块,可以被 ADK 代理调用以执行特定操作。ADK 工具的使用方式类似于您使用其他常规编程工具的方式。 函数调用 可以使用 Gemini 或其他生成式 AI 模型。通过 ADK 工具,您可以执行各种操作和编程功能,例如:

  • 查询数据库
  • 发送 API 请求:获取天气数据、预订系统相关服务
  • 在互联网上搜索
  • 正在执行代码片段。
  • 从文档中检索信息(RAG)
  • 与其他软件或服务进行交互

ADK 工具与集成(ADK Tools and Integrations)

在为 ADK 构建自己的工具之前,请先了解一下相关资源或指南。 ADK 工具与集成(ADK Tools and Integrations) 对于那些可以与 ADK Agents 一起使用的预构建工具和集成方案,您可以……(此处应继续说明具体使用方法或可用的功能。)

什么是工具?

在 ADK(AI Development Kit)的背景下,**“工具”(Tool)**指的是为 AI 代理提供的某种特定功能,使该代理能够执行某些操作,并与其所处的环境进行交互——这些操作超出了其核心的文本生成和推理能力。能够执行复杂任务的 AI 代理与普通的自然语言模型之间的区别,往往就在于它们对各种工具的**有效利用**。

从技术角度来看,工具通常是一种模块化的代码组件。就像 Python、Java 或 TypeScript 一样,这个函数也是用函数语法定义的。它可以是一个类方法(class method),也可以是一个专门设计的代理(specialized agent),其目的是执行某个特定且预先定义好的任务。这些任务通常需要与外部系统或数据进行交互。

代理工具调用(Agent tool call)

主要特点

**以行动为导向(Action-Oriented):** 这些工具为代理执行特定的操作,例如搜索信息、调用 API 或进行计算。

扩展代理的功能: 这些工具使代理人能够获取实时信息、影响外部系统,并克服其训练数据中固有的知识局限性。

执行预定义的逻辑: 至关重要的是,这些工具会执行由开发者预先定义的具体逻辑。它们本身并不具备像代理的核心大型语言模型(LLM)那样的独立推理能力。大型语言模型会决定使用哪种工具、在何时使用以及使用哪些输入数据,而工具本身则只是执行其被赋予的功能而已。

代理人如何使用这些工具

代理通过各种机制(这些机制通常涉及函数调用)动态地使用各种工具。整个过程一般遵循以下步骤:

  1. 推理(Reasoning): 该代理的 large language model(LLM)会分析其系统指令、对话记录以及用户请求的内容。
  2. **选择:** 根据分析结果,大型语言模型(LLM)会决定使用哪种工具(如果有的话)来执行任务。决策过程会考虑代理可使用的工具列表,以及每个工具对应的文档字符串(docstrings)。
  3. 调用(Invocation): 大型语言模型(LLM)会为所选工具生成所需的参数(输入数据),并触发该工具的执行。
  4. 观察结果: 代理接收工具返回的输出结果(result)。
  5. **Finalization:** (注:该术语为专业术语,通常用于描述“完成某项过程或任务的最后阶段”;在中文中可译为“最终处理”或“收尾工作”。) 该代理将工具的输出结果整合到其持续的推理过程中,以此来制定下一条回复内容、决定后续的行动步骤,或判断目标是否已经实现。

可以将这些工具视为一套专门的工具包,代理的智能核心(即大型语言模型,LLM)可以根据需要访问并使用这些工具来完成任务。

ADK中的工具类型

ADK 通过支持多种类型的工具,提供了极大的灵活性:

  1. 功能工具(Function Tools): 这些工具是由您自己开发的,专门为满足您特定应用程序的需求而设计的。
  2. 内置工具: 该框架提供了用于常见任务的即用型工具。 例如:Google 搜索、代码执行、基于检索结果的生成技术(Retrieval-Augmented Generation,简称 RAG)。
  3. 第三方工具: 可以从流行的外部库中无缝集成各种工具。

请访问上述链接中的相应文档页面,以获取每种工具类型的详细信息及使用示例。

在代理的说明中引用该工具

在代理的指令中,您可以直接通过使用该工具的名称来引用它。 function name. 如果该工具的…… function name 和 `docstring` 如果这些描述足够详细、清晰,那么您的指令就可以主要集中在……(即:如果描述足够详细,指令就可以主要关注其他内容)。 在什么情况下,大型语言模型(LLM)应该使用该工具?这样做有助于提高信息的清晰度,也让模型能够更好地理解每个工具的用途(即这些工具被设计用来实现什么功能)。

It is 这一点至关重要,因为它能明确地指导代理如何处理不同的返回值。 例如,如果某个工具返回了一条错误消息,那么你的使用说明应该明确指出:代理应该重新尝试该操作、放弃该任务,还是向用户请求更多信息。

此外,ADK 支持工具的顺序使用:一个工具的输出可以作为另一个工具的输入。在实现这样的工作流程时,非常重要的一点是…… 描述工具使用的预期顺序。 根据代理的指示,引导模型完成必要的步骤。

示例:

以下示例展示了代理如何使用各种工具来完成任务。 在说明中引用这些函数的名称它还展示了如何指导代理(agent)进行相应的操作。 处理来自各种工具的不同返回值例如成功或错误消息,以及如何协调这些信息(即如何处理这些消息)。 多种工具的顺序使用 为了完成任务。

# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types

APP_NAME="weather_sentiment_agent"
USER_ID="user1234"
SESSION_ID="1234"
MODEL_ID="gemini-2.0-flash"

# Tool 1
def get_weather_report(city: str) -> dict:
    """Retrieves the current weather report for a specified city.

    Returns:
        dict: A dictionary containing the weather information with a 'status' key ('success' or 'error') and a 'report' key with the weather details if successful, or an 'error_message' if an error occurred.
    """
    if city.lower() == "london":
        return {"status": "success", "report": "The current weather in London is cloudy with a temperature of 18 degrees Celsius and a chance of rain."}
    elif city.lower() == "paris":
        return {"status": "success", "report": "The weather in Paris is sunny with a temperature of 25 degrees Celsius."}
    else:
        return {"status": "error", "error_message": f"Weather information for '{city}' is not available."}

weather_tool = FunctionTool(func=get_weather_report)


# Tool 2
def analyze_sentiment(text: str) -> dict:
    """Analyzes the sentiment of the given text.

    Returns:
        dict: A dictionary with 'sentiment' ('positive', 'negative', or 'neutral') and a 'confidence' score.
    """
    if "good" in text.lower() or "sunny" in text.lower():
        return {"sentiment": "positive", "confidence": 0.8}
    elif "rain" in text.lower() or "bad" in text.lower():
        return {"sentiment": "negative", "confidence": 0.7}
    else:
        return {"sentiment": "neutral", "confidence": 0.6}

sentiment_tool = FunctionTool(func=analyze_sentiment)


# Agent
weather_sentiment_agent = Agent(
    model=MODEL_ID,
    name='weather_sentiment_agent',
    instruction="""You are a helpful assistant that provides weather information and analyzes the sentiment of user feedback.
**If the user asks about the weather in a specific city, use the 'get_weather_report' tool to retrieve the weather details.**
**If the 'get_weather_report' tool returns a 'success' status, provide the weather report to the user.**
**If the 'get_weather_report' tool returns an 'error' status, inform the user that the weather information for the specified city is not available and ask if they have another city in mind.**
**After providing a weather report, if the user gives feedback on the weather (e.g., 'That's good' or 'I don't like rain'), use the 'analyze_sentiment' tool to understand their sentiment.** Then, briefly acknowledge their sentiment.
You can handle these tasks sequentially if needed.""",
    tools=[weather_tool, sentiment_tool]
)

async def main():
    """Main function to run the agent asynchronously."""
    # Session and Runner Setup
    session_service = InMemorySessionService()
    # Use 'await' to correctly create the session
    await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)

    runner = Runner(agent=weather_sentiment_agent, app_name=APP_NAME, session_service=session_service)

    # Agent Interaction
    query = "weather in london?"
    print(f"User Query: {query}")
    content = types.Content(role='user', parts=[types.Part(text=query)])

    # The runner's run method handles the async loop internally
    events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)

    for event in events:
        if event.is_final_response() and event.content and event.content.parts:
            final_response = event.content.parts[0].text
            print("Agent Response:", final_response)

# Standard way to run the main async function
if __name__ == "__main__":
    asyncio.run(main())
/**
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { LlmAgent, FunctionTool, InMemoryRunner, isFinalResponse, stringifyContent } from '@google/adk';
import { z } from "zod";
import { Content, createUserContent } from "@google/genai";

/**
 * Retrieves the current weather report for a specified city.
 */
function getWeatherReport(params: { city: string }): Record<string, any> {
    if (params.city.toLowerCase().includes("london")) {
        return {
            "status": "success",
            "report": "The current weather in London is cloudy with a " +
                "temperature of 18 degrees Celsius and a chance of rain.",
        };
    }
    if (params.city.toLowerCase().includes("paris")) {
        return {
            "status": "success",
            "report": "The weather in Paris is sunny with a temperature of 25 " +
                "degrees Celsius.",
        };
    }
    return {
        "status": "error",
        "error_message": `Weather information for '${params.city}' is not available.`,
    };
}

/**
 * Analyzes the sentiment of a given text.
 */
function analyzeSentiment(params: { text: string }): Record<string, any> {
    if (params.text.includes("cloudy") || params.text.includes("rain")) {
        return { "status": "success", "sentiment": "negative" };
    }
    if (params.text.includes("sunny")) {
        return { "status": "success", "sentiment": "positive" };
    }
    return { "status": "success", "sentiment": "neutral" };
}

const weatherTool = new FunctionTool({
    name: "get_weather_report",
    description: "Retrieves the current weather report for a specified city.",
    parameters: z.object({
        city: z.string().describe("The city to get the weather for."),
    }),
    execute: getWeatherReport,
});

const sentimentTool = new FunctionTool({
    name: "analyze_sentiment",
    description: "Analyzes the sentiment of a given text.",
    parameters: z.object({
        text: z.string().describe("The text to analyze the sentiment of."),
    }),
    execute: analyzeSentiment,
});

const instruction = `
    You are a helpful assistant that first checks the weather and then analyzes
    its sentiment.

    Follow these steps:
    1. Use the 'get_weather_report' tool to get the weather for the requested
       city.
    2. If the 'get_weather_report' tool returns an error, inform the user about
       the error and stop.
    3. If the weather report is available, use the 'analyze_sentiment' tool to
       determine the sentiment of the weather report.
    4. Finally, provide a summary to the user, including the weather report and
       its sentiment.
    `;

const agent = new LlmAgent({
    name: "weather_sentiment_agent",
    instruction: instruction,
    tools: [weatherTool, sentimentTool],
    model: "gemini-2.5-flash"
});

async function main() {

    const runner = new InMemoryRunner({ agent: agent, appName: "weather_sentiment_app" });

    await runner.sessionService.createSession({
        appName: "weather_sentiment_app",
        userId: "user1",
        sessionId: "session1"
    });

    const newMessage: Content = createUserContent("What is the weather in London?");

    for await (const event of runner.runAsync({
        userId: "user1",
        sessionId: "session1",
        newMessage: newMessage,
    })) {
        if (isFinalResponse(event) && event.content?.parts?.length) {
            const text = stringifyContent(event).trim();
            if (text) {
                console.log(text);
            }
        }
    }
}

main();
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
    "context"
    "fmt"
    "log"
    "strings"

    "google.golang.org/adk/v2/agent"
    "google.golang.org/adk/v2/agent/llmagent"
    "google.golang.org/adk/v2/model/gemini"
    "google.golang.org/adk/v2/runner"
    "google.golang.org/adk/v2/session"
    "google.golang.org/adk/v2/tool"
    "google.golang.org/adk/v2/tool/functiontool"
    "google.golang.org/genai"
)

type getWeatherReportArgs struct {
    City string `json:"city" jsonschema:"The city for which to get the weather report."`
}

type getWeatherReportResult struct {
    Status string `json:"status"`
    Report string `json:"report,omitempty"`
}

func getWeatherReport(ctx agent.Context, args getWeatherReportArgs) (getWeatherReportResult, error) {
    if strings.ToLower(args.City) == "london" {
        return getWeatherReportResult{Status: "success", Report: "The current weather in London is cloudy with a temperature of 18 degrees Celsius and a chance of rain."}, nil
    }
    if strings.ToLower(args.City) == "paris" {
        return getWeatherReportResult{Status: "success", Report: "The weather in Paris is sunny with a temperature of 25 degrees Celsius."}, nil
    }
    return getWeatherReportResult{}, fmt.Errorf("weather information for '%s' is not available.", args.City)
}

type analyzeSentimentArgs struct {
    Text string `json:"text" jsonschema:"The text to analyze for sentiment."`
}

type analyzeSentimentResult struct {
    Sentiment  string  `json:"sentiment"`
    Confidence float64 `json:"confidence"`
}

func analyzeSentiment(ctx agent.Context, args analyzeSentimentArgs) (analyzeSentimentResult, error) {
    if strings.Contains(strings.ToLower(args.Text), "good") || strings.Contains(strings.ToLower(args.Text), "sunny") {
        return analyzeSentimentResult{Sentiment: "positive", Confidence: 0.8}, nil
    }
    if strings.Contains(strings.ToLower(args.Text), "rain") || strings.Contains(strings.ToLower(args.Text), "bad") {
        return analyzeSentimentResult{Sentiment: "negative", Confidence: 0.7}, nil
    }
    return analyzeSentimentResult{Sentiment: "neutral", Confidence: 0.6}, nil
}

func main() {
    ctx := context.Background()
    model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
    if err != nil {
        log.Fatal(err)
    }

    weatherTool, err := functiontool.New(
        functiontool.Config{
            Name:        "get_weather_report",
            Description: "Retrieves the current weather report for a specified city.",
        },
        getWeatherReport,
    )
    if err != nil {
        log.Fatal(err)
    }

    sentimentTool, err := functiontool.New(
        functiontool.Config{
            Name:        "analyze_sentiment",
            Description: "Analyzes the sentiment of the given text.",
        },
        analyzeSentiment,
    )
    if err != nil {
        log.Fatal(err)
    }

    weatherSentimentAgent, err := llmagent.New(llmagent.Config{
        Name:        "weather_sentiment_agent",
        Model:       model,
        Instruction: "You are a helpful assistant that provides weather information and analyzes the sentiment of user feedback. **If the user asks about the weather in a specific city, use the 'get_weather_report' tool to retrieve the weather details.** **If the 'get_weather_report' tool returns a 'success' status, provide the weather report to the user.** **If the 'get_weather_report' tool returns an 'error' status, inform the user that the weather information for the specified city is not available and ask if they have another city in mind.** **After providing a weather report, if the user gives feedback on the weather (e.g., 'That's good' or 'I don't like rain'), use the 'analyze_sentiment' tool to understand their sentiment.** Then, briefly acknowledge their sentiment. You can handle these tasks sequentially if needed.",
        Tools:       []tool.Tool{weatherTool, sentimentTool},
    })
    if err != nil {
        log.Fatal(err)
    }

    sessionService := session.InMemoryService()
    runner, err := runner.New(runner.Config{
        AppName:        "weather_sentiment_agent",
        Agent:          weatherSentimentAgent,
        SessionService: sessionService,
    })
    if err != nil {
        log.Fatal(err)
    }

    session, err := sessionService.Create(ctx, &session.CreateRequest{
        AppName: "weather_sentiment_agent",
        UserID:  "user1234",
    })
    if err != nil {
        log.Fatal(err)
    }

    run(ctx, runner, session.Session.ID(), "weather in london?")
    run(ctx, runner, session.Session.ID(), "I don't like rain.")
}

func run(ctx context.Context, r *runner.Runner, sessionID string, prompt string) {
    fmt.Printf("\n> %s\n", prompt)
    events := r.Run(
        ctx,
        "user1234",
        sessionID,
        genai.NewContentFromText(prompt, genai.RoleUser),
        agent.RunConfig{
            StreamingMode: agent.StreamingModeNone,
        },
    )
    for event, err := range events {
        if err != nil {
            log.Fatalf("ERROR during agent execution: %v", err)
        }

        if event.Content.Parts[0].Text != "" {
            fmt.Printf("Agent Response: %s\n", event.Content.Parts[0].Text)
        }
    }
}
import com.google.adk.agents.BaseAgent;
import com.google.adk.agents.LlmAgent;
import com.google.adk.runner.Runner;
import com.google.adk.sessions.InMemorySessionService;
import com.google.adk.sessions.Session;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
import com.google.adk.tools.ToolContext; // Ensure this import is correct
import com.google.common.collect.ImmutableList;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class WeatherSentimentAgentApp {

  private static final String APP_NAME = "weather_sentiment_agent";
  private static final String USER_ID = "user1234";
  private static final String SESSION_ID = "1234";
  private static final String MODEL_ID = "gemini-2.0-flash";

  /**
   * Retrieves the current weather report for a specified city.
   *
   * @param city The city for which to retrieve the weather report.
   * @param toolContext The context for the tool.
   * @return A dictionary containing the weather information.
   */
  public static Map<String, Object> getWeatherReport(
      @Schema(name = "city")
      String city,
      @Schema(name = "toolContext")
      ToolContext toolContext) {
    Map<String, Object> response = new HashMap<>();

    if (city.toLowerCase(Locale.ROOT).equals("london")) {
      response.put("status", "success");
      response.put(
          "report",
          "The current weather in London is cloudy with a temperature of 18 degrees Celsius and a"
              + " chance of rain.");
    } else if (city.toLowerCase(Locale.ROOT).equals("paris")) {
      response.put("status", "success");
      response.put(
          "report", "The weather in Paris is sunny with a temperature of 25 degrees Celsius.");
    } else {
      response.put("status", "error");
      response.put(
          "error_message", String.format("Weather information for '%s' is not available.", city));
    }
    return response;
  }

  /**
   * Analyzes the sentiment of the given text.
   *
   * @param text The text to analyze.
   * @param toolContext The context for the tool.
   * @return A dictionary with sentiment and confidence score.
   */
  public static Map<String, Object> analyzeSentiment(
      @Schema(name = "text")
      String text,
      @Schema(name = "toolContext")
      ToolContext toolContext) {
    Map<String, Object> response = new HashMap<>();
    String lowerText = text.toLowerCase(Locale.ROOT);
    if (lowerText.contains("good") || lowerText.contains("sunny")) {
      response.put("sentiment", "positive");
      response.put("confidence", 0.8);
    } else if (lowerText.contains("rain") || lowerText.contains("bad")) {
      response.put("sentiment", "negative");
      response.put("confidence", 0.7);
    } else {
      response.put("sentiment", "neutral");
      response.put("confidence", 0.6);
    }
    return response;
  }

  /**
   * Calls the agent with the given query and prints the final response.
   *
   * @param runner The runner to use.
   * @param query The query to send to the agent.
   */
  public static void callAgent(Runner runner, String query) {
    Content content = Content.fromParts(Part.fromText(query));

    InMemorySessionService sessionService = (InMemorySessionService) runner.sessionService();
    Session session =
        sessionService
            .createSession(APP_NAME, USER_ID, /* state= */ null, SESSION_ID)
            .blockingGet();

    runner
        .runAsync(session.userId(), session.id(), content)
        .forEach(
            event -> {
              if (event.finalResponse()
                  && event.content().isPresent()
                  && event.content().get().parts().isPresent()
                  && !event.content().get().parts().get().isEmpty()
                  && event.content().get().parts().get().get(0).text().isPresent()) {
                String finalResponse = event.content().get().parts().get().get(0).text().get();
                System.out.println("Agent Response: " + finalResponse);
              }
            });
  }

  public static void main(String[] args) throws NoSuchMethodException {
    FunctionTool weatherTool =
        FunctionTool.create(
            WeatherSentimentAgentApp.class.getMethod(
                "getWeatherReport", String.class, ToolContext.class));
    FunctionTool sentimentTool =
        FunctionTool.create(
            WeatherSentimentAgentApp.class.getMethod(
                "analyzeSentiment", String.class, ToolContext.class));

    BaseAgent weatherSentimentAgent =
        LlmAgent.builder()
            .model(MODEL_ID)
            .name("weather_sentiment_agent")
            .description("Weather Sentiment Agent")
            .instruction("""
                    You are a helpful assistant that provides weather information and analyzes the
                    sentiment of user feedback
                    **If the user asks about the weather in a specific city, use the
                    'get_weather_report' tool to retrieve the weather details.**
                    **If the 'get_weather_report' tool returns a 'success' status, provide the
                    weather report to the user.**
                    **If the 'get_weather_report' tool returns an 'error' status, inform the
                    user that the weather information for the specified city is not available
                    and ask if they have another city in mind.**
                    **After providing a weather report, if the user gives feedback on the
                    weather (e.g., 'That's good' or 'I don't like rain'), use the
                    'analyze_sentiment' tool to understand their sentiment.** Then, briefly
                    acknowledge their sentiment.
                    You can handle these tasks sequentially if needed.
                    """)
            .tools(ImmutableList.of(weatherTool, sentimentTool))
            .build();

    InMemorySessionService sessionService = new InMemorySessionService();
    Runner runner = new Runner(weatherSentimentAgent, APP_NAME, null, sessionService);

    // Change the query to ensure the tool is called with a valid city that triggers a "success"
    // response from the tool, like "london" (without the question mark).
    callAgent(runner, "weather in paris");
  }
}
import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.annotations.Param
import com.google.adk.kt.annotations.Tool
import com.google.adk.kt.models.Gemini
import com.google.adk.kt.runners.InMemoryRunner
import com.google.adk.kt.sessions.InMemorySessionService
import com.google.adk.kt.sessions.SessionKey
import com.google.adk.kt.types.Content
import com.google.adk.kt.types.Part
import com.google.adk.kt.types.Role
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking

private const val APP_NAME = "weather_sentiment_agent"
private const val USER_ID = "user1234"
private const val SESSION_ID = "1234"

class WeatherSentimentTools {
    /**
     * Retrieves the current weather report for a specified city.
     *
     * Returns a map with a "status" key ("success" or "error"), plus a "report"
     * with the weather details on success or an "error_message" on failure.
     */
    @Tool
    fun getWeatherReport(
        @Param("The city to retrieve the weather report for.") city: String,
    ): Map<String, String> =
        when (city.lowercase()) {
            "london" ->
                mapOf(
                    "status" to "success",
                    "report" to
                        "The current weather in London is cloudy with a temperature " +
                        "of 18 degrees Celsius and a chance of rain.",
                )
            "paris" ->
                mapOf(
                    "status" to "success",
                    "report" to
                        "The weather in Paris is sunny with a temperature of " +
                        "25 degrees Celsius.",
                )
            else ->
                mapOf(
                    "status" to "error",
                    "error_message" to "Weather information for '$city' is not available.",
                )
        }

    /**
     * Analyzes the sentiment of the given text.
     *
     * Returns a map with a "sentiment" ("positive", "negative" or "neutral") and
     * a "confidence" score.
     */
    @Tool
    fun analyzeSentiment(
        @Param("The text to analyze.") text: String,
    ): Map<String, Any> {
        val lowered = text.lowercase()
        return when {
            "good" in lowered || "sunny" in lowered ->
                mapOf("sentiment" to "positive", "confidence" to 0.8)
            "rain" in lowered || "bad" in lowered ->
                mapOf("sentiment" to "negative", "confidence" to 0.7)
            else -> mapOf("sentiment" to "neutral", "confidence" to 0.6)
        }
    }
}

fun main() =
    runBlocking {
        // The instruction names each tool and says how to handle its return values,
        // including chaining one tool's output into the next.
        val weatherSentimentAgent =
            LlmAgent(
                name = "weather_sentiment_agent",
                model = Gemini(name = "gemini-flash-latest"),
                instruction =
                    Instruction(
                        """
                        You are a helpful assistant that provides weather information
                        and analyzes the sentiment of user feedback.

                        If the user asks about the weather in a specific city, use the
                        getWeatherReport tool. If it returns a "success" status, provide
                        the report to the user. If it returns an "error" status, tell the
                        user the information is unavailable and ask for another city.

                        After providing a weather report, if the user gives feedback on
                        the weather, use the analyzeSentiment tool to understand their
                        sentiment, then briefly acknowledge it.
                        """.trimIndent(),
                    ),
                tools = WeatherSentimentTools().generatedTools(),
            )

        val sessionService = InMemorySessionService()
        val runner =
            InMemoryRunner(
                agent = weatherSentimentAgent,
                appName = APP_NAME,
                sessionService = sessionService,
            )
        sessionService.createSession(SessionKey(APP_NAME, USER_ID, SESSION_ID))

        val query = "weather in london?"
        println("User Query: $query")
        val userContent = Content(role = Role.USER, parts = listOf(Part(text = query)))

        val events =
            runner.runAsync(
                userId = USER_ID,
                sessionId = SESSION_ID,
                newMessage = userContent,
            ).toList()

        for (event in events) {
            if (event.isFinalResponse) {
                println("Agent Response: ${event.content?.parts?.firstOrNull()?.text}")
            }
        }
    }

工具上下文(Tool Context)

对于更复杂的场景,ADK 允许您通过添加一个特殊参数,在工具函数中访问额外的上下文信息。 tool_context: ToolContext通过在函数签名中包含这一内容,ADK 将能够…… 自动地 提供一个 `ToolContext` 的一个实例 当你的工具在代理执行过程中被调用时,该类会被实例化。

The ToolContext 提供了对几项关键信息及控制功能的访问权限:

  • state: State:读取并修改当前会话的状态。在此所做的更改会被记录下来并持久化(即不会在会话结束时丢失)。

  • actions: EventActions在工具运行后,该设置会影响代理的后续操作(例如:跳过摘要生成功能,或将任务转交给另一个代理)。

  • function_call_id: str | None:该框架为此次特定的工具调用分配的唯一标识符。该标识符有助于追踪相关事件,并与身份验证响应进行关联;在单个模型响应中同时调用了多个工具时,该标识符也会发挥重要作用。

  • invocation_id: str:当前调用的唯一标识符。

  • agent_name: str:正在运行的代理程序的名称。

  • get_auth_response(auth_config):如果在此工具调用之前已经完成了身份验证流程,则会返回相应的身份验证凭据。

  • 服务访问:用于与已配置的服务(如 Artifacts 和 Memory)进行交互的方法。

请注意,您不应该包含该内容。 tool_context 该参数出现在工具函数的文档字符串(docstring)中。由于…… ToolContext 该代码片段会由 ADK 框架自动插入到目标程序中。 之后;随后 大型语言模型(LLM)决定调用某个工具函数;不过这个函数与模型的决策过程并无直接关系,将其包含在模型的功能中反而可能会让模型变得混乱(即:该函数的存在反而可能干扰模型的正常运行)。

状态管理(State Management)

The tool_context.state `attribute` 提供了对当前会话相关状态的直接读写访问权限。它的行为类似于字典(dictionary),但会确保所有修改都被记录为“差异值”(deltas),并由会话服务(session service)负责持久化这些更改。这使得工具能够在不同的交互过程或代理步骤(agent steps)之间维护和共享信息。

  • 读取状态(Reading State):使用标准的字典访问方式。tool_context.state['my_key'])或 .get() `method`(方法)tool_context.state.get('my_key', default_value)).

  • “Writing State”(写作状态):直接为变量赋值tool_context.state['new_key'] = 'new_value'这些更改会被记录在最终事件的状态变量 `state_delta` 中。

  • 状态前缀(State Prefixes)请记住标准的状态前缀:

    • app:*:该功能对应用程序的所有用户均可见(即所有用户均可使用该功能)。

    • user:*:仅与当前用户在其所有会话中的行为相关。

    • (无前缀):仅与当前会话相关。

    • temp:*:这种机制是临时性的,数据不会在多次调用之间被保留(适用于在单次运行过程中传递数据,但在需要在多个大型语言模型(LLM)调用之间进行操作的工具环境中,其实用性较低)。

# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from google.adk.tools import ToolContext, FunctionTool

def update_user_preference(preference: str, value: str, tool_context: ToolContext):
    """Updates a user-specific preference."""
    user_prefs_key = "user:preferences"
    # Get current preferences or initialize if none exist
    preferences = tool_context.state.get(user_prefs_key, {})
    preferences[preference] = value
    # Write the updated dictionary back to the state
    tool_context.state[user_prefs_key] = preferences
    print(f"Tool: Updated user preference '{preference}' to '{value}'")
    return {"status": "success", "updated_preference": preference}

pref_tool = FunctionTool(func=update_user_preference)

# In an Agent:
# my_agent = Agent(..., tools=[pref_tool])

# When the LLM calls update_user_preference(preference='theme', value='dark', ...):
# The tool_context.state will be updated, and the change will be part of the
# resulting tool response event's actions.state_delta.
import { Context } from '@google/adk';

// Updates a user-specific preference.
export function updateUserThemePreference(
  value: string,
  context: Context
): Record<string, any> {
  const userPrefsKey = "user:preferences";

  // Get current preferences or initialize if none exist
  const preferences = context.state.get(userPrefsKey, {}) as Record<string, any>;
  preferences["theme"] = value;

  // Write the updated dictionary back to the state
  context.state.set(userPrefsKey, preferences);
  console.log(
    `Tool: Updated user preference ${userPrefsKey} to ${JSON.stringify(context.state.get(userPrefsKey))}`
  );

  return {
    status: "success",
    updated_preference: context.state.get(userPrefsKey),
  };
  // When the LLM calls updateUserThemePreference("dark"):
  // The context.state will be updated, and the change will be part of the
  // resulting tool response event's actions.stateDelta.
}
import (
    "fmt"

    "google.golang.org/adk/v2/agent"
)

type updateUserPreferenceArgs struct {
    Preference string `json:"preference" jsonschema:"The name of the preference to set."`
    Value      string `json:"value" jsonschema:"The value to set for the preference."`
}

type updateUserPreferenceResult struct {
    UpdatedPreference string `json:"updated_preference"`
}

func updateUserPreference(ctx agent.Context, args updateUserPreferenceArgs) (*updateUserPreferenceResult, error) {
    userPrefsKey := "user:preferences"
    val, err := ctx.State().Get(userPrefsKey)
    if err != nil {
        val = make(map[string]any)
    }

    preferencesMap, ok := val.(map[string]any)
    if !ok {
        preferencesMap = make(map[string]any)
    }

    preferencesMap[args.Preference] = args.Value

    if err := ctx.State().Set(userPrefsKey, preferencesMap); err != nil {
        return nil, err
    }

    fmt.Printf("Tool: Updated user preference '%s' to '%s'\n", args.Preference, args.Value)
    return &updateUserPreferenceResult{
        UpdatedPreference: args.Preference,
    }, nil
}
import com.google.adk.tools.FunctionTool;
import com.google.adk.tools.ToolContext;

// Updates a user-specific preference.
public Map<String, String> updateUserThemePreference(String value, ToolContext toolContext) {
  String userPrefsKey = "user:preferences:theme";

  // Get current preferences or initialize if none exist
  String preference = toolContext.state().getOrDefault(userPrefsKey, "").toString();
  if (preference.isEmpty()) {
    preference = value;
  }

  // Write the updated dictionary back to the state
  toolContext.state().put("user:preferences", preference);
  System.out.printf("Tool: Updated user preference %s to %s", userPrefsKey, preference);

  return Map.of("status", "success", "updated_preference", toolContext.state().get(userPrefsKey).toString());
  // When the LLM calls updateUserThemePreference("dark"):
  // The toolContext.state will be updated, and the change will be part of the
  // resulting tool response event's actions.stateDelta.
}
import com.google.adk.kt.annotations.Param
import com.google.adk.kt.annotations.Tool
import com.google.adk.kt.tools.ToolContext

class UserPreferenceTools {
    /**
     * Updates a user-specific preference.
     */
    @Tool
    fun updateUserPreference(
        @Param("The name of the preference to update.") preference: String,
        @Param("The value to set the preference to.") value: String,
        context: ToolContext,
    ): Map<String, String> {
        // One key per preference, so each write stands on its own. The "user:"
        // prefix scopes the value to this user across all their sessions.
        val userPrefsKey = "user:preferences:$preference"

        // Read through the readonly view of the context.
        val previous = context.context.state[userPrefsKey] as? String

        // Kotlin has no mutable `state` on ToolContext. Writing through
        // actions.stateDelta is what puts the change on the resulting event, which
        // is the same effect as assigning to `tool_context.state` in Python.
        context.actions.stateDelta[userPrefsKey] = value

        println("Tool: Updated user preference '$preference' from '$previous' to '$value'")
        return mapOf("status" to "success", "updated_preference" to preference)
    }
}

// In an agent:
//   LlmAgent(..., tools = UserPreferenceTools().generatedTools())
//
// When the LLM calls updateUserPreference(preference = "theme", value = "dark"),
// the delta is written to the session state and travels on the resulting tool
// response event as actions.stateDelta.

控制代理流程(Controlling Agent Flow)

The tool_context.actions 在 Python 和 TypeScript 中使用 `attribute` ToolContext.actions() 在 Java 中,以及…… agent.Context.Actions() 在 Go 语言中,`holds an` 表示“持有某个值”或“包含某个元素”。 EventActions 通过修改该对象的属性,您的工具可以影响代理或框架在工具执行完成后所执行的操作。

  • skip_summarization: bool(默认值:无)如果将该参数设置为 `True`,则会指示 ADK 跳过通常用于总结工具输出结果的 LLM(Large Language Model,大型语言模型)调用。当您的工具返回的值本身就是用户可以直接使用的信息时,这种方法非常有用。

  • transfer_to_agent: str:将此字段设置为另一个代理的名称。框架将停止当前代理的执行。 将对话的控制权转移给指定的代理。这使得工具能够动态地将任务分配给更专业的处理人员。

  • escalate: bool: (默认值:None)将此值设置为 True 表示当前代理无法处理该请求,应将其控制权传递给其上级代理(如果该代理属于层级结构的一部分)。在 LoopAgent 中,设置该值为 True 时,请求会继续被传递给下一个代理进行处理。 escalate=True 在子代理的工具中,该操作会终止循环(即停止该程序的重复执行)。

示例:

# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio

from google.adk.agents import Agent
from google.adk.tools import FunctionTool
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools import ToolContext
from google.genai import types

APP_NAME="customer_support_agent"
USER_ID="user1234"
SESSION_ID="1234"


def check_and_transfer(query: str, tool_context: ToolContext) -> str:
    """Checks if the query requires escalation and transfers to another agent if needed."""
    if "urgent" in query.lower():
        print("Tool: Detected urgency, transferring to the support agent.")
        tool_context.actions.transfer_to_agent = "support_agent"
        return "Transferring to the support agent..."
    else:
        return f"Processed query: '{query}'. No further action needed."

escalation_tool = FunctionTool(func=check_and_transfer)

support_agent = Agent(
    model='gemini-2.0-flash',
    name='support_agent',
    instruction="""You are the dedicated support agent. Mentioned you are a support handler and please help the user with their urgent issue."""
)

# Pass `sub_agents` to the constructor: that is what links `support_agent` back
# to `main_agent` as its parent. Assigning `main_agent.sub_agents` afterwards
# leaves `support_agent.parent_agent` unset, so transfers fail.
main_agent = Agent(
    model='gemini-2.0-flash',
    name='main_agent',
    instruction="""You are the first point of contact for customer support of an analytics tool. Answer general queries. If the user indicates urgency, use the 'escalation_tool' tool.""",
    tools=[escalation_tool],
    sub_agents=[support_agent]
)

# Session and Runner
async def setup_session_and_runner():
    session_service = InMemorySessionService()
    session = await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
    runner = Runner(agent=main_agent, app_name=APP_NAME, session_service=session_service)
    return session, runner

# Agent Interaction
async def call_agent_async(query):
    content = types.Content(role='user', parts=[types.Part(text=query)])
    session, runner = await setup_session_and_runner()
    events = runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=content)

    async for event in events:
        if event.is_final_response() and event.content and event.content.parts:
            final_response = event.content.parts[0].text
            print("Agent Response: ", final_response)

async def main():
    await call_agent_async("this is urgent, i cant login")

# Note: In Colab, you can directly 'await call_agent_async(...)' at the top level.
if __name__ == "__main__":
    asyncio.run(main())
/**
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { LlmAgent, FunctionTool, Context, InMemoryRunner, isFinalResponse, stringifyContent } from '@google/adk';
import { z } from "zod";
import { Content, createUserContent } from "@google/genai";

function checkAndTransfer(
  params: { query: string },
  context?: Context
): Record<string, any> {
  if (!context) {
    // This should not happen in a normal ADK flow where the tool is called by an agent.
    throw new Error("Context is required to transfer agents.");
  }
  if (params.query.toLowerCase().includes("urgent")) {
    console.log("Tool: Urgent query detected, transferring to support_agent.");
    context.actions.transferToAgent = "support_agent";
    return { status: "success", message: "Transferring to support agent." };
  }

  console.log("Tool: Query is not urgent, handling normally.");
  return { status: "success", message: "Query will be handled by the main agent." };
}

const transferTool = new FunctionTool({
  name: "check_and_transfer",
  description: "Checks the user's query and transfers to a support agent if urgent.",
  parameters: z.object({
    query: z.string().describe("The user query to analyze."),
  }),
  execute: checkAndTransfer,
});

const supportAgent = new LlmAgent({
  name: "support_agent",
  description: "Handles urgent user requests about accounts.",
  instruction: "You are the support agent. Handle the user's urgent request.",
  model: "gemini-2.5-flash"
});

const mainAgent = new LlmAgent({
  name: "main_agent",
  description: "The main agent that routes non-urgent queries.",
  instruction: "You are the main agent. Use the check_and_transfer tool to analyze the user query. If the query is not urgent, handle it yourself.",
  tools: [transferTool],
  subAgents: [supportAgent],
  model: "gemini-2.5-flash"
});

async function main() {
  const runner = new InMemoryRunner({ agent: mainAgent, appName: "customer_support_app" });

  console.log("--- Running with a non-urgent query ---");
  await runner.sessionService.createSession({ appName: "customer_support_app", userId: "user1", sessionId: "session1" });
  const nonUrgentMessage: Content = createUserContent("I have a general question about my account.");
  for await (const event of runner.runAsync({ userId: "user1", sessionId: "session1", newMessage: nonUrgentMessage })) {
    if (isFinalResponse(event) && event.content?.parts?.length) {
      const text = stringifyContent(event).trim();
      if (text) {
        console.log(`Final Response: ${text}`);
      }
    }
  }

  console.log("\n--- Running with an urgent query ---");
  await runner.sessionService.createSession({ appName: "customer_support_app", userId: "user1", sessionId: "session2" });
  const urgentMessage: Content = createUserContent("My account is locked and this is urgent!");
  for await (const event of runner.runAsync({ userId: "user1", sessionId: "session2", newMessage: urgentMessage })) {
    if (isFinalResponse(event) && event.content?.parts?.length) {
      const text = stringifyContent(event).trim();
      if (text) {
        console.log(`Final Response: ${text}`);
      }
    }
  }
}

main();
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
    "context"
    "fmt"
    "log"
    "strings"

    "google.golang.org/adk/v2/agent"
    "google.golang.org/adk/v2/agent/llmagent"
    "google.golang.org/adk/v2/model/gemini"
    "google.golang.org/adk/v2/runner"
    "google.golang.org/adk/v2/session"
    "google.golang.org/adk/v2/tool"
    "google.golang.org/adk/v2/tool/functiontool"
    "google.golang.org/genai"
)

type checkAndTransferArgs struct {
    Query string `json:"query" jsonschema:"The user's query to check for urgency."`
}

type checkAndTransferResult struct {
    Status string `json:"status"`
}

func checkAndTransfer(ctx agent.Context, args checkAndTransferArgs) (checkAndTransferResult, error) {
    if strings.Contains(strings.ToLower(args.Query), "urgent") {
        fmt.Println("Tool: Detected urgency, transferring to the support agent.")
        ctx.Actions().TransferToAgent = "support_agent"
        return checkAndTransferResult{Status: "Transferring to the support agent..."}, nil
    }
    return checkAndTransferResult{Status: fmt.Sprintf("Processed query: '%s'. No further action needed.", args.Query)}, nil
}

func main() {
    ctx := context.Background()
    model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
    if err != nil {
        log.Fatal(err)
    }

    supportAgent, err := llmagent.New(llmagent.Config{
        Name:        "support_agent",
        Model:       model,
        Instruction: "You are the dedicated support agent. Mentioned you are a support handler and please help the user with their urgent issue.",
    })
    if err != nil {
        log.Fatal(err)
    }

    checkAndTransferTool, err := functiontool.New(
        functiontool.Config{
            Name:        "check_and_transfer",
            Description: "Checks if the query requires escalation and transfers to another agent if needed.",
        },
        checkAndTransfer,
    )
    if err != nil {
        log.Fatal(err)
    }

    mainAgent, err := llmagent.New(llmagent.Config{
        Name:        "main_agent",
        Model:       model,
        Instruction: "You are the first point of contact for customer support of an analytics tool. Answer general queries. If the user indicates urgency, use the 'check_and_transfer' tool.",
        Tools:       []tool.Tool{checkAndTransferTool},
        SubAgents:   []agent.Agent{supportAgent},
    })
    if err != nil {
        log.Fatal(err)
    }

    sessionService := session.InMemoryService()
    runner, err := runner.New(runner.Config{
        AppName:        "customer_support_agent",
        Agent:          mainAgent,
        SessionService: sessionService,
    })
    if err != nil {
        log.Fatal(err)
    }

    session, err := sessionService.Create(ctx, &session.CreateRequest{
        AppName: "customer_support_agent",
        UserID:  "user1234",
    })
    if err != nil {
        log.Fatal(err)
    }

    run(ctx, runner, session.Session.ID(), "this is urgent, i cant login")
}

func run(ctx context.Context, r *runner.Runner, sessionID string, prompt string) {
    fmt.Printf("\n> %s\n", prompt)
    events := r.Run(
        ctx,
        "user1234",
        sessionID,
        genai.NewContentFromText(prompt, genai.RoleUser),
        agent.RunConfig{
            StreamingMode: agent.StreamingModeNone,
        },
    )
    for event, err := range events {
        if err != nil {
            log.Fatalf("ERROR during agent execution: %v", err)
        }

        if event.Content.Parts[0].Text != "" {
            fmt.Printf("Agent Response: %s\n", event.Content.Parts[0].Text)
        }
    }
}
import com.google.adk.agents.LlmAgent;
import com.google.adk.runner.Runner;
import com.google.adk.sessions.InMemorySessionService;
import com.google.adk.sessions.Session;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
import com.google.adk.tools.ToolContext;
import com.google.common.collect.ImmutableList;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class CustomerSupportAgentApp {

  private static final String APP_NAME = "customer_support_agent";
  private static final String USER_ID = "user1234";
  private static final String SESSION_ID = "1234";
  private static final String MODEL_ID = "gemini-2.0-flash";

  /**
   * Checks if the query requires escalation and transfers to another agent if needed.
   *
   * @param query The user's query.
   * @param toolContext The context for the tool.
   * @return A map indicating the result of the check and transfer.
   */
  public static Map<String, Object> checkAndTransfer(
      @Schema(name = "query", description = "the user query")
      String query,
      @Schema(name = "toolContext", description = "the tool context")
      ToolContext toolContext) {
    Map<String, Object> response = new HashMap<>();
    if (query.toLowerCase(Locale.ROOT).contains("urgent")) {
      System.out.println("Tool: Detected urgency, transferring to the support agent.");
      toolContext.actions().setTransferToAgent("support_agent");
      response.put("status", "transferring");
      response.put("message", "Transferring to the support agent...");
    } else {
      response.put("status", "processed");
      response.put(
          "message", String.format("Processed query: '%s'. No further action needed.", query));
    }
    return response;
  }

  /**
   * Calls the agent with the given query and prints the final response.
   *
   * @param runner The runner to use.
   * @param query The query to send to the agent.
   */
  public static void callAgent(Runner runner, String query) {
    Content content =
        Content.fromParts(Part.fromText(query));

    InMemorySessionService sessionService = (InMemorySessionService) runner.sessionService();
    // Fixed: session ID does not need to be an optional.
    Session session =
        sessionService
            .createSession(APP_NAME, USER_ID, /* state= */ null, SESSION_ID)
            .blockingGet();

    runner
        .runAsync(session.userId(), session.id(), content)
        .forEach(
            event -> {
              if (event.finalResponse()
                  && event.content().isPresent()
                  && event.content().get().parts().isPresent()
                  && !event.content().get().parts().get().isEmpty()
                  && event.content().get().parts().get().get(0).text().isPresent()) {
                String finalResponse = event.content().get().parts().get().get(0).text().get();
                System.out.println("Agent Response: " + finalResponse);
              }
            });
  }

  public static void main(String[] args) throws NoSuchMethodException {
    FunctionTool escalationTool =
        FunctionTool.create(
            CustomerSupportAgentApp.class.getMethod(
                "checkAndTransfer", String.class, ToolContext.class));

    LlmAgent supportAgent =
        LlmAgent.builder()
            .model(MODEL_ID)
            .name("support_agent")
            .description("""
                The dedicated support agent.
                Mentions it is a support handler and helps the user with their urgent issue.
            """)
            .instruction("""
                You are the dedicated support agent.
                Mentioned you are a support handler and please help the user with their urgent issue.
            """)
            .build();

    LlmAgent mainAgent =
        LlmAgent.builder()
            .model(MODEL_ID)
            .name("main_agent")
            .description("""
                The first point of contact for customer support of an analytics tool.
                Answers general queries.
                If the user indicates urgency, uses the 'check_and_transfer' tool.
                """)
            .instruction("""
                You are the first point of contact for customer support of an analytics tool.
                Answer general queries.
                If the user indicates urgency, use the 'check_and_transfer' tool.
                """)
            .tools(ImmutableList.of(escalationTool))
            .subAgents(supportAgent)
            .build();
    // Fixed: LlmAgent.subAgents() expects 0 arguments.
    // Sub-agents are now added to the main agent via its builder,
    // as `subAgents` is a property that should be set during agent construction
    // if it's not dynamically managed.

    InMemorySessionService sessionService = new InMemorySessionService();
    Runner runner = new Runner(mainAgent, APP_NAME, null, sessionService);

    // Agent Interaction
    callAgent(runner, "this is urgent, i cant login");
  }
}
import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.annotations.Param
import com.google.adk.kt.annotations.Tool
import com.google.adk.kt.models.Gemini
import com.google.adk.kt.runners.InMemoryRunner
import com.google.adk.kt.sessions.InMemorySessionService
import com.google.adk.kt.sessions.SessionKey
import com.google.adk.kt.tools.ToolContext
import com.google.adk.kt.types.Content
import com.google.adk.kt.types.Part
import com.google.adk.kt.types.Role
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking

private const val APP_NAME = "customer_support_agent"
private const val USER_ID = "user1234"
private const val SESSION_ID = "1234"

class EscalationTools {
    /**
     * Checks if the query requires escalation and transfers to another agent if needed.
     */
    @Tool
    fun checkAndTransfer(
        @Param("The user query to triage.") query: String,
        context: ToolContext,
    ): String =
        if ("urgent" in query.lowercase()) {
            println("Tool: Detected urgency, transferring to the support agent.")
            // Setting transferToAgent on the actions hands control to the named
            // agent once this tool returns.
            context.actions.transferToAgent = "support_agent"
            "Transferring to the support agent..."
        } else {
            "Processed query: '$query'. No further action needed."
        }
}

fun main() =
    runBlocking {
        val supportAgent =
            LlmAgent(
                name = "support_agent",
                model = Gemini(name = "gemini-flash-latest"),
                instruction =
                    Instruction(
                        "You are the dedicated support agent. Mention that you are a " +
                            "support handler and help the user with their urgent issue.",
                    ),
            )

        val mainAgent =
            LlmAgent(
                name = "main_agent",
                model = Gemini(name = "gemini-flash-latest"),
                instruction =
                    Instruction(
                        "You are the first point of contact for customer support of an " +
                            "analytics tool. Answer general queries. If the user indicates " +
                            "urgency, use the checkAndTransfer tool.",
                    ),
                tools = EscalationTools().generatedTools(),
                subAgents = listOf(supportAgent),
            )

        val sessionService = InMemorySessionService()
        val runner =
            InMemoryRunner(
                agent = mainAgent,
                appName = APP_NAME,
                sessionService = sessionService,
            )
        sessionService.createSession(
            SessionKey(APP_NAME, USER_ID, SESSION_ID),
        )

        val query = "this is urgent, i cant login"
        val userContent = Content(role = Role.USER, parts = listOf(Part(text = query)))

        val events =
            runner.runAsync(
                userId = USER_ID,
                sessionId = SESSION_ID,
                newMessage = userContent,
            ).toList()

        for (event in events) {
            if (event.isFinalResponse) {
                println("Agent Response: ${event.content?.parts?.firstOrNull()?.text}")
            }
        }
    }
说明(Explanation)
  • 我们定义了两个代理(agents): main_agent 和 support_agent. The main_agent 它被设计为最初的联系点(即用户与系统交互的第一个入口)。
  • The check_and_transfer 当通过 `tool` 调用时…… main_agent该系统会检查用户的查询内容。
  • 如果查询中包含“urgent”这个词,该工具将会访问相应的资源或数据。 tool_context具体来说: tool_context.actions,并将 `transfer_to_agent` 属性设置为 support_agent.
  • 此操作向框架发出信号,表示…… 将对话的控制权转移给名为 “[代理人名称]” 的代理。 support_agent.
  • 当……的时候 main_agent 处理紧急查询…… check_and_transfer 该工具会触发数据传输过程。后续的响应理想情况下应该来自……(此处应填写具体的来源或系统)。 support_agent.
  • 对于普通的、没有紧急性的查询,该工具会直接对其进行处理,而不会触发数据传输。

这个示例说明了:通过其 `ToolContext` 中的 `EventActions`,某个工具如何能够动态地影响对话的流程,并将控制权转移给另一个专门的代理(即负责处理特定任务的系统或人员)。

身份验证(Authentication)

`ToolContext` 为工具提供了与已认证的 API 进行交互的机制。如果您的工具需要处理身份验证(即用户认证)相关的工作,您可以参考以下内容:

  • request_credential(auth_config: AuthConfig) (在 Python 中)或者 requestCredential(authConfig: AuthConfig) (在 TypeScript 中):如果您的工具判断需要身份验证,但用户凭据不可用,请调用此方法。该方法会向框架发出信号,使其根据提供的 `auth_config` 开始身份验证流程。

  • get_auth_response(auth_config: AuthConfig) (在 Python 中)或者 getAuthResponse(authConfig: AuthConfig) (在 TypeScript 中):在后续的调用中(在 `request_credential` 被成功处理之后),使用此函数来获取用户提供的凭据。该函数会返回一个包含凭据的对象。 AuthCredential,或 None 如果还没有可用的凭据(credential),则……

有关身份验证流程、配置方式及使用示例的详细说明,请参阅专门的“工具身份验证”文档页面。

基于上下文的数据访问方法(Context-Aware Data Access Methods)

这些方法为你的工具提供了方便的方式,使其能够与与会话或用户相关联的持久数据进行交互;这些数据由已配置的服务进行管理。在 Python 中,下面列出的所有方法都属于用于处理“工件”(artifacts)和内存(memory)相关操作的方法。 async因此,你的工具函数必须是一个(具体的函数类型或实现方式需要根据上下文来确定)。 async def 和 await them.

  • list_artifacts() (在 Python 中)或者 listArtifacts() (在 Java 和 TypeScript 中):通过 `artifact_service` 返回当前会话中存储的所有工件的文件名(或键)列表。这些工件通常是用户上传的文件(如图片、文档等),也可能是由工具/代理程序生成的文件。

  • load_artifact(filename: str):根据文件名从存储库中检索特定的工件(artifact)。 artifact_service您可以可选地指定一个版本号;如果未指定,则会返回最新版本。返回值为…… google.genai.types.Part 一个对象,其中包含该“工件”(artifact)的数据及其 MIME 类型;如果找不到该“工件”,则该对象的值为 `None`。

  • save_artifact(filename: str, artifact: types.Part):将某个“artefact”的新版本保存到 `artifact_service` 中,并返回该新版本的编号(编号从 0 开始)。

  • search_memory(query: str):(支持 ADK Python、Go 和 TypeScript 语言) 使用已配置的设置来查询用户的长期记忆(即用户过去存储在记忆中的信息)。 memory_service这对于从过去的交互记录或存储的知识中检索相关信息非常有用。该结构的……(此处原文内容不完整)。 SearchMemoryResponse 这取决于具体的内存服务实现方式,但通常会包含相关的文本片段或对话记录。

示例:

# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from google.adk.tools import ToolContext, FunctionTool
from google.genai import types


async def process_document(
    document_name: str, analysis_query: str, tool_context: ToolContext
) -> dict:
    """Analyzes a document using context from memory."""

    # 1. Load the artifact
    print(f"Tool: Attempting to load artifact: {document_name}")
    document_part = await tool_context.load_artifact(document_name)

    if not document_part:
        return {"status": "error", "message": f"Document '{document_name}' not found."}

    document_text = document_part.text  # Assuming it's text for simplicity
    print(f"Tool: Loaded document '{document_name}' ({len(document_text)} chars).")

    # 2. Search memory for related context
    print(f"Tool: Searching memory for context related to: '{analysis_query}'")
    memory_response = await tool_context.search_memory(
        f"Context for analyzing document about {analysis_query}"
    )
    memory_context = "\n".join(
        [
            m.content.parts[0].text
            for m in memory_response.memories
            if m.content and m.content.parts
        ]
    )  # Simplified extraction
    print(f"Tool: Found memory context: {memory_context[:100]}...")

    # 3. Perform analysis (placeholder)
    analysis_result = f"Analysis of '{document_name}' regarding '{analysis_query}' using memory context: [Placeholder Analysis Result]"
    print("Tool: Performed analysis.")

    # 4. Save the analysis result as a new artifact
    analysis_part = types.Part.from_text(text=analysis_result)
    new_artifact_name = f"analysis_{document_name}"
    version = await tool_context.save_artifact(new_artifact_name, analysis_part)
    print(f"Tool: Saved analysis result as '{new_artifact_name}' version {version}.")

    return {
        "status": "success",
        "analysis_artifact": new_artifact_name,
        "version": version,
    }


doc_analysis_tool = FunctionTool(func=process_document)

# In an Agent:
# Assume artifact 'report.txt' was previously saved.
# Assume memory service is configured and has relevant past data.
# my_agent = Agent(..., tools=[doc_analysis_tool], artifact_service=..., memory_service=...)
import { Part } from "@google/genai";
import { Context } from '@google/adk';

// Analyzes a document using context from memory.
export async function processDocument(
  params: { documentName: string; analysisQuery: string },
  context?: Context
): Promise<Record<string, any>> {
  if (!context) {
    throw new Error("Context is required for this tool.");
  }

  // 1. List all available artifacts
  const artifacts = await context.listArtifacts();
  console.log(`Listing all available artifacts: ${artifacts}`);

  // 2. Load an artifact
  console.log(`Tool: Attempting to load artifact: ${params.documentName}`);
  const documentPart = await context.loadArtifact(params.documentName);
  if (!documentPart) {
    console.log(`Tool: Document '${params.documentName}' not found.`);
    return {
      status: "error",
      message: `Document '${params.documentName}' not found.`, 
    };
  }

  const documentText = documentPart.text ?? "";
  console.log(
    `Tool: Loaded document '${params.documentName}' (${documentText.length} chars).`
  );

  // 3. Search memory for related context
  console.log(`Tool: Searching memory for context related to '${params.analysisQuery}'`);
  const memory_results = await context.searchMemory(params.analysisQuery);
  console.log(`Tool: Found ${memory_results.memories.length} relevant memories.`);
  const context_from_memory = memory_results.memories
    .map((m) => m.content.parts[0].text)
    .join("\n");

  // 4. Perform analysis (placeholder)
  const analysisResult =
    `Analysis of '${params.documentName}' regarding '${params.analysisQuery}':\n` +
    `Context from Memory:\n${context_from_memory}\n` +
    `[Placeholder Analysis Result]`;
  console.log("Tool: Performed analysis.");

  // 5. Save the analysis result as a new artifact
  const analysisPart: Part = { text: analysisResult };
  const newArtifactName = `analysis_${params.documentName}`;
  await context.saveArtifact(newArtifactName, analysisPart);
  console.log(`Tool: Saved analysis result to '${newArtifactName}'.`);

  return {
    status: "success",
    analysis_artifact: newArtifactName,
  };
}
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
    "fmt"

    "google.golang.org/adk/v2/agent"
    "google.golang.org/genai"
)

type processDocumentArgs struct {
    DocumentName  string `json:"document_name" jsonschema:"The name of the document to be processed."`
    AnalysisQuery string `json:"analysis_query" jsonschema:"The query for the analysis."`
}

type processDocumentResult struct {
    Status           string `json:"status"`
    AnalysisArtifact string `json:"analysis_artifact,omitempty"`
    Version          int64  `json:"version,omitempty"`
    Message          string `json:"message,omitempty"`
}

func processDocument(ctx agent.Context, args processDocumentArgs) (*processDocumentResult, error) {
    fmt.Printf("Tool: Attempting to load artifact: %s\n", args.DocumentName)

    // List all artifacts
    listResponse, err := ctx.Artifacts().List(ctx)
    if err != nil {
        return nil, fmt.Errorf("failed to list artifacts")
    }

    fmt.Println("Tool: Available artifacts:")
    for _, file := range listResponse.FileNames {
        fmt.Printf(" - %s\n", file)
    }

    documentPart, err := ctx.Artifacts().Load(ctx, args.DocumentName)
    if err != nil {
        return nil, fmt.Errorf("document '%s' not found", args.DocumentName)
    }

    fmt.Printf("Tool: Loaded document '%s' of size %d bytes.\n", args.DocumentName, len(documentPart.Part.InlineData.Data))

    // 3. Search memory for related context
    fmt.Printf("Tool: Searching memory for context related to: '%s'\n", args.AnalysisQuery)
    memoryResp, err := ctx.SearchMemory(ctx, args.AnalysisQuery)
    if err != nil {
        fmt.Printf("Tool: Error searching memory: %v\n", err)
    }
    memoryResultCount := 0
    if memoryResp != nil {
        memoryResultCount = len(memoryResp.Memories)
    }
    fmt.Printf("Tool: Found %d memory results.\n", memoryResultCount)

    analysisResult := fmt.Sprintf("Analysis of '%s' regarding '%s' using memory context: [Placeholder Analysis Result]", args.DocumentName, args.AnalysisQuery)
    fmt.Println("Tool: Performed analysis.")

    analysisPart := genai.NewPartFromText(analysisResult)
    newArtifactName := fmt.Sprintf("analysis_%s", args.DocumentName)
    version, err := ctx.Artifacts().Save(ctx, newArtifactName, analysisPart)
    if err != nil {
        return nil, fmt.Errorf("failed to save artifact")
    }
    fmt.Printf("Tool: Saved analysis result as '%s' version %d.\n", newArtifactName, version.Version)

    return &processDocumentResult{
        Status:           "success",
        AnalysisArtifact: newArtifactName,
        Version:          version.Version,
    }, nil
}
// Analyzes a document using context from memory.
// You can also list, load and save artifacts using Callback Context or LoadArtifacts tool.
public static @NonNull Maybe<ImmutableMap<String, Object>> processDocument(
    @Annotations.Schema(description = "The name of the document to analyze.") String documentName,
    @Annotations.Schema(description = "The query for the analysis.") String analysisQuery,
    ToolContext toolContext) {

  // 1. List all available artifacts
  System.out.printf(
      "Listing all available artifacts %s:", toolContext.listArtifacts().blockingGet());

  // 2. Load an artifact to memory
  System.out.println("Tool: Attempting to load artifact: " + documentName);
  Part documentPart = toolContext.loadArtifact(documentName, Optional.empty()).blockingGet();
  if (documentPart == null) {
    System.out.println("Tool: Document '" + documentName + "' not found.");
    return Maybe.just(
        ImmutableMap.<String, Object>of(
            "status", "error", "message", "Document '" + documentName + "' not found."));
  }
  String documentText = documentPart.text().orElse("");
  System.out.println(
      "Tool: Loaded document '" + documentName + "' (" + documentText.length() + " chars).");

  // 3. Perform analysis (placeholder)
  String analysisResult =
      "Analysis of '"
          + documentName
          + "' regarding '"
          + analysisQuery
          + " [Placeholder Analysis Result]";
  System.out.println("Tool: Performed analysis.");

  // 4. Save the analysis result as a new artifact
  Part analysisPart = Part.fromText(analysisResult);
  String newArtifactName = "analysis_" + documentName;

  toolContext.saveArtifact(newArtifactName, analysisPart);

  return Maybe.just(
      ImmutableMap.<String, Object>builder()
          .put("status", "success")
          .put("analysis_artifact", newArtifactName)
          .build());
}
// FunctionTool processDocumentTool =
//      FunctionTool.create(ToolContextArtifactExample.class, "processDocument");
// In the Agent, include this function tool.
// LlmAgent agent = LlmAgent().builder().tools(processDocumentTool).build();
import com.google.adk.kt.annotations.Param
import com.google.adk.kt.annotations.Tool
import com.google.adk.kt.tools.ToolContext
import com.google.adk.kt.types.Part

class DocAnalysisTools {
    /**
     * Analyzes a document held in the session's artifacts.
     *
     * Artifact access is suspending in Kotlin, so the tool is a `suspend fun`.
     * `searchMemory` is not available on the Kotlin ToolContext; to bring
     * long-term memory into a turn, add LoadMemoryTool or PreloadMemoryTool to
     * the agent instead.
     */
    @Tool
    suspend fun processDocument(
        @Param("The name of the document to analyze.") documentName: String,
        @Param("The query for the analysis.") analysisQuery: String,
        context: ToolContext,
    ): Map<String, String> {
        // 1. List all available artifacts.
        println("Tool: Available artifacts: ${context.listArtifacts()}")

        // 2. Load the requested artifact.
        println("Tool: Attempting to load artifact: $documentName")
        val documentPart = context.loadArtifact(documentName)
        if (documentPart == null) {
            println("Tool: Document '$documentName' not found.")
            return mapOf(
                "status" to "error",
                "message" to "Document '$documentName' not found.",
            )
        }

        val documentText = documentPart.text.orEmpty()
        println("Tool: Loaded '$documentName' (${documentText.length} chars).")

        // 3. Perform the analysis (placeholder).
        val analysisResult =
            "Analysis of '$documentName' regarding '$analysisQuery' " +
                "[Placeholder Analysis Result]"
        println("Tool: Performed analysis.")

        // 4. Save the analysis back as a new artifact. saveArtifact returns the
        // new version number and records the change in actions.artifactDelta.
        val newArtifactName = "analysis_$documentName"
        context.saveArtifact(newArtifactName, Part(text = analysisResult))

        return mapOf(
            "status" to "success",
            "analysis_artifact" to newArtifactName,
        )
    }
}

通过利用…… ToolContext通过这些工具,开发人员可以创建更加复杂且能够感知上下文的自定义工具,这些工具能够与 ADK 的架构无缝集成,从而提升其代理程序的整体功能。

定义有效的工具功能

当将某个方法或函数用作 ADK 工具时,其定义方式会显著影响代理程序正确使用该工具的能力。代理程序所使用的大型语言模型(LLM)在很大程度上依赖于该函数的实现细节。 名称, 参数(参数值), 类型提示(Type Hints),以及 `docstring` / 源代码注释 为了理解其用途并生成正确的调用(即执行相应的操作)。

以下是定义有效工具功能的关键指导原则:

  • 函数名称:

    • 请使用描述性强的名称(以动词加名词的形式构成),这些名称能够清楚地表明相应的操作(例如:……)。 get_weather, searchDocuments, schedule_meeting).
    • 请避免使用诸如“generic_name”之类的通用名称。 run, process, handle_data或者使用过于模糊的名称(例如: doStuff即使有详细的描述,像这样的名称仍然…… do_stuff 这可能会让模型混淆:应该在什么时候使用该工具,而不是在其他情况下使用它(例如……)。 cancelFlight.
    • 在工具选择过程中,大型语言模型(LLM)会使用函数名称作为主要的识别依据。
  • 参数(参数值):

    • 你的函数可以包含任意数量的参数。
    • 请使用清晰且具有描述性的名称(例如: city 而不是 c, search_query 而不是 q).
    • 在 Python 中提供类型提示(type hints)。 对于所有参数(例如, city: str, user_id: int, items: list[str]这是非常重要的,因为 ADK 需要根据这些信息为大型语言模型(LLM)生成正确的架构(schema)。
    • 确保所有参数类型的正确性…… 可序列化为 JSON 格式的对象所有 Java 原始类型,以及标准的 Python 类型(如……) str, int, float, bool, list, dict这些类及其组合通常都是安全的。除非它们有明确的 JSON 表示形式,否则应避免将复杂的自定义类实例作为直接参数传递。
    • 对于模型必须提供的信息,请避免使用默认值。 例如:应避免…… def my_func(destination: str = "Paris") 目标值应该来自用户输入或对话上下文。对于那些真正属于可选性的配置参数,可以使用默认值;但请不要使用默认值来隐藏那些工具架构中要求用户必须提供的必要输入信息。
    • self / cls “已自动处理”: 像这样的隐式参数(Implicit parameters)…… self (例如方法)或 cls (对于类方法而言,它们会由 ADK 自动处理,并从显示给大型语言模型(LLM)的架构中排除。你只需要为工具要求大型语言模型提供的逻辑参数定义类型提示和描述即可。)
  • 返回类型:

    • 该函数的返回值 必须是一个字典(dictionary)。dict) 在 Python 中,一个……(in Python, a……) 地图(Map) 在 Java 中,或者使用一种简单的方法(即“plain”方法)。 对象 在 TypeScript 中。
    • 如果你的函数返回的不是字典类型的数据(例如字符串、数字或列表),ADK框架会自动将其转换为字典或 Map 类型的数据。 {'result': your_original_return_value} 在将结果返回给模型之前。
    • 设计字典/映射的键值对(即确定键和值应该是什么)。 描述性强的,且易于理解。 由大型语言模型(LLM)生成/处理。请记住:模型会读取这些输出结果,以此来决定它的下一步行动。
    • 请包含有意义的键(即那些能够表达具体信息的字段)。例如,不要仅仅返回一个错误代码,而应该提供更多关于错误原因的详细信息。 500, return {'status': 'error', 'error_message': 'Database connection failed'}.
    • 这是一个……(It’s a……) 强烈推荐的实践方法(或做法) 要包含一个…… status `key`(例如: 'success', 'error', 'pending', 'ambiguous')以明确显示该工具对模型执行后的结果。
  • 文档字符串/源代码注释:

    • 这一点非常重要。 文档字符串(docstring)是大型语言模型(LLM)描述性信息的主要来源。
    • 请明确说明该工具的具体用途或功能。 (注:根据提供的信息,“does”是一个动词,意为“做”或“进行”。在编程或技术语境中,它通常用于表示某个操作或功能的执行。由于“does”本身没有具体的含义或用法,因此无法为其添加占位符或 API 标识符。以下是一个简单的示例,说明如何在代码中使用该动词。) **示例:** ```python def do_something(): # 执行某些操作 print("操作已完成。") do_something() ``` 在这个示例中,`do_something()` 是一个函数,用于执行特定的操作(例如打印一条消息)。当调用 `do_something()` 时,该函数会执行其中的代码,并输出“操作已完成。”. 请明确说明该工具的用途及其局限性(即它的功能范围和适用条件)。
    • “Explain” 的意思是“解释”或“说明”。它用于要求某人用简单、清晰的语言来解释某个概念、过程或情况。例如:“Can you explain this rule to me?”(你能给我解释一下这条规则吗?) 当……的时候 应该使用这个工具。 提供相关背景信息或示例场景,以帮助大型语言模型(LLM)做出决策。
    • Describe 每个参数 显然。 请解释大型语言模型(LLM)需要提供哪些信息才能支持该论点。
    • **描述:** 该功能用于获取关于某个特定对象或资源的详细信息。用户可以通过提供相应的参数或输入来请求相关数据,系统会根据这些参数来查询数据库或内部存储,并返回相应的结果。结果可能包括对象的属性、状态、位置等详细信息。该功能在许多应用程序和系统中都非常常见,例如管理系统、数据库查询工具、物联网设备监控等。 “structure and meaning of the expected” 的意思是:某事物(或某种现象)的“结构”(即其组成要素及其相互关系)以及其“含义”(即其所代表的意义或功能)。这个短语通常用于描述需要被理解或解释的对象(如数据结构、语言语法、社会现象等)。 dict 返回值尤其是那些不同的…… status 值以及相关的数据键。
    • 请勿描述被注入的 `ToolContext` 参数。. 避免提及那些可选的内容。 tool_context: ToolContext 这个参数仅出现在文档字符串(docstring)的描述中,实际上它并不是大型语言模型(LLM)需要了解的参数。`ToolContext` 是由 ADK(Application Development Kit)注入到程序中的。 之后;随后 大型语言模型(LLM)决定自己来处理这件事。

    一个好的定义示例:

def lookup_order_status(order_id: str) -> dict:
  """Fetches the current status of a customer's order using its ID.

  Use this tool ONLY when a user explicitly asks for the status of
  a specific order and provides the order ID. Do not use it for
  general inquiries.

  Args:
      order_id: The unique identifier of the order to look up.

  Returns:
      A dictionary indicating the outcome.
      On success, status is 'success' and includes an 'order' dictionary.
      On failure, status is 'error' and includes an 'error_message'.
      Example success: {'status': 'success', 'order': {'state': 'shipped', 'tracking_number': '1Z9...'}}
      Example error: {'status': 'error', 'error_message': 'Order ID not found.'}
  """
  # ... function implementation to fetch status ...
  if status_details := fetch_status_from_backend(order_id):
    return {
        "status": "success",
        "order": {
            "state": status_details.state,
            "tracking_number": status_details.tracking,
        },
    }
  else:
    return {"status": "error", "error_message": f"Order ID {order_id} not found."}
/**
 * Fetches the current status of a customer's order using its ID.
 *
 * Use this tool ONLY when a user explicitly asks for the status of
 * a specific order and provides the order ID. Do not use it for
 * general inquiries.
 *
 * @param params The parameters for the function.
 * @param params.order_id The unique identifier of the order to look up.
 * @returns A dictionary indicating the outcome.
 *          On success, status is 'success' and includes an 'order' dictionary.
 *          On failure, status is 'error' and includes an 'error_message'.
 *          Example success: {'status': 'success', 'order': {'state': 'shipped', 'tracking_number': '1Z9...'}}
 *          Example error: {'status': 'error', 'error_message': 'Order ID not found.'}
 */
async function lookupOrderStatus(params: { order_id: string }): Promise<Record<string, any>> {
  // ... function implementation to fetch status from a backend ...
  const status_details = await fetchStatusFromBackend(params.order_id);
  if (status_details) {
    return {
      "status": "success",
      "order": {
        "state": status_details.state,
        "tracking_number": status_details.tracking,
      },
    };
  } else {
    return { "status": "error", "error_message": `Order ID ${params.order_id} not found.` };
  }
}

// Placeholder for a backend call
async function fetchStatusFromBackend(order_id: string): Promise<{state: string, tracking: string} | null> {
    if (order_id === "12345") {
        return { state: "shipped", tracking: "1Z9..." };
    }
    return null;
}
import (
    "fmt"

    "google.golang.org/adk/v2/agent"
)

type lookupOrderStatusArgs struct {
    OrderID string `json:"order_id" jsonschema:"The ID of the order to look up."`
}

type order struct {
    State          string `json:"state"`
    TrackingNumber string `json:"tracking_number"`
}

type lookupOrderStatusResult struct {
    Status string `json:"status"`
    Order  order  `json:"order,omitempty"`
}

func lookupOrderStatus(ctx agent.Context, args lookupOrderStatusArgs) (*lookupOrderStatusResult, error) {
    // ... function implementation to fetch status ...
    statusDetails, ok := fetchStatusFromBackend(args.OrderID)
    if !ok {
        return nil, fmt.Errorf("order ID %s not found", args.OrderID)
    }
    return &lookupOrderStatusResult{
        Status: "success",
        Order: order{
            State:          statusDetails.State,
            TrackingNumber: statusDetails.Tracking,
        },
    }, nil
}
/**
 * Retrieves the current weather report for a specified city.
 *
 * @param city The city for which to retrieve the weather report.
 * @param toolContext The context for the tool.
 * @return A dictionary containing the weather information.
 */
public static Map<String, Object> getWeatherReport(String city, ToolContext toolContext) {
    Map<String, Object> response = new HashMap<>();
    if (city.toLowerCase(Locale.ROOT).equals("london")) {
        response.put("status", "success");
        response.put(
                "report",
                "The current weather in London is cloudy with a temperature of 18 degrees Celsius and a"
                        + " chance of rain.");
    } else if (city.toLowerCase(Locale.ROOT).equals("paris")) {
        response.put("status", "success");
        response.put("report", "The weather in Paris is sunny with a temperature of 25 degrees Celsius.");
    } else {
        response.put("status", "error");
        response.put("error_message", String.format("Weather information for '%s' is not available.", city));
    }
    return response;
}
import com.google.adk.kt.annotations.Param
import com.google.adk.kt.annotations.Tool

class OrderTools {
    /**
     * Fetches the current status of a customer's order using its ID.
     *
     * Use this tool ONLY when a user explicitly asks for the status of a specific
     * order and provides the order ID. Do not use it for general inquiries.
     *
     * Returns a map indicating the outcome. On success, "status" is "success" and
     * an "order" map holds the "state" and "tracking_number". On failure, "status"
     * is "error" and "error_message" explains why.
     */
    @Tool
    fun lookupOrderStatus(
        @Param("The unique identifier of the order to look up.") orderId: String,
    ): Map<String, Any> {
        val statusDetails = fetchStatusFromBackend(orderId)
        return if (statusDetails != null) {
            mapOf(
                "status" to "success",
                "order" to
                    mapOf(
                        "state" to statusDetails.state,
                        "tracking_number" to statusDetails.tracking,
                    ),
            )
        } else {
            mapOf(
                "status" to "error",
                "error_message" to "Order ID $orderId not found.",
            )
        }
    }
}

private data class OrderStatusDetails(val state: String, val tracking: String)

private fun fetchStatusFromBackend(orderId: String): OrderStatusDetails? =
    if (orderId == "1Z9") OrderStatusDetails(state = "shipped", tracking = "1Z9...") else null
  • 简洁与专注:
    • “让工具始终专注于其核心功能”: 每个工具理想情况下都应该只执行一项定义明确的任务。
    • 参数越少越好: 模型通常能够更可靠地处理那些参数较少且定义明确的工具,相比之下,处理那些具有大量可选参数或复杂参数的工具会更加困难。
    • 使用简单的数据类型: 优先使用基本数据类型(basic types)。str, int, bool, float, List[str],在……中 Python; int, byte, short, long, float, double, boolean 和 char 在……里面;处于……状态 Java;或者 string, number, boolean以及像这样的数组: string[] 在……里面;处于……状态 TypeScript)尽可能避免将复杂的自定义类或深度嵌套的结构作为参数传递。
    • 分解复杂的任务: 将那些执行多个不同逻辑步骤的函数拆分为更小、更专注于特定任务的子函数或模块。例如,不要使用一个单一的函数来完成所有逻辑操作,而是将其分解为多个专门处理不同逻辑部分的函数。 update_user_profile(profile: ProfileObject) 工具:考虑使用不同的工具(如……)。 update_user_name(name: str), update_user_address(address: str), update_user_preferences(preferences: list[str])等等。这样,大型语言模型(LLM)就能更容易地选择并使用所需的功能/能力了。

通过遵循这些指导原则,您可以为大型语言模型(LLM)提供所需的清晰度和结构,使其能够有效地使用您的自定义功能工具,从而实现更强大、更可靠的代理行为(即模型执行任务的能力)。

工具集:工具的分类与管理方式(以及工具的动态提供机制)

在 ADK 中得到支持。Python v0.5.0TypeScript v0.2.0Java v0.3.0Kotlin v0.1.0

除了各种单独的工具之外,ADK还引入了一个新的概念…… Toolset 通过……的方式 BaseToolset 接口(在……中定义): google.adk.tools.base_toolset). 该工具集允许您管理和提供一系列(资源或服务)。 BaseTool 这些实例通常会被动态地分配给某个代理(agent)。

这种方法对以下情况非常有益:

  • 整理相关工具: 用于实现共同功能的工具分类(例如:所有用于数学运算的工具,或所有与特定 API 进行交互的工具)。
  • 动态工具可用性: 允许代理根据当前上下文(例如用户权限、会话状态或其他运行时条件)使用不同的工具。 get_tools 工具集的配置方式(即“方法”)可以决定哪些工具会被公开(即可以被用户使用)。
  • 集成外部工具提供商: 这些工具集可以充当来自外部系统(例如遵循 OpenAPI 规范的系统或 MCP 服务器)的工具的“适配器”,将这些工具转换为与 ADK 兼容的形式。 BaseTool objects.

The BaseToolset 接口

任何在 ADK 中充当工具集的类都应该实现…… BaseToolset 这是一个抽象基类(abstract base class)。该接口主要定义了两个方法:

  • async def get_tools(...) -> list[BaseTool]: 这是该工具集的核心方法。当 ADK 代理需要了解自己可用的工具时,它会调用此方法来获取相关信息。 get_tools() 在每一个(情况下) BaseToolset 提供的实例…… tools list.

    • 它接收一个可选参数(optional parameter)。 readonly_context (某个类的)一个实例 ReadonlyContext该上下文提供了对某些信息的只读访问权限,例如当前会话状态(current session state)。readonly_context.state该工具集会使用这些信息(包括请求类型、代理名称以及调用 ID)来动态决定应该返回哪些工具。
    • It 必须;应当 返回一个值。 list 的 BaseTool 实例(例如: FunctionTool, RestApiTool).
  • async def close(self) -> None: 当不再需要该工具集时(例如,代理服务器正在关闭时),ADK框架会调用这个异步方法。 Runner 该工具集即将被关闭。请实现此方法,以执行必要的清理操作,例如关闭网络连接、释放文件句柄,或清理工具集所管理的其他资源。

在 Python 中,基础(base)指的是某种类型或对象的基础实现或默认行为。例如,`int` 类型的基础实现可能是用于存储整数的数据结构;`str` 类型的基础实现可能是用于存储字符串的数据结构。这些基础实现通常由 Python 的内置类型模块(如 `int.py`、`str.py` 等)提供。 __init__ 此外,还提供了两个仅使用关键字的选项,这些选项需要由你的子类进行传递。 super().__init__(...):

  • tool_filter: 一个工具名称的列表,或者…… ToolPredicate `callable`.

  • tool_name_prefix: 这是工具集工具名称的前缀。当设置了前缀后,ADK 会将工具集中的每个工具都暴露给大型语言模型(LLM)。 <prefix>_<tool_name>.

将工具集与代理(Agents)结合使用

你可以包含你的(某些对象或组件的)实例。 BaseToolset 直接在……中实现(这些功能/解决方案)。 LlmAgent's tools 列表,以及各个单独的元素 BaseTool instances.

当代理程序初始化或需要确定自身的可用功能时,ADK框架会遍历相关内容(具体内容未在文档中明确说明)。 tools list:

  • 如果某个项目属于(某个类别或类型),则…… BaseTool 在实例中,该对象可以直接被使用。
  • 如果某个项目属于(某个类别或类型),则…… BaseToolset 实例及其(相关内容) get_tools() 该方法被调用(使用了当前的参数)。 ReadonlyContext),以及返回的列表 BaseTool“s”被添加到了代理可使用的工具列表中。

示例:一个简单的数学工具集

让我们创建一个简单的工具集示例,该工具集能够提供基本的算术运算功能。

import asyncio
from typing import Optional, List, Dict, Any

from google.adk.agents import LlmAgent
from google.adk.agents.readonly_context import ReadonlyContext
from google.adk.tools import BaseTool, FunctionTool
from google.adk.tools.base_toolset import BaseToolset
from google.adk.tools.tool_context import ToolContext
from google.adk.runners import InMemoryRunner


# 1. Define the individual tool functions
def add_numbers(a: int, b: int, tool_context: ToolContext) -> Dict[str, Any]:
    """Adds two integer numbers.
    Args:
        a: The first number.
        b: The second number.
    Returns:
        A dictionary with the sum, e.g., {'status': 'success', 'result': 5}
    """
    print(f"Tool: add_numbers called with a={a}, b={b}")
    result = a + b
    # Example: Storing something in tool_context state
    tool_context.state["last_math_operation"] = "addition"
    return {"status": "success", "result": result}


def subtract_numbers(a: int, b: int) -> Dict[str, Any]:
    """Subtracts the second number from the first.
    Args:
        a: The first number.
        b: The second number.
    Returns:
        A dictionary with the difference, e.g., {'status': 'success', 'result': 1}
    """
    print(f"Tool: subtract_numbers called with a={a}, b={b}")
    return {"status": "success", "result": a - b}


# 2. Create the Toolset by implementing BaseToolset
class SimpleMathToolset(BaseToolset):
    def __init__(self, prefix: str = "math"):
        self.prefix = prefix
        super().__init__(tool_name_prefix=self.prefix) # Toolset can customize names by passing a prefix

        # Create FunctionTool instances once
        self._add_tool = FunctionTool(
            func=add_numbers,
        )
        self._subtract_tool = FunctionTool(
            func=subtract_numbers,
        )
        print(f"SimpleMathToolset initialized with prefix '{self.prefix}'")

    async def get_tools(
        self, readonly_context: Optional[ReadonlyContext] = None
    ) -> List[BaseTool]:
        print("SimpleMathToolset.get_tools() called.")
        # Example of dynamic behavior:
        # Could use readonly_context.state to decide which tools to return
        # For instance, if readonly_context.state.get("enable_advanced_math"):
        #    return [self._add_tool, self._subtract_tool, self._multiply_tool]

        # For this simple example, always return both tools
        tools_to_return = [self._add_tool, self._subtract_tool]
        print(f"SimpleMathToolset providing tools: {[t.name for t in tools_to_return]}")
        return tools_to_return

    async def close(self) -> None:
        # No resources to clean up in this simple example
        print(f"SimpleMathToolset.close() called for prefix '{self.prefix}'.")
        await asyncio.sleep(0)  # Placeholder for async cleanup if needed


# 3. Define an individual tool (not part of the toolset)
def greet_user(name: str = "User") -> Dict[str, str]:
    """Greets the user."""
    print(f"Tool: greet_user called with name={name}")
    return {"greeting": f"Hello, {name}!"}


greet_tool = FunctionTool(func=greet_user)

# 4. Instantiate the toolset
math_toolset_instance = SimpleMathToolset(prefix="calculator")

# 5. Define an agent that uses both the individual tool and the toolset
calculator_agent = LlmAgent(
    name="CalculatorAgent",
    model="gemini-flash-latest",  # Replace with your desired model
    instruction="You are a helpful calculator and greeter. "
    "Use 'greet_user' for greetings. "
    "Use 'calculator_add_numbers' to add and 'calculator_subtract_numbers' to subtract. "
    "Announce the state of 'last_math_operation' if it's set.",
    tools=[greet_tool, math_toolset_instance],  # Individual tool  # Toolset instance
)

# 6. Run the agent
runner = InMemoryRunner(agent=calculator_agent, app_name="toolset_example_app")

async def main():
    print("\n--- Query 1: Greeting ---")
    await runner.run_debug("Hi there!")
    print("\n--- Query 2: Addition ---")
    await runner.run_debug("What is 5 plus 3?")
    await math_toolset_instance.close()

if __name__ == "__main__":
    asyncio.run(main())
/**
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { LlmAgent, FunctionTool, Context, BaseToolset, InMemoryRunner, isFinalResponse, BaseTool, stringifyContent } from '@google/adk';
import { z } from "zod";
import { Content, createUserContent } from "@google/genai";

function addNumbers(params: { a: number; b: number }, context?: Context): Record<string, any> {
  if (!context) {
    throw new Error("Context is required for this tool.");
  }
  const result = params.a + params.b;
  context.state.set("last_math_result", result);
  return { result: result };
}

function subtractNumbers(params: { a: number; b: number }): Record<string, any> {
  return { result: params.a - params.b };
}

function greetUser(params: { name: string }): Record<string, any> {
  return { greeting: `Hello, ${params.name}!` };
}

class SimpleMathToolset extends BaseToolset {
  private readonly tools: BaseTool[];

  constructor(prefix = "") {
    super([]); // No filter
    this.tools = [
      new FunctionTool({
        name: `${prefix}add_numbers`,
        description: "Adds two numbers and stores the result in the session state.",
        parameters: z.object({ a: z.number(), b: z.number() }),
        execute: addNumbers,
      }),
      new FunctionTool({
        name: `${prefix}subtract_numbers`,
        description: "Subtracts the second number from the first.",
        parameters: z.object({ a: z.number(), b: z.number() }),
        execute: subtractNumbers,
      }),
    ];
  }

  async getTools(): Promise<BaseTool[]> {
    return this.tools;
  }

  async close(): Promise<void> {
    console.log("SimpleMathToolset closed.");
  }
}

async function main() {
  const mathToolset = new SimpleMathToolset("calculator_");
  const greetTool = new FunctionTool({
    name: "greet_user",
    description: "Greets the user.",
    parameters: z.object({ name: z.string() }),
    execute: greetUser,
  });

  const instruction =
    `You are a calculator and a greeter.
    If the user asks for a math operation, use the calculator tools.
    If the user asks for a greeting, use the greet_user tool.
    The result of the last math operation is stored in the 'last_math_result' state variable.`;

  const calculatorAgent = new LlmAgent({
    name: "calculator_agent",
    instruction: instruction,
    tools: [greetTool, mathToolset],
    model: "gemini-2.5-flash",
  });

  const runner = new InMemoryRunner({ agent: calculatorAgent, appName: "toolset_app" });
  await runner.sessionService.createSession({ appName: "toolset_app", userId: "user1", sessionId: "session1" });

  const message: Content = createUserContent("What is 5 + 3?");

  for await (const event of runner.runAsync({ userId: "user1", sessionId: "session1", newMessage: message })) {
    if (isFinalResponse(event) && event.content?.parts?.length) {
      const text = stringifyContent(event).trim();
      if (text) {
        console.log(`Response from agent: ${text}`);
      }
    }
  }

  await mathToolset.close();
}

main();
import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.ReadonlyContext;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.BaseTool;
import com.google.adk.tools.BaseToolset;
import com.google.adk.tools.FunctionTool;
import com.google.adk.tools.ToolContext;
import io.reactivex.rxjava3.core.Flowable;
import java.util.HashMap;
import java.util.Map;

public class SimpleMathToolsetApp {

  // 1. Define the individual tool functions

  /**
   * Adds two integer numbers.
   *
   * @param a The first number.
   * @param b The second number.
   * @param toolContext The tool context.
   * @return A map with the sum.
   */
  public static Map<String, Object> addNumbers(
      @Schema(name = "a", description = "The first number") int a,
      @Schema(name = "b", description = "The second number") int b,
      ToolContext toolContext) {
    System.out.println("Tool: add_numbers called with a=" + a + ", b=" + b);
    int result = a + b;
    // Example: Storing something in tool_context state
    toolContext.state().put("last_math_operation", "addition");
    Map<String, Object> response = new HashMap<>();
    response.put("status", "success");
    response.put("result", result);
    return response;
  }

  /**
   * Subtracts the second number from the first.
   *
   * @param a The first number.
   * @param b The second number.
   * @return A map with the difference.
   */
  public static Map<String, Object> subtractNumbers(
      @Schema(name = "a", description = "The first number") int a,
      @Schema(name = "b", description = "The second number") int b) {
    System.out.println("Tool: subtract_numbers called with a=" + a + ", b=" + b);
    Map<String, Object> response = new HashMap<>();
    response.put("status", "success");
    response.put("result", a - b);
    return response;
  }

  // 2. Create the Toolset by implementing BaseToolset
  public static class SimpleMathToolset implements BaseToolset {
    private final BaseTool addTool;
    private final BaseTool subtractTool;

    public SimpleMathToolset() throws NoSuchMethodException {
      // Create FunctionTool instances once
      this.addTool =
          FunctionTool.create(
              SimpleMathToolsetApp.class.getMethod(
                  "addNumbers", int.class, int.class, ToolContext.class));
      this.subtractTool =
          FunctionTool.create(
              SimpleMathToolsetApp.class.getMethod("subtractNumbers", int.class, int.class));
      System.out.println("SimpleMathToolset initialized");
    }

    @Override
    public Flowable<BaseTool> getTools(ReadonlyContext readonlyContext) {
      System.out.println("SimpleMathToolset.getTools() called.");
      // Example of dynamic behavior:
      // Could use readonlyContext to access state and conditionally return tools.
      // For this simple example, always return both tools:
      return Flowable.just(addTool, subtractTool);
    }

    @Override
    public void close() throws Exception {
      // No resources to clean up in this simple example
      System.out.println("SimpleMathToolset.close() called.");
    }
  }

  // 3. Define an individual tool (not part of the toolset)

  /**
   * Greets the user.
   *
   * @param name The name of the user.
   * @return A map with the greeting.
   */
  public static Map<String, Object> greetUser(
      @Schema(name = "name", description = "The name of the user") String name) {
    System.out.println("Tool: greetUser called with name=" + name);
    Map<String, Object> response = new HashMap<>();
    response.put("greeting", "Hello, " + name + "!");
    return response;
  }

  public static void main(String[] args) throws Exception {
    BaseTool greetTool =
        FunctionTool.create(SimpleMathToolsetApp.class.getMethod("greetUser", String.class));

    // 4. Instantiate the toolset
    BaseToolset mathToolsetInstance = new SimpleMathToolset();

    // 5. Define an agent that uses both the individual tool and the toolset
    LlmAgent calculatorAgent =
        LlmAgent.builder()
            .name("CalculatorAgent")
            .model("gemini-2.5-flash") // Replace with your desired model
            .instruction(
                "You are a helpful calculator and greeter. "
                    + "Use 'greetUser' for greetings. "
                    + "Use 'addNumbers' to add and 'subtractNumbers' to subtract. "
                    + "Announce the state of 'last_math_operation' if it's set.")
            .tools(greetTool, mathToolsetInstance) // Individual tool and Toolset instance
            .build();

    // System.out.println("Agent '" + calculatorAgent.name() + "' created.");

    // Runner runner = new Runner(calculatorAgent, ...);
    // ... setup and usage ...

    // Important: Clean up the toolset if it manages resources
    mathToolsetInstance.close();
  }
}
import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.agents.ReadonlyContext
import com.google.adk.kt.annotations.Param
import com.google.adk.kt.annotations.Tool
import com.google.adk.kt.models.Gemini
import com.google.adk.kt.tools.BaseTool
import com.google.adk.kt.tools.ToolContext
import com.google.adk.kt.tools.ToolFilter
import com.google.adk.kt.tools.Toolset
import com.google.adk.kt.tools.isToolSelected

/** The individual tools, exposed by the @Tool annotation. */
class MathTools {
    /**
     * Adds two integer numbers.
     */
    @Tool
    fun addNumbers(
        @Param("The first number.") a: Int,
        @Param("The second number.") b: Int,
        context: ToolContext,
    ): Map<String, Any> {
        // Example: recording something in the session state.
        context.actions.stateDelta["last_math_operation"] = "addition"
        return mapOf("status" to "success", "result" to a + b)
    }

    /**
     * Subtracts the second number from the first.
     */
    @Tool
    fun subtractNumbers(
        @Param("The first number.") a: Int,
        @Param("The second number.") b: Int,
    ): Map<String, Any> = mapOf("status" to "success", "result" to a - b)
}

/** An individual tool, defined outside any toolset. */
class GreetTools {
    /**
     * Greets the user.
     */
    @Tool
    fun greetUser(
        @Param("The name of the user to greet.") name: String,
    ): Map<String, String> {
        println("Tool: greetUser called with name=$name")
        return mapOf("greeting" to "Hello, $name!")
    }
}

/**
 * A toolset that narrows what it exposes with an optional [ToolFilter].
 *
 * A null filter selects every tool, so the filter is genuinely optional.
 */
class SimpleMathToolset(private val filter: ToolFilter? = null) : Toolset {
    private val tools = MathTools().generatedTools()

    override suspend fun getTools(readonlyContext: ReadonlyContext?): List<BaseTool> =
        tools.filter { filter.isToolSelected(it, readonlyContext) }

    /** Releases anything the toolset holds. There is nothing to release here. */
    override fun close() {}
}

/**
 * An agent using both an individual tool and a toolset. Kotlin keeps the two
 * apart: individual tools go in `tools`, toolsets in `toolsets`.
 */
val calculatorAgent =
    LlmAgent(
        name = "calculator_agent",
        model = Gemini(name = "gemini-flash-latest"),
        instruction =
            Instruction(
                "You are a helpful calculator and greeter. Use greetUser for " +
                    "greetings. Use addNumbers to add and subtractNumbers to " +
                    "subtract. Announce the state of 'last_math_operation' if it is set.",
            ),
        tools = GreetTools().generatedTools(),
        toolsets = listOf(SimpleMathToolset()),
    )

在这个例子中:

  • SimpleMathToolset implements BaseToolset 以及它的 get_tools() 该方法返回(method returns) FunctionTool ……的实例 add_numbers 和 subtract_numbers它还会使用前缀来自定义这些名称。
  • The calculator_agent 该系统同时配置了两种单独的设置(或功能)。 greet_tool 以及一个该类的实例(instance of)。 SimpleMathToolset.
  • 当……的时候 calculator_agent 当程序运行时,ADK 会自动被调用。 math_toolset_instance.get_tools()然后,该代理的 Large Language Model(LLM,即大型语言模型)将能够访问这些资源。 greet_user, calculator_add_numbers,以及 calculator_subtract_numbers 用于处理用户请求。
  • The add_numbers 该工具演示了如何将数据写入文件或数据库。 tool_context.state代理的指令中提到了需要读取该状态信息。
  • The close() 会调用该方法来确保工具集所持有的所有资源都被释放。
  • 这个 Kotlin 示例没有在工具名称前添加前缀,因为 adk-kotlin 没有相应的前缀添加机制。 BaseTool.name 该资源是只读的(即只能被读取,无法被修改或删除)。其相关的工具(或功能)仍然可以正常使用。 greetUser, addNumbers 和 subtractNumbersKotlin 也把这两种工具区分开来:不同的工具被分别存储在不同的位置(或目录中)。 tools工具集(toolsets)在……中 toolsets.

工具集中的过滤工具

在 ADK 中得到支持。Kotlin v0.7.0

每个 SDK 都允许开发人员通过名称或某种能够识别当前上下文的条件,来限制传递给模型的数据范围;Python、Java 和 TypeScript 都支持这种过滤机制。 BaseToolset这里的示例是一个使用 Kotlin 语言编写的表单(form)。

与其将这个列表硬编码在程序内部,…… getTools()一个工具集可以接受(某种输入或数据)。 ToolFilter 然后使用该方法将其应用到相应的对象或系统中。 isToolSelected, as SimpleMathToolset 在上面的 Kotlin 例子中,就是这么做的。 ToolFilter.allowList 根据工具的名称来选择相应的工具; ToolFilter.Predicate 接收…… ReadonlyContext因此,工具列表可能会根据会话状态或当前用户的情况而有所不同。当过滤器参数为 `null` 时,该工具列表会包含所有可用的工具;这也是为什么同一个类在未使用任何过滤条件的情况下仍然能够正常工作的原因。

// SimpleMathToolset, defined above, applies its optional ToolFilter inside
// getTools(). Passing one narrows what the same toolset exposes.

// Expose a fixed subset by name.
val addOnlyMath = SimpleMathToolset(ToolFilter.allowList("addNumbers"))

// Or decide per invocation. The predicate receives the ReadonlyContext, so the
// tool list can depend on session state, the user, or anything else on it.
val contextAwareMath =
    SimpleMathToolset(
        ToolFilter.Predicate { tool, context ->
            tool.name == "addNumbers" || context?.state?.get("enable_advanced_math") == true
        },
    )

这些工具集提供了一种强大的方式,用于组织、管理并向您的 ADK(Application Development Kit)代理动态提供各种工具。这样一来,应用程序就变得更加模块化、易于维护且具有更好的适应性。