在 Vertex AI Agent Engine 上开发和部署代理

本页介绍了如何使用以下代理框架创建和部署代理,以返回指定日期两种货币之间的汇率:

准备工作

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI and Cloud Storage APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI and Cloud Storage APIs.

    Enable the APIs

  8. 如需获得使用 Vertex AI Agent Engine 所需的权限,请让您的管理员为您授予项目的以下 IAM 角色:

    如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

    您也可以通过自定义角色或其他预定义角色来获取所需的权限。

    安装并初始化 Python 版 Vertex AI SDK

    1. 运行以下命令以安装 Vertex AI SDK for Python 和其他所需的软件包:

      ADK

      pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,adk]

      LangGraph

      pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,langchain]

      LangChain

      pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,langchain]

      AG2

      pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,ag2]

      LlamaIndex

      pip install --upgrade --quiet google-cloud-aiplatform[agent_engines,llama_index]
    2. 以用户身份进行身份验证

      Colab

      运行以下代码:

      from google.colab import auth
      
      auth.authenticate_user(project_id="PROJECT_ID")
      

      Cloud Shell

      您无需执行任何操作。

      本地 Shell

      运行以下命令:

      gcloud auth application-default login
    3. 运行以下代码以导入 Vertex AI Agent Engine 并初始化 SDK:

      import vertexai
      from vertexai import agent_engines
      
      vertexai.init(
          project="PROJECT_ID",               # Your project ID.
          location="LOCATION",                # Your cloud region.
          staging_bucket="gs://BUCKET_NAME",  # Your staging bucket.
      )
      

    开发代理

    首先,开发一个工具:

    def get_exchange_rate(
        currency_from: str = "USD",
        currency_to: str = "EUR",
        currency_date: str = "latest",
    ):
        """Retrieves the exchange rate between two currencies on a specified date."""
        import requests
    
        response = requests.get(
            f"https://api.frankfurter.app/{currency_date}",
            params={"from": currency_from, "to": currency_to},
        )
        return response.json()
    

    接下来,实例化代理:

    ADK

    from google.adk.agents import Agent
    from vertexai.preview.reasoning_engines import AdkApp
    
    agent = Agent(
        model="gemini-2.0-flash",
        name='currency_exchange_agent',
        tools=[get_exchange_rate],
    )
    
    app = AdkApp(agent=agent)
    

    LangGraph

    from vertexai import agent_engines
    
    agent = agent_engines.LanggraphAgent(
        model="gemini-2.0-flash",
        tools=[get_exchange_rate],
        model_kwargs={
            "temperature": 0.28,
            "max_output_tokens": 1000,
            "top_p": 0.95,
        },
    )
    

    LangChain

    from vertexai import agent_engines
    
    agent = agent_engines.LangchainAgent(
        model="gemini-2.0-flash",
        tools=[get_exchange_rate],
        model_kwargs={
            "temperature": 0.28,
            "max_output_tokens": 1000,
            "top_p": 0.95,
        },
    )
    

    AG2

    from vertexai import agent_engines
    
    agent = agent_engines.AG2Agent(
        model="gemini-2.0-flash",
        runnable_name="Get Exchange Rate Agent",
        tools=[get_exchange_rate],
    )
    

    LlamaIndex

    from vertexai.preview import reasoning_engines
    
    def runnable_with_tools_builder(model, runnable_kwargs=None, **kwargs):
        from llama_index.core.query_pipeline import QueryPipeline
        from llama_index.core.tools import FunctionTool
        from llama_index.core.agent import ReActAgent
    
        llama_index_tools = []
        for tool in runnable_kwargs.get("tools"):
            llama_index_tools.append(FunctionTool.from_defaults(tool))
        agent = ReActAgent.from_tools(llama_index_tools, llm=model, verbose=True)
        return QueryPipeline(modules = {"agent": agent})
    
    agent = reasoning_engines.LlamaIndexQueryPipelineAgent(
        model="gemini-2.0-flash",
        runnable_kwargs={"tools": [get_exchange_rate]},
        runnable_builder=runnable_with_tools_builder,
    )
    

    最后,在本地测试代理:

    ADK

    for event in app.stream_query(
        user_id="USER_ID",
        message="What is the exchange rate from US dollars to SEK today?",
    ):
        print(event)
    

    其中,USER_ID 是用户定义的 ID,字符数上限为 128。

    LangGraph

    agent.query(input={"messages": [
        ("user", "What is the exchange rate from US dollars to SEK today?"),
    ]})
    

    LangChain

    agent.query(
        input="What is the exchange rate from US dollars to SEK today?"
    )
    

    AG2

    agent.query(
        input="What is the exchange rate from US dollars to SEK today?"
    )
    

    LlamaIndex

    agent.query(
        input="What is the exchange rate from US dollars to SEK today?"
    )
    

    部署代理

    如需部署代理,请执行以下操作:

    ADK

    from vertexai import agent_engines
    
    remote_agent = agent_engines.create(
        app,
        requirements=["google-cloud-aiplatform[agent_engines,adk]"],
    )
    

    LangGraph

    from vertexai import agent_engines
    
    remote_agent = agent_engines.create(
        agent,
        requirements=["google-cloud-aiplatform[agent_engines,langchain]"],
    )
    

    LangChain

    from vertexai import agent_engines
    
    remote_agent = agent_engines.create(
        agent,
        requirements=["google-cloud-aiplatform[agent_engines,langchain]"],
    )
    

    AG2

    from vertexai import agent_engines
    
    remote_agent = agent_engines.create(
        agent,
        requirements=["google-cloud-aiplatform[agent_engines,ag2]"],
    )
    

    LlamaIndex

    from vertexai import agent_engines
    
    remote_agent = agent_engines.create(
        agent,
        requirements=["google-cloud-aiplatform[agent_engines,llama_index]"],
    )
    

    这会在 Vertex AI 中创建一个 reasoningEngine 资源。

    使用代理

    通过发送查询来测试已部署的代理:

    ADK

    for event in remote_agent.stream_query(
        user_id="USER_ID",
        message="What is the exchange rate from US dollars to SEK today?",
    ):
        print(event)
    

    LangGraph

    remote_agent.query(input={"messages": [
        ("user", "What is the exchange rate from US dollars to SEK today?"),
    ]})
    

    LangChain

    remote_agent.query(
        input="What is the exchange rate from US dollars to SEK today?"
    )
    

    AG2

    remote_agent.query(
        input="What is the exchange rate from US dollars to SEK today?"
    )
    

    LlamaIndex

    remote_agent.query(
        input="What is the exchange rate from US dollars to SEK today?"
    )
    

    清理

    为避免因本页中使用的资源导致您的 Google Cloud 账号产生费用,请按照以下步骤操作。

    remote_agent.delete(force=True)
    

    后续步骤