Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Add 'data' type to ThreadMessageLike #1601

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

brandonbevans
Copy link

@brandonbevans brandonbevans commented Feb 12, 2025

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

Copy link

vercel bot commented Feb 12, 2025

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

A member of the Team first needs to authorize it.

Comment on lines 24 to +25
export type ThreadMessageLike = {
readonly role: "assistant" | "user" | "system";
readonly role: "assistant" | "user" | "system" | "data";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default case in fromThreadMessageLike does not handle the new data role, causing runtime errors when processing data messages

📝 Committable Code Suggestion

‼️ Ensure you review the code suggestion before committing it to the branch. Make sure it replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export type ThreadMessageLike = {
readonly role: "assistant" | "user" | "system";
readonly role: "assistant" | "user" | "system" | "data";
export type ThreadMessageLike = {
readonly role: "assistant" | "user" | "system" | "data";

Copy link
Contributor

promptless bot commented Feb 12, 2025

📝 Documentation updates detected! You can review documentation updates here

@@ -22,7 +22,7 @@ import {
import { parsePartialJson } from "../../utils/json/parse-partial-json";

export type ThreadMessageLike = {
readonly role: "assistant" | "user" | "system";
readonly role: "assistant" | "user" | "system" | "data";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 'data' role is added to the type but not handled in the switch statement of fromThreadMessageLike function, which will cause the 'unsupportedRole' error case to be triggered.


export type MessageRole = "user" | "assistant" | "system";
export type MessageRole = "user" | "assistant" | "system" | "data";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@@ -22,7 +22,7 @@ import {
import { parsePartialJson } from "../../utils/json/parse-partial-json";

export type ThreadMessageLike = {
readonly role: "assistant" | "user" | "system";
readonly role: "assistant" | "user" | "system" | "data";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding 'data' to ThreadMessageLike is not enough; the conversion function (fromThreadMessageLike) doesn’t handle role 'data', causing the default case to throw an error. Consider adding a case for 'data' or handling it appropriately.

Copy link

trag-bot bot commented Feb 12, 2025

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.

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Summary

Added 'data' role to ThreadMessageLike and MessageRole types to support Vercel AI SDK compatibility, though implementation is incomplete.

  • Missing implementation for 'data' role handling in fromThreadMessageLike function in /packages/react/src/runtimes/external-store/ThreadMessageLike.tsx
  • Need corresponding ThreadDataMessage type definition in /packages/react/src/types/AssistantTypes.ts
  • CoreMessage and ThreadMessage unions need to be updated to include the new 'data' role type
  • Type inconsistency between MessageRole and message handling implementations could cause runtime errors

💡 (1/5) You can manually trigger the bot by mentioning @greptileai in a comment!

2 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings | Greptile

Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

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 4370db5 and bae2c48.

📒 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: ⚠️ 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: ⚠️ 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.

@brandonbevans
Copy link
Author

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.

@Yonom
Copy link
Member

Yonom commented Feb 15, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants