追踪 LangChain🦜⛓️

LangChain 是一个用于构建大语言模型(LLM)驱动应用程序的开源框架。
MLflow Tracing 为 LangChain 提供了自动追踪功能。你可以通过调用 mlflow.langchain.autolog() 函数来启用 LangChain 追踪,嵌套的追踪信息会在调用链(chains)时自动记录到活动的 MLflow 实验中。在 TypeScript 中,你可以将 MLflow LangChain 回调函数传递给 callbacks 选项。
- Python
- JS / TS
import mlflow
mlflow.langchain.autolog()
LangChain.js 追踪通过 OpenTelemetry 摄取实现。请参阅下方的入门指南章节以获取完整设置。
入门
MLflow 支持在 Python 和 TypeScript/JavaScript 中追踪 LangChain。请选择下方相应的选项卡开始使用。
- Python
- JS / TS (v1)
- JS / TS (v0)
1. 启动 MLflow
如果你还没有 MLflow 服务器,请按照自托管指南启动 MLflow 服务器。
2. 安装依赖项
pip install langchain langchain-openai mlflow
3. 启用追踪
import mlflow
# Calling autolog for LangChain will enable trace logging.
mlflow.langchain.autolog()
# Optional: Set a tracking URI and an experiment
mlflow.set_experiment("LangChain")
mlflow.set_tracking_uri("https://:5000")
4. 定义链并调用它
import mlflow
import os
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7, max_tokens=1000)
prompt_template = PromptTemplate.from_template(
"Answer the question as if you are {person}, fully embodying their style, wit, personality, and habits of speech. "
"Emulate their quirks and mannerisms to the best of your ability, embracing their traits—even if they aren't entirely "
"constructive or inoffensive. The question is: {question}"
)
chain = prompt_template | llm | StrOutputParser()
# Let's test another call
chain.invoke({
"person": "Linus Torvalds",
"question": "Can I just set everyone's access to sudo to make things easier?",
})
5. 在 MLflow UI 中查看追踪信息
访问 https://:5000(或你自定义的 MLflow 追踪服务器 URL)以在 MLflow UI 中查看追踪信息。
1. 启动 MLflow
如果你还没有 MLflow 服务器,请按照自托管指南启动 MLflow 服务器。
2. 安装所需的依赖项:
npm i langchain @langchain/core @langchain/openai @arizeai/openinference-instrumentation-langchain
3. 启用 OpenTelemetry
在你的应用程序中为 LangChain 启用 OpenTelemetry 插桩
import { NodeTracerProvider, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { LangChainInstrumentation } from "@arizeai/openinference-instrumentation-langchain";
import * as CallbackManagerModule from "@langchain/core/callbacks/manager";
// Set up the OpenTelemetry
const provider = new NodeTracerProvider(
{
spanProcessors: [new SimpleSpanProcessor(new OTLPTraceExporter({
// Set MLflow tracking server URL with `/v1/traces` path. You can also use the OTEL_EXPORTER_OTLP_TRACES_ENDPOINT environment variable instead.
url: "https://:5000/v1/traces",
// Set the experiment ID in the header. You can also use the OTEL_EXPORTER_OTLP_TRACES_HEADERS environment variable instead.
headers: {
"x-mlflow-experiment-id": "123",
},
}))],
}
);
provider.register();
// Enable LangChain instrumentation
const lcInstrumentation = new LangChainInstrumentation();
lcInstrumentation.manuallyInstrument(CallbackManagerModule);
4. 定义 LangChain 代理(Agent)并调用它
请注意,createAgent API 在 LangChain.js v1.0 及更高版本中可用。如果你使用的是 LangChain 0.x,请改用 v0 示例。
import { createAgent, tool } from "langchain";
import * as z from "zod";
const getWeather = tool(
(input) => `It's always sunny in ${input.city}!`,
{
name: "get_weather",
description: "Get the weather for a given city",
schema: z.object({
city: z.string().describe("The city to get the weather for"),
}),
}
);
const agent = createAgent({
model: "gpt-4o-mini",
tools: [getWeather],
});
await agent.invoke({
messages: [{ role: "user", content: "What's the weather in Tokyo?" }],
});
5. 在 MLflow UI 中查看追踪信息
访问 https://:5000(或你自定义的 MLflow 追踪服务器 URL)以在 MLflow UI 中查看追踪信息。
1. 启动 MLflow
如果你还没有 MLflow 服务器,请按照自托管指南启动 MLflow 服务器。
2. 安装依赖项
安装所需的依赖项
npm i langchain @langchain/core @langchain/openai @arizeai/openinference-instrumentation-langchain
3. 启用 OpenTelemetry
在你的应用程序中为 LangChain 启用 OpenTelemetry 插桩
import { NodeTracerProvider, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { LangChainInstrumentation } from "@arizeai/openinference-instrumentation-langchain";
import * as CallbackManagerModule from "@langchain/core/callbacks/manager";
// Set up the OpenTelemetry
const provider = new NodeTracerProvider(
{
spanProcessors: [new SimpleSpanProcessor(new OTLPTraceExporter({
// Set MLflow tracking server URL. You can also use the OTEL_EXPORTER_OTLP_TRACES_ENDPOINT environment variable instead.
url: "https://:5000/v1/traces",
// Set the experiment ID in the header. You can also use the OTEL_EXPORTER_OTLP_TRACES_HEADERS environment variable instead.
headers: {
"x-mlflow-experiment-id": "123",
},
}))],
}
);
provider.register();
// Enable LangChain instrumentation
const lcInstrumentation = new LangChainInstrumentation();
lcInstrumentation.manuallyInstrument(CallbackManagerModule);
4. 定义 LangChain 链并调用它
import { OpenAI } from "@langchain/openai";
import { PromptTemplate } from "@langchain/core/prompts";
const model = new OpenAI("gpt-4o-mini");
const prompt = PromptTemplate.fromTemplate("What is a good name for a company that makes {product}?");
const chain = prompt.pipe({ llm: model });
const res = await chain.invoke({ product: "colorful socks" });
console.log({ res });
5. 在 MLflow UI 中查看追踪信息
访问 https://:5000(或你自定义的 MLflow 追踪服务器 URL)以在 MLflow UI 中查看追踪信息。
上述示例已确认可在以下版本要求中正常工作
pip install openai==1.30.5 langchain==0.2.1 langchain-openai==0.1.8 langchain-community==0.2.1 mlflow==2.14.0 tiktoken==0.7.0
MLflow 会捕获通过 LangChain 模型传递的图像内容部分。详情请参阅追踪中的多模态内容和附件。
支持的 API
LangChain 的自动追踪支持以下 API。
invokebatchstreamainvokeabatchastreamget_relevant_documents(用于检索器)__call__(用于链和 AgentExecutors)
追踪 Token 使用量和成本
MLflow 会自动追踪 LangChain 的 Token 使用量和成本。链调用期间每次 LLM 调用的 Token 使用量都会记录在每个追踪/跨度(Trace/Span)中,聚合的成本和时间趋势会显示在内置仪表板中。有关以编程方式访问此信息的详细信息,请参阅Token 使用量和成本追踪文档。
自定义追踪行为
有时你可能希望自定义记录到追踪中的信息。你可以通过创建一个继承自 MlflowLangchainTracer 的自定义回调处理程序来实现这一点。MlflowLangchainTracer 是一个回调处理程序,它被注入到 LangChain 模型推理过程中,以自动记录追踪信息。它会在一组链动作(如 on_chain_start、on_llm_start)开始时启动一个新的跨度,并在动作完成时结束它。各种元数据,如跨度类型、动作名称、输入、输出、延迟等,都会自动记录到跨度中。
以下示例演示了当聊天模型开始运行时,如何向跨度记录额外的属性。
from mlflow.langchain.langchain_tracer import MlflowLangchainTracer
class CustomLangchainTracer(MlflowLangchainTracer):
# Override the handler functions to customize the behavior. The method signature is defined by LangChain Callbacks.
def on_chat_model_start(
self,
serialized: Dict[str, Any],
messages: List[List[BaseMessage]],
*,
run_id: UUID,
tags: Optional[List[str]] = None,
parent_run_id: Optional[UUID] = None,
metadata: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
**kwargs: Any,
):
"""Run when a chat model starts running."""
attributes = {
**kwargs,
**metadata,
# Add additional attribute to the span
"version": "1.0.0",
}
# Call the _start_span method at the end of the handler function to start a new span.
self._start_span(
span_name=name or self._assign_span_name(serialized, "chat model"),
parent_run_id=parent_run_id,
span_type=SpanType.CHAT_MODEL,
run_id=run_id,
inputs=messages,
attributes=kwargs,
)
结合 MLflow Tracing SDK (JS / TS) 使用
当将 LangChain.js 与基于 OpenTelemetry 的追踪结合使用时,你可以将自动生成的追踪与 MLflow Tracing SDK (@mlflow/core) 结合使用,在同一个追踪中添加自定义跨度、设置标签并更新追踪元数据。
import { init, withSpan } from "@mlflow/core";
import { LangChainInstrumentation } from "@arizeai/openinference-instrumentation-langchain";
import * as CallbackManagerModule from "@langchain/core/callbacks/manager";
// Initialize MLflow SDK - sets up the OTel provider to capture all spans
init({
trackingUri: "https://:5000",
experimentId: "<your-experiment-id>",
});
// Enable LangChain instrumentation
const lcInstrumentation = new LangChainInstrumentation();
lcInstrumentation.manuallyInstrument(CallbackManagerModule);
// Add custom MLflow spans alongside the auto-generated LangChain traces
const result = await withSpan(
{ name: "custom_step", inputs: { query: "test" } },
async (span) => {
// your LangChain application logic here
return { result: "success" };
}
);
有关详细说明和示例,请参阅结合使用 OpenTelemetry SDK 和 MLflow Tracing SDK。
禁用自动追踪
可以通过调用 mlflow.langchain.autolog(disable=True) 或 mlflow.autolog(disable=True) 全局禁用 LangChain 的自动追踪。