开发 LangGraph 应用

本页介绍了如何使用特定于框架的 LangGraph 模板(Vertex AI SDK for Python 中的 LanggraphAgent 类)来开发应用。该应用会返回指定日期两种货币之间的汇率。

构建代理时,您有以下几个选项:

  • 创建自定义 Python 类(请参阅自定义应用模板
  • 在 Vertex AI SDK for Python 中开发 LangChain 应用(请参阅开发 LangChain 应用)。
  • 在 Vertex AI SDK for Python 中开发 LangGraph 应用(当前文档)。

以下步骤介绍了如何使用 LanggraphAgent 预构建模板创建此应用:

  1. 定义和配置模型
  2. 定义和使用工具
  3. (可选)存储检查点
  4. (可选)自定义提示模板
  5. (可选)自定义编排

准备工作

请按照设置环境中的步骤设置您的环境。

第 1 步:定义和配置模型

定义要使用的模型版本

model = "gemini-1.5-flash-001"

(可选)配置模型的安全设置。如需详细了解可用于 Gemini 中安全设置的选项,请参阅配置安全属性。 以下示例展示了如何配置安全设置:

from langchain_google_vertexai import HarmBlockThreshold, HarmCategory

safety_settings = {
    HarmCategory.HARM_CATEGORY_UNSPECIFIED: HarmBlockThreshold.BLOCK_NONE,
    HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
    HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_ONLY_HIGH,
    HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
    HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
}

(可选)按以下方式指定模型参数

model_kwargs = {
    # temperature (float): The sampling temperature controls the degree of
    # randomness in token selection.
    "temperature": 0.28,
    # max_output_tokens (int): The token limit determines the maximum amount of
    # text output from one prompt.
    "max_output_tokens": 1000,
    # top_p (float): Tokens are selected from most probable to least until
    # the sum of their probabilities equals the top-p value.
    "top_p": 0.95,
    # top_k (int): The next token is selected from among the top-k most
    # probable tokens. This is not supported by all model versions. See
    # https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/image-understanding#valid_parameter_values
    # for details.
    "top_k": None,
    # safety_settings (Dict[HarmCategory, HarmBlockThreshold]): The safety
    # settings to use for generating content.
    # (you must create your safety settings using the previous step first).
    "safety_settings": safety_settings,
}

使用模型配置创建 LanggraphAgent

agent = reasoning_engines.LanggraphAgent(
    model=model,                # Required.
    model_kwargs=model_kwargs,  # Optional.
)

如果您在交互式环境(例如终端或 Colab 笔记本)中运行,则可以将查询作为中间测试步骤运行:

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

print(response)

响应是类似于以下示例的 Python 字典:

{
  'messages': [{
    'id': ['langchain', 'schema', 'messages', 'HumanMessage'],
    'kwargs': {
      'content': 'What is the exchange rate from US dollars to Swedish currency?',
      'id': '5473dd25-d796-42ad-a690-45bc49a64bec',
      'type': 'human',
    },
    'lc': 1,
    'type': 'constructor',
  }, {
    'id': ['langchain', 'schema', 'messages', 'AIMessage'],
    'kwargs': {
      'content': """
        I do not have access to real-time information, including currency exchange rates.

        To get the most up-to-date exchange rate from US dollars to Swedish currency (SEK),
        I recommend checking a reliable online currency converter like: ...

        These websites will provide you with the current exchange rate and allow you to
        convert specific amounts.""",
      'id': 'run-c42f9940-8ba8-42f1-a625-3aa0780c9e87-0',
      ...
      'usage_metadata': {
        'input_tokens': 12,
        'output_tokens': 145,
        'total_tokens': 157,
      },
    },
    'lc': 1,
    'type': 'constructor',
  }],
}

(可选)高级自定义

LanggraphAgent 模板默认使用 ChatVertexAI,因为它可提供对 Google Cloud中所有基础模型的访问权限。如需使用无法通过 ChatVertexAI 获取的模型,您可以使用以下签名的 Python 函数指定 model_builder= 参数:

from typing import Optional

def model_builder(
    *,
    model_name: str,                      # Required. The name of the model
    model_kwargs: Optional[dict] = None,  # Optional. The model keyword arguments.
    **kwargs,                             # Optional. The remaining keyword arguments to be ignored.
):

如需查看 LangChain 中支持的聊天模型及其功能的列表,请参阅聊天模型model=model_kwargs= 支持的值集特定于每个聊天模型,因此您必须参阅相应文档以了解详情。

ChatVertexAI

默认安装

当您省略 model_builder 参数时,LanggraphAgent 模板中会使用该参数,例如

agent = reasoning_engines.LanggraphAgent(
    model=model,                # Required.
    model_kwargs=model_kwargs,  # Optional.
)

ChatAnthropic

首先,按照其文档设置账号并安装软件包。

接下来,定义用于返回 ChatAnthropicmodel_builder

def model_builder(*, model_name: str, model_kwargs = None, **kwargs):
    from langchain_anthropic import ChatAnthropic
    return ChatAnthropic(model_name=model_name, **model_kwargs)

最后在 LanggraphAgent 模板中使用它,代码如下:

agent = reasoning_engines.LanggraphAgent(
    model="claude-3-opus-20240229",                       # Required.
    model_builder=model_builder,                          # Required.
    model_kwargs={
        "api_key": "ANTHROPIC_API_KEY",  # Required.
        "temperature": 0.28,                              # Optional.
        "max_tokens": 1000,                               # Optional.
    },
)

ChatOpenAI

您可以将 ChatOpenAI 与 Gemini 的 ChatCompletions API 结合使用。

首先,按照其文档安装软件包。

接下来,定义用于返回 ChatOpenAImodel_builder

def model_builder(
    *,
    model_name: str,
    model_kwargs = None,
    project: str,   # Specified via vertexai.init
    location: str,  # Specified via vertexai.init
    **kwargs,
):
    import google.auth
    from langchain_openai import ChatOpenAI

    # Note: the credential lives for 1 hour by default.
    # After expiration, it must be refreshed.
    creds, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
    auth_req = google.auth.transport.requests.Request()
    creds.refresh(auth_req)

    if model_kwargs is None:
        model_kwargs = {}

    endpoint = f"https://{location}-aiplatform.googleapis.com"
    base_url = f'{endpoint}/v1beta1/projects/{project}/locations/{location}/endpoints/openapi'

    return ChatOpenAI(
        model=model_name,
        base_url=base_url,
        api_key=creds.token,
        **model_kwargs,
    )

最后在 LanggraphAgent 模板中使用它,代码如下:

agent = reasoning_engines.LanggraphAgent(
    model="google/gemini-1.5-pro-001",  # Or "meta/llama3-405b-instruct-maas"
    model_builder=model_builder,        # Required.
    model_kwargs={
        "temperature": 0,               # Optional.
        "max_retries": 2,               # Optional.
    },
)

第 2 步:定义和使用工具

定义模型后,下一步是定义模型用于推理的工具。这里的工具可以是 LangChain 工具,也可以是 Python 函数。您还可以将定义的 Python 函数转换为 LangChain 工具

定义函数时,请务必添加能完整而清晰地描述函数的参数、函数的用途以及函数返回内容的注释。模型会使用此信息来确定要使用的函数。您还必须在本地测试函数,以确认其是否正常运行。

使用以下代码定义一个返回汇率的函数:

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.

    Uses the Frankfurter API (https://api.frankfurter.app/) to obtain
    exchange rate data.

    Args:
        currency_from: The base currency (3-letter currency code).
            Defaults to "USD" (US Dollar).
        currency_to: The target currency (3-letter currency code).
            Defaults to "EUR" (Euro).
        currency_date: The date for which to retrieve the exchange rate.
            Defaults to "latest" for the most recent exchange rate data.
            Can be specified in YYYY-MM-DD format for historical rates.

    Returns:
        dict: A dictionary containing the exchange rate information.
            Example: {"amount": 1.0, "base": "USD", "date": "2023-11-24",
                "rates": {"EUR": 0.95534}}
    """
    import requests
    response = requests.get(
        f"https://api.frankfurter.app/{currency_date}",
        params={"from": currency_from, "to": currency_to},
    )
    return response.json()

如需在应用中使用函数之前先对其进行测试,请运行以下命令:

get_exchange_rate(currency_from="USD", currency_to="SEK")

响应应该类似以下内容:

{'amount': 1.0, 'base': 'USD', 'date': '2024-02-22', 'rates': {'SEK': 10.3043}}

如需在 LanggraphAgent 模板内使用该工具,您需要将其添加到 tools= 参数下的工具列表中:

agent = reasoning_engines.LanggraphAgent(
    model=model,                # Required.
    tools=[get_exchange_rate],  # Optional.
    model_kwargs=model_kwargs,  # Optional.
)

您可以通过对应用发起测试查询在本地测试该应用。运行以下命令,使用美元和瑞典克朗在本地测试应用:

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

响应是一个类似于以下内容的字典:

{"input": "What is the exchange rate from US dollars to Swedish currency?",
 "output": "For 1 US dollar you will get 10.7345 Swedish Krona."}

(可选)多种工具

可以通过其他方式定义和实例化 LanggraphAgent 的工具。

接地工具

首先,导入 generate_models 软件包并创建工具

from vertexai.generative_models import grounding, Tool

grounded_search_tool = Tool.from_google_search_retrieval(
    grounding.GoogleSearchRetrieval()
)

接下来,在 LanggraphAgent 模板内使用该工具:

agent = reasoning_engines.LanggraphAgent(
    model=model,
    tools=[grounded_search_tool],
)
agent.query(input={"messages": [
    ("user", "When is the next total solar eclipse in US?"),
]})

响应是一个类似于以下内容的字典:

{"input": "When is the next total solar eclipse in US?",
 "output": """The next total solar eclipse in the U.S. will be on August 23, 2044.
 This eclipse will be visible from three states: Montana, North Dakota, and
 South Dakota. The path of totality will begin in Greenland, travel through
 Canada, and end around sunset in the United States."""}

如需了解详情,请参阅接地

LangChain 工具

首先,安装用于定义该工具的软件包。

pip install langchain-google-community

接下来,导入软件包并创建工具。

from langchain_google_community import VertexAISearchRetriever
from langchain.tools.retriever import create_retriever_tool

retriever = VertexAISearchRetriever(
    project_id="PROJECT_ID",
    data_store_id="DATA_STORE_ID",
    location_id="DATA_STORE_LOCATION_ID",
    engine_data_type=1,
    max_documents=10,
)
movie_search_tool = create_retriever_tool(
    retriever=retriever,
    name="search_movies",
    description="Searches information about movies.",
)

最后,在 LanggraphAgent 模板内使用该工具:

agent = reasoning_engines.LanggraphAgent(
    model=model,
    tools=[movie_search_tool],
)
response = agent.query(input={"messages": [
    ("user", "List some sci-fi movies from the 1990s"),
]})

print(response)

它应该会返回如下所示的响应:

{"input": "List some sci-fi movies from the 1990s",
 "output": """Here are some sci-fi movies from the 1990s:
    * The Matrix (1999): A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.
    * Star Wars: Episode I - The Phantom Menace (1999): Two Jedi Knights escape a hostile blockade to find a queen and her protector, and come across a young boy [...]
    * Men in Black (1997): A police officer joins a secret organization that monitors extraterrestrial interactions on Earth.
    [...]
 """}

如需查看完整示例,请访问笔记本

如需查看 LangChain 中可用的更多工具示例,请访问 Google 工具

Vertex AI 扩展程序

首先,导入扩展程序软件包并创建工具

from typing import Optional

def generate_and_execute_code(
    query: str,
    files: Optional[list[str]] = None,
    file_gcs_uris: Optional[list[str]] = None,
) -> str:
    """Get the results of a natural language query by generating and executing
    a code snippet.

    Example queries: "Find the max in [1, 2, 5]" or "Plot average sales by
    year (from data.csv)". Only one of `file_gcs_uris` and `files` field
    should be provided.

    Args:
        query:
            The natural language query to generate and execute.
        file_gcs_uris:
            Optional. URIs of input files to use when executing the code
            snippet. For example, ["gs://input-bucket/data.csv"].
        files:
            Optional. Input files to use when executing the generated code.
            If specified, the file contents are expected be base64-encoded.
            For example: [{"name": "data.csv", "contents": "aXRlbTEsaXRlbTI="}].
    Returns:
        The results of the query.
    """
    operation_params = {"query": query}
    if files:
        operation_params["files"] = files
    if file_gcs_uris:
        operation_params["file_gcs_uris"] = file_gcs_uris

    from vertexai.preview import extensions

    # If you have an existing extension instance, you can get it here
    # i.e. code_interpreter = extensions.Extension(resource_name).
    code_interpreter = extensions.Extension.from_hub("code_interpreter")
    return extensions.Extension.from_hub("code_interpreter").execute(
        operation_id="generate_and_execute",
        operation_params=operation_params,
    )

接下来,在 LanggraphAgent 模板内使用该工具:

agent = reasoning_engines.LanggraphAgent(
    model=model,
    tools=[generate_and_execute_code],
)
response = agent.query(input={"messages": [("user", """
    Using the data below, construct a bar chart that includes only the height values with different colors for the bars:

    tree_heights_prices = {
      \"Pine\": {\"height\": 100, \"price\": 100},
      \"Oak\": {\"height\": 65, \"price\": 135},
      \"Birch\": {\"height\": 45, \"price\": 80},
      \"Redwood\": {\"height\": 200, \"price\": 200},
      \"Fir\": {\"height\": 180, \"price\": 162},
    }
""")]})

print(response)

它应该会返回如下所示的响应:

{"input": """Using the data below, construct a bar chart that includes only the height values with different colors for the bars:

 tree_heights_prices = {
    \"Pine\": {\"height\": 100, \"price\": 100},
    \"Oak\": {\"height\": 65, \"price\": 135},
    \"Birch\": {\"height\": 45, \"price\": 80},
    \"Redwood\": {\"height\": 200, \"price\": 200},
    \"Fir\": {\"height\": 180, \"price\": 162},
 }
 """,
 "output": """Here's the generated bar chart:
 ```python
 import matplotlib.pyplot as plt

 tree_heights_prices = {
    "Pine": {"height": 100, "price": 100},
    "Oak": {"height": 65, "price": 135},
    "Birch": {"height": 45, "price": 80},
    "Redwood": {"height": 200, "price": 200},
    "Fir": {"height": 180, "price": 162},
 }

 heights = [tree["height"] for tree in tree_heights_prices.values()]
 names = list(tree_heights_prices.keys())

 plt.bar(names, heights, color=['red', 'green', 'blue', 'purple', 'orange'])
 plt.xlabel('Tree Species')
 plt.ylabel('Height')
 plt.title('Tree Heights')
 plt.show()
 ```
 """}

如需了解详情,请访问 Vertex AI 扩展程序

您可以在 LanggraphAgent 中使用您创建的所有工具(或部分工具):

agent = reasoning_engines.LanggraphAgent(
    model=model,
    tools=[
        get_exchange_rate,         # Optional (Python function)
        grounded_search_tool,      # Optional (Grounding Tool)
        movie_search_tool,         # Optional (Langchain Tool)
        generate_and_execute_code, # Optional (Vertex Extension)
    ],
)

response = agent.query(input={"messages": [
    ("user", "List some sci-fi movies from the 1990s"),
]})

print(response)

(可选)工具配置

借助 Gemini,您可以对工具使用情况施加限制。例如,您可以强制模型仅生成函数调用(“强制函数调用”),而不是允许模型生成自然语言回答。

from vertexai.preview.generative_models import ToolConfig

agent = reasoning_engines.LanggraphAgent(
    model="gemini-1.5-pro",
    tools=[search_arxiv, get_exchange_rate],
    model_tool_kwargs={
        "tool_config": {  # Specify the tool configuration here.
            "function_calling_config": {
                "mode": ToolConfig.FunctionCallingConfig.Mode.ANY,
                "allowed_function_names": ["search_arxiv", "get_exchange_rate"],
            },
        },
    },
)

response = agent.query(input={"messages": [
    ("user", "Explain the Schrodinger equation in a few sentences"),
]})

print(response)

如需了解详情,请参阅工具配置

第 3 步:存储检查点

如需跟踪聊天消息并将其附加到数据库,请定义 checkpointer_builder 函数并在创建应用时传入该函数。

设置数据库

首先,安装并使用相关软件包来设置您选择的数据库(例如 Firestore 或 Spanner):

接下来,定义 checkpointer_builder 函数,如下所示:

Spanner

checkpointer_kwargs = {
    "instance_id": "INSTANCE_ID",
    "database_id": "DATABASE_ID",
    "project_id": "PROJECT_ID",
}

def checkpointer_builder(**kwargs):
    from langchain_google_spanner import SpannerCheckpointSaver

    checkpointer = SpannerCheckpointSaver(**kwargs)
    checkpointer.setup()

    return checkpointer

最后,创建应用并将其作为 checkpointer_builder 传入:

agent = reasoning_engines.LanggraphAgent(
    model=model,
    checkpointer_kwargs=checkpointer_kwargs,    # <- new
    checkpointer_builder=checkpointer_builder,  # <- new
)

查询应用时,请务必指定 thread_id,以便应用记住过去的问题和答案:

response = agent.query(
    input={"messages": [
        ("user", "What is the exchange rate from US dollars to Swedish currency?")
    ]},
    config={"configurable": {"thread_id": "THREAD_ID"}},
)

print(response)

您可以检查后续查询是否会保留会话记忆内容:

response = agent.query(
    input={"messages": [("user", "How much is 100 USD?")]},
    config={"configurable": {"thread_id": "THREAD_ID"}},
)

print(response)

第 4 步:自定义提示模板

提示模板有助于将用户输入转换为模型的说明,并用于指导模型的响应,帮助其理解上下文并生成相关且连贯的语言输出。如需了解详情,请访问 ChatPromptTemplates

默认提示模板按顺序分为多个部分。

部分 说明
(可选)系统说明 有关将应用于所有查询的代理的说明。
(可选)聊天记录 与过去会话的聊天记录对应的消息。
用户输入 需要代理响应的用户查询。
代理 Scratchpad 代理在使用工具和执行推理来为用户编制回答时创建的消息(例如通过调用函数)。

如果您创建应用时未指定自己的提示模板,系统会生成默认提示模板,其完整内容如下所示:

from langchain_core.prompts import ChatPromptTemplate
from langchain.agents.format_scratchpad.tools import format_to_tool_messages

prompt_template = {
    "user_input": lambda x: x["input"],
    "history": lambda x: x["history"],
    "agent_scratchpad": lambda x: format_to_tool_messages(x["intermediate_steps"]),
} | ChatPromptTemplate.from_messages([
    ("system", "{system_instruction}"),
    ("placeholder", "{history}"),
    ("user", "{user_input}"),
    ("placeholder", "{agent_scratchpad}"),
])

在以下示例中,您在实例化应用时会隐式使用完整的提示模板:

system_instruction = "I help look up the rate between currencies"

agent = reasoning_engines.LanggraphAgent(
    model=model,
    system_instruction=system_instruction,
    checkpointer_kwargs=checkpointer_kwargs,
    checkpointer_builder=checkpointer_builder,
    tools=[get_exchange_rate],
)

您可以使用自己的提示模板替换默认提示模板,并在构建应用时使用该模板,例如:


custom_prompt_template = {
    "user_input": lambda x: x["input"],
    "history": lambda x: x["history"],
    "agent_scratchpad": lambda x: format_to_tool_messages(x["intermediate_steps"]),
} | ChatPromptTemplate.from_messages([
    ("placeholder", "{history}"),
    ("user", "{user_input}"),
    ("placeholder", "{agent_scratchpad}"),
])

agent = reasoning_engines.LanggraphAgent(
    model=model,
    prompt=custom_prompt_template,
    checkpointer_kwargs=checkpointer_kwargs,
    checkpointer_builder=checkpointer_builder,
    tools=[get_exchange_rate],
)

response = agent.query(
    input={"messages": [
        ("user", "What is the exchange rate from US dollars to Swedish currency?"),
    ]}
    config={"configurable": {"thread_id": "THREAD_ID"}},
)

print(response)

第 5 步:自定义编排

所有 LangChain 组件都实现了可运行对象接口,该接口为编排提供了输入和输出架构。LanggraphAgent 需要构建一个可响应查询的可运行对象。默认情况下,LanggraphAgent 将使用 langgraph 中的预构建 React 应用实现来构建此类可运行项。

如果您打算执行以下操作,则可能需要自定义编排:(i) 实现执行一组确定性步骤(而不是执行开放式推理)的应用,或者 (ii) 以 ReAct 类似方式提示应用为每个步骤添加注解,说明执行该步骤的原因。为此,您必须在创建 LanggraphAgent 时替换默认可运行对象,方法是使用具有以下签名的 Python 函数指定 runnable_builder= 参数:

from typing import Optional
from langchain_core.language_models import BaseLanguageModel

def runnable_builder(
    model: BaseLanguageModel,
    *,
    system_instruction: Optional[str] = None,
    prompt: Optional["RunnableSerializable"] = None,
    tools: Optional[Sequence["_ToolLike"]] = None,
    checkpointer: Optional[Any] = None,
    runnable_kwargs: Optional[Mapping[str, Any]] = None,
    **kwargs,
):

其中

  • model 对应于从 model_builder 返回的聊天模型(请参阅定义和配置模型);
  • tools 对应于要使用的工具和配置(请参阅定义和使用工具),
  • checkpointer 对应于用于存储检查点(请参阅存储检查点)的数据库,
  • system_instructionprompt 对应于提示配置(请参阅自定义提示模板);
  • runnable_kwargs 是您可以用于自定义要构建的可运行项的关键字参数。

这样,您就可以通过不同的选项自定义编排逻辑。

ChatModel

在最简单的情况下,如需创建不进行编排的应用,您可以为 LanggraphAgent 替换 runnable_builder,以直接返回 model

from langchain_core.language_models import BaseLanguageModel

def llm_builder(model: BaseLanguageModel, **kwargs):
    return model

agent = reasoning_engines.LanggraphAgent(
    model=model,
    runnable_builder=llm_builder,
)

ReAct

如需根据您自己的 prompt 使用您自己的 ReAct 应用替换默认工具调用行为(请参阅自定义提示模板),您需要替换 LanggraphAgentrunnable_builder

from typing import Sequence
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts import BasePromptTemplate
from langchain_core.tools import BaseTool
from langchain import hub

def react_builder(
    model: BaseLanguageModel,
    *,
    tools: Sequence[BaseTool],
    prompt: BasePromptTemplate,
    agent_executor_kwargs = None,
    **kwargs,
):
    from langchain.agents.react.agent import create_react_agent
    from langchain.agents import AgentExecutor

    agent = create_react_agent(model, tools, prompt)
    return AgentExecutor(agent=agent, tools=tools, **agent_executor_kwargs)

agent = reasoning_engines.LanggraphAgent(
    model=model,
    tools=[get_exchange_rate],
    prompt=hub.pull("hwchase17/react"),
    agent_executor_kwargs={"verbose": True}, # Optional. For illustration.
    runnable_builder=react_builder,
)

LCEL 语法

如需使用 LangChain 表达式语言 (LCEL) 构建以下图表,

   Input
   /   \
 Pros  Cons
   \   /
  Summary

您需要替换 LanggraphAgentrunnable_builder

def lcel_builder(*, model, **kwargs):
    from operator import itemgetter
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.runnables import RunnablePassthrough
    from langchain_core.output_parsers import StrOutputParser

    output_parser = StrOutputParser()

    planner = ChatPromptTemplate.from_template(
        "Generate an argument about: {input}"
    ) | model | output_parser | {"argument": RunnablePassthrough()}

    pros = ChatPromptTemplate.from_template(
        "List the positive aspects of {argument}"
    ) | model | output_parser

    cons = ChatPromptTemplate.from_template(
        "List the negative aspects of {argument}"
    ) | model | output_parser

    final_responder = ChatPromptTemplate.from_template(
        "Argument:{argument}\nPros:\n{pros}\n\nCons:\n{cons}\n"
        "Generate a final response given the critique",
    ) | model | output_parser

    return planner | {
        "pros": pros,
        "cons": cons,
        "argument": itemgetter("argument"),
    } | final_responder

agent = reasoning_engines.LanggraphAgent(
    model=model,
    runnable_builder=lcel_builder,
)

LangGraph

如需使用 LangGraph 构建以下图表,

   Input
   /   \
 Pros  Cons
   \   /
  Summary

您需要替换 LanggraphAgentrunnable_builder

def langgraph_builder(*, model, **kwargs):
    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.output_parsers import StrOutputParser
    from langgraph.graph import END, MessageGraph

    output_parser = StrOutputParser()

    planner = ChatPromptTemplate.from_template(
        "Generate an argument about: {input}"
    ) | model | output_parser

    pros = ChatPromptTemplate.from_template(
        "List the positive aspects of {input}"
    ) | model | output_parser

    cons = ChatPromptTemplate.from_template(
        "List the negative aspects of {input}"
    ) | model | output_parser

    summary = ChatPromptTemplate.from_template(
        "Input:{input}\nGenerate a final response given the critique",
    ) | model | output_parser

    builder = MessageGraph()
    builder.add_node("planner", planner)
    builder.add_node("pros", pros)
    builder.add_node("cons", cons)
    builder.add_node("summary", summary)

    builder.add_edge("planner", "pros")
    builder.add_edge("planner", "cons")
    builder.add_edge("pros", "summary")
    builder.add_edge("cons", "summary")
    builder.add_edge("summary", END)
    builder.set_entry_point("planner")
    return builder.compile()

agent = reasoning_engines.LanggraphAgent(
    model=model,
    runnable_builder=langgraph_builder,
)

# Example query
response = agent.query(input={"role": "user", "content": "scrum methodology"})

print(response)

后续步骤