SuperAPI AI 工具集

components

前端与建站

查看项目

更新于 10-16 02:09

技能介绍

用途

Tambo Components 用于在 Tambo 应用中创建和注册组件,使 AI 能够参与组件的生成与更新。它提供两种组件类型:生成式组件(generative,由 AI 按需创建)和可交互组件(interactable,预先放置、由 AI 更新)。

主要能力

生成式组件

AI 根据用户消息动态选择并渲染这些组件。注册时使用 TamboComponent 数组,每个条目包含 name、component、description 和 propsSchema。description 用于告诉 AI 何时使用该组件;propsSchema 是 Zod 对象,每个字段通过 .describe() 添加说明。

示例:

import { TamboProvider, TamboComponent } from "@tambo-ai/react";
import { z } from "zod";

const WeatherCardSchema = z.object({
  city: z.string().describe("City name"),
  temperature: z.number().describe("Temperature in Celsius"),
  condition: z.string().describe("Weather condition"),
});

const components: TamboComponent[] = [
  {
    name: "WeatherCard",
    component: WeatherCard,
    description:
      "Displays weather for a city. Use when user asks about weather.",
    propsSchema: WeatherCardSchema,
  },
];

<TamboProvider apiKey={apiKey} components={components}>
  <App />
</TamboProvider>;

渲染生成式组件

在消息列表中使用 ComponentRenderer 渲染 AI 生成的组件:

import { ComponentRenderer } from "@tambo-ai/react";

function Message({
  message,
  threadId,
}: {
  message: TamboThreadMessage;
  threadId: string;
}) {
  return (
    <div>
      {message.content.map((block) => {
        switch (block.type) {
          case "text":
            return <p key={`${message.id}:text`}>{block.text}</p>;
          case "component":
            return (
              <ComponentRenderer
                key={block.id}
                content={block}
                threadId={threadId}
                messageId={message.id}
              />
            );
          default:
            return null;
        }
      })}
    </div>
  );
}

生成式组件要点

  • propsSchema:Zod 对象,每个字段使用 .describe()。
  • description:告诉 AI 何时使用该组件。
  • 流式传输:props 初始为 undefined,应将其设为可选或优雅处理。
  • 使用 z.infer<typeof Schema> 获取 TypeScript props 类型。

可交互组件

预先放置在 UI 中,AI 可以观察并通过自然语言更新其 props。使用 withTamboInteractable 包装组件:

import { withTamboInteractable } from "@tambo-ai/react";
import { z } from "zod";

const NoteSchema = z.object({
  title: z.string().describe("Note title"),
  content: z.string().describe("Note content"),
  color: z.enum(["white", "yellow", "blue"]).optional(),
});

function Note({ title, content, color = "white" }: Props) {
  return (
    <div style={{ backgroundColor: color }}>
      <h3>{title}</h3>
      <p>{content}</p>
    </div>
  );
}

export const InteractableNote = withTamboInteractable(Note, {
  componentName: "Note",
  description: "A note with editable title, content, and color",
  propsSchema: NoteSchema,
});

可交互组件的工作方式

  • 自动注册:组件挂载时自动注册。
  • 上下文发送:当前 props 自动对 AI 可见。
  • 工具注册:更新工具自动注册。
  • 双向:用户编辑与 AI 更新均可生效。

使用方式

通过 TamboProvider 的 components 属性注册生成式组件;通过 withTamboInteractable 包装并导出可交互组件。生成式组件在消息列表中用 ComponentRenderer 渲染。

适用场景

  • 生成式:聊天回复、仪表盘。
  • 可交互:设置、表单、任务看板。

限制

生成式组件为一次性渲染,props 生成一次;可交互组件在会话期间持久存在,AI 可更新 props。生成式组件在流式传输期间 props 初始为 undefined,需要按可选处理。