主题
使用 HTTP 请求头进行运行时配置
LangGraph 允许通过运行时配置动态修改智能体的行为与权限。使用 LangSmith Deployment 时,你可以在请求体(config)或特定的请求头中传递该配置。这使得你可以基于用户身份或其他请求进行调整。
出于隐私考虑,可以通过 langgraph.json 文件中的 http.configurable_headers 部分,控制哪些请求头会被传递到运行时配置。
以下是自定义包含与排除请求头的方式:
json
{
"http": {
"configurable_headers": {
"includes": ["x-user-id", "x-organization-id", "my-prefix-*"],
"excludes": ["authorization", "x-api-key"]
}
}
}includes 和 excludes 列表接受精确的请求头名称,或使用 * 匹配任意数量字符的模式。出于安全考虑,不支持其他正则表达式模式。
在图中使用
你可以在图中通过任意节点的 config 参数访问被包含的请求头。
python
def my_node(state, config):
organization_id = config["configurable"].get("x-organization-id")
...或者从 context 中获取(在工具中或其他嵌套函数中很有用)。
python
from langgraph.config import get_config
def search_everything(query: str):
organization_id = get_config()["configurable"].get("x-organization-id")
...你甚至可以用它来动态编译图。
python
# 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 graphjson
{
"graphs": {"agent": "my_grph.py:generate_agent"}
}不使用可配置请求头
如果你不想使用可配置请求头,只需在 s 列表中设置一个通配符模式即可:
json
{
"http": {
"configurable_headers": {
"excludes": ["*"]
}
}
}这将排除所有请求头,使其不会被添加到你的运行配置中。
请注意,排除优先于包含。