跳到内容

可配置的请求头

LangGraph 允许通过运行时配置动态修改智能体的行为和权限。使用 LangGraph Platform 时,您可以在请求体 (config) 或特定的请求头中传递此配置。这使得可以根据用户身份或其他请求数据进行调整(有关如何在图中访问的更多详细信息,请参阅配置操作指南)。

为了隐私,请通过 langgraph.json 文件中的 http.configurable_headers 部分控制哪些请求头传递给运行时配置。

以下是自定义包含和排除的请求头的方法

{
  "http": {
    "configurable_headers": {
      "include": ["x-user-id", "x-organization-id", "my-prefix-*"],
      "exclude": ["authorization", "x-api-key"]
    }
  }
}

includeexclude 列表接受精确的请求头名称或使用 * 匹配任意数量字符的模式。为了您的安全,不支持其他正则表达式模式。

在图中使用

您可以使用任何节点的 config 参数在图中访问包含的请求头。

def my_node(state, config):
  organization_id = config["configurable"].get("x-organization-id")
  ...

或者通过从上下文获取(在工具中或在其他嵌套函数中很有用)。

from langgraph.config import get_config

def search_everything(query: str):
  organization_id = get_config()["configurable"].get("x-organization-id")
  ...

您甚至可以使用此功能动态编译图。

# my_graph.py.
import contextlib

@contextlib.asynccontextmanager
async def generate_agent(config):
  organization_id = config["configurable"].get("x-organization-id")
  if organization_id == "org1":
    graph = ...
    yield graph
  else:
    graph = ...
    yield graph
{
  "graphs": {"agent": "my_grph.py:generate_agent"}
}

有关如何使用运行时配置的更多示例,请查阅配置操作指南

选择退出可配置请求头

如果您想选择退出可配置请求头,只需在 exclude 列表中设置一个通配符模式

{
  "http": {
    "configurable_headers": {
      "exclude": ["*"]
    }
  }
}

这将排除所有请求头被添加到您的运行配置中。

请注意,排除优先于包含。

评论