Colaboração Multiagente

Criando e orquestrando vários agentes.

Supervisor-Colaborador - Multiagente

Este exemplo demonstra como criar e orquestrar vários agentes que colaboram para realizar uma tarefa.

Temos um fluxo de trabalho de marketing com três agentes:

  1. Um agente colaborador do Analisador de Tendências que pesquisa palavras-chave de tendência de acordo com um tópico.
  2. Um agente colaborador do Content Writer que escreve um blog usando as palavras-chave de tendência.
  3. Um agente supervisor do Diretor de Marketing que orquestra os dois agentes acima e trata do envio de um e-mail ao usuário.

O usuário interage com o agente do Diretor de Marketing (como o único ponto de contato).

Python

multi_agents.py

import json
from oci.addons.adk import Agent, AgentClient, tool

@tool
def get_trending_keywords(topic):
    """ Get the trending keywords for a given topic. """
    # Here is a mock implementation
    return json.dumps({"topic": topic, "keywords": ["agent", "stargate", "openai"]})

@tool
def send_email(recipient, subject, body):
    """ Send an email to a recipient. """
    # Here is a mock implementation
    print("Sending email to ", recipient, "with subject", subject, "and body", body)
    return "Sent!"

def main():

    # A shared client for all agents
    client = AgentClient(
        auth_type="api_key",
        profile="DEFAULT",
        region="us-chicago-1"
    )

    # trend analyzer collaborator agent
    trend_analyzer = Agent(
        name="Trend Analyzer",
        instructions="You use the tools provided to analyze the trending keywords of given topics.",
        agent_endpoint_id="ocid1.genaiagentendpoint...",
        client=client,
        tools=[
            get_trending_keywords,
        ]
    )

    # content writer collaborator agent
    content_writer = Agent(
        name="Content Writer",
        instructions="You write a mini blog post (4 sentences) using the trending keywords.",
        agent_endpoint_id="ocid1.genaiagentendpoint...",
        client=client,
    )

    # marketing director supervisor agent
    marketing_director = Agent(
        name="Marketing Director",
        instructions="You ask the trend analyzer for trending keywords and "
         + " You then ask the content writer to write a blog post using the trending keywords. "
         + " You then send email to 'jane.doe@example.com' with the blog post."
         + " Then summarize the actions you took and reply to the user.",
        agent_endpoint_id="ocid1.genaiagentendpoint...",
        client=client,
        tools=[
            trend_analyzer.as_tool(
                tool_name="analyze_trending_keywords",
                tool_description="Analyze the trending keywords of given topics",
            ),
            content_writer.as_tool(
                tool_name="write_blog_post",
                tool_description="Write a blog post using the trending keywords.",
            ),
            send_email,
        ]
    )

    # Set up the agents once
    trend_analyzer.setup()
    content_writer.setup()
    marketing_director.setup()

    # Use the supervisor agent to process the end user request
    input = "Produce a blog post about current trends in the AI industry."
    response = marketing_director.run(input, max_steps=5)
    response.pretty_print()


if __name__ == "__main__":
    main()

O método as_tool() é um método de conveniência que permite passar o agente colaborador como uma ferramenta para o agente supervisor.

Passando o objeto do agente diretamente para as ferramentas

Como alternativa, você pode passar o objeto do agente diretamente para o parâmetro tools do construtor Agent do agente do supervisor.

Python

marketing_director = Agent(
    name="Marketing Director",
    instructions="...",
    agent_endpoint_id="ocid1.genaiagentendpoint...",
    client=client,
    tools=[
        trend_analyzer, # pass the agent object directly
        content_writer, # pass the agent object directly
        send_email,
    ]
)

Isso equivale a chamar o método as_tool() do agente colaborador, sem especificar o nome da ferramenta personalizada e a descrição da ferramenta. O ADK usa o nome do agente colaborador como o nome da ferramenta e a descrição do agente colaborador como a descrição da ferramenta.


Observação: recomendamos usar o método as_tool() para passar o agente colaborador como uma ferramenta para o agente supervisor. Essa abordagem dá a você um controle mais explícito sobre o nome da ferramenta e a descrição da ferramenta, que são importantes para o LLM entender as ferramentas.


Java

MultiAgentTools.java

package demos.multiagents;

import com.oracle.bmc.adk.tools.Param;
import com.oracle.bmc.adk.tools.Tool;
import com.oracle.bmc.adk.tools.Toolkit;
import com.oracle.bmc.ConfigFileReader;
import com.oracle.bmc.adk.agent.Agent;
import com.oracle.bmc.adk.agent.RunOptions;
import com.oracle.bmc.adk.client.AgentClient;
import com.oracle.bmc.adk.examples.multiagents.tools.MultiAgentTools;
import com.oracle.bmc.adk.tools.FunctionTool;
import com.oracle.bmc.adk.run.RunResponse;
import com.oracle.bmc.auth.BasicAuthenticationDetailsProvider;
import com.oracle.bmc.auth.SessionTokenAuthenticationDetailsProvider;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public class MultiAgentTools {
    @Tool(name = "get_trending_keywords", description = "Get the trending keywords for a given topic")
    public static String getTrendingKeywords(
          @Param(description = "The topic to get trending keywords for") String topic) {
        return "{\"topic\": \"" + topic + "\", \"keywords\": [\"agent\", \"stargate\", \"openai\"]}";
      }

    @Tool(name = "send_email", description = "Send an email to a recipient")
    public static String sendEmail(
          @Param(description = "The recipient email address") String recipient,
          @Param(description = "The email subject") String subject,
          @Param(description = "The email body content") String body) {
        System.out.println(
            "Sending email to " + recipient + " with subject " + subject + " and body " + body);
        return "Sent!";
      }

  public static void main(String[] args) throws Exception {
    final String TREND_AGENT_ID =
        "ocid1.genaiagentendpoint.oc1.us-chicago-1...";
    final String CONTENT_AGENT_ID =
        "ocid1.genaiagentendpoint.oc1.us-chicago-1...";
    final String MARKET_AGENT_ID =
        "ocid1.genaiagentendpoint.oc1.us-chicago-1...";
    final String configLocation = "~/.oci/config";
    final String configProfile = "DEFAULT";

    BasicAuthenticationDetailsProvider authProvider =
            new SessionTokenAuthenticationDetailsProvider(
                    ConfigFileReader.parse(configLocation, configProfile));

   AgentClient agentClient = AgentClient.builder()
        .authProvider(authProvider)
        .region("us-chicago-1")
        .build();

  Method emailMethod =
        MultiAgentTools.class.getMethod("sendEmail", String.class);
    FunctionTool emailTool = new FunctionTool(null, emailMethod);

  Method trendingMethod =
        MultiAgentTools.class.getMethod("getTrendingKeywords", String.class);
    FunctionTool trendingTool = new FunctionTool(null, trendingKeywordsMethod);

    Agent trendAnalyzer = Agent.builder()
            .client(agentClient)
            .agentEndpointId(TREND_AGENT_ID)
            .instructions("You use the tools provided to analyze the trend of topics")
            .tools(Arrays.asList(trendingTool))
            .name("Trend Analyzer")
            .build();

    Agent contentWriter = Agent.builder()
            .client(agentClient)
            .agentEndpointId(TREND_AGENT_ID)
            .instructions("You write a mini blog post (4 sentences) about the trending topics.")
            .tools(null)
            .name("Content Writer")
            .build();

    Agent marketingDirector = Agent.builder()
            .client(agentClient)
            .agentEndpointId(MARKET_AGENT_ID)
            .instructions(
                     "You ask the trend analyzer for trending topics, then ask the content writer "
                + "to write a blog post about them. Finally, send the post via email to j.jing.y.yang@oracle.com "
                + "and summarize the actions taken.",
            )
            .tools(Arrays.asList(
                trendAnalyzer.asTool("analyze_trending_keywords",
                    "Analyze the trending keywords of given topics",
                    5),
                contentWriter.asTool("write_blog_post",
                    "Write a blog post using the trending keywords.",
                    5),
                emailTool))
            .name("Marketing Director")
            .build();

    trendAnalyzer.setup();
    contentWriter.setup();
    marketingDirector.setup();

    String input = "Produce a blog post about current trends in the AI industry.";
    final Integer maxStep = 5;

    final RunOptions runOptions = RunOptions.builder().maxSteps(maxStep).build();
    RunResponse response = marketingDirector.run(input, runOptions);

    response.prettyPrint();
  }
}

Como Ele Funciona

Estamos usando o padrão agente como ferramenta para implementar o workflow hierárquico de vários agentes.

  1. O agente supervisor pode chamar o método run do agente colaborador como ferramenta.
  2. O agente supervisor recebe a resposta de execução do agente colaborador.
  3. O supervisor decide o que fazer a seguir com base na resposta do agente colaborador.

O que o método as_tool() faz é converter o método run() do agente colaborador em uma ferramenta de função que pode ser usada pelo agente supervisor.

Orquestração usando LLM

Ao tornar um agente colaborador como uma ferramenta, usamos essencialmente os recursos de uso de ferramentas do LLM do agente supervisor para orquestrar o fluxo de trabalho de vários agentes.

Neste exemplo, estamos dando ao supervisor muita flexibilidade e agência, ao custo de desistir de nossa capacidade de controlar precisamente o fluxo do fluxo de trabalho. Para controlar com precisão o fluxo do workflow de vários agentes, consulte o exemplo Workflow Determinístico.