assistant-ui icon indicating copy to clipboard operation
assistant-ui copied to clipboard

Add 'data' type to ThreadMessageLike

Open brandonbevans opened this issue 10 months ago β€’ 6 comments

For Vercel AI SDK compatibility with messages, ThreadMessageLike needs to be able to accept a 'data' role as well, otherweise we get a type error like the following: Screenshot 2025-02-12 at 11 12 10β€―AM

Where "Message[]" is from the "ai" package

import { AssistantRuntimeProvider } from '@assistant-ui/react';
import { useChatRuntime } from '@assistant-ui/react-ai-sdk';
import { Message } from 'ai';
export function MyRuntimeProvider({
  children,
  chatId,
  namespace,
  messages
}: Readonly<{
  children: React.ReactNode;
  messages: Message[];
}>) {
  // const initialMessages = messages.map((msg) => ({
  //   role: msg.role as 'system' | 'user' | 'assistant',
  //   content: msg.content,
  //   createdAt: msg.createdAt
  // }));

  const runtime = useChatRuntime({
    api: '/api/chat',
    initialMessages: messages
  });
  return (
    <AssistantRuntimeProvider runtime={runtime}>
      {children}
    </AssistantRuntimeProvider>
  );
}

Currently for this code to work, the commented out code is required, because MessageThreadLike doesn't allow for the role: 'data' that is present in the Message type from the "ai" package

brandonbevans avatar Feb 12 '25 19:02 brandonbevans

@brandonbevans is attempting to deploy a commit to the assistant-ui Team on Vercel.

A member of the Team first needs to authorize it.

vercel[bot] avatar Feb 12 '25 19:02 vercel[bot]

πŸ“ Documentation updates detected! You can review documentation updates here

promptless[bot] avatar Feb 12 '25 19:02 promptless[bot]

Pull request summary

  • Added new role "data" to the ThreadMessageLike type to accommodate additional message types.
  • Updated the MessageRole type to include "data" for consistency across message handling.
  • Reorganized import statements in ThreadMessageLike.tsx and AssistantTypes.ts for clarity and to remove unused imports.
  • Ensured that the new role is reflected in both the message type definitions and the associated content parts.

trag-bot[bot] avatar Feb 12 '25 19:02 trag-bot[bot]

Walkthrough

The changes extend the available message roles by adding a new role, "data", to both the ThreadMessageLike type and the MessageRole type. In the ThreadMessageLike file, the content property has been updated to include additional content elements, specifically FileContentPart and CompleteAttachment, while adjustments in the conversion function accommodate these new types and enforce role-specific error handling rules. In the AssistantTypes file, the import statements have been reorganized and the MessageRole type declaration has been updated to include the new role. These modifications update type definitions and associated logic for processing message content and roles across the application.

[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

πŸ”§ ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/react/src/runtimes/external-store/ThreadMessageLike.tsx

Oops! Something went wrong! :(

ESLint: 9.20.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js. If you are using a .eslintrc.* file, please follow the migration guide to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by https://eslint.org/chat/help to chat with the team.

packages/react/src/types/AssistantTypes.ts

Oops! Something went wrong! :(

ESLint: 9.20.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js. If you are using a .eslintrc.* file, please follow the migration guide to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by https://eslint.org/chat/help to chat with the team.


πŸ“œ Recent review details

Configuration used: CodeRabbit UI Review profile: ASSERTIVE Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 4370db53495f8c00f6a39202a966234433cfa6b6 and bae2c4893256205e02395b8ea2527beab4769c74.

πŸ“’ Files selected for processing (2)
  • packages/react/src/runtimes/external-store/ThreadMessageLike.tsx (2 hunks)
  • packages/react/src/types/AssistantTypes.ts (1 hunks)
πŸ”‡ Additional comments (5)
packages/react/src/runtimes/external-store/ThreadMessageLike.tsx (3)

24-59: LGTM! The ThreadMessageLike type has been updated to support the 'data' role.

The type definition correctly includes the new role while maintaining the existing structure.


86-185: :warning: Potential issue

Add case for 'data' role in switch statement.

The switch statement doesn't handle the 'data' role, causing runtime errors when processing data messages. This is a critical issue that needs to be addressed.

Add a case for the 'data' role before the default case. Here's a suggested implementation:

 switch (role) {
   case "assistant":
     // ... existing assistant case
   case "user":
     // ... existing user case
   case "system":
     // ... existing system case
+  case "data":
+    return {
+      ...common,
+      role,
+      content: content.map((part): ThreadUserContentPart => {
+        const type = part.type;
+        switch (type) {
+          case "text":
+          case "file":
+            return part;
+          default: {
+            const unhandledType: "tool-call" | "reasoning" | "image" | "audio" | "ui" = type;
+            throw new Error(
+              `Unsupported data content part type: ${unhandledType}`,
+            );
+          }
+        }
+      }),
+      metadata: {
+        custom: metadata?.custom ?? {},
+      },
+    };
   default: {
     // ... existing default case
   }
 }
🧰 Tools
πŸͺ› Biome (1.9.4)

[error] 107-107: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 114-114: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 167-167: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)


77-84: Define constraints for 'data' role.

The error handling section defines constraints for attachments, status, and metadata.steps. Consider if similar constraints should apply to the 'data' role.

Please verify:

  1. Should attachments be allowed for data messages?
  2. Should status be supported for data messages?
  3. Should metadata.steps be supported for data messages?
packages/react/src/types/AssistantTypes.ts (2)

8-8: LGTM! MessageRole type updated to include 'data' role.

The type definition correctly includes the new role.


233-234: :warning: Potential issue

Add ThreadDataMessage type and update ThreadMessage union.

The 'data' role is added to MessageRole but there's no corresponding message type definition (like ThreadDataMessage) or handling in ThreadMessage union type.

Add the following type definitions:

+export type ThreadDataMessage = MessageCommonProps & {
+  readonly role: "data";
+  readonly content: readonly (TextContentPart | FileContentPart)[];
+  readonly metadata: {
+    readonly custom: Record<string, unknown>;
+  };
+};

-export type ThreadMessage = BaseThreadMessage &
-  (ThreadSystemMessage | ThreadUserMessage | ThreadAssistantMessage);
+export type ThreadMessage = BaseThreadMessage &
+  (ThreadSystemMessage | ThreadUserMessage | ThreadAssistantMessage | ThreadDataMessage);
✨ Finishing Touches
  • [ ] πŸ“ Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❀️ Share
πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot] avatar Feb 12 '25 19:02 coderabbitai[bot]

Hey @Yonom I would love to add this change but the bots bring up a good point about not propogating this "data" content type through the code. It seems like it may be a bit beyond me.

brandonbevans avatar Feb 15 '25 21:02 brandonbevans

Hmm - ThreadMessageLike is not intended to be compatible with AI SDK's message type... it just happens to overlap enough for some cases

nevertheless - especially when using useChatRuntime, I'd want to let you pass in AI SDK UI message objects to initialMessages - so the solution is probably to add a ~convertUIMessage helper function which converts messages to ThreadMessage - and then have useChatRuntime support it

Let me investigate this a bit more and get back to you

Yonom avatar Feb 15 '25 23:02 Yonom