# @grafana/agento11y 中文文档

规范地址：https://npmcn.com/package/%40grafana/agento11y/

版本：0\.16\.0
npm 元数据更新时间：2026-10-29T15:44:59.345Z
中文译文更新时间：2026-11-16T21:40:38.227Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40grafana/agento11y
原文对照：https://npmcn.com/package/%40grafana/agento11y/?lang=original
项目主页：https://github.com/grafana/agento11y#readme
源码仓库：https://github.com/grafana/agento11y

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.8 MB，206 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：18 个
- peer 依赖：@strands-agents/sdk ^1\.5\.0
- 首次发布：2026-07-21T15:30:28.504Z
- 最新版本发布：2026-10-29T15:44:56.552Z
- 近 30 天下载量：63470（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：9（近 12 个月 9 个）

## 中文简介

`@grafana/agento11y` 使用您的 OpenTeleometry tracker/ meters 设置实现 LLM 生成和工具执行远程测量的规范化.

## 安装

```sh
npm install @grafana/agento11y
```

也可以使用：`pnpm add @grafana/agento11y`、`yarn add @grafana/agento11y`、`bun add @grafana/agento11y`

## README

# Grafana 代理可观察性类型Script/JavaScript SDK

`@grafana/agento11y` 使用您的 OpenTeleometry tracker/ meters 设置实现 LLM 生成和工具执行远程测量的规范化.

## 安装

```bash
pnpm add @grafana/agento11y
```

对于只需要核心的低依赖性运行时间 `Agento11yClient` 生成导出 API,使用瘦芯包 :

```bash
pnpm add @grafana/agento11y-core
```

对于Grafana Cloud 设置的走过(在哪里找到端点 URL, 例如 ID, 和 API 令牌), 指的是 [Grafana 云设置指南](https://grafana.com/docs/grafana-cloud/machine-learning/agent-observability/get-started/grafana-cloud/)。 。 。 .

## 验证

从 repo 根运行 JavaScript SDK 共享核心兼容套件 :

```bash
mise run test:ts:sdk-conformance
```

从 repo 根运行跨语言集合核心相容套件 :

```bash
mise run sdk:conformance
```

## 快速启动

下面的片段明确配置了SDK. 作为替代方案,设置 `AGENTO11Y_*` 环境变量和呼叫 `new Agento11yClient()` 没有任何论据——参见: [Grafana 云设置指南](https://grafana.com/docs/grafana-cloud/machine-learning/agent-observability/get-started/grafana-cloud/) 用于变量名称.

```ts
import { Agento11yClient } from "@grafana/agento11y";

const client = new Agento11yClient({
  generationExport: {
    protocol: "http",
    endpoint: "https://agento11y-prod-<region>.grafana.net",
    auth: {
      mode: "basic",
      tenantId: process.env.AGENTO11Y_AUTH_TENANT_ID,
      basicPassword: process.env.AGENTO11Y_AUTH_TOKEN,
    },
  },
  api: {
    endpoint: "https://agento11y-prod-<region>.grafana.net",
  },
});

await client.startGeneration(
  {
    conversationId: "conv-1",
    model: { provider: "openai", name: "gpt-5" },
  },
  async (recorder) => {
    const outputText = "Hello from model";
    recorder.setResult({
      output: [{ role: "assistant", content: outputText }],
    });
  }
);

await client.shutdown();
```

## 内容抓取

`contentCapture` 控制SDK在输出的生成有效载荷和OTel的属性中包含的内容。 见 [内容抓取模式](https://npmcn.com/package/%40grafana/docs/concepts/content-capture-modes.md) 用于 Cononical 模式矩阵和默认; 下面的片段显示如何在 TypeScript 中将其接线.

客户端级别默认 :

```ts
import { Agento11yClient } from "@grafana/agento11y";

const client = new Agento11yClient({
  contentCapture: "metadata_only",
});
```

SDK 核心客户端处理 `"default"` 作为 `"no_tool_content"`:生成内容被捕获,但工具执行参数和结果不超出范围.

每代覆盖 :

```ts
await client.startGeneration(
  {
    model: { provider: "openai", name: "gpt-5" },
    contentCapture: "full",
  },
  async (recorder) => {
    recorder.setResult({ output: [{ role: "assistant", content: "hi" }] });
  }
);
```

每个工具执行覆盖( 这里) `"full"` 选择获取工具参数和跨度结果 :

```ts
await client.startToolExecution(
  { toolName: "search", contentCapture: "full" },
  async (recorder) => {
    recorder.setResult({ arguments: { q: "weather" }, result: { tempC: 18 } });
  }
);
```

动态分辨率通过 `contentCaptureResolver`数字 :

```ts
const client = new Agento11yClient({
  contentCaptureResolver: (metadata) => {
    if (metadata?.["tenant"] === "healthcare") {
      return "metadata_only";
    }
    return "default"; // defer to `contentCapture`
  },
});
```

解析器接收录制的元数据(或 `undefined` 用于记录没有元数据的类型,如工具执行)。 当一个框架链或检索器以出错结束时,它也会调用带有该运行元数据的解析器,以决定是否显示出错文本. 丢出的错误被抓住并当作 `"metadata_only"` (失闭.

分辨率优先( 最高至最低) :

1.  每集记录 `contentCapture` 打开 `GenerationStart` 编号 : `ToolExecutionStart`
2.  `contentCaptureResolver` 返回值
3.  客户一级 `contentCapture` (违约) `"no_tool_content"`(中文(简体) )

与"去","Python","Java"和"NET SDK"不同,JS SDK没有通过Async上下文来传播解析的捕捉模式,因此在一代块内开始的工具执行不会自动地继承一代模式. 设定 `contentCapture` 每个 `ToolExecutionStart` 当您需要工具来遵循非违约政策时.

用户提供 `metadata` 财务报告和审定财务报表 `tags` 不被任何捕获模式剥离。 SDK-内部元数据密钥,包含内容(例如. `call_error`, (中文(简体) ), `agento11y.conversation.title`)与匹配内容一起剥去。 见 [标记和元数据](https://npmcn.com/package/%40grafana/docs/concepts/tags-and-metadata.md) 用于客户端标签、每代标签、元数据以及 `userId` 每个显示( export vs 跨度 vs 度量衡) .

## 提醒前编辑

使用 `generationSanitizer` 当您想要编辑以前正常世代的子字符串时 验证、 跨度同步、 调试快照和导出 .

工具执行跨度显示相同的对话标题、工具参数、结果和错误,所以 SDK也把消毒器放在他们身上 代代相传 `operationName: 'execute_tool'` 仅保留该文本: `conversationTitle`,作为论据 `tool_call` 部分, 结果和错误 `tool_result` 部件,错误 1 `isError: true`编辑 消毒剂在跨度开始时称为有标题的一次,在结束时称为有其他名称的一次. 文本 消毒器去除 远离范围 。 如果有人打来电话,那电话的短信就留下 ; 跨度保留工具名称和错误类别.

```ts
import {
  Agento11yClient,
  createSecretRedactionSanitizer,
} from "@grafana/agento11y";

const client = new Agento11yClient({
  generationSanitizer: createSecretRedactionSanitizer({
    redactInputMessages: false, // omit to fall back to AGENTO11Y_REDACT_INPUT_MESSAGES, then false
    redactEmailAddresses: true,
  }),
});
```

内置消毒器:

-   编辑助理文本和思维中的高度自信秘密格式
-   编辑系统提示、工具调用输入和工具结果中的秘密格式外加密钥/值密钥
-   默认编辑电子邮件地址
-   编辑对话框标题并调用错误
-   编辑历史助手转折和输入工具消息
-   除非启用输入编辑,否则用户输入保持不变

要保存电子邮件地址, 请明确选择退出 :

```ts
const client = new Agento11yClient({
  generationSanitizer: createSecretRedactionSanitizer({
    redactEmailAddresses: false,
  }),
});
```

### 通过环境变量配置编辑

`createSecretRedactionSanitizer()` 读取 `AGENTO11Y_REDACT_INPUT_MESSAGES` 联合国 `1/0`, (中文(简体) ), `true/false`, (中文(简体) ), `yes/no`, (中文(简体) ), `on/off`当 `redactInputMessages` 省略. 优先是明确的选项 > env var > `false`未识别的嵌入值是 警告并倒回下一层, 所以打字不能静地翻转 编辑.

```ts
import {
  createSecretRedactionSanitizer,
  Agento11yClient,
} from "@grafana/agento11y";

// Omit redactInputMessages so AGENTO11Y_REDACT_INPUT_MESSAGES decides.
const client = new Agento11yClient({
  generationSanitizer: createSecretRedactionSanitizer(),
});
```

## 虎克和卫兵

在LLM呼叫前,需要代理可观察性警卫规则运行时使用钩子. SDK评估您请求路径上的钩子; Grafana Cloud 配置的守护规则决定是允许,拒绝,还是转换输入.

虎克默认被禁用. 启用客户端并拨打 `evaluateHook(...)` 在提供者提出请求之前:

```ts
import { HookDeniedError, Agento11yClient } from "@grafana/agento11y";

const client = new Agento11yClient({
  hooks: { enabled: true, phases: ["preflight"], timeoutMs: 15_000, failOpen: true },
});

let messages = [{ role: "user" as const, content: "Summarize this customer note..." }];
const response = await client.evaluateHook({
  phase: "preflight",
  context: {
    agentName: "support-agent",
    agentVersion: "1.0.0",
    model: { provider: "openai", name: "gpt-5" },
    conversationId: "support-case-42",
  },
  input: {
    messages,
    systemPrompt: "You are a helpful support agent.",
    conversationPreview: "Summarize this customer note...",
  },
});

if (response.action === "deny") {
  throw new HookDeniedError(response.reason ?? "", response.ruleId, response.evaluations);
}

messages = response.transformedInput?.messages ?? messages;
```

与 `failOpen: true`,钩子运输错误的解决 允许一个没有评估者不会阻断生产流量。 设定 `failOpen: false` 用于关闭的严格路径.

设定 `hooks.strictTransforms: true` 拒绝错误或空 `transformed_input` 在解码器丢弃数据之前。 默认是 `false`它保留了允许解码。 严格模式接受相同的有效SDK,蛇 case,和Go/protobuf编码. 提供无效或空变换、空收件和不支持的变换字段 `HookTransformError`. 弃权 `transformed_input` 仍然有效.

导入 `HookTransformError` 从 `@grafana/agento11y` 或者说 `@grafana/agento11y-core`。该错误没有反应有效载荷、源输入或认证信头。 SDK 投出错误, 即使用 `failOpen: true`;调用者不得将其作为评价员出局或转发原始投入. 严格的解码验证形状,而不是您的集成是否能够安全地应用重写. 拒绝会改变您的整合 .

使用 `client.evaluateHook(request, { strictTransforms: true })`。该覆盖不会改变客户端配置.

设定 `context.conversationId` 改为: `startGeneration(...)`。SDK还读取 `withConversationId(...)` 和在省略显性关联字段时活动的 OpenTelection 跨度。 这使得Agent Observative保留了被拒绝的飞行前尝试,即使没有创建LLM生成.

如果您使用已转换的输入, 请将已转换的信件/系统提示传递给提供者, 并将相同的值记录在 `startGeneration(...)`。如果您使用 Vercel AI SDK 适配器,请参见 `docs/frameworks/vercel-ai-sdk.md` 用于自动飞行前接线.

在您的应用程序 OTEL SDK 设置中配置 OTEL 导出器( 追踪/ 测量) 。 你可以选择通过 `tracer` 财务报告和审定财务报表 `meter` 直接转到 `Agento11yClient`。 。 。 .

在创建代理 11y 客户端前快速 OTEL 设置模式 :

```ts
import { NodeSDK } from "@opentelemetry/sdk-node";

const otel = new NodeSDK();
await otel.start();
```

见 [打开远程设置](https://npmcn.com/package/%40grafana/docs/concepts/otel-setup.md) 全线,包括OTLP 度量出口国,以及为何在跳过这一步骤时分析仍为空.

## 核心 API

-   `startGeneration(...)` 财务报告和审定财务报表 `startStreamingGeneration(...)`
-   `client.startToolExecution(...)` 财务报告和审定财务报表 `GenerationRecorder.startToolExecution(...)`
-   记录方法 : `setResult(...)`, (中文(简体) ), `setCallError(...)`, (中文(简体) ), `end()`, (中文(简体) ), `getError()`
-   生命周期 : `flush()`, (中文(简体) ), `shutdown()`

### 手动 `try/finally` 样式

```ts
const recorder = client.startGeneration({
  model: { provider: "anthropic", name: "claude-sonnet-4-5" },
});

try {
  recorder.setResult({
    output: [{ role: "assistant", content: "Done" }],
  });
} catch (error) {
  recorder.setCallError(error);
  throw error;
} finally {
  recorder.end();
}
```

## 嵌入可观察性

使用 `startEmbedding(...)` 用于嵌入 API 调用。 嵌入式记录只创建OTel跨度和SDK度量衡,不为生成输出定序.

```ts
await client.startEmbedding(
  {
    agentName: "retrieval-worker",
    agentVersion: "1.0.0",
    model: { provider: "openai", name: "text-embedding-3-small" },
  },
  async (recorder) => {
    const response = await openai.embeddings.create(request);
    recorder.setResult({
      inputCount: request.input.length,
      inputTokens: response.usage?.prompt_tokens ?? 0,
      inputTexts: request.input,
      responseModel: response.model,
    });
  }
);
```

输入文本抓取为选入 :

```ts
const client = new Agento11yClient({
  embeddingCapture: {
    captureInput: true,
    maxInputItems: 20,
    maxTextLength: 1024,
  },
});
```

`embeddingCapture.captureInput` 可能以跨度显示PII/文件内容。 默认情况下保留其禁用并仅允许用于范围调试.

TrackQL 示例 :

-   `traces{gen_ai.operation.name="embeddings"}`
-   `traces{gen_ai.operation.name="embeddings" && gen_ai.request.model="text-embedding-3-small"}`
-   `traces{gen_ai.operation.name="embeddings" && error.type!=""}`

## 工具执行示例

使用 `GenerationRecorder.startToolExecution(...)` 将工具跨到该代,包括跨 `await`,没有全局背景管理器。 该方法不会改变活性上下文或继承生成捕获设置,身份,或请求模型. 在必须匹配一代时明确设定这些工具选项. `client.startToolExecution(...)` 仍然可用,并使用活动的 OpenTelection 上下文.

```ts
await client.startGeneration(
  {
    conversationId: "weather-session",
    agentName: "weather-agent",
    model: { provider: "openai", name: "gpt-5" },
    tools: [{ name: "weather", type: "function" }],
    contentCapture: "metadata_only",
  },
  async (generation) => {
    const city = await Promise.resolve("Paris");
    const tool = generation.startToolExecution({
      toolName: "weather",
      conversationId: "weather-session",
      agentName: "weather-agent",
      requestProvider: "openai",
      requestModel: "gpt-5",
      contentCapture: "metadata_only",
    });
    try {
      tool.setResult({ arguments: { city }, result: { tempC: 18 } });
    } catch (error) {
      tool.setCallError(error);
      throw error;
    } finally {
      tool.end();
    }
    generation.setResult({ output: [{ role: "assistant", content: "18°C in Paris" }] });
  }
);
```

生成回调自动结束生成. 工具厂返回一个记录器;称为 `end()` 你自己来 以上两段录音均省略以下内容 `metadata_only`。配置 OpenTeleometry 服务商以保留跨度;明确的父目录不会创建导出者.

### 追踪技能载荷、资源读取和命令

设定 `ToolExecutionStart.executionKind` 明确改为 `"load_skill"`, (中文(简体) ), `"read_skill_resource"`,或 `"command"`。 。 。 . 这个 `ToolExecutionKind` 类型定义这些值。 SDK不会从工具名,路径或参数中推断出执行类型. 技能和进程属性如下 [合并 GenAI # 498](https://github.com/open-telemetry/semantic-conventions-genai/pull/498)仍在发展之中.

| 执行种类 | 含义 | 适用领域 |
| --- | --- | --- |
| `"load_skill"` | 装入技能指令 | `skillName`, (中文(简体) ), `skillDescription`, (中文(简体) ), `skillSourceURI` |
| `"read_skill_resource"` | 读取技能资源 | 以上技能领域, `skillResourceName` |
| `"command"` | 执行命令,可以选择技能 | 以上技能/资源领域, `processExecutableName`, (中文(简体) ), `processExecutablePath`; 补全 `processExitCode` |

未设定或未识别的执行类型保留了通用工具行为,并释放出任何技能或进程属性. SDK忽略了不适用字段. 技能场发射 `gen_ai.skill.name`, (中文(简体) ), `gen_ai.skill.description`, (中文(简体) ), `gen_ai.skill.source.uri`,以及 `gen_ai.skill.resource.name`。 。 。 . 进程字段发射 `process.executable.name`, (中文(简体) ), `process.executable.path`,以及 `process.exit.code`。 。 。 . SDK 不双写 `agento11y.skill.name`。 。 。 .

扩展名起始于 `execute_tool <tool>` 并使用被裁剪的非空白身份:

-   `load_skill` 当出现时, 附加技能名称 .
-   `read_skill_resource` 附录 `<skill> <resource>`或仅仅是 `<resource>` 没有技能。 没有资源,它就一无所有.
-   `command` 使用相同的资源后缀,然后倒回可执行名称,然后没有后缀.

技能资源读取和命令从不使用只使用技能后缀. 跨度名称和适用的结构名称在创建时可供采样者使用. 私人字段和完成退出代码被排除在采样器属性之外.

进程字段描述一个直接执行的进程. 不要从外壳文本、管道或指令批次中推断出来. `ToolExecutionResult.processExitCode` 是可选的整数值 `number`:省略表示未知;零记录成功完成. 只释放出安全的整数。 布尔、字符串和分数值不被强制输入退出代码. 退出代码独立于已记录的执行错误. 例如,记录一个已知的完成代码如下:

```ts
await client.startToolExecution(
  {
    toolName: "exec",
    executionKind: "command",
    skillName: "review",
    skillResourceName: "scripts/check.py",
    processExecutableName: "python3",
  },
  async (recorder) => {
    recorder.setResult({ processExitCode: 0 });
  }
);
```

`skillDescription`, (中文(简体) ), `skillSourceURI`,以及 `processExecutablePath` 属于私人内容. SDK在有效范围内省略它们 `"metadata_only"` 或者说 `"full_with_metadata_spans"`在解析器和解析器之后. 核心 `"no_tool_content"` 保留这些私有字段; 参数/结果仍然需要现有内容的选入. 每个导出的技能源 URI 有用户信息、查询和片段被移除, 甚至在下面 `"full"`。 。 。 . 无效的或相对的 URI 不使用网络或文件系统查找而省略. 当调试历史被启用时,抓取模式不会对工具快照进行消毒:原始参数,结果,以及错误文本都保留在那里.

通用工具记录和 `executeToolCalls` 保持不变. 对于 `load_skill`, (中文(简体) ), `read_skill_resource`,以及 `command`, (中文(简体) ), `gen_ai.client.operation.duration` 添加 `agento11y.tool.execution.kind`。 。 。 . 包括一个被修剪的,无缝的 `gen_ai.skill.name` ,包括失败的尝试和减少的抓取模式. 没有添加资源或过程度量度. 见 [客户计量合同](https://npmcn.com/package/%40grafana/docs/concepts/tool-call-vs-tool-execution.md#client-metrics)。 。 。 .

## 提供者助手

-   打开AI : `docs/providers/openai.md`
-   安东尼: `docs/providers/anthropic.md`
-   双子座: `docs/providers/gemini.md`

## 框架处理器

使用模块子路径导出用于框架召回集成 :

-   兰彩: `@grafana/agento11y/langchain`
-   兰格: `@grafana/agento11y/langgraph`
-   OpenAI 代理 : `@grafana/agento11y/openai-agents`
-   拉玛因德克斯: `@grafana/agento11y/llamaindex`
-   Google ADK: (英语) `@grafana/agento11y/google-adk`
-   Vercel AI SDK: (中文(简体) ) `@grafana/agento11y/vercel-ai-sdk`
-   特工队: `@grafana/agento11y/strands`
-   兰彩指南: `docs/frameworks/langchain.md`
-   LangGraph 向导 : `docs/frameworks/langgraph.md`
-   OpenAI 代理指南 : `docs/frameworks/openai-agents.md`
-   LlamaIndex 指南 : `docs/frameworks/llamaindex.md`
-   谷歌 ADK 指南 : `docs/frameworks/google-adk.md`
-   Vercel AI SDK指南: `docs/frameworks/vercel-ai-sdk.md`
-   Strands 代理指南 : `docs/frameworks/strands.md`

```ts
import { Agento11yClient } from "@grafana/agento11y";
import { withAgento11yLangChainCallbacks } from "@grafana/agento11y/langchain";
import { withAgento11yLangGraphCallbacks } from "@grafana/agento11y/langgraph";
import { withAgento11yOpenAIAgentsHooks } from "@grafana/agento11y/openai-agents";
import { withAgento11yLlamaIndexCallbacks } from "@grafana/agento11y/llamaindex";
import { withAgento11yGoogleAdkPlugins } from "@grafana/agento11y/google-adk";
import { createAgento11yVercelAiSdk } from "@grafana/agento11y/vercel-ai-sdk";
import { withAgento11yStrandsHooks } from "@grafana/agento11y/strands";
import { Runner } from "@openai/agents";
import { CallbackManager } from "llamaindex";

const client = new Agento11yClient();
const langChainConfig = withAgento11yLangChainCallbacks(undefined, client, { providerResolver: "auto" });
const langGraphConfig = withAgento11yLangGraphCallbacks(undefined, client, { providerResolver: "auto" });
const runner = new Runner();
const openAIAgentsHooks = withAgento11yOpenAIAgentsHooks(runner, client, { providerResolver: "auto" });
const callbackManager = new CallbackManager();
const llamaIndexConfig = withAgento11yLlamaIndexCallbacks({ callbackManager }, client, { providerResolver: "auto" });
const googleAdkRunnerConfig = withAgento11yGoogleAdkPlugins(undefined, client, { providerResolver: "auto" });
const vercelAiSdk = createAgento11yVercelAiSdk(client, { agentName: "vercel-agent" });
const strandsConfig = withAgento11yStrandsHooks(undefined, client, { conversationId: "chat-123" });
```

框架处理器使用 `Agento11yClient` 假设你通过。 如果客户端配置为 `generationSanitizer`,同样的编辑政策自动适用于记录的世代 通过LangChain,LangGraph,OpenAI Agents,LlamaIndex,Google ADK,和Vercel AI SDK集成. 同样的编辑政策也适用于斯特兰德斯代理世代.

每个框架处理器注入:

-   `agento11y.framework.name` (单位:千美元)`langchain`, (中文(简体) ), `langgraph`, (中文(简体) ), `openai-agents`, (中文(简体) ), `llamaindex`, (中文(简体) ), `google-adk`, (中文(简体) ), `vercel-ai-sdk`,或 `strands`(中文(简体) )
-   `agento11y.framework.source` (单位:千美元)`handler` 对于现有的召回处理器, `framework` 对于Vercel AI SDK钩, `hooks` 用于 Strands )
-   `agento11y.framework.language` (单位:千美元)`javascript` 对于现有的召回处理器, `typescript` 为 Vercel AI SDK 和 Strands 钩)
-   `metadata["agento11y.framework.run_id"]`
-   `metadata["agento11y.framework.thread_id"]` (当有)
-   `metadata["agento11y.framework.parent_run_id"]` (如有)
-   `metadata["agento11y.framework.component_name"]`
-   `metadata["agento11y.framework.run_type"]`
-   `metadata["agento11y.framework.tags"]`
-   `metadata["agento11y.framework.retry_attempt"]` (如有)
-   `metadata["agento11y.framework.event_id"]` (如有)
-   `metadata["agento11y.framework.langgraph.node"]` (可用时 LangGraph)

对话绘图是对话的第一:

-   `conversation_id` 编号 : `session_id` 编号 : `group_id` 从框架上下文
-   接下来 `thread_id`
-   决定性倒计时 `agento11y:framework:<framework_name>:<run_id>`

当生成元数据中存在时,低心力框架密钥被复制到生成跨属性上.

对LangGraph的坚持,通过 `configurable.thread_id` 并反复使用它

```ts
const threadConfig = {
  ...withAgento11yLangGraphCallbacks(undefined, client, { providerResolver: "auto" }),
  configurable: { thread_id: 'customer-42' },
};
await graph.invoke({ prompt: 'Remember my timezone is UTC+1.', answer: '' }, threadConfig);
await graph.invoke({ prompt: 'What timezone did I give you?', answer: '' }, threadConfig);
```

## 行为

-   生成模式是明确的: `SYNC` 财务报告和审定财务报表 `STREAM`。 。 。 .
-   生成导出支持 HTTP, gRPC, 以及 `none` (仅以文书为主.
-   追踪/测量使用 `config.tracer`编号 :`config.meter` 提供,否则 OTEL 全球.
-   导出与被限制的队列和重试/后退同步 。 每个导出请求默认为30秒的超时.
-   `flush()` 排出排队的世代. `shutdown()` 运行最终冲出,期限与配置的请求超时相等。 当最后期限过后,它会丢弃已排队的出口而不进行再试并关闭出口商.
-   空工具名会生成一个禁用工具记录器.
-   生成/工具跨度总是包括 SDK 身份属性:
    -   `agento11y.sdk.name=sdk-js`
-   常态化生成元数据总是包括相同的SDK身份密钥;相冲突的调用器值被覆盖.
-   原始提供者的文物选入(`rawArtifacts: true`) (中文(简体) ).

## 只使用仪器模式( 没有生成发送)

设定 `generationExport.protocol` 改为 `"none"` 保持生成/工具的仪器和跨度,同时使生成运输失效.

```ts
const client = new Agento11yClient({
  generationExport: {
    protocol: "none",
  },
});
```

## SDK 度量衡

SDK通过您配置的 OTL 测量器提供商 来发布这些 OTel 直方图 :

-   `gen_ai.client.operation.duration`
-   `gen_ai.client.token.usage`
-   `gen_ai.client.time_to_first_token`
-   `gen_ai.client.tool_calls_per_operation`

## 生成导出认证模式

Auth 配置为 `generationExport`。 。 。 .

-   `mode: "none"`
-   `mode: "tenant"` (所需经费) `tenantId`输入 `X-Scope-OrgID`(中文(简体) )
-   `mode: "bearer"` (所需经费) `bearerToken`输入 `Authorization: Bearer <token>`(中文(简体) )
-   `mode: "basic"` (所需经费) `basicPassword` + 键 `basicUser` 或者说 `tenantId`输入 `Authorization: Basic <base64(user:password)>`; 还注入 `X-Scope-OrgID` 何时 `tenantId` 设定——仅用于多租户部署,格拉法纳云不需要)

在客户端配置解析时丢出无效的模式/字段组合 .

如果已包含明确的信头 `Authorization` 或者说 `X-Scope-OrgID`,明确标题优先.

```ts
const client = new Agento11yClient({
  generationExport: {
    protocol: "http",
    endpoint: "https://agento11y-prod-<region>.grafana.net",
    auth: {
      mode: "basic",
      tenantId: process.env.AGENTO11Y_AUTH_TENANT_ID,
      basicPassword: process.env.AGENTO11Y_AUTH_TOKEN,
    },
  },
  api: {
    endpoint: "https://agento11y-prod-<region>.grafana.net",
  },
});
```

### Grafana Cloud auth( 基础) :

对于格拉法纳云,使用 `basic` 认证模式 。 用户名是您的 Grafana Cloud 实例/租户 ID 密码是您的 Grafana Cloud API 密钥 。 见 [Grafana Cloud Agent 开始观察文件](https://grafana.com/docs/grafana-cloud/machine-learning/agent-observability/get-started/grafana-cloud/) 用于完整的设置步骤; 对于 SDK 端点, 复制 **API 網址** 从 **可观察性 • 代理可观察性 • 配置**看起来像 `https://agento11y-prod-<region>.grafana.net`。 。 。 .

```ts
const client = new Agento11yClient({
  generationExport: {
    protocol: "http",
    endpoint: "https://agento11y-prod-<region>.grafana.net",
    auth: {
      mode: "basic",
      tenantId: process.env.AGENTO11Y_AUTH_TENANT_ID,
      basicPassword: process.env.AGENTO11Y_AUTH_TOKEN,
    },
  },
});
```

如果您的部署需要不同的用户名, 设置 `basicUser` 明确:

```ts
auth: {
  mode: "basic",
  tenantId: process.env.AGENTO11Y_AUTH_TENANT_ID,
  basicUser: process.env.AGENTO11Y_AUTH_TENANT_ID,
  basicPassword: process.env.AGENTO11Y_AUTH_TOKEN,
},
```

## 导出超时

`AGENTO11Y_EXPORT_TIMEOUT_MS` 设置每一代或工作流程步骤导出请求的超时。 它接受来自 `1` 结束 `2147483647` 默认为 `30000` 毫秒长. 明确 `generationExport.timeoutMs` 值战胜环境变量.

`shutdown()` 使用与它最后冲洗的最后期限相同的解答超时,所以一个已经在飞行中的请求会有一个完整的尝试.

## 导出重试和队列调制

生成和工作流程步输出默认重试5次,以5秒为指数回放上限. 设定 `AGENTO11Y_MAX_RETRIES` 财务报告和审定财务报表 `AGENTO11Y_MAX_BACKOFF_MS` 到基-10整数 `1` 结束 `2147483647` 以覆盖这些默认值。 明确 `generationExport.maxRetries` 财务报告和审定财务报表 `generationExport.maxBackoffMs` 值战胜环境变量.

每个内导队列默认保存有2000个记录. 设定 `AGENTO11Y_QUEUE_SIZE` 到基-10整数 `1` 结束 `2147483647` 以推翻这个能力。 每秒最高记录的大小乘以预期的断电数,加上头室。 世代和工作流程步骤对这种能力有单独的队列. 较大的队列会消耗应用程序内存,并且无法从进程重新启动中存活下来. 明确 `generationExport.queueSize` 值战胜环境变量.

在背景出口商中进行检索。 当一个导出正在重试时, 内嵌队列可以填充, 并且可以丢弃更新一代 。 使用重试预算大小的短而已知的中断,而不是永久的多分钟设置.

## 连接自定义环境 vars

SDK 只自动装入 `AGENTO11Y_*` (原始内容存档于2013-10-12) (中文(简体) ). env vars (n`AGENTO11Y_ENDPOINT`, (中文(简体) ), `AGENTO11Y_PROTOCOL`, (中文(简体) ), `AGENTO11Y_AUTH_MODE`, (中文(简体) ), `AGENTO11Y_AUTH_TOKEN`当您打电话时 `new Agento11yClient()`。对于任何其他的 env var(例如您的秘密管理者以不同名称曝光的),请在您的应用程序中读取,并将值传递到配置中:

```ts
const generationBearerToken = (process.env.MY_APP_AGENTO11Y_TOKEN ?? "").trim();

const client = new Agento11yClient({
  generationExport: {
    protocol: "http",
    endpoint: "https://agento11y-prod-<region>.grafana.net",
    auth:
      generationBearerToken.length > 0
        ? { mode: "bearer", bearerToken: generationBearerToken }
        : {
            mode: "basic",
            tenantId: process.env.AGENTO11Y_AUTH_TENANT_ID,
            basicPassword: process.env.AGENTO11Y_AUTH_TOKEN,
          },
  },
  api: {
    endpoint: "https://agento11y-prod-<region>.grafana.net",
  },
});
```

共同地貌学:

-   格拉法纳云:一代人 `basic` 模式,带有实例 ID 和 API 密钥.
-   直接面向摄入的API:世代 `tenant` 模式.
-   通过 OTEL 收集器/合金进行追踪/测量:在您的应用程序 OTEL SDK 设置中配置出口商.
-   企业代理: 生成 `bearer` 模式到代理;代理认证和向上转发租户头.

## 对话评分

使用 SDK 帮助提交用户化的收视率 :

```ts
const result = await client.submitConversationRating("conv-123", {
  ratingId: "rat-123",
  rating: "CONVERSATION_RATING_VALUE_BAD",
  comment: "Answer ignored user context",
  metadata: { channel: "assistant-ui" },
  source: "sdk-js",
});

console.log(result.rating.rating, result.summary.hasBadRating);
```

`submitConversationRating` 向 `api.endpoint`,它应该是来自代理可观察性配置的Grafana Cloud Agent Observation API URL,并使用已经配置在SDK客户端上的同一代输出认证头.

## 实验

离线 evals:运行一个代理 在一个数据集,分级,并发布运行,试验, 并得分给观察特工 API生活在一个单独的子路径上,所以 导入核心软件包从不将实验代码拖入边缘运行时间 捆绑 :

```ts
import { ExperimentsClient, withExperiment } from "@grafana/agento11y/experiments";

const client = new ExperimentsClient({
  endpoint: process.env.AGENTO11Y_ENDPOINT,
  tenantId: process.env.AGENTO11Y_AUTH_TENANT_ID,
  ingestToken: process.env.AGENTO11Y_AUTH_TOKEN,
});

const suite = {
  suiteId: "smoke",
  name: "Smoke",
  testCases: [{ testCaseId: "add", input: "2+2", expected: "4" }],
};
const verifier = { evaluatorId: "exact", version: "1", kind: "deterministic" };

await withExperiment(client, { experimentId: "run-1", name: "smoke run", suite }, async (experiment) => {
  for (const testCase of suite.testCases) {
    await experiment.withTrial(testCase, async (trial) => {
      const answer = await runAgent(testCase.input);
      trial.recordIO({ input: testCase.input, output: answer });
      trial.finalScore(answer === testCase.expected, { evaluator: verifier });
    });
  }
});
```

`withExperiment` 完成成功和失败路径的运行 `withTrial` 结束审判,结束审判 `errored` 当召回时 掷出. 使用 `Experiment.start`, (中文(简体) ), `trial.start()`,以及 `close()` 直接当 a 运行拥有自己的控制流.

存于房客的估价师也可以分试,而不是分分 在跑道上计算。 这条路是实验性的,需要 `AGENTO11Y_ENABLE_EXPERIMENTAL_FEATURES=true`数字 :

```ts
await experiment.withTrial(testCase, async (trial) => {
  const { conversationId } = await runInstrumentedAgent(testCase.input);
  trial.bindConversation(conversationId);
  await trial.evaluate("helpfulness");
});
```

见 [`docs/experiments.md`](https://npmcn.com/package/%40grafana/agento11y/docs/experiments.md) 全表面:分数 种类、当地法官、文物、报告、便携式和所储存的套间、跨程序 实验,以及实验性OpenTeleometry实验遥测.

Expoinfoo 用户可以通过其 `afterAll` 钩入 `createPromptfooExtension` 从 `@grafana/agento11y/promptfoo`见 [`Promptfoo integration guide`](https://npmcn.com/package/%40grafana/agento11y/docs/integrations/promptfoo.md) 编辑 [`runnable example`](https://npmcn.com/package/%40grafana/examples/experiments/promptfoo/README.md)。 。 。 .

## 常见问题

### @grafana/agento11y 是什么？

@grafana/agento11y 使用您的 OpenTeleometry tracker/ meters 设置实现 LLM 生成和工具执行远程测量的规范化\.

### 如何安装 @grafana/agento11y？

在项目目录运行 npm install @grafana/agento11y，或使用 pnpm add / yarn add / bun add。

### @grafana/agento11y 支持 TypeScript 吗？

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

### @grafana/agento11y 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @grafana/agento11y 可以商用吗？

@grafana/agento11y 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @grafana/agento11y 的下载量有多少？

根据 npm 官方下载统计，@grafana/agento11y 在 2026/10/17 – 2026/11/15 这 30 天内被下载 63,470 次，日均约 2,116 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @grafana/agento11y 还在维护吗？

最新版本 0\.16\.0 发布于 2026/10/29（18 天前）；至今共发布 9 个版本，其中过去 12 个月发布了 9 个；首次发布于 2026/07/21。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

