使用 LangChain 代理

除了使用智能体的一般说明之外,本页还介绍了特定于 LangchainAgent 的功能。

准备工作

本教程假定您已阅读并遵循以下说明:

支持的操作

LangchainAgent 支持以下操作:

  • query:用于同步获取对查询的响应。
  • stream_query:用于对查询的响应进行流式传输。

querystream_query 方法都支持相同类型的实参:

  • input:要发送给智能体的消息。
  • config:查询上下文的配置(如果适用)。

查询智能体

命令:

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

它相当于以下内容(完整形式):

agent.query(input={
    "input": [ # The input is represented as a list of messages (each message as a dict)
        {
            # The role (e.g. "system", "user", "assistant", "tool")
            "role": "user",
            # The type (e.g. "text", "tool_use", "image_url", "media")
            "type": "text",
            # The rest of the message (this varies based on the type)
            "text": "What is the exchange rate from US dollars to Swedish currency?",
        },
    ]
})

角色用于帮助模型在回答时区分不同类型的消息。如果输入中省略了 role,则默认为 "user"

角色 说明
system 用于告知聊天模型如何表现并提供其他背景信息。并非所有聊天模型提供商都支持此功能。
user 表示用户与模型互动时的输入,通常以文本或其他互动输入的形式呈现。
assistant 表示来自模型的回答,可以包含文本或调用工具的请求。
tool 一种消息,用于在检索到外部数据或完成处理后,将工具调用的结果传递回模型。

消息的 type 还会决定如何解读消息的其余部分(请参阅处理多模态内容)。

使用多模态内容查询智能体

我们将使用以下代理(将输入转发给模型,不使用任何工具)来说明如何将多模态输入传递给代理:

agent = agent_engines.LangchainAgent(
    model="gemini-2.0-flash",
    runnable_builder=lambda model, **kwargs: model,
)

多模态消息通过指定 type 和相应数据的内容块来表示。一般来说,对于多模态内容,您需要将 type 指定为 "media",将 file_uri 指向 Cloud Storage URI,并指定用于解读文件的 mime_type

图片

agent.query(input={"input": [
    {"type": "text", "text": "Describe the attached media in 5 words!"},
    {"type": "media", "mime_type": "image/jpeg", "file_uri": "gs://cloud-samples-data/generative-ai/image/cricket.jpeg"},
]})

视频

agent.query(input={"input": [
    {"type": "text", "text": "Describe the attached media in 5 words!"},
    {"type": "media", "mime_type": "video/mp4", "file_uri": "gs://cloud-samples-data/generative-ai/video/pixel8.mp4"},
]})

音频

agent.query(input={"input": [
    {"type": "text", "text": "Describe the attached media in 5 words!"},
    {"type": "media", "mime_type": "audio/mp3", "file_uri": "gs://cloud-samples-data/generative-ai/audio/pixel.mp3"},
]})

如需查看 Gemini 支持的 MIME 类型列表,请参阅以下文档:

使用可运行的配置查询代理

查询代理时,您还可以为代理指定 config(遵循 RunnableConfig 的架构)。以下是两种常见场景:

  • 默认配置参数:
  • 自定义配置参数(通过 configurable):

例如:

import uuid

run_id = uuid.uuid4()  # Generate an ID for tracking the run later.

response = agent.query(
    input="What is the exchange rate from US dollars to Swedish currency?",
    config={  # Specify the RunnableConfig here.
        "run_id": run_id                               # Optional.
        "tags": ["config-tag"],                        # Optional.
        "metadata": {"config-key": "config-value"},    # Optional.
        "configurable": {"session_id": "SESSION_ID"}   # Optional.
    },
)

print(response)

后续步骤