@ grafana/ 协助员
与格拉法纳助理合并的定义和公用事业类型.
安装
npm install @grafana/assistant
使用量
检查助理可用性
import { isAssistantAvailable } from '@grafana/assistant';
// Check if the assistant is available
isAssistantAvailable().subscribe((available) => {
if (available) {
console.log('Assistant is available');
}
});
使用助理钩 (反应)
import { useAssistant } from '@grafana/assistant';
function MyComponent() {
const { isLoading, isAvailable, openAssistant, closeAssistant } = useAssistant();
if (isLoading) {
return <div>Loading...</div>;
}
if (!isAvailable || !openAssistant) {
return <div>Assistant not available</div>;
}
return (
<button onClick={() => openAssistant({
origin: 'grafana/panel-data-analyzer',
prompt: 'Help me analyze data' })}>
Open Assistant
</button>
);
}
打开助理侧边栏
import { openAssistant, closeAssistant } from '@grafana/assistant';
// Open the assistant with an initial prompt
openAssistant({ origin: 'grafana/some-feature', prompt: 'Show me CPU usage over the last hour' });
// Open the assistant with initial prompt and autoSend set to false
openAssistant({
origin: 'grafana-datasources/prometheus/some-feature',
prompt: 'Help me analyze data',
autoSend: false,
});
// Open the assistant without an initial prompt
openAssistant({
origin: 'grafana-slo-app/some-page',
});
// Close the assistant
closeAssistant();
与助理使用上下文
import { openAssistant, createAssistantContextItem } from '@grafana/assistant';
// Create context items to provide additional information to the assistant
const datasourceContext = createAssistantContextItem('datasource', {
datasourceUid: 'prometheus-uid',
});
const dashboardContext = createAssistantContextItem('dashboard', {
dashboardUid: 'dashboard-uid',
dashboardTitle: 'System Overview',
folderUid: 'folder-uid',
folderTitle: 'Production',
});
// Open the assistant with initial prompt and context
openAssistant({
origin: 'grafana/dashboard-page',
prompt: 'Analyze the CPU metrics from this dashboard',
context: [datasourceContext, dashboardContext],
});
// Create hidden context for system instructions (won't show in UI pills)
const systemInstructions = createAssistantContextItem('structured', {
hidden: true,
title: 'System Instructions',
data: {
instructions: 'When analyzing metrics, always consider seasonal patterns and anomalies',
preferences: 'Use clear, technical language and provide actionable insights',
},
});
// Include hidden context with visible context
openAssistant({
prompt: 'What are the trends in this data?',
context: [datasourceContext, systemInstructions],
});
提供特定页面上下文
您可以在与特定 URL 模式相匹配的页面上打开助手时注册自动包含的上下文项目。 这个 providePageContext 函数返回一个设置函数,允许您动态地更新上下文 :
import { providePageContext, createAssistantContextItem } from '@grafana/assistant';
// Create initial context for dashboard pages
const dashboardContext = createAssistantContextItem('structured', {
data: {
name: 'Dashboard Context',
pageType: 'dashboard',
capabilities: ['view', 'edit', 'share'],
help: 'Use the assistant to analyze dashboard data, create queries, or troubleshoot issues.',
},
});
// Register context for all dashboard pages and get a setter function
const setContext = providePageContext('/d/*', [dashboardContext]);
// Later, dynamically update the context based on user interactions or data changes
setContext([
dashboardContext,
createAssistantContextItem('structured', {
data: {
name: 'Panel Context',
selectedPanel: 'cpu-usage-panel',
panelType: 'graph',
},
}),
]);
// Clean up when no longer needed
setContext.unregister();
// Example: Provide hidden system instructions for explore pages
providePageContext('/explore', [
createAssistantContextItem('structured', {
hidden: true,
title: 'Additional instructions',
data: {
'System Instructions':
'When working with explore queries, always validate the time range and check for data availability. Suggest using recording rules for expensive queries.',
},
}),
]);
在反应组件中使用页面上下文
对于反应组件,使用 useProvidePageContext 自动处理清理的钩子 :
import { useProvidePageContext, createAssistantContextItem } from '@grafana/assistant';
function DashboardComponent() {
const dashboardContext = createAssistantContextItem('structured', {
data: {
name: 'Dashboard Context',
pageType: 'dashboard'
}
});
// Automatically cleans up on unmount
const setContext = useProvidePageContext('/d/*', [dashboardContext]);
// Update context when needed
const handlePanelSelect = (panelId: string) => {
setContext([
dashboardContext,
createAssistantContextItem('structured', {
data: {
name: 'Panel Context',
selectedPanel: panelId
}
})
]);
};
return <div>Dashboard content</div>;
}
访问当前页面上下文
使用 usePageContext 连接到当前页面的所有活动上下文 :
import { usePageContext } from '@grafana/assistant';
function MyComponent() {
const pageContext = usePageContext();
console.log('Active context items:', pageContext);
return <div>Page has {pageContext.length} context items</div>;
}
创建上下文项目
这个 createAssistantContextItem 函数允许您创建结构化上下文项目,为助手提供有关您 Grafana 资源的额外信息.
import { createAssistantContextItem } from '@grafana/assistant';
// Create a datasource context
const datasourceContext = createAssistantContextItem('datasource', {
datasourceUid: 'prom-123',
title: 'Main Datasource', // Optional custom title
icon: 'database', // Optional custom icon
});
// Create a dashboard context
const dashboardContext = createAssistantContextItem('dashboard', {
dashboardUid: 'dash-456',
dashboardTitle: 'Application Overview',
folderUid: 'folder-789',
folderTitle: 'Production Dashboards',
});
// Create a label context
const labelContext = createAssistantContextItem('label_name', {
datasourceUid: 'prom-123',
datasourceType: 'prometheus',
labelName: 'service',
});
// Create a label value context
const labelValueContext = createAssistantContextItem('label_value', {
datasourceUid: 'prom-123',
datasourceType: 'prometheus',
labelName: 'service',
labelValue: 'api-server',
});
// Create a folder context
const folderContext = createAssistantContextItem('dashboard_folder', {
folderUid: 'folder-789',
folderTitle: 'Production Dashboards',
});
// Create structured data context
const structuredContext = createAssistantContextItem('structured', {
data: {
name: 'Custom Data',
metrics: ['cpu_usage', 'memory_usage'],
threshold: 80,
},
});
// Create generic context
const genericContext = createAssistantContextItem('unknown', {
id: 'my-context',
text: 'Some additional context information',
});
// Create component context for custom React components
const componentContext = createAssistantContextItem('component', {
components: {
MyCustomComponent: MyCustomComponentImplementation,
AnotherComponent: AnotherComponentImplementation,
},
prompt: `
- When mentioning specific entities, use the your_app_MyCustomComponent with the syntax: <your_app_MyCustomComponent prop1={'value1'} prop2={'value2'} />
- Custom components must never be wrapped in code blocks (backticks \` or \`\`\`).
- Always provide all required props when using custom components.
`,
namespace: 'your_app', // Optional: Namespace for your components (defaults to 'components')
});
// Create hidden context (useful for system instructions)
const hiddenInstructions = createAssistantContextItem('structured', {
hidden: true, // Won't be shown in UI pills but will be sent to the assistant
title: 'Page-specific instructions',
data: {
instructions: 'Always provide step-by-step explanations',
context: 'This is a complex system with multiple dependencies',
},
});
为助理用户注册自定义组件
这个 component 上下文类型允许您注册自定义 React 组件,助手可以在答复中使用这些组件。 这对渲染特定域的UI元素增强用户体验特别有用.
重要内容: 部件在使用前必须得到#grafana-assistant的批准. 请联系Grafana助理团队,请在生产过程中执行您的定制组件之前进行审查和批准.
方法1:使用提供成分(建议)
import { provideComponents } from '@grafana/assistant';
import MyEntityMention from 'components/MyEntityMentionComponent';
import MyCustomChart from 'components/MyCustomChartComponent';
/**
* Configure the assistant context for your app plugin.
* This sets up custom components that will be available to the Grafana Assistant
* when users are on any page matching the provided pattern.
*/
export function configureAssistantContext() {
provideComponents(
`
- When mentioning an entity in text, always use the your_app_MyEntityMention component: <your_app_MyEntityMention name={'entity name here'} type={'entity type here'} />
- For displaying charts, use the your_app_MyCustomChart component: <your_app_MyCustomChart data={chartData} title={'Chart Title'} />
- Custom components must never be wrapped in code blocks (backticks \` or \`\`\`).
`,
'your_app', // namespace
{
MyEntityMention,
MyCustomChart,
},
/.*/ // matches all pages
);
}
方法 2: 使用创建助理连接项目提供页面连接
import { createAssistantContextItem, providePageContext } from '@grafana/assistant';
import MyEntityMention from 'components/MyEntityMentionComponent';
import MyCustomChart from 'components/MyCustomChartComponent';
export function configureAssistantContext() {
providePageContext(/.*/, [
createAssistantContextItem('component', {
components: {
MyEntityMention,
MyCustomChart,
},
prompt: `
- When mentioning an entity in text, always use the your_app_MyEntityMention component: <your_app_MyEntityMention name={'entity name here'} type={'entity type here'} />
- For displaying charts, use the your_app_MyCustomChart component: <your_app_MyCustomChart data={chartData} title={'Chart Title'} />
- Custom components must never be wrapped in code blocks (backticks \` or \`\`\`).
`,
namespace: 'your_app', // Optional: defaults to 'components' if not provided
}),
]);
}
组件背景的要点 :
- 需要核准:%%% 部件在使用前必须得到# grafana- assistant 的批准
- 构成部分: 其反应组件执行的组件名称记录
- 提示: 向助理说明如何和何时使用这些组件
- 命名空间: 您的应用程序组件( 例如 “ your app” 、 “ datasource” ) 的独有标识符 。 可选 - 如果不提供“ 组件” 默认值
- 组件使用量: 部分在助理答复中作为参考
<namespace_ComponentName prop={'value'} />(注意下划线格式) - 无代码块: 自定义组件永远不应被标记下代码块包裹
执行:
interface MyEntityMentionProps {
name: string;
type: string;
env?: string;
site?: string;
namespace?: string;
properties?: string;
}
const MyEntityMention: React.FC<MyEntityMentionProps> = ({ name, type, env, site, namespace, properties }) => {
return (
<span
className="entity-mention"
data-entity-type={type}
title={`${type}: ${name}`}
>
{name}
</span>
);
};
export default MyEntityMention;
使用系统指令的隐藏上下文
这个 hidden 参数允许您向助手提供上下文而不在UI药丸中显示。 这对于:
- 系统指令: 提供特定特定页面的行为指南
- 元数据: 包含如果显示可能会混淆用户的技术细节
- 背景规则: 添加特定页面规则而不对接口进行打乱
示例使用案例:
// Provide exploration-specific guidelines
providePageContext('/explore', [
createAssistantContextItem('structured', {
hidden: true,
title: 'Explore Page Guidelines',
data: {
instructions: [
'Always validate time ranges before running queries',
'Suggest using recording rules for expensive queries',
'Warn about queries that might impact performance',
],
queryLimits: {
maxTimeRange: '24h',
suggestedSampleInterval: '1m',
},
},
}),
]);
// Add dashboard-specific context
providePageContext('/d/*', [
createAssistantContextItem('structured', {
hidden: true,
title: 'Dashboard Instructions',
data: {
bestPractices: 'Encourage users to use template variables for flexibility',
performance: 'Suggest panel caching for slow queries',
},
}),
]);
向助理展示职能
import {
getExposeAssistantFunctionsConfig,
newFunctionNamespace,
FunctionImplementation,
FunctionNamespace,
NamedFunctions,
} from '@grafana/assistant';
// Define your functions
const myFunctions: NamedFunctions = {
getMetrics: (datasource: string) => {
return ['cpu_usage', 'memory_usage', 'disk_io'];
},
calculateAverage: (values: number[]) => {
return values.reduce((a, b) => a + b, 0) / values.length;
},
};
// Create a namespace for your functions
const namespace = newFunctionNamespace('myPlugin', myFunctions);
// Export the configuration for your plugin
export const getExtensionConfigs = () => [getExposeAssistantFunctionsConfig([namespace])];
贡献助理扩展(实验)
实验: aPI正在积极开发中,未来发布可能会有变化。 它需要一个 Grafana 版本与
AppPlugin.addFunction()编号 :addedFunctions支持(2025年2月+,本套件涵盖>=12.1.0相对依赖性最低标准).
应用插件可以帮助Grafana助理——聊天轨道"chits"(扩展工具卡细节和在助理文本中的内含组件),提议的第一个消息("启动"),点播工作流程指南("技能"),画布的自定义文物类型,以及模式/系统即时贡献——通过对显示的功能进行注册 ASSISTANT_EXTENSION_POINT数字 :
import { AppPlugin } from '@grafana/data';
import { getAssistantExtensionConfig, AssistantExtensionManifest } from '@grafana/assistant';
const manifest: AssistantExtensionManifest = {
schemaVersion: 1,
chits: [{ kind: 'tool-details', toolNames: ['myplugin_run_check'], component: MyToolDetails }],
starters: [{ label: 'Run a check', message: 'Run a check against my production environment' }],
skills: [
{
id: 'author-check',
title: 'Author a check',
description: 'Step-by-step workflow for creating a check with the myplugin tools.',
content: '# Author a check\n\n1. List existing checks...\n2. Draft the check...\n3. Validate before saving.',
},
],
artifactKinds: [
{
ext: '.grafana-myplugin-app.check',
label: 'Check',
icon: 'check',
tabPriority: 0, // ascending: lower promotes earlier, among your own kinds (built-ins always come first)
validate: (data) => isCheck(data),
renderer: CheckRenderer,
},
],
promptContributions: [
{
modeId: 'authoring',
label: 'Check authoring',
description: 'Author checks with guided help',
whenToUse: 'When the user asks to create or edit checks',
compose: 'append',
prompt: 'You can author checks using the myplugin tools.',
},
],
};
export const plugin = new AppPlugin().addFunction(getAssistantExtensionConfig(manifest));
艺术品制造器和工具栏接收其 node 加号 fs: AssistantArtifactFs - 一个只读的手柄(list编号 :read编号 :has在谈话的 文物档案系统。 它通过设计包括了其他插件的和内置的文物(组合是点). 没有写字表层:只有助理验证后才能写出文物 write_artifact 路径,而渲染器必须治疗 fs 除了他们自己的节点之外 是唯一的文物内容来源.
starters 显示在新聊天中显示的首个消息, 明显归属于您的插件; 选择一个发送 message 作为普通的,用户可见的用户消息. 他们从不自动同意,从不隐藏,也从不修改系统提示. 助理执行界限:每个插件最大3个启动器, message 最多500个字符, label 最多可有80个字符——超出一个盖子的条目被全部删除.
skills 教授助理插件特定的工作流程,而不添加本地的即时文本:只有一行目录条目(标题、描述、手柄)在即时出现,以及 content 只有在用户附加技能或模型加载时才加载。 每种技能都列在下面 plugin:{yourPluginId}:{id} 和列表中只读的助理技能设置页面,归属于您的插件。 技能只存在于你的注册状态下——他们从未坚持过或指数化. 技能内容只在助理的代理技能运行时间被启用时才到达模型;只读设置列表不需要额外的旗帜. 助理执行限制, 将违反的条目全部放下( 永远不要截取): 最大每个插件5个技能, id [a-z][a-z0-9-]* 最多64个字符, title 最多80岁, description 最多500个, content 最多为32768个UTF-8字节.
启动者对提供问题
使用 provideQuestions 在您插件已经运行的页面中建议问题 —— 它被 URL 扫描, 通过页面文本注册, 需要您的模块被加载到该页面, 并且没有属性 。 使用表单 starters 在助理的新鲜聊天中,他们通过扩展点旅行(您的模块是按需加载的),明显归属于您的插件,受助理的每插件杀关机和盖子的制约,并且将来会静态地宣布。 两者都有意共享相同的渲染表面并发送路径.
还宣布目标如下: extensions.addedFunctions 在你身边 plugin.json显式功能必须纯正而稳定:同样的环境必须总是产生同样的(深度-等同的)显式——在注册前在自己的特征旗帜上登出门来,而不是返回不同的显式. 除组件和函数引用外,清单中的所有内容都是JSON可序列化的.
使用打开助理按钮组件
这个 OpenAssistantButton 是一个预建的按钮组件,它提供了一个简单的方法,通过一个按钮点击,向您的用户界面添加助手功能。 它自动检查可用性,如果助理不可用,则隐藏自己.
import { OpenAssistantButton, createAssistantContextItem } from '@grafana/assistant';
function MyDashboard() {
const dashboardContext = createAssistantContextItem('dashboard', {
dashboardUid: 'dashboard-123',
dashboardTitle: 'CPU Metrics Dashboard'
});
return (
<div>
<h1>Dashboard</h1>
{/* Basic usage */}
<OpenAssistantButton
prompt="Help me analyze the CPU usage trends in this dashboard"
context={[dashboardContext]}
origin="grafana/dashboard-menu"
/>
{/* Icon-only button */}
<OpenAssistantButton
prompt="Show me optimization suggestions"
iconOnlyButton={true}
name="Get AI suggestions"
size="md"
origin="grafana-datasources/loki/query-editor"
/>
{/* Button without auto-send */}
<OpenAssistantButton
prompt="What patterns do you see in the data?"
autoSend={false}
name="Ask Assistant"
size="lg"
origin="grafana/panel-viewer"
/>
</div>
);
}
API 参考
反应钩
useAssistant(): AssistantHook
一个反应钩子,提供助手可用状态和控制功能.
回返情况: 具有下列属性的对象:
isLoading: boolean- 是否仍在检查可用性isAvailable: boolean- 助理是否可用openAssistant?: (props: OpenAssistantProps) => void- 打开助手的功能( 如果无法使用, 未定义)closeAssistant?: () => void- 关闭助理的功能(如果无法使用,则未定义)toggleAssistant?: (props: OpenAssistantProps) => void- 切换助手的功能( 如果无法使用, 则未定义)
useTerms(): { accepted: boolean; loading: boolean; error: string | null }
反应钩来检查条款和条件接受状态. 自动获取挂载时的术语数据并提供加载/error状态 .
回返情况: 具有下列属性的对象:
accepted: boolean- 是否接受和更新条款loading: boolean- 检查是否正在进行中error: string | null- 如果检查失败, 错误消息, 否则无效
useLimits(): LimitsHookResult
检查用户快速限制的回放钩 。 在助理插件更新限制时,通过自定义事件自动获取限制挂载上的数据并收听实时更新.
回返情况: 具有下列属性的对象:
count: number- 现月及时清点limit: number- 月即时限(0=无限制)month: string- 本月,YYY-MM格式isLimitReached: boolean- 是否已达到限额loading: boolean- 初始获取是否在进行中error: string | null- 如果获取失败, 错误消息, 否则无效refetch: () => void- 手动调整限制的功能
示例
import { useLimits } from '@grafana/assistant';
function MyComponent() {
const { count, limit, isLimitReached, loading, error } = useLimits();
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
if (isLimitReached) {
return <div>Monthly limit reached ({count}/{limit})</div>;
}
return <div>Prompts used: {count}/{limit || 'unlimited'}</div>;
}
checkLimits(): Promise<LimitsData>
用于检查用户快速限制的自动同步函数 。 以限制数据返回承诺 .
回返情况: 以:
count: number- 现月及时清点limit: number- 月即时限(0=无限制)month: string- 本月,YYY-MM格式isLimitReached: boolean- 是否已达到限额
示例
import { checkLimits } from '@grafana/assistant';
async function checkUserLimits() {
try {
const { isLimitReached, count, limit } = await checkLimits();
if (isLimitReached) {
console.log(`Limit reached: ${count}/${limit}`);
}
} catch (error) {
console.error('Failed to check limits:', error);
}
}
usePageContext(): ChatContextItem[]
基于已注册的 URL 模式返回当前页面所有活动上下文项目的回放钩头 .
回返情况: 矩阵 ChatContextItem 匹配当前页面 URL 的对象.
useProvidePageContext(urlPattern: string | RegExp, initialContext?: ChatContextItem[]): (context: ChatContextItem[]) => void
用于提供在卸载上自动清理的页面上下文的反应钩子 。 这是React组件中使用页面上下文的建议方式.
参数:
urlPattern- URL 模式(字符串或RegExp)与页面 URL相匹配initialContext- ChatContext 项目的初始阵列, 以在模式匹配时提供( 默认为空阵列)
回返情况: 用于更新上下文的设置函数
usePageComponents(): Record<string, ComponentImplementation>
一个反应钩子,提供当前页面的所有可用组件. 此勾钩在 URL 更改或组件注册更改时自动更新 .
回返情况: 包含当前页面所有可用组件的对象,按键 namespace_componentName 格式.
示例
import { usePageComponents } from '@grafana/assistant';
function MyAssistantComponent() {
const components = usePageComponents();
// Access components registered with namespace 'myapp' and component name 'EntityMention'
const EntityMentionComponent = components['myapp_EntityMention'];
return (
<div>
Available components: {Object.keys(components).join(', ')}
</div>
);
}
反应组件
<OpenAssistantButton />
一个预建的 React 组件,它让一个按钮打开 Grafana 助理,并带有可配置的即时和上下文 .
参数:
prompt: string- 说吧 需求 在助手中显示的初始提示origin: string- 说吧 需求 打开助手的请求的来源 。 结构上应该使用前缀和第一部分作为命名空间。 例如:"grafana-data sources/prometheus/query-buildinger","grafana-slo-app/slo-editor-overview"context?: ChatContextItem[]- 可选上下文项目创建createAssistantContextItemautoSend?: boolean- 是否自动发送初始提示( 默认为true(中文(简体) )title?: string- 在按钮上显示的文本(默认为'Analyze with Assistant'(中文(简体) )size?: 'xs' | 'sm' | 'md' | 'lg'- 按钮大小(默认值)'sm'(中文(简体) )iconOnlyButton?: boolean- 狦true,将工具提示(默认为false(中文(简体) )
<QueryWithAssistantButton />
一个为查询编辑器设计的按钮组件,该组件会打开预被查询上下文,数据源信息所覆盖的助理侧边栏和一个可操作的快取. 它自动检测用户是否正在创建新查询或更新已有查询,并相应调整提示. 如果助理不在场,则不作任何说明.
参数:
size?: ComponentSize- 按钮大小('xs', (中文(简体) ),'sm', (中文(简体) ),'md', (中文(简体) ),'lg'),默认为'sm'currentQuery: DataQuery- 说吧 需求 当前查询正在编辑queries: DataQuery[]- 说吧 需求 编辑器中的所有查询( 用于提供兄弟姐妹查询的背景)dataSourceInstanceSettings: DataSourceInstanceSettings- 说吧 需求 数据源实例设置app?: CoreApp- 应用程序上下文(例如,CoreApp.Explore, (中文(简体) ),CoreApp.Dashboard(中文(简体) )datasourceApi: DataSourceApi | null- 说吧 需求 数据源 API 实例( 用于获取查询显示文本)title?: string- 按钮文本(默认为'Query with Assistant'(中文(简体) )
示例
import { QueryWithAssistantButton } from '@grafana/assistant';
import { CoreApp } from '@grafana/data';
function QueryEditor({ query, queries, datasource, datasourceSettings }) {
return (
<div>
{/* Your query editor UI */}
<QueryWithAssistantButton
size="sm"
currentQuery={query}
queries={queries}
dataSourceInstanceSettings={datasourceSettings}
app={CoreApp.Explore}
datasourceApi={datasource}
/>
{/* With custom title */}
<QueryWithAssistantButton
size="sm"
currentQuery={query}
queries={queries}
dataSourceInstanceSettings={datasourceSettings}
app={CoreApp.Explore}
datasourceApi={datasource}
title="Ask AI"
/>
</div>
);
}
<AITextInput />
一个 AI 驱动的文本输入组件,使用内线助手生成内容. 在生成和集成发送按钮时具有梯度边框动画的特性。 完全可以生成标题、标签或名称等短式内容.
参数:
value: string- 说吧 需求 输入的当前值( 控制组件)onChange: (value: string) => void- 说吧 需求 当输入值改变时调用origin: string- 说吧 需求 分析跟踪的出处(例如“grafana/panel-editor/title”)placeholder?: string- 占位符文本(默认为“ 请求 AI 生成... ”)systemPrompt?: string- 可选系统提示以引导助手的行为onComplete?: (text: string) => void- 一代成功完成时召回onError?: (error: Error) => void- 如果在生成过程中发生错误, 召回onDelta?: (delta: string) => void- 召回在一代人时期收到的流出信号disabled?: boolean- 输入是否被禁用autoGenerate?: boolean- 当为真时, 如果值为空, 在挂载时自动生成内容( 使用)systemPrompt以示及时)streaming?: boolean- 当真实时, 流会实时生成文字输入 。 当错误( 默认) 时, 显示占位符直到生成完成className?: string- 其他CSS类名称data-testid?: string- 测试身份证
示例
import { AITextInput } from '@grafana/assistant';
import { useState } from 'react';
function PanelEditor() {
const [title, setTitle] = useState('');
return (
<AITextInput
value={title}
onChange={setTitle}
origin="grafana/panel-editor/title"
systemPrompt="Generate a concise, descriptive panel title. Return only the title text."
placeholder="Ask AI to generate a title..."
autoGenerate
streaming
onComplete={(text) => {
setTitle(text);
console.log('Generated:', text);
}}
/>
);
}
<AITextArea />
一个AI驱动的文本区域组件,它使用内置助手生成更长的内容. 在生成和集成发送按钮时具有梯度边框动画的特性。 使用 Cmd/Ctrl+Enter 提交。 用于描述、文档或多行内容生成.
参数:
value: string- 说吧 需求 文本区的当前值( 控制组件)onChange: (value: string) => void- 说吧 需求 当文本区值改变时调用origin: string- 说吧 需求 分析跟踪的出处(例如“grafana/panel-editor/描述”)placeholder?: string- 占位符文本( 默认为“ 请求 AI 生成... ” ( Cmd/ Ctrl+ Enter 发送) )systemPrompt?: string- 可选系统提示以引导助手的行为onComplete?: (text: string) => void- 一代成功完成时召回onError?: (error: Error) => void- 如果在生成过程中发生错误, 召回onDelta?: (delta: string) => void- 召回在一代人时期收到的流出信号disabled?: boolean- 文本区域是否被禁用autoGenerate?: boolean- 当为真时, 如果值为空, 在挂载时自动生成内容( 使用)systemPrompt以示及时)streaming?: boolean- 当真实时, 串流实时生成文本进入文本区域 。 当错误( 默认) 时, 显示占位符直到生成完成rows?: number- 文本区域行数( 默认为 4)className?: string- 其他CSS类名称data-testid?: string- 测试身份证
示例
import { AITextArea } from '@grafana/assistant';
import { useState } from 'react';
function DashboardEditor() {
const [description, setDescription] = useState('');
return (
<AITextArea
value={description}
onChange={setDescription}
origin="grafana/dashboard-editor/description"
systemPrompt="Generate a clear dashboard description in 2-3 sentences."
placeholder="Ask AI to generate a description... (Cmd/Ctrl+Enter to send)"
rows={6}
autoGenerate
streaming
onComplete={(text) => {
setDescription(text);
console.log('Generated:', text);
}}
/>
);
}
useAIGeneration(options): UseAIGenerationResult
后面的钩子 AITextInput 财务报告和审定财务报表 AITextArea。当您想要同样的内线辅助重写行为,但使用自己的触发和文本控制时使用它——例如,在纯文本区域旁边的"Improve with AI"按钮.
选项( E)UseAIGenerationOptions:
value: string- 说吧 需求 当前文本( 控制)onChange: (value: string) => void- 说吧 需求 用生成的文本调用( 生成时为空白)origin: string- 说吧 需求 分析跟踪的起源systemPrompt?: string- 可选系统迅速引导助理getUserPrompt?: (textInput: string) => string- 将当前文本接入发送给助手的提示onComplete?: (text: string) => void编号 :onError?: (error: Error) => void编号 :onDelta?: (delta: string) => void- 世代生命周期召回disabled?: boolean, (中文(简体) ),autoGenerate?: boolean, (中文(简体) ),streaming?: boolean- 语义与AITextArea
回返情况: { displayValue, isSendDisabled, handleGenerate, isGenerating, error }
示例
import { useAIGeneration } from '@grafana/assistant';
import { useState } from 'react';
function InstructionsField() {
const [text, setText] = useState('');
const { handleGenerate, isGenerating } = useAIGeneration({
value: text,
onChange: setText,
origin: 'my-app/instructions',
systemPrompt: 'Refine the user input into a clear, actionable prompt. Output only the prompt.',
getUserPrompt: (input) => `Improve this prompt, keeping its intent: ${input}`,
});
return (
<div>
<button type="button" onClick={handleGenerate} disabled={!text.trim() || isGenerating}>
{isGenerating ? 'Improving…' : 'Improve with AI'}
</button>
<textarea value={text} onChange={(e) => setText(e.target.value)} />
</div>
);
}
使用内线助理
这个 useInlineAssistant 钩子在不打开侧边栏的情况下生成内容的内行——最适合用AI生成的文本来填充表单字段.
import { useInlineAssistant } from '@grafana/assistant';
import { useState } from 'react';
export function PanelEditor() {
const [title, setTitle] = useState('');
const titleGen = useInlineAssistant();
return (
<div>
<Input
value={titleGen.isGenerating ? titleGen.content : title}
onChange={(e) => setTitle(e.target.value)}
/>
<Button
onClick={() => {
titleGen.generate({
prompt: 'Generate a panel title for CPU metrics',
origin: 'my-plugin/panel-editor',
agentName: 'panel-title-generator',
agentId: 'v1',
onComplete: (text) => setTitle(text),
onError: (err) => console.error(err)
});
}}
disabled={titleGen.isGenerating}
>
{titleGen.isGenerating ? 'Generating...' : 'Generate'}
</Button>
</div>
);
}
关键特性 :
isGenerating- 布尔表示正在生成中content- 流动内容(实时更新)generate(options)- 开始新一代- 每个实例都是独立的,多用于并行字段
对于仪器,保留 origin 侧重于请求的来源和使用 agentName 对于稳定 逻辑内线剂 在这个整合。 SDK 命名空间 agentName 编辑 origin 命名空间,所以不同的集成可以安全地再利用名称,例如 title-generator 没有在西吉尔相撞。 使用 agentId 当您想要标记一个版本或执行标识符时.
使用带有内置助手的工具
工具通过自定义动作来扩展助手的能力. 工具可以同时返回文本和结构化数据(artifacts). 要获取文物数据,请包括: onToolComplete 在工具执行中调用.
import { createTool } from '@grafana/assistant';
import { z } from 'zod';
import type { ToolInvokeOptions, ToolOutput } from '@grafana/assistant';
// Define artifact type
interface WeatherData {
city: string;
temperature: { celsius: number; fahrenheit: number };
conditions: string;
humidity: number;
}
// Create tool schema
const weatherSchema = z.object({
city: z.string().describe('The city name to get weather for'),
});
// Create tool that accepts onToolComplete callback
export const createWeatherTool = (onToolComplete: (data: WeatherData) => void) => {
return createTool(
async (input: z.infer<typeof weatherSchema>): Promise<ToolOutput> => {
const { city } = input;
// Fetch weather data (simplified example)
const weatherData: WeatherData = {
city,
temperature: { celsius: 22, fahrenheit: 72 },
conditions: 'Sunny',
humidity: 65,
};
// Call the callback to pass artifact data
onToolComplete(weatherData);
// Return tuple: [text response, artifact]
return [
`Current weather in ${city}: ${weatherData.temperature.celsius}°C, ${weatherData.conditions}`,
weatherData,
];
},
{
name: 'get_weather',
description: 'Fetches weather information and returns structured data.',
inputSchema: z.toJSONSchema(weatherSchema),
validate: (input) => weatherSchema.parse(input),
responseFormat: 'content_and_artifact',
}
);
};
// Use the tool with inline assistant
export function WeatherComponent() {
const [result, setResult] = useState('');
const [weatherData, setWeatherData] = useState<WeatherData | null>(null);
const gen = useInlineAssistant();
const handleGetWeather = () => {
gen.generate({
prompt: 'What is the weather in San Francisco?',
origin: 'my-plugin/weather',
tools: [createWeatherTool((data) => setWeatherData(data))], // Pass callback
onComplete: (text) => setResult(text),
onError: (err) => console.error(err),
});
};
return (
<div>
<Button onClick={handleGetWeather} disabled={gen.isGenerating}>
Get Weather
</Button>
{result && <div>{result}</div>}
{weatherData && <pre>{JSON.stringify(weatherData, null, 2)}</pre>}
</div>
);
}
对调查的结构性意见(Lens)
这个 useInvestigationThroughLens 钩子从一个有条理的 LLM 生成的 对调查报告的看法 由你提供的 JSON Schema 塑造 当主机插件( 例如 IRM) 持有时使用 investigationId 并想要一份紧凑的、打字的调查摘要——一份行政标题、促成因素、后续行动——而不提交全面报告.
有两件事能让计划有效:
- 外地
descriptions是模型的每个字段指示 - 这就是引导机制 观众、音调、长度限制、倒置措辞和允许的值都属于描述(和enums, 模型必须尊重). - 保留LLM场进行合成. 决定性的元数据——调查状态,时间戳,工作空间链接——提供给模型的逐字记录,并通过而不是生成复制,因此是元数据类型字段(例如.
{ investigationLink, createdAt })工作但浪费了镜头. 问只有报告才能回答什么问题.
宣布计划 as const 钩子推断 data 从它(通过) json-schema-to-ts:
import { useInvestigationThroughLens } from '@grafana/assistant';
const incidentReviewSchema = {
type: 'object',
properties: {
headline: {
type: 'string',
description: 'One sentence describing the incident for an executive audience, max 80 characters.',
},
customerImpact: {
type: 'string',
description:
"Plain-language description of the impact on end users, or 'none observed' if the report shows no user-facing impact.",
},
contributingFactors: {
type: 'array',
items: { type: 'string' },
description: 'Distinct technical or process factors that contributed to the incident.',
},
followUps: {
type: 'array',
description: 'Concrete follow-up actions to prevent recurrence.',
items: {
type: 'object',
properties: {
action: { type: 'string' },
urgency: { type: 'string', enum: ['now', 'this-week', 'backlog'] },
rationale: {
type: 'string',
description: 'Why this action prevents recurrence, grounded in the report.',
},
},
required: ['action', 'urgency', 'rationale'],
additionalProperties: false,
},
},
},
required: ['headline', 'customerImpact', 'contributingFactors', 'followUps'],
additionalProperties: false,
} as const;
export function IncidentReview({ investigationId }: { investigationId: string }) {
const lens = useInvestigationThroughLens(incidentReviewSchema, investigationId, {
origin: 'grafana-irm/incident-review',
});
if (lens.status === 'loading') {
return <Spinner />;
}
if (lens.status === 'error') {
return <span>{lens.error.message}</span>;
}
// lens.data is fully typed from the schema:
// { headline: string; customerImpact: string; contributingFactors: string[];
// followUps: Array<{ action: string; urgency: 'now' | 'this-week' | 'backlog'; rationale: string }> }
return (
<section>
<h3>{lens.data.headline}</h3>
<p>{lens.data.customerImpact}</p>
<ul>
{lens.data.followUps.map((f) => (
<li key={f.action}>
[{f.urgency}] {f.action} — {f.rationale}
</li>
))}
</ul>
</section>
);
}
行为:
- 宣告:当计划或
investigationId变化.refresh()重生,绕行缓存. - 缓存(Cached):结果被缓存到每个(调查,计划,报告内容),因此重载不会为一份不变的报告再生成.
- 依据:确定性事实(身份、标题、状况、时间戳、链接)从调查元数据中逐字复制——模型只从报告中得出分析领域(摘要、根源).
- 校验:该模型的输出被校验出与您的计划相对应,在失败前进行一次纠正重试.
- 过
enabled: false选择推迟生成,直到满足先决条件。 重新启用默认服务缓存结果; 如果报告在禁用时可能已经更改( 例如, 仍在流出) , 也设定refreshOnEnable: true因此通过再启用而触发的获取会绕过缓存一次.
结果 - 歧视工会—— data 财务报告和审定财务报表 error 永不共存 :
type UseInvestigationThroughLensResult<T> =
| { status: 'loading'; refresh: () => void }
| { status: 'success'; data: T; refresh: () => void }
| { status: 'error'; error: InvestigationLensError; refresh: () => void };
错误代码 (单位:千美元)lens.error.code:
unavailable——Grafana助理插件没有安装,被禁用,或者太老,无法提供镜头. 钩子从不扔进你的外表 把它当作"藏出地表".no_report——调查不存在或尚未形成报告.permission_denied——当前用户无法阅读调查.validation_failed——模型输出在经过一次修正重试后不符合"计划".llm_error——生成请求本身失败(网络,使用限制,提供者出错).
对于归属, origin 遵循与内置助手相同的常规 : 第一个路径段识别您的集成, 并命名在使用跟踪中的生成 .
可用函数
isAssistantAvailable(): Observable<boolean>
检查助理插件是否可用 .
回返情况: 发射的 RxJS 观测器 true 如果助手有空的话, false 否则.
条款和条件
说明: 在大多数情况下,插件不需要直接检查术语. 格拉法纳助理在条款不被接受时自动处理案件,在程序开始前敦促用户接受条款.
checkTerms(): Promise<boolean>
检查是否接受并更新条款和条件. 此函数核实:
- 已接受条件
- 已接受的版本匹配或超过当前版本
回返情况: 一个承诺,决心 true 如果条件被接受并更新, false 否则.
掷出 : API 调用失败时出错 .
示例
import { checkTerms } from '@grafana/assistant';
try {
const accepted = await checkTerms();
if (!accepted) {
// Show terms acceptance UI
}
} catch (error) {
// Handle error
console.error('Failed to check terms:', error);
}
侧边栏函数
openAssistant(props: OpenAssistantProps): void
打开 Grafana 助理侧边栏 .
参数:
props: OpenAssistantProps- 配置对象origin: string- 请求的起源打开了助手。 结构上应该使用前缀和第一部分作为命名空间。 例如:"grafana-data sources/prometheus/query-buildinger","grafana-slo-app/slo-editor-overview"prompt?: string- 在助理中显示可选初始提示context?: ChatContextItem[]- 向助理提供补充资料的可选上下文项目autoSend?: boolean- 自动发送初始提示的可选旗帜
closeAssistant(): void
关闭 Grafana 助理侧边栏 .
上下文函数
createAssistantContextItem<T>(type: T, params: ContextTypeParams<T>): ChatContextItem
创建可以传递给助手的上下文项目以提供补充信息.
参数:
type- 要创建的背景类型。 支持的类型 :'datasource'- 数据源背景'dashboard'- 盘子上下文'dashboard_folder'- 文件夹上下文'label_name'- 标签名称上下文'label_value'- 标签值上下文'structured'- 自定义结构化数据背景'component'- 自定义反应组件上下文'unknown'- 通用文本上下文
params- 上下文类型特有的参数(见上下文类型一节)。 所有上下文类型支持 :hidden?: boolean- 如果选中的话, 上下文项目将不会在 UI 药丸中显示, 但仍会发送给助手 。 这对提供系统指令,行为指南,或者其他元数据来说是有用的,这些元数据不应该使用户界面杂乱无章.
回返情况: A 类 ChatContextItem 可以传递给 openAssistant
providePageContext(urlPattern: string | RegExp, initialContext: ChatContextItem[]): ((context: ChatContextItem[]) => void) & { unregister: () => void }
根据 URL 模式为特定页面注册上下文项目。 返回设置函数以动态更新上下文 。 在匹配模式的页面上打开助手时,上下文会自动包含.
参数:
urlPattern- URL模式(用通配符或RegExp字符串)与页面 URL相匹配- 字符串模式支持
*(匹配任意字符)和**(匹配任何路径段) - RegExp 模式提供了完整的 Regex 匹配能力
- 字符串模式支持
initialContext- 初始数组ChatContextItem以提供模式匹配时
回返情况: 用于更新上下文的设置函数,其中包含 unregister 清除方法
实例:
// String patterns - returns setter function
const setDashboardContext = providePageContext('/d/*', initialContext); // Match any dashboard
const setExploreContext = providePageContext('/explore**', initialContext); // Match explore and subpaths
// RegExp patterns
const setSpecificContext = providePageContext(/^\/d\/[a-zA-Z0-9]+$/, initialContext); // Match specific dashboard format
// Update context dynamically
setDashboardContext([...newContext]);
// Cleanup when done
setDashboardContext.unregister();
provideComponents(prompt: string, namespace: string, components: Record<string, ComponentImplementation>, urlPattern?: string | RegExp): ((context: ChatContextItem[]) => void) & { unregister: () => void }
向助理提供组件的简化功能。 这个是方便的包裹 providePageContext 专门用于登记组件.
参数:
prompt- 向助理提供关于如何和何时使用这些部件的指示namespace- 应用程序组件(例如“ myapp” 、“ datasource” )的独有标识符components- 记录其执行反应部分的构成部分名称urlPattern- 与页面 URL相匹配的可选 URL 模式(默认为/.*/- 匹配所有页面)
回返情况: 用于更新上下文的设置函数,其中包含 unregister 清除方法
示例
import { provideComponents } from '@grafana/assistant';
import MyEntityMention from './components/MyEntityMention';
import MyCustomChart from './components/MyCustomChart';
// Register components for all pages
const setComponents = provideComponents(
`
- When mentioning entities, use the myapp_MyEntityMention component: <myapp_MyEntityMention name={'entity-name'} type={'entity-type'} />
- For charts, use the myapp_MyCustomChart component: <myapp_MyCustomChart data={chartData} title={'Chart Title'} />
- Custom components must never be wrapped in code blocks.
`,
'myapp',
{
MyEntityMention,
MyCustomChart,
}
);
// Register components only for dashboard pages
const setDashboardComponents = provideComponents(
'Use components to enhance dashboard analysis.',
'dashboard',
{ MyEntityMention },
'/d/*'
);
// Cleanup when done
setComponents.unregister();
问题系统
问题系统允许外部方为特定页面提供带有可选上下文的样本提示. 它重新使用现有的页面上下文基础设施,但提供了一个侧重于问题的更简单的界面.
provideQuestions(urlPattern: string | RegExp, initialQuestions: Question[]): ((questions: Question[]) => void) & { unregister: () => void }
根据 URL 模式注册特定页面的问题。 返回设置函数以动态更新问题.
参数:
urlPattern- URL模式(用通配符或RegExp字符串)与页面 URL相匹配initialQuestions- 初始数组Question以提供模式匹配时
回返情况: 用于更新问题的设置函数,其中包含 unregister 清除方法
实例:
// Register questions for dashboard pages
const setQuestions = provideQuestions('/d/*', [
{
prompt: 'What metrics are available in this dashboard?',
context: [], // Optional context items created with `createAssistantContextItem`
},
{
prompt: 'How can I optimize the queries in this dashboard?',
context: [
createAssistantContextItem('dashboard', {
dashboardUid: 'dashboard-uid',
dashboardTitle: 'System Overview',
folderUid: 'folder-uid',
folderTitle: 'Production',
}),
],
},
]);
// Update questions dynamically
setQuestions([
{
prompt: 'What are the key insights from this dashboard?',
context: [],
},
]);
// Cleanup when done
setQuestions.unregister();
useProvideQuestions(urlPattern: string | RegExp, initialQuestions?: Question[]): (questions: Question[]) => void
反应钩子用于提供自动清理出舱的问题. 这是React组件中使用问题的建议方式.
参数:
urlPattern- URL 模式(字符串或RegExp)与页面 URL相匹配initialQuestions- 当模式匹配时( 默认为空阵列) 要提供的初始问题组
回返情况: 用于更新问题的设置函数
示例
function DashboardComponent() {
const setQuestions = useProvideQuestions('/d/*', [
{
prompt: "What does this dashboard show?",
},
{
prompt: "How can I improve this dashboard?",
}
]);
return <div>Dashboard</div>;
}
useQuestions(): Question[]
反应钩子以获取符合当前 URL 的所有问题 。 此过滤页面上下文仅返回问题类型项目 .
回返情况: 所有匹配注册中的问题组
示例
function AssistantComponent() {
const questions = useQuestions();
return (
<div>
<h3>Suggested Questions:</h3>
{questions.map((question, index) => (
<div key={index}>
<p>{question.prompt}</p>
{question.context && question.context.length > 0 && (
<p>Has additional context</p>
)}
</div>
))}
</div>
);
}
侧边栏类型
OpenAssistantProps
type OpenAssistantProps = {
prompt?: string;
context?: ChatContextItem[];
autoSend?: boolean;
};
打开助手的配置对象 .
prompt- 可选初始显示提示context- 可选上下文项目autoSend- 自动发送初始提示的可选旗帜
ChatContextItem
type ChatContextItem = {
node: TreeNode;
occurrences: string[];
};
向助手提供结构化信息的上下文项目 .
页面上下文类型
PageContextRegistration
interface PageContextRegistration {
id: string;
urlPattern: string | RegExp;
context: ChatContextItem[];
}
代表已注册的页面上下文映射 .
问题类型
Question
interface Question {
prompt: string; // The sample prompt/question
context?: ChatContextItem[]; // Optional context items
}
以可选的即时和上下文表示问题.
QuestionRegistration
interface QuestionRegistration {
id: string;
urlPattern: string | RegExp;
questions: Question[];
}
代表已注册的问题映射.
上下文类型
数据源背景参数
interface CreateDatasourceContextParams {
datasourceUid: string;
title?: string;
icon?: IconName;
hidden?: boolean; // If true, the context item will not be shown in the context pills
}
Dashboard 上下文参数
interface CreateDashboardContextParams {
dashboardUid: string;
dashboardTitle: string;
folderUid?: string;
folderTitle?: string;
title?: string;
icon?: IconName;
hidden?: boolean; // If true, the context item will not be shown in the context pills
}
文件夹上下文参数
interface CreateFolderContextParams {
folderUid: string;
folderTitle: string;
title?: string;
icon?: IconName;
hidden?: boolean; // If true, the context item will not be shown in the context pills
}
标签名称上下文参数
interface CreateLabelNameContextParams {
datasourceUid: string;
datasourceType: string;
labelName: string;
title?: string;
icon?: IconName;
hidden?: boolean; // If true, the context item will not be shown in the context pills
}
标签值上下文参数
interface CreateLabelValueContextParams {
datasourceUid: string;
datasourceType: string;
labelName: string;
labelValue: string;
title?: string;
icon?: IconName;
hidden?: boolean; // If true, the context item will not be shown in the context pills
}
结构数据背景参数
interface StructuredNodeDataParams {
data: Record<string, any>;
title?: string;
icon?: IconName;
hidden?: boolean; // If true, the context item will not be shown in the context pills
}
内容参数
interface CreateComponentContextParams {
components: Record<string, React.ComponentType<any>>;
prompt: string;
namespace?: string; // Optional: defaults to 'components' if not provided
title?: string;
icon?: IconName;
hidden?: boolean; // If true, the context item will not be shown in the context pills
}
通用上下文参数
interface NodeDataParams {
id: string;
text?: string;
title?: string;
icon?: IconName;
hidden?: boolean; // If true, the context item will not be shown in the context pills
}
函数扩展类型
CallbackFunction
type CallbackFunction = () => FunctionNamespace[];
一个函数返回函数命名空间的数组.
FunctionImplementation
type FunctionImplementation = (...args: any[]) => any;
一种功能执行类型,可以向助手曝光.
NamedFunctions
type NamedFunctions = Record<string, FunctionImplementation>;
其执行的函数名称记录 .
FunctionNamespace
type FunctionNamespace = {
namespace: string;
functions: NamedFunctions;
};
组在一个命名空间下运行 .
工具函数
newFunctionNamespace(namespace: string, functions: NamedFunctions): FunctionNamespace
创建新的函数命名空间.
参数:
namespace: string- 命名空间标识符functions: NamedFunctions- 命名空间中要包含的功能
getExposeAssistantFunctionsConfig(namespaces: FunctionNamespace[]): PluginExtensionAddedFunctionConfig
为向助手显示函数创建插件扩展配置.
参数:
namespaces: FunctionNamespace[]- 用于曝光的函数命名空间阵列
常数
CALLBACK_EXTENSION_POINT
const CALLBACK_EXTENSION_POINT = 'grafana-assistant-app/callback/v0-alpha';
用于注册助理功能的扩展点ID.
其他导出类型
该套件还输出下列类型的先进用途:
// Data types for context items
export type DashboardNodeData;
export type DatasourceNodeData;
export type FolderNodeData;
export type LabelNameNodeData;
export type LabelValueNodeData;
export type StructuredNodeData;
export type TreeNode;
export type ItemDataType;
// Component types
export type ComponentImplementation;
export type NamedComponents;
许可证
阿帕奇 - 2.0