惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
IT之家
IT之家
Last Week in AI
Last Week in AI
J
Java Code Geeks
L
LangChain Blog
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
博客园 - Franky
博客园 - 司徒正美
月光博客
月光博客
博客园 - 叶小钗
Vercel News
Vercel News
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
B
Blog RSS Feed
人人都是产品经理
人人都是产品经理
H
Help Net Security
G
Google Developers Blog
D
DataBreaches.Net

Chat SDK Documentation

History | Chat SDK History | Chat SDK List a vendor-official adapter | Chat SDK Approvals | Chat SDK Vercel Connect | Chat SDK Teams Low-Level APIs | Chat SDK CLI | Chat SDK Platform Adapters | Chat SDK State Adapters | Chat SDK Cards | Chat SDK Getting Started | Chat SDK Introduction | Chat SDK Modals | Chat SDK Slack Low-Level APIs | Chat SDK Streaming | Chat SDK Testing | Chat SDK Overview | Chat SDK Cards | Chat SDK Overview | Chat SDK Markdown | Chat SDK Modals | Chat SDK AI SDK Tools | Chat SDK Types | Chat SDK Message Subject | Chat SDK Conversation History | Chat SDK Transcripts | Chat SDK Slack bot with Next.js and Redis Actions | Chat SDK Direct Messages | Chat SDK Emoji | Chat SDK
toAiMessages | Chat SDK
Vercel · 2026-05-29 · via Chat SDK Documentation

Convert Chat SDK messages to AI SDK conversation format.

Convert an array of Message objects into the { role, content }[] format expected by the AI SDK. The output is structurally compatible with AI SDK's ModelMessage[].

import { toAiMessages } from "chat/ai";

toAiMessages is also re-exported from the main chat entrypoint for backwards compatibility (with a @deprecated JSDoc hint), but new code should import it from chat/ai alongside createChatTools and the rest of the AI utilities.

import { toAiMessages } from "chat/ai";

bot.onSubscribedMessage(async (thread, message) => {
  const result = await thread.adapter.fetchMessages(thread.id, { limit: 20 });
  const history = await toAiMessages(result.messages);
  const response = await agent.stream({ prompt: history });
  await thread.post(response.fullStream);
});
function toAiMessages(
  messages: Message[],
  options?: ToAiMessagesOptions
): Promise<AiMessage[]>

Parameters

Options

Returns

Promise<AiMessage[]> — an array of messages with role and content fields, directly assignable to AI SDK's ModelMessage[].

  • Role mappingauthor.isMe === true maps to "assistant", all others to "user"
  • Filtering — Messages with empty or whitespace-only text are removed
  • Sorting — Messages are sorted chronologically (oldest first) by metadata.dateSent
  • Links — Link metadata (URL, title, description, site name) is appended to message content. Embedded message links are labeled as [Embedded message: ...]
  • Attachments — Images and text files (JSON, XML, YAML, etc.) are included as multipart content using fetchData(). Video and audio attachments trigger onUnsupportedAttachment
type AiMessage = AiUserMessage | AiAssistantMessage;

interface AiUserMessage {
  role: "user";
  content: string | AiMessagePart[];
}

interface AiAssistantMessage {
  role: "assistant";
  content: string;
}

User messages have multipart content when attachments are present:

type AiMessagePart = AiTextPart | AiImagePart | AiFilePart;

interface AiTextPart {
  type: "text";
  text: string;
}

interface AiImagePart {
  type: "image";
  image: DataContent | URL;
  mediaType?: string;
}

interface AiFilePart {
  type: "file";
  data: DataContent | URL;
  filename?: string;
  mediaType: string;
}

Multi-user context

Prefix each user message with their username so the AI model can distinguish speakers:

const history = await toAiMessages(result.messages, { includeNames: true });
// [{ role: "user", content: "[alice]: Hello" },
//  { role: "assistant", content: "Hi there!" },
//  { role: "user", content: "[bob]: Thanks" }]

Transforming messages

Replace raw user IDs with readable names:

const history = await toAiMessages(result.messages, {
  transformMessage: (aiMessage) => {
    if (typeof aiMessage.content === "string") {
      return {
        ...aiMessage,
        content: aiMessage.content.replace(/<@U123>/g, "@VercelBot"),
      };
    }
    return aiMessage;
  },
});

Filtering messages

Skip messages from a specific user:

const history = await toAiMessages(result.messages, {
  transformMessage: (aiMessage, source) => {
    if (source.author.userId === "U_NOISY_BOT") return null;
    return aiMessage;
  },
});

Handling unsupported attachments

const history = await toAiMessages(result.messages, {
  onUnsupportedAttachment: (attachment, message) => {
    logger.warn(`Skipped ${attachment.type} attachment in message ${message.id}`);
  },
});
TypeMIME typesIncluded as
imageAny image MIME typeFilePart with base64 data
filetext/*, application/json, application/xml, application/javascript, application/typescript, application/yaml, application/tomlFilePart with base64 data
videoAnySkipped (triggers onUnsupportedAttachment)
audioAnySkipped (triggers onUnsupportedAttachment)
fileOther (e.g. application/pdf)Silently skipped

Attachments require fetchData() to be available on the attachment object. Attachments without fetchData() are silently skipped.