AgentInsight JS SDK 接口文档
版本: v5.3.0
生成日期: 2026-05-22
评审团队: SDK架构师 / SDK资深使用者 / 资深程序员 / SDK测试员
AgentInsight SDK 提供 JS/TS 和 Python 两种语言的集成接口,帮助开发者快速接入 LLM/Agent 应用可观测能力。
版本: v5.3.0
生成日期: 2026-05-22
评审团队: SDK架构师 / SDK资深使用者 / 资深程序员 / SDK测试员
# {#核心追踪功能}核心追踪功能
npm install @agentinsight/tracing @agentinsight/otel
# {#或使用高级客户端-包含-prompt-score-dataset-管理}或使用高级客户端(包含 Prompt/Score/Dataset 管理)
npm install @agentinsight/client
# {#openai-集成}OpenAI 集成
npm install @agentinsight/openai
# {#langchain-集成}LangChain 集成
npm install @agentinsight/langchainimport { AgentInsightSpanProcessor } from "@agentinsight/otel";
import { startObservation } from "@agentinsight/tracing";
import { NodeSDK } from "@opentelemetry/sdk-node";
// 1. 初始化 OpenTelemetry
const sdk = new NodeSDK({
spanProcessors: [
new AgentInsightSpanProcessor({
publicKey: process.env.AGENTINSIGHT_PUBLIC_KEY!,
secretKey: process.env.AGENTINSIGHT_SECRET_KEY!,
baseUrl: process.env.AGENTINSIGHT_BASE_URL!,
}),
],
});
sdk.start();
// 2. 创建观察
const observation = startObservation("my-task", {
input: { query: "Hello" },
}, { asType: "span" });
// 3. 更新并结束
observation.update({ output: { result: "World" } });
observation.end();
// 4. 关闭时刷新
await sdk.shutdown();import { init, getClient } from "@agentinsight/client";
const client = init({
publicKey: "pk-...",
secretKey: "sk-...",
baseUrl: "https://agent.goldebridge.com",
});
// 后续任何地方获取客户端
const currentClient = getClient();基础包,提供 API 客户端、类型定义、常量、日志器和媒体处理。其他所有包均依赖此包。
AGENTINSIGHT_SDK_VERSIONexport const AGENTINSIGHT_SDK_VERSION: string;当前 SDK 版本号(如 "5.3.0")。
import { AGENTINSIGHT_SDK_VERSION } from "@agentinsight/core";
console.log(`SDK Version: ${AGENTINSIGHT_SDK_VERSION}`);AGENTINSIGHT_TRACER_NAMEexport const AGENTINSIGHT_TRACER_NAME: string;OpenTelemetry Tracer 的 instrumentation scope 名称("langfuse-sdk")。
AgentInsightOtelSpanAttributesexport enum AgentInsightOtelSpanAttributes {
TRACE_NAME = "langfuse.trace.name",
TRACE_USER_ID = "user.id",
TRACE_SESSION_ID = "session.id",
TRACE_TAGS = "langfuse.trace.tags",
TRACE_PUBLIC = "langfuse.trace.public",
TRACE_METADATA = "langfuse.trace.metadata",
TRACE_INPUT = "langfuse.trace.input",
TRACE_OUTPUT = "langfuse.trace.output",
OBSERVATION_TYPE = "langfuse.observation.type",
OBSERVATION_METADATA = "langfuse.observation.metadata",
OBSERVATION_LEVEL = "langfuse.observation.level",
OBSERVATION_STATUS_MESSAGE = "langfuse.observation.status_message",
OBSERVATION_INPUT = "langfuse.observation.input",
OBSERVATION_OUTPUT = "langfuse.observation.output",
OBSERVATION_COMPLETION_START_TIME = "langfuse.observation.completion_start_time",
OBSERVATION_MODEL = "langfuse.observation.model.name",
OBSERVATION_MODEL_PARAMETERS = "langfuse.observation.model.parameters",
OBSERVATION_USAGE_DETAILS = "langfuse.observation.usage_details",
OBSERVATION_COST_DETAILS = "langfuse.observation.cost_details",
OBSERVATION_PROMPT_NAME = "langfuse.observation.prompt.name",
OBSERVATION_PROMPT_VERSION = "langfuse.observation.prompt.version",
ENVIRONMENT = "langfuse.environment",
RELEASE = "langfuse.release",
VERSION = "langfuse.version",
AS_ROOT = "langfuse.internal.as_root",
}OpenTelemetry Span 属性键枚举,用于在 span 上设置 AgentInsight 特定的属性。
Loggerclass Logger {
constructor(params?: { logLevel?: "DEBUG" | "INFO" | "WARN" | "ERROR" });
debug(message: string, ...args: unknown[]): void;
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
error(message: string, ...args: unknown[]): void;
}LoggerSingletonclass LoggerSingleton {
static getInstance(): Logger;
static setLogLevel(level: "DEBUG" | "INFO" | "WARN" | "ERROR"): void;
}import { LoggerSingleton } from "@agentinsight/core";
LoggerSingleton.setLogLevel("DEBUG");
const logger = LoggerSingleton.getInstance();
logger.info("Application started");AgentInsightAPIClientclass AgentInsightAPIClient {
constructor(params: {
publicKey: string;
secretKey: string;
baseUrl: string;
timeout?: number;
});
readonly annotations: AnnotationClient;
readonly datasets: DatasetClient;
readonly observations: ObservationClient;
readonly models: ModelClient;
readonly projects: ProjectClient;
readonly prompts: PromptClient;
readonly scores: ScoreClient;
readonly ingestion: IngestionClient;
readonly opentelemetry: OtelClient;
}底层 API 客户端,提供对 AgentInsight REST API 的直接访问。通常不直接使用,而是通过 AgentInsightClient 访问。
AgentInsightAPIErrorclass AgentInsightAPIError extends Error {
readonly statusCode: number;
readonly statusText: string;
readonly body: string;
readonly url: string;
}AgentInsightAPITimeoutErrorclass AgentInsightAPITimeoutError extends Error {
readonly url: string;
readonly timeout: number;
}AgentInsightErrorclass AgentInsightError extends Error { }SDK 异常层次结构的基类。
AgentInsightAuthenticationErrorclass AgentInsightAuthenticationError extends AgentInsightError { }认证失败时抛出。
AgentInsightConnectionErrorclass AgentInsightConnectionError extends AgentInsightError { }网络连接失败时抛出。
AgentInsightSerializationErrorclass AgentInsightSerializationError extends AgentInsightError { }数据序列化/反序列化失败时抛出。
AgentInsightConfigurationErrorclass AgentInsightConfigurationError extends AgentInsightError { }配置错误时抛出(如缺少必要凭证且 strictMode 启用)。
AgentInsightTimeoutErrorclass AgentInsightTimeoutError extends AgentInsightError { }操作超时时抛出。
import {
AgentInsightError,
AgentInsightConfigurationError,
AgentInsightTimeoutError,
} from "@agentinsight/core";
try {
const client = new AgentInsightClient({
strictMode: true,
});
} catch (e) {
if (e instanceof AgentInsightConfigurationError) {
console.error("配置错误:", e.message);
}
}提供 OpenTelemetry 追踪原语,包括观察类型、span 包装器和上下文管理。依赖
@agentinsight/core。
AgentInsight 支持 10 种观察类型:
| 类型 | 说明 | 典型场景 |
|---|---|---|
span |
通用操作 | 任意函数调用、工作流步骤 |
generation |
LLM 调用 | Chat Completion、文本生成 |
event |
瞬时事件 | 用户登录、状态变更 |
agent |
AI 代理 | ReAct Agent、Plan-and-Execute |
tool |
工具调用 | API 请求、数据库查询 |
chain |
多步管道 | RAG Pipeline、MapReduce |
retriever |
文档检索 | 向量搜索、关键词搜索 |
evaluator |
质量评估 | 相似度评分、正确性检查 |
guardrail |
安全检查 | 内容审核、PII 检测 |
embedding |
文本嵌入 | 向量化、特征提取 |
startObservation()创建一个新的观察 span。返回的观察对象可链式调用 update() 和 end()。
function startObservation(
name: string,
attributes?: AgentInsightSpanAttributes,
options?: { asType?: "span"; parentSpanContext?: SpanContext }
): AgentInsightSpan;
function startObservation(
name: string,
attributes?: AgentInsightGenerationAttributes,
options: { asType: "generation"; parentSpanContext?: SpanContext }
): AgentInsightGeneration;
// ... 其他 8 种类型类似示例 — 基础 Span:
import { startObservation } from "@agentinsight/tracing";
const span = startObservation("process-data", {
input: { data: "raw" },
});
const result = processData("raw");
span.update({ output: { result } });
span.end();示例 — Generation(LLM 调用):
const gen = startObservation("chat-completion", {
input: { messages: [{ role: "user", content: "Hello" }] },
model: "gpt-4-turbo",
modelParameters: { temperature: 0.7, maxTokens: 500 },
}, { asType: "generation" });
const response = await openai.chat.completions.create({ ... });
gen.update({
output: { content: response.choices[0].message.content },
usageDetails: {
promptTokens: response.usage.prompt_tokens,
completionTokens: response.usage.completion_tokens,
totalTokens: response.usage.total_tokens,
},
costDetails: { totalCost: 0.002 },
});
gen.end();示例 — 嵌套观察:
const parent = startObservation("agent-workflow", {
input: { query: "research AI" },
}, { asType: "agent" });
const child = startObservation("web-search", {
input: { query: "AI papers" },
}, { asType: "tool", parentSpanContext: parent.spanContext() });
child.update({ output: { results: ["paper1", "paper2"] } });
child.end();
parent.update({ output: { answer: "AI is..." } });
parent.end();startActiveObservation()创建一个观察 span 并在回调函数执行期间将其设为活跃 span。回调结束后自动结束 span。
function startActiveObservation<F extends (obs: AgentInsightSpan) => unknown>(
name: string,
fn: F,
options?: { asType?: "span"; endOnExit?: boolean }
): ReturnType<F>;
function startActiveObservation<F extends (obs: AgentInsightGeneration) => unknown>(
name: string,
fn: F,
options: { asType: "generation"; endOnExit?: boolean }
): ReturnType<F>;
// ... 其他类型类似示例:
import { startActiveObservation } from "@agentinsight/tracing";
const result = await startActiveObservation(
"process-order",
async (observation) => {
const validation = await validateOrder(orderId);
observation.update({ output: { valid: validation.ok } });
return validation;
},
{ asType: "span" }
);示例 — Generation 类型:
await startActiveObservation(
"generate-summary",
async (observation) => {
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: "Summarize this" }],
});
observation.update({
output: { content: response.choices[0].message.content },
usageDetails: {
promptTokens: response.usage.prompt_tokens,
completionTokens: response.usage.completion_tokens,
totalTokens: response.usage.total_tokens,
},
});
},
{ asType: "generation" }
);observe()高阶函数,将任意函数包装为带追踪能力的版本。自动捕获输入/输出、处理异常、保持类型签名。
function observe<T extends (...args: any[]) => any>(
fn: T,
options?: ObserveOptions
): T;ObserveOptions:
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
name |
string |
函数名 | 观察名称 |
asType |
AgentInsightObservationType |
"span" |
观察类型 |
captureInput |
boolean |
true |
是否捕获函数输入 |
captureOutput |
boolean |
true |
是否捕获函数输出 |
parentSpanContext |
SpanContext |
— | 父 span 上下文 |
endOnExit |
boolean |
true |
函数退出时是否自动结束观察 |
示例 — 基础包装:
import { observe } from "@agentinsight/tracing";
const processOrder = observe(
async (orderId: string, items: CartItem[]) => {
const validation = await validateOrder(orderId, items);
const payment = await processPayment(validation);
return { orderId, status: "confirmed" };
},
{
name: "process-order",
asType: "span",
captureInput: true,
captureOutput: true,
}
);
// 调用方式不变,自动追踪
const result = await processOrder("ord_123", cartItems);示例 — LLM 调用:
const generateSummary = observe(
async (document: string, maxWords: number = 100) => {
const response = await openai.chat.completions.create({
model: "gpt-4-turbo",
messages: [
{ role: "system", content: `Summarize in ${maxWords} words` },
{ role: "user", content: document },
],
});
return response.choices[0].message.content;
},
{
name: "document-summarizer",
asType: "generation",
captureInput: true,
captureOutput: true,
}
);示例 — 类方法装饰:
class UserService {
createUser: (userData: UserData) => Promise<User>;
constructor() {
this.createUser = observe(this.createUser.bind(this), {
name: "create-user",
asType: "span",
captureInput: false,
captureOutput: true,
});
}
async createUser(userData: UserData) {
return await db.users.create(userData);
}
}updateActiveObservation()更新当前活跃的观察 span 的属性。
function updateActiveObservation(
attributes: AgentInsightSpanAttributes,
options?: { asType: "span" }
): void;
function updateActiveObservation(
attributes: AgentInsightGenerationAttributes,
options: { asType: "generation" }
): void;
// ... 其他类型类似import { startActiveObservation, updateActiveObservation } from "@agentinsight/tracing";
await startActiveObservation("llm-call", async () => {
const response = await openai.chat.completions.create({ ... });
updateActiveObservation({
output: { content: response.choices[0].message.content },
usageDetails: {
promptTokens: response.usage.prompt_tokens,
completionTokens: response.usage.completion_tokens,
totalTokens: response.usage.total_tokens,
},
}, { asType: "generation" });
}, {}, { asType: "generation" });setActiveTraceIO()设置当前活跃 trace 的输入/输出。
function setActiveTraceIO(attributes: AgentInsightTraceAttributes): void;import { setActiveTraceIO } from "@agentinsight/tracing";
setActiveTraceIO({
input: { query: "user question" },
output: { response: "assistant answer" },
});setActiveTraceAsPublic()将当前活跃 trace 设为公开访问。
function setActiveTraceAsPublic(): void;import { setActiveTraceAsPublic } from "@agentinsight/tracing";
startActiveObservation("my-operation", () => {
setActiveTraceAsPublic();
});createTraceId()异步生成一个新的 trace ID。可传入 seed 进行确定性生成。
async function createTraceId(seed?: string): Promise<string>;import { createTraceId } from "@agentinsight/tracing";
const traceId = await createTraceId();
const deterministicId = await createTraceId("my-seed-value");getActiveTraceId()获取当前活跃 span 的 trace ID。
function getActiveTraceId(): string | undefined;getActiveSpanId()获取当前活跃 span 的 span ID。
function getActiveSpanId(): string | undefined;import { getActiveTraceId, getActiveSpanId } from "@agentinsight/tracing";
const traceId = getActiveTraceId();
const spanId = getActiveSpanId();所有观察类型共享基类方法,并各自拥有类型特定的属性。
| 方法 | 签名 | 说明 |
|---|---|---|
update() |
update(attributes: *Attributes): this |
更新观察属性 |
end() |
end(): void |
结束观察 |
spanContext() |
spanContext(): SpanContext |
获取 span 上下文 |
id |
string |
Span ID |
traceId |
string |
Trace ID |
otelSpan |
Span |
底层 OTEL Span |
| 类名 | 类型标识 | 特有属性 |
|---|---|---|
AgentInsightSpan |
"span" |
— |
AgentInsightGeneration |
"generation" |
model, modelParameters, usageDetails, costDetails, completionStartTime, prompt |
AgentInsightEvent |
"event" |
— |
AgentInsightAgent |
"agent" |
— |
AgentInsightTool |
"tool" |
— |
AgentInsightChain |
"chain" |
— |
AgentInsightRetriever |
"retriever" |
— |
AgentInsightEvaluator |
"evaluator" |
— |
AgentInsightGuardrail |
"guardrail" |
— |
AgentInsightEmbedding |
"embedding" |
— |
Node.js 专属包,提供
AgentInsightSpanProcessor,将 OpenTelemetry span 导出到 AgentInsight 服务器。依赖@agentinsight/core。
将 OpenTelemetry span 批量导出到 AgentInsight 服务器,支持数据屏蔽、媒体上传和智能过滤。
interface AgentInsightSpanProcessorParams {
publicKey?: string;
secretKey?: string;
baseUrl?: string;
exporter?: SpanExporter;
flushAt?: number;
flushInterval?: number;
mask?: MaskFunction;
shouldExportSpan?: ShouldExportSpan;
environment?: string;
release?: string;
timeout?: number;
additionalHeaders?: Record<string, string>;
exportMode?: "immediate" | "batched";
strictMode?: boolean;
}| 参数 | 类型 | 默认值 | 环境变量 | 说明 |
|---|---|---|---|---|
publicKey |
string |
— | AGENTINSIGHT_PUBLIC_KEY |
AgentInsight 公钥 |
secretKey |
string |
— | AGENTINSIGHT_SECRET_KEY |
AgentInsight 密钥 |
baseUrl |
string |
— | AGENTINSIGHT_BASE_URL |
服务器基础 URL |
exporter |
SpanExporter |
OTLP HTTP | — | 自定义 span 导出器 |
flushAt |
number |
15 |
AGENTINSIGHT_FLUSH_AT |
批量导出阈值 |
flushInterval |
number |
1 |
AGENTINSIGHT_FLUSH_INTERVAL |
刷新间隔(秒) |
mask |
MaskFunction |
— | — | 数据屏蔽函数 |
shouldExportSpan |
ShouldExportSpan |
— | — | Span 过滤函数 |
environment |
string |
— | AGENTINSIGHT_TRACING_ENVIRONMENT |
环境标识 |
release |
string |
— | AGENTINSIGHT_RELEASE |
版本标识 |
timeout |
number |
— | AGENTINSIGHT_TIMEOUT |
请求超时(秒) |
additionalHeaders |
Record<string, string> |
{} |
— | 附加 HTTP 头 |
exportMode |
"immediate" | "batched" |
"batched" |
— | 导出模式 |
strictMode |
boolean |
false |
AGENTINSIGHT_STRICT_MODE |
严格模式 |
| 方法 | 签名 | 说明 |
|---|---|---|
onStart |
onStart(span: Span, parentContext: Context): void |
Span 开始时调用 |
onEnd |
onEnd(span: ReadableSpan): void |
Span 结束时调用 |
forceFlush |
forceFlush(): Promise<void> |
强制刷新所有待处理 span |
shutdown |
shutdown(): Promise<void> |
优雅关闭处理器 |
import { AgentInsightSpanProcessor } from "@agentinsight/otel";
import { NodeSDK } from "@opentelemetry/sdk-node";
const sdk = new NodeSDK({
spanProcessors: [
new AgentInsightSpanProcessor({
publicKey: "pk-lf-...",
secretKey: "sk-lf-...",
baseUrl: "https://agent.goldebridge.com",
}),
],
});
sdk.start();
// 应用关闭时
process.on("SIGTERM", async () => {
await sdk.shutdown();
});new AgentInsightSpanProcessor({
publicKey: "pk-lf-...",
secretKey: "sk-lf-...",
baseUrl: "https://agent.goldebridge.com",
exportMode: "immediate",
});new AgentInsightSpanProcessor({
publicKey: "pk-lf-...",
secretKey: "sk-lf-...",
baseUrl: "https://agent.goldebridge.com",
mask: ({ data }) => {
if (typeof data === "string") {
return data.replace(/\b\d{16}\b/g, "[REDACTED_CARD]");
}
return data;
},
});import { isDefaultExportSpan } from "@agentinsight/otel";
new AgentInsightSpanProcessor({
publicKey: "pk-lf-...",
secretKey: "sk-lf-...",
baseUrl: "https://agent.goldebridge.com",
shouldExportSpan: ({ otelSpan }) => {
return isDefaultExportSpan(otelSpan);
},
});new AgentInsightSpanProcessor({
publicKey: "pk-lf-...",
secretKey: "sk-lf-...",
baseUrl: "https://agent.goldebridge.com",
strictMode: true,
});isAgentInsightSpan()判断 span 是否来自 AgentInsight tracer。
function isAgentInsightSpan(span: ReadableSpan): boolean;isLangfuseSpan()isAgentInsightSpan 的兼容别名,与 Python SDK 对齐。
function isLangfuseSpan(span: ReadableSpan): boolean;isGenAISpan()判断 span 是否包含 gen_ai. 属性(与生成式 AI 相关)。
function isGenAISpan(span: ReadableSpan): boolean;isKnownLLMInstrumentor()判断 span 是否来自已知的 LLM instrumentation scope。
function isKnownLLMInstrumentor(span: ReadableSpan): boolean;isDefaultExportSpan()默认过滤逻辑:导出 AgentInsight span 或 GenAI span 或已知 LLM instrumentor 的 span。
function isDefaultExportSpan(span: ReadableSpan): boolean;import {
isAgentInsightSpan,
isLangfuseSpan,
isGenAISpan,
isKnownLLMInstrumentor,
isDefaultExportSpan,
} from "@agentinsight/otel";MaskFunctiontype MaskFunction = (params: { data: any }) => any | Promise<any>;ShouldExportSpantype ShouldExportSpan = (params: { otelSpan: ReadableSpan }) => boolean;高级客户端,提供 Prompt、Dataset、Score、Media、Experiment 等管理功能。依赖
@agentinsight/core和@agentinsight/tracing。
init()创建并设置全局默认客户端实例。
function init(params: AgentInsightClientParams): AgentInsightClient;import { init } from "@agentinsight/client";
const client = init({
publicKey: "pk-lf-...",
secretKey: "sk-lf-...",
baseUrl: "https://agent.goldebridge.com",
});getClient()获取当前全局默认客户端实例。
function getClient(): AgentInsightClient | null;import { getClient } from "@agentinsight/client";
const client = getClient();
if (client) {
await client.flush();
}interface AgentInsightClientParams {
publicKey?: string;
secretKey?: string;
baseUrl?: string;
timeout?: number;
fetch?: FetchFn;
debug?: boolean;
strictMode?: boolean;
}| 参数 | 类型 | 环境变量 | 说明 |
|---|---|---|---|
publicKey |
string |
AGENTINSIGHT_PUBLIC_KEY |
公钥 |
secretKey |
string |
AGENTINSIGHT_SECRET_KEY |
密钥 |
baseUrl |
string |
AGENTINSIGHT_BASE_URL |
服务器 URL |
timeout |
number |
— | 请求超时(毫秒) |
fetch |
FetchFn |
— | 自定义 fetch 函数 |
debug |
boolean |
— | 调试模式 |
strictMode |
boolean |
AGENTINSIGHT_STRICT_MODE |
严格模式(缺少凭证时抛出错误) |
AgentInsightConfigtype AgentInsightConfig = AgentInsightClientParams;与 Python SDK 对齐的配置类型别名。
| 方法 | 签名 | 说明 |
|---|---|---|
flush |
flush(): Promise<void> |
刷新所有待发送数据 |
shutdown |
shutdown(): Promise<void> |
关闭客户端 |
| 属性 | 类型 | 说明 |
|---|---|---|
prompt |
PromptManager |
Prompt 管理 |
dataset |
DatasetManager |
数据集管理 |
score |
ScoreManager |
评分管理 |
media |
MediaManager |
媒体管理 |
experiment |
ExperimentManager |
实验管理 |
import { AgentInsightClient } from "@agentinsight/client";
const client = new AgentInsightClient({
publicKey: "pk-lf-...",
secretKey: "sk-lf-...",
baseUrl: "https://agent.goldebridge.com",
});const prompt = await client.prompt.get("my-prompt", { version: 2 });
console.log(prompt.prompt); // Prompt 文本
console.log(prompt.config); // Prompt 配置await client.score.create({
traceId: "trace-123",
name: "quality",
value: 0.92,
comment: "High quality response",
dataType: "NUMERIC",
});const dataset = await client.dataset.get("my-dataset");
const items = await client.dataset.listItems("my-dataset");const experiment = await client.experiment.create({
name: "quality-eval",
datasetName: "test-dataset",
});
const run = await client.experiment.run({
experimentId: experiment.id,
task: async (data) => {
return await myModel(data.input);
},
scores: [
async ({ output, expected }) => {
return { name: "accuracy", value: computeAccuracy(output, expected) };
},
],
});const url = await client.getTraceUrl("trace-123");
console.log(url);const client = new AgentInsightClient({
publicKey: "pk-lf-...",
secretKey: "sk-lf-...",
baseUrl: "https://agent.goldebridge.com",
strictMode: true,
});提供 OpenAI SDK 的自动追踪包装。依赖
@agentinsight/core和@agentinsight/tracing。
observeOpenAI()包装 OpenAI SDK 实例,自动追踪所有 API 调用。
function observeOpenAI<SDKType extends object>(
sdk: SDKType,
options?: AgentInsightConfig
): SDKType;AgentInsightConfiginterface AgentInsightConfig {
publicKey?: string;
secretKey?: string;
baseUrl?: string;
flushAt?: number;
flushInterval?: number;
mask?: MaskFunction;
shouldExportSpan?: ShouldExportSpan;
environment?: string;
release?: string;
timeout?: number;
additionalHeaders?: Record<string, string>;
exportMode?: "immediate" | "batched";
}import OpenAI from "openai";
import { observeOpenAI } from "@agentinsight/openai";
const openai = observeOpenAI(
new OpenAI({ apiKey: process.env.OPENAI_API_KEY }),
{
publicKey: "pk-lf-...",
secretKey: "sk-lf-...",
baseUrl: "https://agent.goldebridge.com",
}
);
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: "Hello!" }],
});
// 自动追踪:模型名、token 用量、延迟等const stream = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: "Tell me a story" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}const response = await openai.chat.completions.create({
model: "gpt-4-turbo",
messages: [{ role: "user", content: "What's the weather in SF?" }],
tools: [
{
type: "function",
function: {
name: "get_weather",
parameters: { type: "object", properties: { city: { type: "string" } } },
},
},
],
});提供 LangChain 的 Callback Handler,自动追踪链式调用。依赖
@agentinsight/core和@agentinsight/tracing。
CallbackHandler实现 LangChain 的回调接口,自动将链式调用映射为 AgentInsight 观察类型。
interface CallbackHandlerOptions {
userId?: string;
sessionId?: string;
tags?: string[];
version?: string;
environment?: string;
release?: string;
traceMetadata?: Record<string, unknown>;
}| 参数 | 类型 | 说明 |
|---|---|---|
userId |
string |
用户标识 |
sessionId |
string |
会话标识 |
tags |
string[] |
标签列表 |
version |
string |
版本标识 |
environment |
string |
环境标识 |
release |
string |
发布标识 |
traceMetadata |
Record<string, unknown> |
Trace 级元数据 |
import { CallbackHandler } from "@agentinsight/langchain";
import { ChatOpenAI } from "@langchain/openai";
const agentInsightHandler = new CallbackHandler({
userId: "user-123",
sessionId: "session-456",
tags: ["production", "v2"],
environment: "production",
});
const model = new ChatOpenAI({ modelName: "gpt-4" });
const response = await model.invoke(
[{ role: "user", content: "Hello!" }],
{ callbacks: [agentInsightHandler] }
);import { CallbackHandler } from "@agentinsight/langchain";
import { initializeAgentExecutor } from "langchain/agents";
const handler = new CallbackHandler({
userId: "user-abc",
sessionId: "session-xyz",
environment: "staging",
});
const agent = await initializeAgentExecutor(
{ llm: model, tools: [searchTool, calculatorTool] },
{ callbacks: [handler] }
);
const result = await agent.call({
input: "What is 2 + 2?",
});type AgentInsightObservationType =
| "span"
| "generation"
| "event"
| "agent"
| "tool"
| "chain"
| "retriever"
| "evaluator"
| "guardrail"
| "embedding";type ObservationLevel = "DEFAULT" | "DEBUG" | "WARNING" | "ERROR";AgentInsightSpanAttributes所有观察类型的基础属性:
interface AgentInsightSpanAttributes {
input?: unknown;
output?: unknown;
metadata?: unknown;
level?: ObservationLevel;
statusMessage?: string;
version?: string;
}AgentInsightGenerationAttributes扩展 AgentInsightSpanAttributes:
interface AgentInsightGenerationAttributes extends AgentInsightSpanAttributes {
completionStartTime?: Date;
model?: string;
modelParameters?: Record<string, string | number>;
usageDetails?: Record<string, number>;
costDetails?: Record<string, number>;
prompt?: {
name: string;
version: number;
isFallback: boolean;
};
}AgentInsightTraceAttributesTrace 级属性:
interface AgentInsightTraceAttributes {
input?: unknown;
output?: unknown;
public?: boolean;
}以下类型当前等同于 AgentInsightSpanAttributes,未来版本将添加类型特定属性:
type AgentInsightEventAttributes = AgentInsightSpanAttributes;
type AgentInsightAgentAttributes = AgentInsightSpanAttributes;
type AgentInsightToolAttributes = AgentInsightSpanAttributes;
type AgentInsightChainAttributes = AgentInsightSpanAttributes;
type AgentInsightRetrieverAttributes = AgentInsightSpanAttributes;
type AgentInsightEvaluatorAttributes = AgentInsightSpanAttributes;
type AgentInsightGuardrailAttributes = AgentInsightSpanAttributes;
type AgentInsightEmbeddingAttributes = AgentInsightSpanAttributes;Error
├── AgentInsightAPIError (HTTP API 错误)
│ └── AgentInsightAPITimeoutError (API 超时)
└── AgentInsightError (SDK 基础异常)
├── AgentInsightAuthenticationError (认证失败)
├── AgentInsightConnectionError (网络连接失败)
├── AgentInsightSerializationError (序列化失败)
├── AgentInsightConfigurationError (配置错误)
└── AgentInsightTimeoutError (操作超时)当 strictMode 启用时,SDK 在以下场景会抛出 AgentInsightConfigurationError 而非静默警告:
AgentInsightClient 时缺少 publicKey 或 secretKeyAgentInsightSpanProcessor 时缺少必要凭证import { AgentInsightClient } from "@agentinsight/client";
try {
const client = new AgentInsightClient({ strictMode: true });
} catch (e) {
if (e instanceof AgentInsightConfigurationError) {
console.error("缺少必要配置:", e.message);
}
}| 变量 | 说明 | 适用包 | 默认值 |
|---|---|---|---|
AGENTINSIGHT_PUBLIC_KEY |
公钥 | otel, client | — |
AGENTINSIGHT_SECRET_KEY |
密钥 | otel, client | — |
AGENTINSIGHT_BASE_URL |
服务器 URL | otel, client | — |
AGENTINSIGHT_FLUSH_AT |
批量导出阈值 | otel | 15 |
AGENTINSIGHT_FLUSH_INTERVAL |
刷新间隔(秒) | otel | 1 |
AGENTINSIGHT_TIMEOUT |
请求超时(秒) | otel | — |
AGENTINSIGHT_TRACING_ENVIRONMENT |
环境标识 | otel | — |
AGENTINSIGHT_RELEASE |
版本标识 | otel | — |
AGENTINSIGHT_LOG_LEVEL |
日志级别 | core | INFO |
AGENTINSIGHT_STRICT_MODE |
严格模式 | otel, client | false |
@agentinsight/core (无内部依赖)
├── @agentinsight/tracing (依赖 core)
├── @agentinsight/otel (依赖 core,Node.js 专属)
├── @agentinsight/client (依赖 core + tracing)
├── @agentinsight/openai (依赖 core + tracing)
└── @agentinsight/langchain (依赖 core + tracing)| 使用场景 | 需要安装的包 |
|---|---|
| 仅追踪 | @agentinsight/tracing + @agentinsight/otel |
| 追踪 + 评分/Prompt | @agentinsight/client + @agentinsight/otel |
| OpenAI 集成 | @agentinsight/openai |
| LangChain 集成 | @agentinsight/langchain + @agentinsight/otel |
| 全功能 | @agentinsight/client + @agentinsight/openai + @agentinsight/langchain |
文档结束
本文档由 SDK 专家团队多轮评审产出,覆盖所有 6 个包的公开接口、类型定义、示例代码和最佳实践。
agentinsight.bat 一键打包发布项目根目录提供了 agentinsight.bat 脚本,可自动完成从环境检查到 npm 发布的全流程。
agentinsight-js/
└── agentinsight.bat:: 1. 先配置 NPM Token(仅需一次)
npm config set //registry.npmjs.org/:_authToken "npm_YOUR_TOKEN"
:: 2. 运行打包发布脚本
agentinsight.bat脚本按顺序执行以下 5 个步骤:
| 步骤 | 说明 | 失败处理 |
|---|---|---|
| [1/5] 检查运行环境 | 检查 Node.js(≥20)和 pnpm/npm 是否可用 | 缺少 Node.js 则中止 |
| [2/5] 修复 package.json | 将 workspace:^ 替换为 ^5.3.0(npm 不支持 workspace 协议) |
警告但继续 |
| [3/5] 安装依赖 | 执行 pnpm install(或 npm install) |
中止 |
| [4/5] 构建全部包 | 执行 pnpm build,生成 dist/ 产物(CJS + ESM 双格式) |
中止 |
| [5/5] 发布到 NPM | 按依赖顺序发布 6 个包,发布前需确认 | 用户取消则跳过 |
脚本严格按照包间依赖顺序发布,确保下游包的依赖在 npm 上已可用:
@agentinsight/core → 第 1 个发布(无内部依赖)
@agentinsight/tracing → 第 2 个发布(依赖 core)
@agentinsight/otel → 第 3 个发布(依赖 core)
@agentinsight/client → 第 4 个发布(依赖 core + tracing)
@agentinsight/openai → 第 5 个发布(依赖 core + tracing)
@agentinsight/langchain → 第 6 个发布(依赖 core + tracing)步骤 [5/5] 发布前会提示确认:
请确认已配置 NPM Token:
npm config set //registry.npmjs.org/:_authToken "npm_YOUR_TOKEN"
是否继续发布? (输入 y 继续):输入 y 继续发布,其他输入则跳过发布步骤。
================================================================
AgentInsight JS SDK - 打包 & 发布脚本
================================================================
[1/5] 检查运行环境...
Node.js: v24.0.0
包管理: pnpm
[2/5] 修复 package.json 中的内部依赖...
修复: core
修复: tracing
修复: otel
修复: client
修复: openai
修复: langchain
[3/5] 安装依赖...
依赖安装完成
[4/5] 构建全部包...
构建完成
[5/5] 发布到 NPM...
--- 发布 @agentinsight/core ---
@agentinsight/core 发布成功
--- 发布 @agentinsight/tracing ---
@agentinsight/tracing 发布成功
...
✔ 全部 6 个包发布成功
================================================================
完成
================================================================如需更精细的控制,可手动执行各步骤:
:: 1. 修复 workspace:^ 引用(PowerShell)
powershell -Command "
$dirs = @('core','tracing','otel','client','openai','langchain');
foreach($d in $dirs) {
$p = \"packages\$d\package.json\";
$c = Get-Content $p -Raw;
$c = $c -replace 'workspace:\^', '^5.3.0';
Set-Content $p -Value $c -NoNewline;
}
"
:: 2. 安装依赖
pnpm install
:: 3. 构建
pnpm build
:: 4. 按顺序发布
cd packages\core && pnpm publish --access public --no-git-checks && cd ..\..
cd packages\tracing && pnpm publish --access public --no-git-checks && cd ..\..
cd packages\otel && pnpm publish --access public --no-git-checks && cd ..\..
cd packages\client && pnpm publish --access public --no-git-checks && cd ..\..
cd packages\openai && pnpm publish --access public --no-git-checks && cd ..\..
cd packages\langchain && pnpm publish --access public --no-git-checks && cd ..\..发布到 npm 需要配置认证令牌。推荐使用 Automation 类型的令牌(支持 CI/CD 无交互发布):
:: 方式一:通过 npm config(推荐)
npm config set //registry.npmjs.org/:_authToken "npm_YOUR_TOKEN"
:: 方式二:通过环境变量
set NPM_TOKEN=npm_YOUR_TOKEN⚠️ 注意:Granular Access Token(细粒度访问令牌)的只读模式无法发布,必须使用 Automation 类型或 Read/Write 类型的令牌。
:: 查看已发布的包
npm view @agentinsight/core version
npm view @agentinsight/tracing version
npm view @agentinsight/otel version
npm view @agentinsight/client version
npm view @agentinsight/openai version
npm view @agentinsight/langchain version
:: 在新目录中安装测试
mkdir test-sdk && cd test-sdk
npm init -y
npm install @agentinsight/tracing @agentinsight/otel
node -e "const { AgentInsightSpanProcessor } = require('@agentinsight/otel'); console.log('OK:', typeof AgentInsightSpanProcessor);"每个包构建后在 dist/ 目录下生成以下文件:
packages/<package>/dist/
├── index.cjs # CommonJS 格式
├── index.cjs.map # CommonJS Source Map
├── index.d.cts # CommonJS 类型声明
├── index.mjs # ESM 格式
├── index.mjs.map # ESM Source Map
├── index.d.ts # ESM 类型声明
└── index.d.mts # ESM 类型声明(.mts 扩展名)| 格式 | 扩展名 | 适用环境 |
|---|---|---|
| CommonJS | .cjs |
Node.js require() |
| ESM | .mjs |
Node.js import / 浏览器 |
| 类型声明 | .d.ts / .d.cts / .d.mts |
TypeScript |