跳转到内容

使用 LlmAgent 的简单代理(Simple agents with LlmAgent)

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

The LlmAgent `class`,通常被简称为…… Agent该组件是 ADK(Android Development Kit)中的核心组成部分,充当您的代理应用程序(agent application)的核心部分。它利用大型语言模型(Large Language Model, LLM)或生成式人工智能(generative AI)模型的能力来进行推理、理解自然语言、做出决策、生成响应以及与各种工具进行交互。由于这种类型的代理会使用人工智能模型来解释指令和上下文,因此人工智能模型会动态地决定如何执行任务、使用哪些工具(如果需要的话),以及提供什么样的输出。因此,这种代理的行为具有不确定性,因此在设计和评估时必须充分考虑这种不确定性。

构建一个有效的……(此处“……”应为具体的系统、工具或方法名称,但原文未提供详细信息) LlmAgent 这包括明确其身份、通过指令来指导其行为,并为其提供所需的工具和能力。

定义代理的身份和用途。

首先,你需要明确“agent”(代理)的具体含义或功能。 是 ……以及它的功能/作用是什么。 for.

  • name (必填): 每个代理都需要一个唯一的字符串标识符。 name 这对于内部操作至关重要,尤其是在多智能体系统中——在这些系统中,智能体之间需要相互引用任务或委托任务。请选择一个能够准确描述该智能体功能的名称(例如……)。 customer_support_router, billing_inquiry_agent在 Python 中,该名称必须是一个有效的 Python 标识符;否则 ADK 会拒绝使用该名称。 user.

  • description (可选,建议在多智能体系统中使用): 提供对该代理功能的简要概述。此描述主要用于……(此处应填写该描述的具体用途或目标用户)。 其他 LLM(大型语言模型)代理需要判断是否应该将某项任务分配给该代理来处理。 描述该代理的具体职责,以便将其与其他代理区分开来(例如:“负责处理关于当前账单的咨询”,而不仅仅是“简单的账单处理代理”)。

  • model (在 Python 中可选): 请指定将用于驱动该智能体推理功能的底层大型语言模型(LLM)。该模型的标识符可以是一个字符串,例如…… "gemini-flash-latest" 或者一个 BaseLlm `instance`。如果您省略了该参数…… model该代理继承了其“最近邻居”(即距离它最近的那个代理)的模型。 LlmAgent “ancestor”:跳过所有不是其“parent”的元素。 LlmAgent例如: SequentialAgent, ParallelAgent, LoopAgent或者自定义的 BaseAgent如果没有祖先节点为代理设置模型,代理会使用内置的默认模型。该默认模型的具体信息在文档中有详细描述。 配置一个默认模型模型的选择会直接影响代理的功能、成本和性能。请参阅…… 模型 该页面列出了可用的选项及相关注意事项。

# Example: Defining the basic identity
capital_agent = LlmAgent(
    model="gemini-flash-latest",
    name="capital_agent",
    description="Answers user questions about the capital city of a given country."
    # instruction and tools will be added next
)
// Example: Defining the basic identity
const capitalAgent = new LlmAgent({
    model: 'gemini-flash-latest',
    name: 'capital_agent',
    description: 'Answers user questions about the capital city of a given country.',
    // instruction and tools will be added next
});
// Example: Defining the basic identity
agent, err := llmagent.New(llmagent.Config{
    Name:        "capital_agent",
    Model:       model,
    Description: "Answers user questions about the capital city of a given country.",
    // instruction and tools will be added next
})
// Example: Defining the basic identity
LlmAgent capitalAgent =
    LlmAgent.builder()
        .model("gemini-flash-latest")
        .name("capital_agent")
        .description("Answers user questions about the capital city of a given country.")
        // instruction and tools will be added next
        .build();
val capitalAgent =
    LlmAgent(
        name = "capital_agent",
        model = Gemini(name = "gemini-flash-latest"),
        description = "Answers user questions about the capital city of a given country.",
    )

用指令指导代理(agent)的操作。

The instruction 参数可以说是对塑造某个结果(或结果特性)最为关键的要素。 LlmAgent它的行为方式是由一个字符串(或一个返回字符串的函数)来决定的。这个字符串/函数会向代理(agent)传达相应的指令或信息。

  • 它的核心任务或目标。
  • 它的“个性”或“形象”(例如:“你是一个乐于助人的助手”,“你是一个风趣幽默的海盗”)。
  • 对其行为的限制(例如:“只能回答与 X 相关的问题”,“绝不能透露 Y”)。
  • 如何以及何时使用它 tools您应该解释每个工具的用途,以及应该在什么情况下使用它们;同时,还可以补充工具本身所提供的描述内容。
  • 要求其输出的结果格式(例如:“以 JSON 格式回复”,“提供一个带项目符号的列表”)。

编写有效说明的技巧:

  • 表达要清晰、具体: 避免歧义:明确说明所需的操作及预期结果。
  • 使用 Markdown 格式编写文本。 通过使用标题、列表等方式来提高复杂说明的可读性。
  • 提供示例(简短说明): 对于复杂的任务或特定的输出格式,请在说明中直接提供示例。
  • 《指南工具使用说明》: 不要只是列出工具,还要解释它们的用途或功能。 当……的时候 和 为什么 代理应该使用它们。

使用动态状态变量:

  • 该指令是一个字符串模板,你可以使用它来生成所需的输出。 {var} 用于将动态值插入指令的语法。
  • {var} 该代码用于插入名为 `var` 的状态变量的值。
  • {artifact.var} 该代码用于插入名为 `var` 的艺术品的文本内容。
  • 如果状态变量或相关资源不存在,代理程序将会抛出一个错误。如果你想忽略这个错误,可以在错误信息后面添加相应的代码(或配置选项)。 ? 将该值赋给名为 `name` 的变量。 {var?}.
# Example: Adding instructions
capital_agent = LlmAgent(
    model="gemini-flash-latest",
    name="capital_agent",
    description="Answers user questions about the capital city of a given country.",
    instruction="""You are an agent that provides the capital city of a country.
When a user asks for the capital of a country:
1. Identify the country name from the user's query.
2. Use the `get_capital_city` tool to find the capital.
3. Respond clearly to the user, stating the capital city.
Example Query: "What's the capital of France?"
Example Response: "The capital of France is Paris."
""",
    # tools will be added next
)
// Example: Adding instructions
const capitalAgent = new LlmAgent({
    model: 'gemini-flash-latest',
    name: 'capital_agent',
    description: 'Answers user questions about the capital city of a given country.',
    instruction: `You are an agent that provides the capital city of a country.
        When a user asks for the capital of a country:
        1. Identify the country name from the user's query.
        2. Use the \`getCapitalCity\` tool to find the capital.
        3. Respond clearly to the user, stating the capital city.
        Example Query: "What's the capital of France?"
        Example Response: "The capital of France is Paris."
        `,
    // tools will be added next
});
    // Example: Adding instructions
    agent, err := llmagent.New(llmagent.Config{
        Name:        "capital_agent",
        Model:       model,
        Description: "Answers user questions about the capital city of a given country.",
        Instruction: `You are an agent that provides the capital city of a country.
When a user asks for the capital of a country:
1. Identify the country name from the user's query.
2. Use the 'get_capital_city' tool to find the capital.
3. Respond clearly to the user, stating the capital city.
Example Query: "What's the capital of {country}?"
Example Response: "The capital of France is Paris."`,
        // tools will be added next
    })
// Example: Adding instructions
LlmAgent capitalAgent =
    LlmAgent.builder()
        .model("gemini-flash-latest")
        .name("capital_agent")
        .description("Answers user questions about the capital city of a given country.")
        .instruction(
            """
            You are an agent that provides the capital city of a country.
            When a user asks for the capital of a country:
            1. Identify the country name from the user's query.
            2. Use the `get_capital_city` tool to find the capital.
            3. Respond clearly to the user, stating the capital city.
            Example Query: "What's the capital of France?"
            Example Response: "The capital of France is Paris."
            """)
        // tools will be added next
        .build();
val instructedAgent =
    LlmAgent(
        name = "capital_agent",
        model = Gemini(name = "gemini-flash-latest"),
        instruction =
            Instruction(
                """
                You are an agent that provides the capital city of a country.
                When a user asks for the capital of a country:
                1. Identify the country name from the user's query.
                2. Use the `getCapitalCity` tool to find the capital.
                3. Respond clearly to the user, stating the capital city.
                Example Query: "What's the capital of {country}?"
                Example Response: "The capital of France is Paris."
                """.trimIndent(),
            ),
    )

要在 Python 中从 Model Context Protocol (MCP) 服务器动态获取代理指令,请参见…… 具有动态功能的指令(Dynamic instructions with...) McpInstructionProvider.

GlobalInstructionPlugin

为了应用共享规则或保持某种统一的设计风格(即“一致的设计特性”),需要…… 所有 您系统中的代理程序,请使用它们。 GlobalInstructionPlugin **替代** (被弃用的) global_instruction 参数。 对于 ADK Go 的设置,请参考相关文档。 GlobalInstruction 或者 GlobalInstructionProvider 在……的时候;当……发生时 llmagent.Config.

为代理人配备所需的工具。

这些工具能够为您提供……(具体功能或优势需根据上下文补充)。 LlmAgent 这些功能超出了大型语言模型(LLM)内置的知识或推理能力。它们使代理能够与外部世界进行交互、执行计算、获取实时数据或执行特定操作。

  • tools (可选): 提供一份代理可以使用的工具列表。列表中的每个条目都可以包括以下内容:
    • 一个原生的函数或方法(被封装成……) FunctionTool). Python ADK 会自动将原生函数封装成(某种形式)。 FunctionTool 然而,你必须明确地使用特定的语法来包装(即封装)你的 Java 方法。 FunctionTool.create(...)在 Kotlin 中,你可以使用…… @Tool 注释用于自动生成…… FunctionTool 在编译时(at compile-time)。
    • 一个继承自某个类的实例 BaseTool.
    • An AgentTool 将另一个代理“包装”(即将其功能集成到当前代理中),从而实现代理之间的任务委托(即一个代理可以将任务分配给另一个代理来执行)。有关更多信息,请参阅…… 自定义代理工作流程在 Python 中,建议使用以下方法进行设置: mode='single_turn' 在代理(agent)上执行相关操作,并将其添加(add it)到……中。 sub_agents这会自动将其显示为内联工具;同时,请避免使用…… AgentTool(agent=...) 可以直接使用语法(syntax)来表示这些内容。

大型语言模型(LLM)使用了这些函数/工具的名称及其描述(这些描述来源于文档字符串或其他来源)。 description 根据对话内容及其指令,我们需要确定应该使用哪种工具来处理数据(包括字段类型、参数结构等),从而决定调用相应的工具。

# Define a tool function
def get_capital_city(country: str) -> str:
  """Retrieves the capital city for a given country."""
  # Replace with actual logic (e.g., API call, database lookup)
  capitals = {"france": "Paris", "japan": "Tokyo", "canada": "Ottawa"}
  return capitals.get(country.lower(), f"Sorry, I don't know the capital of {country}.")

# Add the tool to the agent
capital_agent = LlmAgent(
    model="gemini-flash-latest",
    name="capital_agent",
    description="Answers user questions about the capital city of a given country.",
    instruction="""You are an agent that provides the capital city of a country... (previous instruction text)""",
    tools=[get_capital_city] # Provide the function directly
)
import {z} from 'zod';
import { LlmAgent, FunctionTool } from '@google/adk';

// Define the schema for the tool's input parameters
const getCapitalCityParamsSchema = z.object({
    country: z.string().describe('The country to get capital for.'),
});

// Define the tool function itself
async function getCapitalCity(params: z.infer<typeof getCapitalCityParamsSchema>): Promise<{ capitalCity: string }> {
const capitals: Record<string, string> = {
    'france': 'Paris',
    'japan': 'Tokyo',
    'canada': 'Ottawa',
};
const result = capitals[params.country.toLowerCase()] ??
    `Sorry, I don't know the capital of ${params.country}.`;
return {capitalCity: result}; // Tools must return an object
}

// Create an instance of the FunctionTool
const getCapitalCityTool = new FunctionTool({
    name: 'getCapitalCity',
    description: 'Retrieves the capital city for a given country.',
    parameters: getCapitalCityParamsSchema,
    execute: getCapitalCity,
});

// Add the tool to the agent
const capitalAgent = new LlmAgent({
    model: 'gemini-flash-latest',
    name: 'capitalAgent',
    description: 'Answers user questions about the capital city of a given country.',
    instruction: 'You are an agent that provides the capital city of a country...', // Note: the full instruction is omitted for brevity
    tools: [getCapitalCityTool], // Provide the FunctionTool instance in an array
});
// Define a tool function
type getCapitalCityArgs struct {
    Country string `json:"country" jsonschema:"The country to get the capital of."`
}
getCapitalCity := func(ctx agent.Context, args getCapitalCityArgs) (map[string]any, error) {
    // Replace with actual logic (e.g., API call, database lookup)
    capitals := map[string]string{"france": "Paris", "japan": "Tokyo", "canada": "Ottawa"}
    capital, ok := capitals[strings.ToLower(args.Country)]
    if !ok {
        return nil, fmt.Errorf("Sorry, I don't know the capital of %s.", args.Country)
    }
    return map[string]any{"result": capital}, nil
}

// Add the tool to the agent
capitalTool, err := functiontool.New(
    functiontool.Config{
        Name:        "get_capital_city",
        Description: "Retrieves the capital city for a given country.",
    },
    getCapitalCity,
)
if err != nil {
    log.Fatal(err)
}
agent, err := llmagent.New(llmagent.Config{
    Name:        "capital_agent",
    Model:       model,
    Description: "Answers user questions about the capital city of a given country.",
    Instruction: "You are an agent that provides the capital city of a country... (previous instruction text)",
    Tools:       []tool.Tool{capitalTool},
})
// Define a tool function
// Retrieves the capital city of a given country.
public static Map<String, Object> getCapitalCity(
        @Schema(name = "country", description = "The country to get capital for")
        String country) {
  // Replace with actual logic (e.g., API call, database lookup)
  Map<String, String> countryCapitals = new HashMap<>();
  countryCapitals.put("canada", "Ottawa");
  countryCapitals.put("france", "Paris");
  countryCapitals.put("japan", "Tokyo");

  String result =
          countryCapitals.getOrDefault(
                  country.toLowerCase(), "Sorry, I couldn't find the capital for " + country + ".");
  return Map.of("result", result); // Tools must return a Map
}

// Add the tool to the agent
FunctionTool capitalTool = FunctionTool.create(experiment.getClass(), "getCapitalCity");
LlmAgent capitalAgent =
    LlmAgent.builder()
        .model("gemini-flash-latest")
        .name("capital_agent")
        .description("Answers user questions about the capital city of a given country.")
        .instruction("You are an agent that provides the capital city of a country... (previous instruction text)")
        .tools(capitalTool) // Provide the function wrapped as a FunctionTool
        .build();
class CapitalService {
    @Tool(description = "Retrieves the capital city for a given country.")
    fun getCapitalCity(
        @Param("The country to get capital for.") country: String,
    ): String {
        val capitals = mapOf("france" to "Paris", "japan" to "Tokyo", "canada" to "Ottawa")
        return capitals[country.lowercase()] ?: "Sorry, I don't know the capital of $country."
    }
}

// Add the tool to the agent
// Note: generatedTools() is generated by KSP for classes containing @Tool annotated functions.
// In a real project, you would need to set up the ADK KSP processor.
// val agentWithTools = LlmAgent(
//     name = "capital_agent",
//     model = Gemini(name = "gemini-flash-latest"),
//     tools = capitalService.generatedTools()
// )

了解更多关于 “Tools in” 的信息。 自定义工具.

高级配置与控制功能

除了核心参数之外, LlmAgent 提供了多种选项,以实现更精细的控制:

对 AI 模型的运行方式进行微调(即对模型的参数或算法进行细小的调整,以优化其性能)。

你可以调整底层 AI 模型生成响应的方式。 generate_content_config.

  • generate_content_config (可选): 传递一个实例。 google.genai.types.GenerateContentConfig 用于控制诸如……之类的参数。 temperature (随机性), max_output_tokens (响应长度), top_p, top_k以及安全设置。在 Python 中,ADK 会引发一个异常(错误)。 ValueError if generate_content_config sets tools, system_instruction, response_schema,或 http_options.base_url设置前三个参数,由代理程序负责处理。 tools, instruction,以及 output_schema 应该使用 `fields`(字段)来传递数据,并在模型或其客户端中设置基础 URL(base URL)。
from google.genai import types

agent = LlmAgent(
    # ... other params
    generate_content_config=types.GenerateContentConfig(
        temperature=0.2, # More deterministic output
        max_output_tokens=250,
        safety_settings=[
            types.SafetySetting(
                category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
                threshold=types.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
            )
        ]
    )
)
import { GenerateContentConfig } from '@google/genai';

const generateContentConfig: GenerateContentConfig = {
    temperature: 0.2, // More deterministic output
    maxOutputTokens: 250,
};

const agent = new LlmAgent({
    // ... other params
    generateContentConfig,
});
import "google.golang.org/genai"

temperature := float32(0.2)
agent, err := llmagent.New(llmagent.Config{
    Name:  "gen_config_agent",
    Model: model,
    GenerateContentConfig: &genai.GenerateContentConfig{
        Temperature:     &temperature,
        MaxOutputTokens: 250,
    },
})
import com.google.genai.types.GenerateContentConfig;

LlmAgent agent =
    LlmAgent.builder()
        // ... other params
        .generateContentConfig(GenerateContentConfig.builder()
            .temperature(0.2F) // More deterministic output
            .maxOutputTokens(250)
            .build())
        .build();
val agentWithConfig =
    LlmAgent(
        name = "capital_agent",
        model = Gemini(name = "gemini-flash-latest"),
        generateContentConfig =
            GenerateContentConfig(
                // More deterministic output
                temperature = 0.2f,
                maxOutputTokens = 250,
                safetySettings =
                    listOf(
                        SafetySetting(
                            category = HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
                            threshold = HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
                        ),
                    ),
            ),
    )

配置一个默认模型

在 ADK 中得到支持。Python v1.22.0

您可以为所有内容设置一个系统范围内的默认模型。 LlmAgent 使用该功能的实例: set_default_model 这是一个类方法(class method)。在创建代理(agent)时,如果您没有指定具体的模型,系统会自动使用 ADK 内置的默认模型。这种设置有助于避免重复指定模型参数,并且可以方便地同时更改所有代理的模型。

from google.adk.agents import LlmAgent

# Set a new default model for all agents
LlmAgent.set_default_model("gemini-flash-latest")

# This agent will now use "gemini-flash-latest" by default
agent_with_default_model = LlmAgent(
    name="default_model_agent",
    instruction="You are a helpful assistant."
)

# You can still override the default for specific agents
specific_agent = LlmAgent(
    name="specific_model_agent",
    model="gemini-pro-latest",
    instruction="You are a creative writer."
)

结构化数据的输入与输出

对于需要与第三方系统进行结构化数据交换的场景: LLM AgentADK(应用程序开发套件)提供了使用模式定义(schema definitions)来指定预期输入格式和所需输出格式的机制。

  • input_schema (可选): 定义一个模式(schema),用于表示当调用该代理(agent)时所需的输入数据结构。 作为一种工具在 Python 中, AgentTool 该过程会验证调用方提供的参数是否符合预定义的规范(即“schema”),并将验证结果作为输入数据传递给调用方。需要注意的是:该规范并不适用于那些直接发送给代理系统的用户消息。

  • output_schema (可选): 定义一个模式,用于表示所需的输出结构。如果该模式被设置,代理程序将据此生成最终的响应。 必须;应当 必须是一个符合该模式的 JSON 字符串。

  • 在 Python 中,支持的架构类型包括:
    • 例如,一个使用 Pydantic 框架定义的模型类: MySchema
    • 原始类型的列表,例如: list[str], list[int], list[bool], list[float]
    • dict
    • google.genai.types.Schema

使用 output_schema 使用(with) tools

在 Python 中,ADK 支持……(请根据实际情况填写具体的支持内容)。 output_schema 和 tools 在同一代理上:这些工具在代理运行期间始终可用,而数据结构(schema)仅适用于最终的响应结果。某些模型允许在单个请求中同时使用这两种方式(即同时使用代理和数据结构),例如 Google Cloud 上的 Gemini 模型。 LiteLlm 对于那些其提供者(provider)支持响应数据(response data)以及相关数据结构(schemas)的模型,ADK 会直接将这些数据传递给目标系统。而对于其他模型,ADK 会先对这些数据进行处理或添加额外的信息,然后再将其传递出去。 set_model_response ```javascript function tool() { // 这里可以编写函数的具体逻辑 } ``` 并指示模型通过该工具返回其最终答案;不过该工具可能无法可靠地正常工作。在这种情况下,可以考虑使用专门的子代理(sub-agents)来负责输出格式的转换工作。

  • output_key (可选): 提供一个字符串类型的键(key)。如果该键被设置,那么代理(agent)的行为将会根据该键的值来决定。 final 响应数据会自动保存到会话的状态字典中(该字典使用指定的键进行存储)。这对于在工作流中的不同代理或步骤之间传递结果非常有用。

    • 在 Python 中,这可能看起来像这样: session.state[output_key] = agent_response_text. 如果 output_schema 此外,ADK 会首先根据预定义的架构(schema)来解析响应数据,并存储解析后的结果,而不是原始的响应文本。 BaseModel 该模式被存储为……(即:该模式被存储在某种特定的数据结构或格式中)。 dict,以及一个 list[BaseModel] 该模式被存储为……(即:该模式被存储在某种特定的数据结构或格式中)。 list[dict].
    • 在 Java 中: session.state().put(outputKey, agentResponseText)
    • 在 Golang 中,回调处理程序(callback handler)内部: ctx.State().Set(output_key, agentResponseText)

    在 Java 和 Kotlin 中,当…… output_schema 如果该选项也被设置了(即被选中),那么…… parsed 响应数据被存储为…… Map “instead of the text.”

Java 和 Kotlin 中的架构验证(Schema Validation)

Java 和 Kotlin 会将响应内容与预定义的规范或标准进行对比,以验证其是否符合要求。 结构;构造;体系 属于该模式(schema)的一部分…… type, required, nullable, anyOf 和 items (请参阅……) SchemaUtils约束字段(例如:) pattern, minLength 和 minimum 这些数据作为模式(schema)的一部分被发送给模型(model),但 ADK 并不会重新验证这些数据;因此,是否接受这些数据由模型自己决定。Python 会使用 Pydantic 模型来进行验证,Pydantic 会确保模型中声明的所有约束条件都得到遵守。

Java 和 Kotlin 只支持顶层对象结构(即没有嵌套结构的对象);如果使用顶层数组或基本数据类型(如整数、字符串等),则会导致验证失败。Python 也支持列表(list)和基本数据类型的输出结构。

如果响应数据无法通过验证,ADK 会记录错误信息,并将原始的响应字符串存储在指定的位置。 output_key “而不是解析后的对象(见……)” LlmAgent).

输入和输出的数据结构(即数据模式)通常是一个……(具体内容在原文中被省略了)。 Pydantic BaseModel.

from pydantic import BaseModel, Field

class CapitalOutput(BaseModel):
    capital: str = Field(description="The capital of the country.")

structured_capital_agent = LlmAgent(
    # ... name, model, description
    instruction="""You are a Capital Information Agent. Given a country, respond ONLY with a JSON object containing the capital. Format: {"capital": "capital_name"}""",
    output_schema=CapitalOutput, # Enforce JSON output
    output_key="found_capital"  # Store result in state['found_capital']
    # tools=[...] may be combined with output_schema; see the note above
)
import {z} from 'zod';
import { Schema, Type } from '@google/genai';

// Define the schema for the output
const CapitalOutputSchema: Schema = {
    type: Type.OBJECT,
    properties: {
        capital: {
            type: Type.STRING,
            description: 'The capital of the country.',
        },
    },
    required: ['capital'],
};

// Create the LlmAgent instance
const structuredCapitalAgent = new LlmAgent({
    // ... name, model, description
    instruction: `You are a Capital Information Agent. Given a country, respond ONLY with a JSON object containing the capital. Format: {"capital": "capital_name"}`,
    outputSchema: CapitalOutputSchema, // Enforce JSON output
    outputKey: 'found_capital', // Store result in state['found_capital']
    // Cannot use tools effectively here
});

输入和输出的数据结构(即数据模式)是…… google.genai.types.Schema `object.`

capitalOutput := &genai.Schema{
    Type:        genai.TypeObject,
    Description: "Schema for capital city information.",
    Properties: map[string]*genai.Schema{
        "capital": {
            Type:        genai.TypeString,
            Description: "The capital city of the country.",
        },
    },
}

agent, err := llmagent.New(llmagent.Config{
    Name:         "structured_capital_agent",
    Model:        model,
    Description:  "Provides capital information in a structured format.",
    Instruction:  `You are a Capital Information Agent. Given a country, respond ONLY with a JSON object containing the capital. Format: {"capital": "capital_name"}`,
    OutputSchema: capitalOutput,
    OutputKey:    "found_capital",
    // Tools can still be added. ADK injects a set_model_response tool when
    // the model can't combine tools with OutputSchema natively.
})

输入和输出的数据结构(即数据模式)是…… google.genai.types.Schema `object.`

private static final Schema CAPITAL_OUTPUT =
    Schema.builder()
        .type("OBJECT")
        .description("Schema for capital city information.")
        .properties(
            Map.of(
                "capital",
                Schema.builder()
                    .type("STRING")
                    .description("The capital city of the country.")
                    .build()))
        .build();

LlmAgent structuredCapitalAgent =
    LlmAgent.builder()
        // ... name, model, description
        .instruction(
                "You are a Capital Information Agent. Given a country, respond ONLY with a JSON object containing the capital. Format: {\"capital\": \"capital_name\"}")
        .outputSchema(CAPITAL_OUTPUT) // Enforce JSON output
        .outputKey("found_capital") // Store result in state.get("found_capital")
        // Cannot use tools(getCapitalCity) effectively here
        .build();

输入和输出的数据结构(schema)是 ADK 自定义的。 com.google.adk.kt.types.Schema在 GenAI SDK 中,并不存在名称相同的类型。从 ADK Kotlin v0.8.0 开始,JSON 架构为以下字段添加了约束条件: pattern, minLength, maxLength, minimum, maximum, minItems, maxItems, format, nullable, default, anyOf 和 title.

val capitalOutput =
    Schema(
        type = Type.OBJECT,
        description = "Schema for capital city information.",
        properties =
            mapOf(
                "capital" to
                    Schema(
                        type = Type.STRING,
                        description = "The capital city of the country.",
                        // Constraint fields, added in adk-kotlin 0.8.0.
                        minLength = 2,
                        maxLength = 60,
                    ),
                "countryCode" to
                    Schema(
                        type = Type.STRING,
                        description = "ISO 3166-1 alpha-2 code for the country.",
                        pattern = "^[A-Z]{2}$",
                    ),
            ),
        required = listOf("capital", "countryCode"),
    )

val structuredCapitalAgent =
    LlmAgent(
        name = "structured_capital_agent",
        model = Gemini(name = "gemini-flash-latest"),
        instruction =
            Instruction(
                "You are a Capital Information Agent. Given a country, respond ONLY " +
                    "with a JSON object holding the capital city and the country's " +
                    "ISO 3166-1 alpha-2 code.",
            ),
        outputSchema = capitalOutput,
        outputKey = "found_capital",
    )

The format 该字段仅接受模型允许的、与该字段类型相匹配的值。有关允许的值,请参阅 Gemini 的相关说明。 Schema 参考文献;参照资料.

The default 该字段必须包含一个原生 JSON 格式的值(即由 JSON 直接支持的格式)。这是 ADK(Adobe Digital Kit)本身的要求。 Json 该工具可以序列化一个对象,但使用的是自定义的(非标准库提供的)序列化器,并且该序列化器不依赖于任何上下文信息(即不使用与序列化过程相关的额外数据)。 Any 序列化器(Serializer)不支持该功能。

管理代理上下文(Manage agent context)

控制代理是否能够接收之前的对话记录。

  • include_contents (可选,默认值:) 'default'): 用于判断是否…… contents (历史数据)会被发送给大型语言模型(LLM)。
    • 'default'代理会接收相关的对话记录。
    • 'none'代理在接收到请求之前没有收到任何预先的信息或提示。 contents它仅根据当前的指令以及所提供的任何输入来执行操作。 current `turn` (适用于无状态任务或需要强制执行特定上下文的场景。)
stateless_agent = LlmAgent(
    # ... other params
    include_contents='none'
)
const statelessAgent = new LlmAgent({
    // ... other params
    includeContents: 'none',
});
import "google.golang.org/adk/v2/agent/llmagent"

agent, err := llmagent.New(llmagent.Config{
    Name:            "stateless_agent",
    Model:           model,
    IncludeContents: llmagent.IncludeContentsNone,
})
import com.google.adk.agents.LlmAgent.IncludeContents;

LlmAgent statelessAgent =
    LlmAgent.builder()
        // ... other params
        .includeContents(IncludeContents.NONE)
        .build();
val statelessAgent =
    LlmAgent(
        name = "capital_agent",
        model = Gemini(name = "gemini-flash-latest"),
        // ... other params
        includeContents = IncludeContents.NONE,
    )

Go v2.0.0:代理执行模式(Agent Execution Modes)

ADK Go v2.0.0 引入了一项明确的设计变更(或:ADK Go v2.0.0 引入了一项新的、明确规定的功能/特性)。 Mode (字段)处于“开启”状态(或:可被使用/被激活的状态)。 llmagent.Config 该设置用于控制代理在基于图的结构或动态工作流中的运行方式。共有三种模式可供选择:

  • ModeChat (当某个代理被用作子代理时的默认设置):该代理会与用户进行多轮对话,并且可以通过其他代理进行访问。 transfer_to_agent.
  • ModeSingleTurn (当代理被用作工作流中的节点时的默认设置:) 该代理会在一次操作中完成任务,而无需与用户进行任何交流。
  • ModeTask:一种任务代理,它会与用户进行交流以完成任务;这与……形成对比。 ModeSingleTurn它可以与用户进行多次交互(即通过多次对话或操作),从而完成整个任务。

当你将某个内容“包裹”(或封装)起来时…… llmagent 使用(with) workflow.NewAgentNode在工作流程中,工作流引擎会自动将模式设置为…… ModeSingleTurn 如果没有指定模式,那么其行为就等同于 Python 的默认行为。 mode="single_turn" 在用作工作流节点的代理上。有关基于图的工作流中如何组合代理的更多信息,请参阅…… 基于图的代理工作流程(Graph-based agent workflows).

一个以某种方式运行的代理程序(agent)。 ModeSingleTurn 节点(例如工作流中的某个节点)只能看到当前轮次(即正在处理的那个步骤),就好像它只能了解自己所处的那个阶段一样。 IncludeContents (注:根据语法规则,“were”应为动词“be”的过去式复数形式,用于表示过去某个时间点发生的动作或状态。由于原句中缺少主语和其他成分,这里仅保留了动词形式。如果需要完整的句子,可以补充主语等成分。) IncludeContentsNone从 ADK Go v2.4.0 版本开始,您可以通过设置来保留对话历史记录。 IncludeContents 给……;发送到…… llmagent.IncludeContentsDefault 显式地(explicitly)。早期版本会忽略单环节点(single-turn nodes)的该设置。

配置计划器(Planner)

在 ADK 中得到支持。Python v0.1.0

planner (可选): 分配一个 BasePlanner 该实例用于在执行任务之前支持多步骤的推理与规划过程。目前主要有两种规划算法(或规划器):

  • BuiltInPlanner: 利用该模型内置的规划功能(例如 Gemini 的“思考”功能)。详见…… Gemini (思考中……) 有关详细信息及示例,请参阅……(请提供具体参考资料或链接)。

    在这里, thinking_budget 该参数用于指导模型在生成响应时应使用多少个“思考令牌”(thinking tokens)。 include_thoughts 该参数用于控制模型是否应在响应中包含其原始的思考过程及内部推理逻辑。

    from google.adk import Agent
    from google.adk.planners import BuiltInPlanner
    from google.genai import types
    
    my_agent = Agent(
        name="my_agent",
        model="gemini-flash-latest",
        planner=BuiltInPlanner(
            thinking_config=types.ThinkingConfig(
                include_thoughts=True,
                thinking_budget=1024,
            )
        ),
        # ... your tools here
    )
    
  • PlanReActPlanner: 这个规划器指示模型在输出结果时遵循特定的结构:首先制定一个计划,然后执行相应的操作(例如调用某些工具),并为其所采取的步骤提供合理的解释(即说明为什么选择这些步骤)。 这种方法对于那些没有内置“思考”功能的模型来说尤其有用。.

    from google.adk import Agent
    from google.adk.planners import PlanReActPlanner
    
    my_agent = Agent(
        name="my_agent",
        model="gemini-flash-latest",
        planner=PlanReActPlanner(),
        # ... your tools here
    )
    

    代理的回复将遵循一种结构化的格式:

    [user]: ai news
    [google_search_agent]: /*PLANNING*/
    1. Perform a Google search for "latest AI news" to get current updates and headlines related to artificial intelligence.
    2. Synthesize the information from the search results to provide a summary of recent AI news.
    
    /*ACTION*/
    /*REASONING*/
    The search results provide a comprehensive overview of recent AI news, covering various aspects like company developments, research breakthroughs, and applications. I have enough information to answer the user's request.
    
    /*FINAL_ANSWER*/
    Here's a summary of recent AI news:
    ....
    

使用内置规划器的示例:

from dotenv import load_dotenv


import asyncio
import os

from google.genai import types
from google.adk.agents.llm_agent import LlmAgent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService # Optional
from google.adk.planners import BasePlanner, BuiltInPlanner, PlanReActPlanner
from google.adk.models import LlmRequest

from google.genai.types import ThinkingConfig
from google.genai.types import GenerateContentConfig

import datetime
from zoneinfo import ZoneInfo

APP_NAME = "weather_app"
USER_ID = "1234"
SESSION_ID = "session1234"

def get_weather(city: str) -> dict:
    """Retrieves the current weather report for a specified city.

    Args:
        city (str): The name of the city for which to retrieve the weather report.

    Returns:
        dict: status and result or error msg.
    """
    if city.lower() == "new york":
        return {
            "status": "success",
            "report": (
                "The weather in New York is sunny with a temperature of 25 degrees"
                " Celsius (77 degrees Fahrenheit)."
            ),
        }
    else:
        return {
            "status": "error",
            "error_message": f"Weather information for '{city}' is not available.",
        }


def get_current_time(city: str) -> dict:
    """Returns the current time in a specified city.

    Args:
        city (str): The name of the city for which to retrieve the current time.

    Returns:
        dict: status and result or error msg.
    """

    if city.lower() == "new york":
        tz_identifier = "America/New_York"
    else:
        return {
            "status": "error",
            "error_message": (
                f"Sorry, I don't have timezone information for {city}."
            ),
        }

    tz = ZoneInfo(tz_identifier)
    now = datetime.datetime.now(tz)
    report = (
        f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
    )
    return {"status": "success", "report": report}

# Step 1: Create a ThinkingConfig
thinking_config = ThinkingConfig(
    include_thoughts=True,   # Ask the model to include its thoughts in the response
    thinking_budget=256      # Limit the 'thinking' to 256 tokens (adjust as needed)
)
print("ThinkingConfig:", thinking_config)

# Step 2: Instantiate BuiltInPlanner
planner = BuiltInPlanner(
    thinking_config=thinking_config
)
print("BuiltInPlanner created.")

# Step 3: Wrap the planner in an LlmAgent
agent = LlmAgent(
    model="gemini-flash-latest",  # Set your model name
    name="weather_and_time_agent",
    instruction="You are an agent that returns time and weather",
    planner=planner,
    tools=[get_weather, get_current_time]
)

# Session and Runner
session_service = InMemorySessionService()
session = asyncio.run(
    session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
)
runner = Runner(agent=agent, app_name=APP_NAME, session_service=session_service)

# Agent Interaction
def call_agent(query):
    content = types.Content(role='user', parts=[types.Part(text=query)])
    events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)

    for event in events:
        print(f"\nDEBUG EVENT: {event}\n")
        if event.is_final_response() and event.content and event.content.parts:
            final_answer = event.content.parts[0].text.strip()
            print("\n🟢 FINAL ANSWER\n", final_answer, "\n")

call_agent("If it's raining in New York right now, what is the current temperature?")

代码执行

在 ADK 中得到支持。Python v0.1.0Java v0.1.0
  • code_executor (可选): 提供一个…… BaseCodeExecutor 该实例允许代理执行来自大型语言模型(LLM)响应中的代码块。有关更多信息,请参阅…… 使用 Gemini 进行代码执行 API.
# 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 LlmAgent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.code_executors import BuiltInCodeExecutor
from google.genai import types

AGENT_NAME = "calculator_agent"
APP_NAME = "calculator"
USER_ID = "user1234"
SESSION_ID = "session_code_exec_async"
GEMINI_MODEL = "gemini-2.0-flash"

# Agent Definition
code_agent = LlmAgent(
    name=AGENT_NAME,
    model=GEMINI_MODEL,
    code_executor=BuiltInCodeExecutor(),
    instruction="""You are a calculator agent.
    When given a mathematical expression, write and execute Python code to calculate the result.
    Return only the final numerical result as plain text, without markdown or code blocks.
    """,
    description="Executes Python code to perform calculations.",
)

# Session and Runner
session_service = InMemorySessionService()
session = asyncio.run(session_service.create_session(
    app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
))
runner = Runner(agent=code_agent, app_name=APP_NAME,
                session_service=session_service)

# Agent Interaction (Async)
async def call_agent_async(query):
    content = types.Content(role="user", parts=[types.Part(text=query)])
    print(f"\n--- Running Query: {query} ---")
    final_response_text = "No final text response captured."
    try:
        # Use run_async
        async for event in runner.run_async(
            user_id=USER_ID, session_id=SESSION_ID, new_message=content
        ):
            print(f"Event ID: {event.id}, Author: {event.author}")

            # --- Check for specific parts FIRST ---
            has_specific_part = False
            if event.content and event.content.parts:
                for part in event.content.parts:  # Iterate through all parts
                    if part.executable_code:
                        # Access the actual code string via .code
                        print(
                            f"  Debug: Agent generated code:\n```python\n{part.executable_code.code}\n```"
                        )
                        has_specific_part = True
                    elif part.code_execution_result:
                        # Access outcome and output correctly
                        print(
                            f"  Debug: Code Execution Result: {part.code_execution_result.outcome} - Output:\n{part.code_execution_result.output}"
                        )
                        has_specific_part = True
                    # Also print any text parts found in any event for debugging
                    elif part.text and not part.text.isspace():
                        print(f"  Text: '{part.text.strip()}'")
                        # Do not set has_specific_part=True here, as we want the final response logic below

            # --- Check for final response AFTER specific parts ---
            # Only consider it final if it doesn't have the specific code parts we just handled
            if not has_specific_part and event.is_final_response():
                if (
                    event.content
                    and event.content.parts
                    and event.content.parts[0].text
                ):
                    final_response_text = event.content.parts[0].text.strip()
                    print(f"==> Final Agent Response: {final_response_text}")
                else:
                    print(
                        "==> Final Agent Response: [No text content in final event]")

    except Exception as e:
        print(f"ERROR during agent run: {e}")
    print("-" * 30)


# Main async function to run the examples
async def main():
    await call_agent_async("Calculate the value of (5 + 7) * 3")
    await call_agent_async("What is 10 factorial?")


# Execute the main async function
try:
    asyncio.run(main())
except RuntimeError as e:
    # Handle specific error when running asyncio.run in an already running loop (like Jupyter/Colab)
    if "cannot be called from a running event loop" in str(e):
        print("\nRunning in an existing event loop (like Colab/Jupyter).")
        print("Please run `await main()` in a notebook cell instead.")
        # If in an interactive environment like a notebook, you might need to run:
        # await main()
    else:
        raise e  # Re-raise other runtime errors
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.BuiltInCodeExecutionTool;
import com.google.common.collect.ImmutableList;
import com.google.genai.types.Content;
import com.google.genai.types.Part;

public class CodeExecutionAgentApp {

  private static final String AGENT_NAME = "calculator_agent";
  private static final String APP_NAME = "calculator";
  private static final String USER_ID = "user1234";
  private static final String SESSION_ID = "session_code_exec_sync";
  private static final String GEMINI_MODEL = "gemini-2.0-flash";

  /**
   * Calls the agent with a query and prints the interaction events and final response.
   *
   * @param runner The runner instance for the agent.
   * @param query The query to send to the agent.
   */
  public static void callAgent(Runner runner, String query) {
    Content content =
        Content.builder().role("user").parts(ImmutableList.of(Part.fromText(query))).build();

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

    System.out.println("\n--- Running Query: " + query + " ---");
    final String[] finalResponseText = {"No final text response captured."};

    try {
      runner
          .runAsync(session.userId(), session.id(), content)
          .forEach(
              event -> {
                System.out.println("Event ID: " + event.id() + ", Author: " + event.author());

                boolean hasSpecificPart = false;
                if (event.content().isPresent() && event.content().get().parts().isPresent()) {
                  for (Part part : event.content().get().parts().get()) {
                    if (part.executableCode().isPresent()) {
                      System.out.println(
                          "  Debug: Agent generated code:\n```python\n"
                              + part.executableCode().get().code()
                              + "\n```");
                      hasSpecificPart = true;
                    } else if (part.codeExecutionResult().isPresent()) {
                      System.out.println(
                          "  Debug: Code Execution Result: "
                              + part.codeExecutionResult().get().outcome()
                              + " - Output:\n"
                              + part.codeExecutionResult().get().output());
                      hasSpecificPart = true;
                    } else if (part.text().isPresent() && !part.text().get().trim().isEmpty()) {
                      System.out.println("  Text: '" + part.text().get().trim() + "'");
                    }
                  }
                }

                if (!hasSpecificPart && event.finalResponse()) {
                  if (event.content().isPresent()
                      && event.content().get().parts().isPresent()
                      && !event.content().get().parts().get().isEmpty()
                      && event.content().get().parts().get().get(0).text().isPresent()) {
                    finalResponseText[0] =
                        event.content().get().parts().get().get(0).text().get().trim();
                    System.out.println("==> Final Agent Response: " + finalResponseText[0]);
                  } else {
                    System.out.println(
                        "==> Final Agent Response: [No text content in final event]");
                  }
                }
              });
    } catch (Exception e) {
      System.err.println("ERROR during agent run: " + e.getMessage());
      e.printStackTrace();
    }
    System.out.println("------------------------------");
  }

  public static void main(String[] args) {
    BuiltInCodeExecutionTool codeExecutionTool = new BuiltInCodeExecutionTool();

    BaseAgent codeAgent =
        LlmAgent.builder()
            .name(AGENT_NAME)
            .model(GEMINI_MODEL)
            .tools(ImmutableList.of(codeExecutionTool))
            .instruction(
                """
                                You are a calculator agent.
                                When given a mathematical expression, write and execute Python code to calculate the result.
                                Return only the final numerical result as plain text, without markdown or code blocks.
                                """)
            .description("Executes Python code to perform calculations.")
            .build();

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

    callAgent(runner, "Calculate the value of (5 + 7) * 3");
    callAgent(runner, "What is 10 factorial?");
  }
}

代码示例

以下示例展示了本页讨论的核心概念。 更复杂的智能体可能会包含模式(schemas)、上下文控制(context control)以及规划功能(planning)。

代码

以下是完整的、基础的内容: capital_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.

# --- Full example code demonstrating LlmAgent with Tools vs. Output Schema ---
import json # Needed for pretty printing dicts
import asyncio 

from google.adk.agents import LlmAgent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from pydantic import BaseModel, Field

# --- 1. Define Constants ---
APP_NAME = "agent_comparison_app"
USER_ID = "test_user_456"
SESSION_ID_TOOL_AGENT = "session_tool_agent_xyz"
SESSION_ID_SCHEMA_AGENT = "session_schema_agent_xyz"
MODEL_NAME = "gemini-2.0-flash"

# --- 2. Define Schemas ---

# Input schema used by both agents
class CountryInput(BaseModel):
    country: str = Field(description="The country to get information about.")

# Output schema ONLY for the second agent
class CapitalInfoOutput(BaseModel):
    capital: str = Field(description="The capital city of the country.")
    # Note: Population is illustrative; the LLM will infer or estimate this
    # as it cannot use tools when output_schema is set.
    population_estimate: str = Field(description="An estimated population of the capital city.")

# --- 3. Define the Tool (Only for the first agent) ---
def get_capital_city(country: str) -> str:
    """Retrieves the capital city of a given country."""
    print(f"\n-- Tool Call: get_capital_city(country='{country}') --")
    country_capitals = {
        "united states": "Washington, D.C.",
        "canada": "Ottawa",
        "france": "Paris",
        "japan": "Tokyo",
    }
    result = country_capitals.get(country.lower(), f"Sorry, I couldn't find the capital for {country}.")
    print(f"-- Tool Result: '{result}' --")
    return result

# --- 4. Configure Agents ---

# Agent 1: Uses a tool and output_key
capital_agent_with_tool = LlmAgent(
    model=MODEL_NAME,
    name="capital_agent_tool",
    description="Retrieves the capital city using a specific tool.",
    instruction="""You are a helpful agent that provides the capital city of a country using a tool.
The user will provide the country name in a JSON format like {"country": "country_name"}.
1. Extract the country name.
2. Use the `get_capital_city` tool to find the capital.
3. Respond clearly to the user, stating the capital city found by the tool.
""",
    tools=[get_capital_city],
    input_schema=CountryInput,
    output_key="capital_tool_result", # Store final text response
)

# Agent 2: Uses output_schema (NO tools possible)
structured_info_agent_schema = LlmAgent(
    model=MODEL_NAME,
    name="structured_info_agent_schema",
    description="Provides capital and estimated population in a specific JSON format.",
    instruction=f"""You are an agent that provides country information.
The user will provide the country name in a JSON format like {{"country": "country_name"}}.
Respond ONLY with a JSON object matching this exact schema:
{json.dumps(CapitalInfoOutput.model_json_schema(), indent=2)}
Use your knowledge to determine the capital and estimate the population. Do not use any tools.
""",
    # *** NO tools parameter here - using output_schema prevents tool use ***
    input_schema=CountryInput,
    output_schema=CapitalInfoOutput, # Enforce JSON output structure
    output_key="structured_info_result", # Store final JSON response
)

# --- 5. Set up Session Management and Runners ---
session_service = InMemorySessionService()

# Create a runner for EACH agent
capital_runner = Runner(
    agent=capital_agent_with_tool,
    app_name=APP_NAME,
    session_service=session_service
)
structured_runner = Runner(
    agent=structured_info_agent_schema,
    app_name=APP_NAME,
    session_service=session_service
)

# --- 6. Define Agent Interaction Logic ---
async def call_agent_and_print(
    runner_instance: Runner,
    agent_instance: LlmAgent,
    session_id: str,
    query_json: str
):
    """Sends a query to the specified agent/runner and prints results."""
    print(f"\n>>> Calling Agent: '{agent_instance.name}' | Query: {query_json}")

    user_content = types.Content(role='user', parts=[types.Part(text=query_json)])

    final_response_content = "No final response received."
    async for event in runner_instance.run_async(user_id=USER_ID, session_id=session_id, new_message=user_content):
        # print(f"Event: {event.type}, Author: {event.author}") # Uncomment for detailed logging
        if event.is_final_response() and event.content and event.content.parts:
            # For output_schema, the content is the JSON string itself
            final_response_content = event.content.parts[0].text

    print(f"<<< Agent '{agent_instance.name}' Response: {final_response_content}")

    current_session = await session_service.get_session(app_name=APP_NAME,
                                                  user_id=USER_ID,
                                                  session_id=session_id)
    stored_output = current_session.state.get(agent_instance.output_key)

    # Pretty print if the stored output looks like JSON (likely from output_schema)
    print(f"--- Session State ['{agent_instance.output_key}']: ", end="")
    try:
        # Attempt to parse and pretty print if it's JSON
        parsed_output = json.loads(stored_output)
        print(json.dumps(parsed_output, indent=2))
    except (json.JSONDecodeError, TypeError):
         # Otherwise, print as string
        print(stored_output)
    print("-" * 30)


# --- 7. Run Interactions ---
async def main():
    # Create separate sessions for clarity, though not strictly necessary if context is managed
    print("--- Creating Sessions ---")
    await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID_TOOL_AGENT)
    await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID_SCHEMA_AGENT)

    print("--- Testing Agent with Tool ---")
    await call_agent_and_print(capital_runner, capital_agent_with_tool, SESSION_ID_TOOL_AGENT, '{"country": "France"}')
    await call_agent_and_print(capital_runner, capital_agent_with_tool, SESSION_ID_TOOL_AGENT, '{"country": "Canada"}')

    print("\n\n--- Testing Agent with Output Schema (No Tool Use) ---")
    await call_agent_and_print(structured_runner, structured_info_agent_schema, SESSION_ID_SCHEMA_AGENT, '{"country": "France"}')
    await call_agent_and_print(structured_runner, structured_info_agent_schema, SESSION_ID_SCHEMA_AGENT, '{"country": "Japan"}')

# --- Run the Agent ---
# Note: In Colab, you can directly use 'await' at the top level.
# If running this code as a standalone Python script, you'll need to use asyncio.run() or manage the event loop.
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 } from '@google/adk';
import { createUserContent, Schema, Type } from '@google/genai';
import type { Part } from '@google/genai';
 import { z } from 'zod';

// --- 1. Define Constants ---
const APP_NAME = "capital_app_ts";
const USER_ID = "test_user_789";
const SESSION_ID_TOOL_AGENT = "session_tool_agent_ts";
const SESSION_ID_SCHEMA_AGENT = "session_schema_agent_ts";
const MODEL_NAME = "gemini-2.5-flash"; // Using flash for speed

// --- 2. Define Schemas ---

// A. Schema for the Tool's parameters (using Zod)
const CountryInput = z.object({
    country: z.string().describe('The country to get the capital for.'),
});

// B. Output schema ONLY for the second agent (using ADK's Schema type)
const CapitalInfoOutputSchema: Schema = {
    type: Type.OBJECT,
    description: "Schema for capital city information.",
    properties: {
        capital: {
            type: Type.STRING,
            description: "The capital city of the country."
        },
        population_estimate: {
            type: Type.STRING,
            description: "An estimated population of the capital city."
        },
    },
    required: ["capital", "population_estimate"],
};


// --- 3. Define the Tool (Only for the first agent) ---
async function getCapitalCity(params: z.infer<typeof CountryInput>): Promise<{ result: string }> {
    console.log(`\n-- Tool Call: getCapitalCity(country='${params.country}') --`);
    const capitals: Record<string, string> = {
        'united states': 'Washington, D.C.',
        'canada': 'Ottawa',
        'france': 'Paris',
        'japan': 'Tokyo',
    };
    const result = capitals[params.country.toLowerCase()] ??
        `Sorry, I couldn't find the capital for ${params.country}.`;
    console.log(`-- Tool Result: '${result}' --`);
    return { result: result }; // Tools must return an object
}

// --- 4. Configure Agents ---

// Agent 1: Uses a tool and outputKey
const getCapitalCityTool = new FunctionTool({
    name: 'get_capital_city',
    description: 'Retrieves the capital city for a given country',
    parameters: CountryInput,
    execute: getCapitalCity,
});

const capitalAgentWithTool = new LlmAgent({
    model: MODEL_NAME,
    name: 'capital_agent_tool',
    description: 'Retrieves the capital city using a specific tool.',
    instruction: `You are a helpful agent that provides the capital city of a country using a tool.
The user will provide the country name in a JSON format like {"country": "country_name"}.
1. Extract the country name.
2. Use the \`get_capital_city\` tool to find the capital.
3. Respond with a JSON object with the key 'capital' and the value as the capital city.
`,
    tools: [getCapitalCityTool],
    outputKey: "capital_tool_result", // Store final text response
});

// Agent 2: Uses outputSchema (NO tools possible)
const structuredInfoAgentSchema = new LlmAgent({
    model: MODEL_NAME,
    name: 'structured_info_agent_schema',
    description: 'Provides capital and estimated population in a specific JSON format.',
    instruction: `You are an agent that provides country information.
The user will provide the country name in a JSON format like {"country": "country_name"}.
Respond ONLY with a JSON object matching this exact schema:
${JSON.stringify(CapitalInfoOutputSchema, null, 2)}
Use your knowledge to determine the capital and estimate the population. Do not use any tools.
`,
    // *** NO tools parameter here - using outputSchema prevents tool use ***
    outputSchema: CapitalInfoOutputSchema,
    outputKey: "structured_info_result",
});


// --- 5. Define Agent Interaction Logic ---
async function callAgentAndPrint(
    runner: InMemoryRunner,
    agent: LlmAgent,
    sessionId: string,
    queryJson: string
) {
    console.log(`\n>>> Calling Agent: '${agent.name}' | Query: ${queryJson}`);
    const message = createUserContent(queryJson);

    let finalResponseContent = "No final response received.";
    for await (const event of runner.runAsync({ userId: USER_ID, sessionId: sessionId, newMessage: message })) {
        if (isFinalResponse(event) && event.content?.parts?.length) {
            finalResponseContent = event.content.parts.map((part: Part) => part.text ?? '').join('');
        }
    }
    console.log(`<<< Agent '${agent.name}' Response: ${finalResponseContent}`);

    // Check the session state
    const currentSession = await runner.sessionService.getSession({ appName: APP_NAME, userId: USER_ID, sessionId: sessionId });
    if (!currentSession) {
        console.log(`--- Session not found: ${sessionId} ---`);
        return;
    }
    const storedOutput = currentSession.state[agent.outputKey!];

    console.log(`--- Session State ['${agent.outputKey}']: `);
    try {
        // Attempt to parse and pretty print if it's JSON
        const parsedOutput = JSON.parse(storedOutput as string);
        console.log(JSON.stringify(parsedOutput, null, 2));
    } catch (e) {
        // Otherwise, print as a string
        console.log(storedOutput);
    }
    console.log("-".repeat(30));
}

// --- 6. Run Interactions ---
async function main() {
    // Set up runners for each agent
    const capitalRunner = new InMemoryRunner({ appName: APP_NAME, agent: capitalAgentWithTool });
    const structuredRunner = new InMemoryRunner({ appName: APP_NAME, agent: structuredInfoAgentSchema });

    // Create sessions
    console.log("--- Creating Sessions ---");
    await capitalRunner.sessionService.createSession({ appName: APP_NAME, userId: USER_ID, sessionId: SESSION_ID_TOOL_AGENT });
    await structuredRunner.sessionService.createSession({ appName: APP_NAME, userId: USER_ID, sessionId: SESSION_ID_SCHEMA_AGENT });

    console.log("\n--- Testing Agent with Tool ---");
    await callAgentAndPrint(capitalRunner, capitalAgentWithTool, SESSION_ID_TOOL_AGENT, '{"country": "France"}');
    await callAgentAndPrint(capitalRunner, capitalAgentWithTool, SESSION_ID_TOOL_AGENT, '{"country": "Canada"}');

    console.log("\n\n--- Testing Agent with Output Schema (No Tool Use) ---");
    await callAgentAndPrint(structuredRunner, structuredInfoAgentSchema, SESSION_ID_SCHEMA_AGENT, '{"country": "France"}');
    await callAgentAndPrint(structuredRunner, structuredInfoAgentSchema, SESSION_ID_SCHEMA_AGENT, '{"country": "Japan"}');
}

main();
package main

import (
    "context"
    "encoding/json"
    "errors"
    "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"
)

// --- Main Runnable Example ---

const (
    modelName = "gemini-flash-latest"
    appName   = "agent_comparison_app"
    userID    = "test_user_456"
)

type getCapitalCityArgs struct {
    Country string `json:"country" jsonschema:"The country to get the capital of."`
}

// getCapitalCity retrieves the capital city of a given country.
func getCapitalCity(ctx agent.Context, args getCapitalCityArgs) (map[string]any, error) {
    fmt.Printf("\n-- Tool Call: getCapitalCity(country='%s') --\n", args.Country)
    capitals := map[string]string{
        "united states": "Washington, D.C.",
        "canada":        "Ottawa",
        "france":        "Paris",
        "japan":         "Tokyo",
    }
    capital, ok := capitals[strings.ToLower(args.Country)]
    if !ok {
        result := fmt.Sprintf("Sorry, I couldn't find the capital for %s.", args.Country)
        fmt.Printf("-- Tool Result: '%s' --\n", result)
        return nil, errors.New(result)
    }
    fmt.Printf("-- Tool Result: '%s' --\n", capital)
    return map[string]any{"result": capital}, nil
}

// callAgent is a helper function to execute an agent with a given prompt and handle its output.
func callAgent(ctx context.Context, a agent.Agent, outputKey string, prompt string) {
    fmt.Printf("\n>>> Calling Agent: '%s' | Query: %s\n", a.Name(), prompt)
    // Create an in-memory session service to manage agent state.
    sessionService := session.InMemoryService()

    // Create a new session for the agent interaction.
    sessionCreateResponse, err := sessionService.Create(ctx, &session.CreateRequest{
        AppName: appName,
        UserID:  userID,
    })
    if err != nil {
        log.Fatalf("Failed to create the session service: %v", err)
    }

    session := sessionCreateResponse.Session

    // Configure the runner with the application name, agent, and session service.
    config := runner.Config{
        AppName:        appName,
        Agent:          a,
        SessionService: sessionService,
    }

    // Create a new runner instance.
    r, err := runner.New(config)
    if err != nil {
        log.Fatalf("Failed to create the runner: %v", err)
    }

    // Prepare the user's message to send to the agent.
    sessionID := session.ID()
    userMsg := &genai.Content{
        Parts: []*genai.Part{
            genai.NewPartFromText(prompt),
        },
        Role: string(genai.RoleUser),
    }

    // Run the agent and process the streaming events.
    for event, err := range r.Run(ctx, userID, sessionID, userMsg, agent.RunConfig{
        StreamingMode: agent.StreamingModeSSE,
    }) {
        if err != nil {
            fmt.Printf("\nAGENT_ERROR: %v\n", err)
        } else if event.Partial {
            // Print partial responses as they are received.
            for _, p := range event.Content.Parts {
                fmt.Print(p.Text)
            }
        }
    }

    // After the run, check if there's an expected output key in the session state.
    if outputKey != "" {
        storedOutput, error := session.State().Get(outputKey)
        if error == nil {
            // Pretty-print the stored output if it's a JSON string.
            fmt.Printf("\n--- Session State ['%s']: ", outputKey)
            storedString, isString := storedOutput.(string)
            if isString {
                var prettyJSON map[string]interface{}
                if err := json.Unmarshal([]byte(storedString), &prettyJSON); err == nil {
                    indentedJSON, err := json.MarshalIndent(prettyJSON, "", "  ")
                    if err == nil {
                        fmt.Println(string(indentedJSON))
                    } else {
                        fmt.Println(storedString)
                    }
                } else {
                    fmt.Println(storedString)
                }
            } else {
                fmt.Println(storedOutput)
            }
            fmt.Println(strings.Repeat("-", 30))
        }
    }
}

func main() {
    ctx := context.Background()

    model, err := gemini.NewModel(ctx, modelName, &genai.ClientConfig{})
    if err != nil {
        log.Fatalf("Failed to create model: %v", err)
    }

    capitalTool, err := functiontool.New(
        functiontool.Config{
            Name:        "get_capital_city",
            Description: "Retrieves the capital city for a given country.",
        },
        getCapitalCity,
    )
    if err != nil {
        log.Fatalf("Failed to create function tool: %v", err)
    }

    countryInputSchema := &genai.Schema{
        Type:        genai.TypeObject,
        Description: "Input for specifying a country.",
        Properties: map[string]*genai.Schema{
            "country": {
                Type:        genai.TypeString,
                Description: "The country to get information about.",
            },
        },
        Required: []string{"country"},
    }

    capitalAgentWithTool, err := llmagent.New(llmagent.Config{
        Name:        "capital_agent_tool",
        Model:       model,
        Description: "Retrieves the capital city using a specific tool.",
        Instruction: `You are a helpful agent that provides the capital city of a country using a tool.
The user will provide the country name in a JSON format like {"country": "country_name"}.
1. Extract the country name.
2. Use the 'get_capital_city' tool to find the capital.
3. Respond clearly to the user, stating the capital city found by the tool.`,
        Tools:       []tool.Tool{capitalTool},
        InputSchema: countryInputSchema,
        OutputKey:   "capital_tool_result",
    })
    if err != nil {
        log.Fatalf("Failed to create capital agent with tool: %v", err)
    }

    capitalInfoOutputSchema := &genai.Schema{
        Type:        genai.TypeObject,
        Description: "Schema for capital city information.",
        Properties: map[string]*genai.Schema{
            "capital": {
                Type:        genai.TypeString,
                Description: "The capital city of the country.",
            },
            "population_estimate": {
                Type:        genai.TypeString,
                Description: "An estimated population of the capital city.",
            },
        },
        Required: []string{"capital", "population_estimate"},
    }
    schemaJSON, _ := json.Marshal(capitalInfoOutputSchema)
    structuredInfoAgentSchema, err := llmagent.New(llmagent.Config{
        Name:        "structured_info_agent_schema",
        Model:       model,
        Description: "Provides capital and estimated population in a specific JSON format.",
        Instruction: fmt.Sprintf(`You are an agent that provides country information.
The user will provide the country name in a JSON format like {"country": "country_name"}.
Respond ONLY with a JSON object matching this exact schema:
%s
Use your knowledge to determine the capital and estimate the population. Do not use any tools.`, string(schemaJSON)),
        InputSchema:  countryInputSchema,
        OutputSchema: capitalInfoOutputSchema,
        OutputKey:    "structured_info_result",
    })
    if err != nil {
        log.Fatalf("Failed to create structured info agent: %v", err)
    }

    fmt.Println("--- Testing Agent with Tool ---")
    callAgent(ctx, capitalAgentWithTool, "capital_tool_result", `{"country": "France"}`)
    callAgent(ctx, capitalAgentWithTool, "capital_tool_result", `{"country": "Canada"}`)

    fmt.Println("\n\n--- Testing Agent with Output Schema (No Tool Use) ---")
    callAgent(ctx, structuredInfoAgentSchema, "structured_info_result", `{"country": "France"}`)
    callAgent(ctx, structuredInfoAgentSchema, "structured_info_result", `{"country": "Japan"}`)
}
// --- Full example code demonstrating LlmAgent with Tools vs. Output Schema ---

import com.google.adk.agents.LlmAgent;
import com.google.adk.events.Event;
import com.google.adk.runner.Runner;
import com.google.adk.sessions.InMemorySessionService;
import com.google.adk.sessions.Session;
import com.google.adk.tools.Annotations;
import com.google.adk.tools.FunctionTool;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import com.google.genai.types.Schema;
import io.reactivex.rxjava3.core.Flowable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class LlmAgentExample {

  // --- 1. Define Constants ---
  private static final String MODEL_NAME = "gemini-2.0-flash";
  private static final String APP_NAME = "capital_agent_tool";
  private static final String USER_ID = "test_user_456";
  private static final String SESSION_ID_TOOL_AGENT = "session_tool_agent_xyz";
  private static final String SESSION_ID_SCHEMA_AGENT = "session_schema_agent_xyz";

  // --- 2. Define Schemas ---

  // Input schema used by both agents
  private static final Schema COUNTRY_INPUT_SCHEMA =
      Schema.builder()
          .type("OBJECT")
          .description("Input for specifying a country.")
          .properties(
              Map.of(
                  "country",
                  Schema.builder()
                      .type("STRING")
                      .description("The country to get information about.")
                      .build()))
          .required(List.of("country"))
          .build();

  // Output schema ONLY for the second agent
  private static final Schema CAPITAL_INFO_OUTPUT_SCHEMA =
      Schema.builder()
          .type("OBJECT")
          .description("Schema for capital city information.")
          .properties(
              Map.of(
                  "capital",
                  Schema.builder()
                      .type("STRING")
                      .description("The capital city of the country.")
                      .build(),
                  "population_estimate",
                  Schema.builder()
                      .type("STRING")
                      .description("An estimated population of the capital city.")
                      .build()))
          .required(List.of("capital", "population_estimate"))
          .build();

  // --- 3. Define the Tool (Only for the first agent) ---
  // Retrieves the capital city of a given country.
  public static Map<String, Object> getCapitalCity(
      @Annotations.Schema(name = "country", description = "The country to get capital for")
      String country) {
    System.out.printf("%n-- Tool Call: getCapitalCity(country='%s') --%n", country);
    Map<String, String> countryCapitals = new HashMap<>();
    countryCapitals.put("united states", "Washington, D.C.");
    countryCapitals.put("canada", "Ottawa");
    countryCapitals.put("france", "Paris");
    countryCapitals.put("japan", "Tokyo");

    String result =
        countryCapitals.getOrDefault(
            country.toLowerCase(), "Sorry, I couldn't find the capital for " + country + ".");
    System.out.printf("-- Tool Result: '%s' --%n", result);
    return Map.of("result", result); // Tools must return a Map
  }

  public static void main(String[] args){
    LlmAgentExample agentExample = new LlmAgentExample();
    FunctionTool capitalTool = FunctionTool.create(agentExample.getClass(), "getCapitalCity");

    // --- 4. Configure Agents ---

    // Agent 1: Uses a tool and output_key
    LlmAgent capitalAgentWithTool =
        LlmAgent.builder()
            .model(MODEL_NAME)
            .name("capital_agent_tool")
            .description("Retrieves the capital city using a specific tool.")
            .instruction(
              """
              You are a helpful agent that provides the capital city of a country using a tool.
              1. Extract the country name.
              2. Use the `get_capital_city` tool to find the capital.
              3. Respond clearly to the user, stating the capital city found by the tool.
              """)
            .tools(capitalTool)
            .inputSchema(COUNTRY_INPUT_SCHEMA)
            .outputKey("capital_tool_result") // Store final text response
            .build();

    // Agent 2: Uses an output schema
    LlmAgent structuredInfoAgentSchema =
        LlmAgent.builder()
            .model(MODEL_NAME)
            .name("structured_info_agent_schema")
            .description("Provides capital and estimated population in a specific JSON format.")
            .instruction(
                String.format("""
                You are an agent that provides country information.
                Respond ONLY with a JSON object matching this exact schema: %s
                Use your knowledge to determine the capital and estimate the population. Do not use any tools.
                """, CAPITAL_INFO_OUTPUT_SCHEMA.toJson()))
            // *** NO tools parameter here - using output_schema prevents tool use ***
            .inputSchema(COUNTRY_INPUT_SCHEMA)
            .outputSchema(CAPITAL_INFO_OUTPUT_SCHEMA) // Enforce JSON output structure
            .outputKey("structured_info_result") // Store final JSON response
            .build();

    // --- 5. Set up Session Management and Runners ---
    InMemorySessionService sessionService = new InMemorySessionService();

    sessionService.createSession(APP_NAME, USER_ID, null, SESSION_ID_TOOL_AGENT).blockingGet();
    sessionService.createSession(APP_NAME, USER_ID, null, SESSION_ID_SCHEMA_AGENT).blockingGet();

    Runner capitalRunner = new Runner(capitalAgentWithTool, APP_NAME, null, sessionService);
    Runner structuredRunner = new Runner(structuredInfoAgentSchema, APP_NAME, null, sessionService);

    // --- 6. Run Interactions ---
    System.out.println("--- Testing Agent with Tool ---");
    agentExample.callAgentAndPrint(
        capitalRunner, capitalAgentWithTool, SESSION_ID_TOOL_AGENT, "{\"country\": \"France\"}");
    agentExample.callAgentAndPrint(
        capitalRunner, capitalAgentWithTool, SESSION_ID_TOOL_AGENT, "{\"country\": \"Canada\"}");

    System.out.println("\n\n--- Testing Agent with Output Schema (No Tool Use) ---");
    agentExample.callAgentAndPrint(
        structuredRunner,
        structuredInfoAgentSchema,
        SESSION_ID_SCHEMA_AGENT,
        "{\"country\": \"France\"}");
    agentExample.callAgentAndPrint(
        structuredRunner,
        structuredInfoAgentSchema,
        SESSION_ID_SCHEMA_AGENT,
        "{\"country\": \"Japan\"}");
  }

  // --- 7. Define Agent Interaction Logic ---
  public void callAgentAndPrint(Runner runner, LlmAgent agent, String sessionId, String queryJson) {
    System.out.printf(
        "%n>>> Calling Agent: '%s' | Session: '%s' | Query: %s%n",
        agent.name(), sessionId, queryJson);

    Content userContent = Content.fromParts(Part.fromText(queryJson));
    final String[] finalResponseContent = {"No final response received."};
    Flowable<Event> eventStream = runner.runAsync(USER_ID, sessionId, userContent);

    // Stream event response
    eventStream.blockingForEach(event -> {
          if (event.finalResponse() && event.content().isPresent()) {
            event
                .content()
                .get()
                .parts()
                .flatMap(parts -> parts.isEmpty() ? Optional.empty() : Optional.of(parts.get(0)))
                .flatMap(Part::text)
                .ifPresent(text -> finalResponseContent[0] = text);
          }
        });

    System.out.printf("<<< Agent '%s' Response: %s%n", agent.name(), finalResponseContent[0]);

    // Retrieve the session again to get the updated state
    Session updatedSession =
        runner
            .sessionService()
            .getSession(APP_NAME, USER_ID, sessionId, Optional.empty())
            .blockingGet();

    if (updatedSession != null && agent.outputKey().isPresent()) {
      // Print to verify if the stored output looks like JSON (likely from output_schema)
      System.out.printf("--- Session State ['%s']: ", agent.outputKey().get());
      }
  }
}
val finalAgent =
    LlmAgent(
        name = "capital_agent",
        model = Gemini(name = "gemini-flash-latest"),
        description = "Answers user questions about the capital city of a given country.",
        instruction =
            Instruction(
                "You are an agent that provides the capital city of a country...",
            ),
        // tools = capitalService.generatedTools() // Assuming tools are added
    )

val sessionService = InMemorySessionService()
val runner = InMemoryRunner(finalAgent, "capital_app", sessionService)

val userMessage = Content(parts = listOf(Part(text = "What is the capital of France?")))

// Use runAsync to get a Flow of events
runner.runAsync(
    userId = "user123",
    sessionId = "session456",
    newMessage = userMessage,
).collect {
        event ->
    if (event.isFinalResponse) {
        val finalResponse = event.content?.parts?.firstOrNull()?.text
        println(finalResponse)
    }
}

附加功能

ADK 为代理提供了本指南未涵盖的额外功能,包括以下内容:

  • 回调函数(Callbacks): 通过拦截代理的执行点来添加更多控制机制,这些执行点包括模型调用之前和之后,以及工具调用之前和之后。 回调函数(Callbacks).
  • 基于图的工作流程: 将大型语言模型(LLM)代理作为步骤,构建基于图的、具有确定性的处理流程(pipeline)。 基于图的代理工作流程(Graph-based agent workflows)在 Go 语言中(版本 v2.0.0 及以上):请使用…… workflow.NewAgentNode 可以将任何大型语言模型(LLM)代理封装为工作流节点(workflow node)。
  • 多智能体系统: 针对代理交互的高级策略,包括: 代理转移(Agent Transfer)disallow_transfer_to_parent, disallow_transfer_to_peers确保应用程序中的每个代理都遵循一致的身份验证机制和规则。GlobalInstructionPlugin,或 GlobalInstruction (在 Go 语言中)。请参阅…… 多智能体工作流程(Multi-agent Workflows) 和 协作代理 团队.