@arizeai/openinference-core

中文文档
2.8.1发布于 2026/10/24Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 137.6万

OpenInference Core provides utilities shared by all OpenInference SDK packages.

原始使用文档
文档目录13 节
  1. Installation
  2. Quick Start (Runnable)
  3. Context Attributes
  4. Function Wrappers
  5. withSpan
  6. traceChain , traceAgent , traceTool , and friends
  7. Custom input/output processors
  8. Decorators ( @observe )
  9. Attribute Helper APIs
  10. Trace Config and Redaction ( OITracer )
  11. Utility Helpers
  12. Docs and Source Code in node_modules
  13. Documentation

OpenInference Core

npm version

@arizeai/openinference-core is the shared tracing foundation for OpenInference JS packages. It provides:

  • context attribute propagation (session.id, user.id, metadata, tags, prompt template)
  • span wrappers (withSpan, traceChain, traceAgent, traceTool)
  • method decorator tracing (@observe)
  • helpers for LLM/retrieval/embedding/tool and annotation/evaluation attributes
  • optional sensitive-data masking through OITracer trace config

Installation

npm install @arizeai/openinference-core

# Only needed if you want to run the Quick Start example in this README:
npm install @arizeai/openinference-semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/resources

Quick Start (Runnable)

This example exports spans to stdout and sets an OpenInference project name.

import {
  OpenInferenceSpanKind,
  SEMRESATTRS_PROJECT_NAME,
} from "@arizeai/openinference-semantic-conventions";
import {
  ConsoleSpanExporter,
  NodeTracerProvider,
  SimpleSpanProcessor,
} from "@opentelemetry/sdk-trace-node";
import { resourceFromAttributes } from "@opentelemetry/resources";

import { withSpan } from "@arizeai/openinference-core";

const provider = new NodeTracerProvider({
  resource: resourceFromAttributes({
    [SEMRESATTRS_PROJECT_NAME]: "openinference-core-demo",
  }),
  spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())],
});

provider.register();

const answerQuestion = withSpan(
  async (question: string) => {
    return `Answer: ${question}`;
  },
  {
    name: "answer-question",
    kind: OpenInferenceSpanKind.CHAIN,
  },
);

async function main() {
  const answer = await answerQuestion("What is OpenInference?");
  console.log(answer);
}

void main();

Context Attributes

Each setter returns a new OpenTelemetry context. Compose them to propagate request-level attributes:

  • setSession(context, { sessionId })
  • setUser(context, { userId })
  • setMetadata(context, metadataObject)
  • setTags(context, string[])
  • setPromptTemplate(context, { template, variables?, version? })
  • setAttributes(context, attributes)
import { context } from "@opentelemetry/api";
import {
  setAttributes,
  setMetadata,
  setPromptTemplate,
  setSession,
  setTags,
  setUser,
} from "@arizeai/openinference-core";

let ctx = context.active();
ctx = setSession(ctx, { sessionId: "sess-42" });
ctx = setUser(ctx, { userId: "user-7" });
ctx = setMetadata(ctx, { tenant: "acme", environment: "prod" });
ctx = setTags(ctx, ["support", "priority-high"]);
ctx = setPromptTemplate(ctx, {
  template: "Answer using docs about {topic}",
  variables: { topic: "billing" },
  version: "v3",
});
ctx = setAttributes(ctx, { "app.request_id": "req-123" });

context.with(ctx, async () => {
  // spans started in this context by openinference-core wrappers
  // include these propagated attributes automatically
});

If you create spans manually with a plain OpenTelemetry tracer, apply propagated attributes explicitly:

import { context, trace } from "@opentelemetry/api";
import { getAttributesFromContext } from "@arizeai/openinference-core";

const tracer = trace.getTracer("manual-tracer");
const span = tracer.startSpan("manual-span");
span.setAttributes(getAttributesFromContext(context.active()));
span.end();

Function Wrappers

withSpan

import { OpenInferenceSpanKind } from "@arizeai/openinference-semantic-conventions";
import { withSpan } from "@arizeai/openinference-core";

const retrieve = withSpan(
  async (query: string) => {
    return [`Document for ${query}`];
  },
  {
    name: "retrieve-documents",
    kind: OpenInferenceSpanKind.RETRIEVER,
  },
);

traceChain, traceAgent, traceTool, and friends

These wrappers call withSpan and set kind automatically. One exists for every OpenInference span kind (traceLLM, traceRetriever, traceReranker, traceEmbedding, traceGuardrail, traceEvaluator, tracePrompt, traceDecision).

import { traceAgent, traceChain, traceTool } from "@arizeai/openinference-core";

const tracedChain = traceChain(async (q: string) => `chain result: ${q}`, {
  name: "rag-chain",
});

const tracedTool = traceTool(async (city: string) => ({ temp: 72, city }), {
  name: "weather-tool",
});

const tracedAgent = traceAgent(
  async (q: string) => {
    const toolResult = await tracedTool("seattle");
    return tracedChain(`${q} (${toolResult.temp}F)`);
  },
  { name: "qa-agent" },
);

Custom input/output processors

import { getInputAttributes, getRetrieverAttributes, withSpan } from "@arizeai/openinference-core";

const retriever = withSpan(async (query: string) => [`Doc A for ${query}`, `Doc B for ${query}`], {
  name: "retriever",
  kind: "RETRIEVER",
  processInput: (query) => getInputAttributes(query),
  processOutput: (documents) =>
    getRetrieverAttributes({
      documents: documents.map((content, i) => ({
        id: `doc-${i}`,
        content,
      })),
    }),
});

Decorators (@observe)

observe wraps class methods with tracing and preserves method this context. Use TypeScript 5+ standard decorators when applying @observe.

import { OpenInferenceSpanKind } from "@arizeai/openinference-semantic-conventions";
import { observe } from "@arizeai/openinference-core";

class ChatService {
  @observe({ kind: OpenInferenceSpanKind.CHAIN })
  async runWorkflow(message: string) {
    return `processed: ${message}`;
  }

  @observe({ name: "llm-call", kind: OpenInferenceSpanKind.LLM })
  async callModel(prompt: string) {
    return `model output for: ${prompt}`;
  }
}

Attribute Helper APIs

Use these helpers to generate OpenInference-compatible attributes and attach them to spans:

  • getLLMAttributes({ provider, modelName, inputMessages, outputMessages, tokenCount, tools, ... })
  • getDecisionAttributes({ provider, system, modelName, requestModelName, responseModelName, tokenCount })
  • getEmbeddingAttributes({ modelName, embeddings })
  • getRetrieverAttributes({ documents })
  • getAnnotationAttributes({ annotations, scope? })
  • getEvaluationAttributes({ evaluations, scope? })
  • getToolAttributes({ name, description?, parameters })
  • getMetadataAttributes(metadataObject)
  • getInputAttributes(input) / getOutputAttributes(output)
  • defaultProcessInput(...args) / defaultProcessOutput(result)

Example:

import { trace } from "@opentelemetry/api";
import { getLLMAttributes } from "@arizeai/openinference-core";

const tracer = trace.getTracer("llm-service");

tracer.startActiveSpan("llm-inference", (span) => {
  span.setAttributes(
    getLLMAttributes({
      provider: "openai",
      modelName: "gpt-4o-mini",
      inputMessages: [{ role: "user", content: "What is OpenInference?" }],
      outputMessages: [{ role: "assistant", content: "OpenInference is..." }],
      tokenCount: { prompt: 12, completion: 44, total: 56 },
      invocationParameters: { temperature: 0.2 },
    }),
  );
  span.end();
});

Trace Config and Redaction (OITracer)

OITracer wraps an OpenTelemetry tracer and can redact or drop sensitive attributes before writing spans:

import { trace } from "@opentelemetry/api";
import { OpenInferenceSpanKind } from "@arizeai/openinference-semantic-conventions";
import { OITracer, withSpan } from "@arizeai/openinference-core";

const tracer = new OITracer({
  tracer: trace.getTracer("my-service"),
  traceConfig: {
    hideInputs: true,
    hideOutputText: true,
    hideEmbeddingVectors: true,
    base64ImageMaxLength: 8_000,
  },
});

const traced = withSpan(async (prompt: string) => `model response for ${prompt}`, {
  tracer,
  kind: OpenInferenceSpanKind.LLM,
  name: "safe-llm-call",
});

You can also configure masking with environment variables:

  • OPENINFERENCE_HIDE_LLM_TOOLS
  • OPENINFERENCE_HIDE_INPUTS
  • OPENINFERENCE_HIDE_OUTPUTS
  • OPENINFERENCE_HIDE_INPUT_MESSAGES
  • OPENINFERENCE_HIDE_OUTPUT_MESSAGES
  • OPENINFERENCE_HIDE_INPUT_IMAGES
  • OPENINFERENCE_HIDE_INPUT_TEXT
  • OPENINFERENCE_HIDE_OUTPUT_TEXT
  • OPENINFERENCE_HIDE_EMBEDDING_VECTORS
  • OPENINFERENCE_BASE64_IMAGE_MAX_LENGTH
  • OPENINFERENCE_HIDE_PROMPTS

Utility Helpers

  • withSafety({ fn, onError? }): wraps a function and returns null on error
  • safelyJSONStringify(value) / safelyJSONParse(value): guarded JSON operations

Docs and Source Code in node_modules

Once you've installed the openinference-core package, you already have the full openinference-core documentation and source code available locally inside node_modules. Your coding agent can read these directly -- no internet access required.

node_modules/@arizeai/openinference-core/src/              # Full source code organized by module
node_modules/@arizeai/openinference-core/docs/             # Official documentation with examples

This means your agent can look up accurate API signatures, implementations, and usage examples directly from the installed package -- ensuring it always uses the version of the SDK that's actually installed in your project.

Documentation

版本与发布记录

@arizeai/openinference-core 共发布 42 个版本,首次发布于 2024/08/20;过去 12 个月发布了 25 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.8.1latest2026/10/2414 天前
2.8.02026/10/021 个月前
2.7.32026/10/021 个月前
2.7.22026/10/011 个月前
2.7.12026/09/191 个月前
2.7.02026/09/151 个月前

关于 @arizeai/openinference-core 的常见问题

@arizeai/openinference-core 是什么?

OpenInference Core provides utilities shared by all OpenInference SDK packages.

如何安装 @arizeai/openinference-core?

在项目目录运行 npm install @arizeai/openinference-core,或使用 pnpm add / yarn add / bun add。

@arizeai/openinference-core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@arizeai/openinference-core 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@arizeai/openinference-core 可以商用吗?

@arizeai/openinference-core 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@arizeai/openinference-core 的下载量有多少?

根据 npm 官方下载统计,@arizeai/openinference-core 在 2026/10/07 – 2026/11/05 这 30 天内被下载 1,375,863 次,日均约 45,862 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@arizeai/openinference-core 还在维护吗?

最新版本 2.8.1 发布于 2026/10/24(14 天前);至今共发布 42 个版本,其中过去 12 个月发布了 25 个;首次发布于 2024/08/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。