# @grafana/llm 中文文档

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

版本：1\.0\.9
npm 元数据更新时间：2026-07-21T17:40:58.184Z
中文译文更新时间：2026-11-16T21:53:32.545Z
软件包许可：Apache-2\.0

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

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

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

- 包体积（解压后）：269 kB，25 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：5 个
- peer 依赖：rxjs ^7\.8\.2，react ^18，@grafana/data ^10\.4\.0 \|\|^11 \|\| ^12，@grafana/runtime ^10\.4\.0 \|\| ^11 \|\| ^12
- 首次发布：2024-03-12T19:35:14.367Z
- 最新版本发布：2026-06-12T15:23:45.335Z
- 近 30 天下载量：100718（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：26（近 12 个月 5 个）

## 中文简介

用于 Grafana 插件中 LLMS 工作的库

## 安装

```sh
npm install @grafana/llm
```

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

## README

# LLM 交互的前端功能

这是方便功能和组件的集合,使与Grafana的LLM功能的相互作用更加容易.

首先,增加最新版本 `@grafana/llm` 切换到软件包中的依赖性

```json
{
  "dependencies": {
    "@grafana/llm": "0.22.0"
  }
}
```

**说明:** 如果你正在写测试 从 `@grafana/llm`,您可能需要配置 Jest 来处理 ES 模块。 详见下方"杰斯"配置部分.

## 游戏配置

### 带有 Jest 的无害环境管理错误

写入从 `@grafana/llm`,你可能会遇到 Jest 错误像 `SyntaxError: Cannot use import statement outside a module`。这样做是因为 `@grafana/llm` 使用Jest需要改造的ES模块依赖性.

如果您正在使用Grafana的插件脚手架,请扩展你的Jest配置,以包括额外的ES模块. 为了方便, `@grafana/llm` 导出所需的模块列表 :

```javascript
// jest.config.js
const { grafanaESModules, nodeModulesToTransform } = require('./.config/jest/utils');
const { grafanaLLMESModules } = require('@grafana/llm/jest');

module.exports = {
  // Jest configuration provided by Grafana scaffolding
  ...require('./.config/jest.config'),
  transformIgnorePatterns: [nodeModulesToTransform([...grafanaESModules, ...grafanaLLMESModules])],
};
```

### MCP 功能性

如果您正在测试使用 MCP( 模式上下文协议) 特性的代码, 请添加 `TransformStream` 组合填充到您的 `jest-setup.js`数字 :

```javascript
// jest-setup.js
// Jest setup provided by Grafana scaffolding
import './.config/jest-setup';

// Add this import and global for MCP functionality
import { TransformStream } from 'node:stream/web';
import { TextEncoder } from 'util';

// TextEncoder may already be present in your setup
global.TextEncoder = TextEncoder;
// Add this line for MCP TransformStream support
global.TransformStream = TransformStream;
```

## 使用量

然后在你的组件中,你可以使用 `llm` 对象从 `@grafana/llm` 像这样:

```typescript
import React, { useState } from 'react';
import { useAsync } from 'react-use';
import { scan } from 'rxjs/operators';

import { openai } from '@grafana/llm';
import { PluginPage } from '@grafana/runtime';

import { Button, Input, Spinner } from '@grafana/ui';

const MyComponent = (): JSX.Element => {
  const [input, setInput] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [reply, setReply] = useState('');

  const { loading, error } = useAsync(async () => {
    const enabled = await openai.enabled();
    if (!enabled) {
      return false;
    }
    if (message === '') {
      return;
    }
    // Stream the completions. Each element is the next stream chunk.
    const stream = openai
      .streamChatCompletions({
        // model: openai.Model.LARGE, // defaults to BASE, use larger model for longer context and complex tasks
        messages: [
          { role: 'system', content: 'You are a helpful assistant with deep knowledge of the Grafana, Prometheus and general observability ecosystem.' },
          { role: 'user', content: message },
        ],
      })
      .pipe(
        // Accumulate the stream chunks into a single string.
        scan((acc, delta) => acc + delta, '')
      );
    // Subscribe to the stream and update the state for each returned value.
    return stream.subscribe(setReply);
  }, [message]);

  if (error) {
    // TODO: handle errors.
    return null;
  }

  return (
    <div>
      <Input value={input} onChange={(e) => setInput(e.currentTarget.value)} placeholder="Enter a message" />
      <br />
      <Button type="submit" onClick={() => setMessage(input)}>
        Submit
      </Button>
      <br />
      <div>{loading ? <Spinner /> : reply}</div>
    </div>
  );
};
```

## 常见问题

### @grafana/llm 是什么？

用于 Grafana 插件中 LLMS 工作的库

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

在项目目录运行 npm install @grafana/llm，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：rxjs（^7\.8\.2）、react（^18）、@grafana/data（^10\.4\.0 \|\|^11 \|\| ^12）、@grafana/runtime（^10\.4\.0 \|\| ^11 \|\| ^12）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

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

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

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

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

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

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

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

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

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

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

