You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态切换LangSmith项目:LangGraph多API日志分流方案问询

问题

我在两个API场景中复用同一个包含大量节点和边的LangGraph图:

  • 作为独立图通过/my-api1对外暴露
  • 作为子图通过/my-api2对外暴露

需求是调用/my-api1时日志记录到LangSmith的project1,调用/my-api2时记录到project2。但因为同一方法/节点被两个场景复用,没法用@traceable装饰器。

目前通过os.environ["LANGCHAIN_PROJECT"] = appConfig.langchain_project能满足场景1的需求,但尝试用RunTree时,不知道如何传入graph和config参数并获取执行结果,相关代码如下:

os.environ["LANGCHAIN_PROJECT"] = appConfig.langchain_project
config = {
"run_id": request.thread_id,
"recursion_limit": 150,
"configurable": {
    "thread_id": str(uuid.uuid4()),
    "checkpoint_ns": ""
   },
}

graph = graph_builder.get_graph()

rt = RunTree(
    run_type="chain",
    name="My Graph",
    inputs=state,
    project_name="project2"
    )

# how to pass graph and config values and get the result?

rt.end(outputs=???)
rt.postRun()

请问有没有其他方式调用图并指定对应的LangSmith项目?

解决方案

方法1:上下文管理器临时切换环境变量

利用上下文管理器临时修改LANGCHAIN_PROJECT环境变量,调用完成后自动恢复原值,避免影响其他请求(注意线程/异步环境下的隔离性):

from contextlib import contextmanager
import os

@contextmanager
def set_langsmith_project(project_name):
    original_project = os.environ.get("LANGCHAIN_PROJECT")
    os.environ["LANGCHAIN_PROJECT"] = project_name
    try:
        yield
    finally:
        if original_project:
            os.environ["LANGCHAIN_PROJECT"] = original_project
        else:
            del os.environ["LANGCHAIN_PROJECT"]

# 在/my-api2中调用图时
with set_langsmith_project("project2"):
    result = graph.invoke(state, config=config)

方法2:RunTree关联LangGraph调用

将RunTree的回调传入LangGraph的配置中,让图的所有子运行关联到指定的RunTree,从而继承project_name:

from langsmith.run_trees import RunTree

# 初始化RunTree
rt = RunTree(
    run_type="chain",
    name="My Graph",
    inputs=state,
    project_name="project2"
)

# 把RunTree回调加入到原config中
config_with_rt = {
    **config,
    "callbacks": [rt.get_callback()]
}

# 执行图并获取结果
result = graph.invoke(state, config=config_with_rt)

# 结束并上报RunTree
rt.end(outputs=result)
rt.post_run()

方法3:LangSmith配置上下文管理器

用LangChain官方提供的configure_langsmith上下文,更优雅地设置项目名称,无需直接操作环境变量:

from langchain_core.tracers.context import configure_langsmith

# 在/my-api2中调用时
with configure_langsmith(project_name="project2"):
    result = graph.invoke(state, config=config)

内容的提问来源于stack exchange,提问作者Mohamed ATia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:55:06