Skip to content

feat: use latest chat UI #418

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

Merged
merged 10 commits into from
Nov 14, 2024
Merged

feat: use latest chat UI #418

merged 10 commits into from
Nov 14, 2024

Conversation

thucpn
Copy link
Collaborator

@thucpn thucpn commented Nov 11, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced chat user interface for improved interaction.
    • Updated document preview handling in the chat input component.
    • Added dynamic loading state and message appending capabilities in chat message content.
  • Bug Fixes

    • Adjusted key assignment in chat messages for better performance.
  • Refactor

    • Improved type safety and clarity in message handling within chat tools.
    • Updated dependency @llamaindex/chat-ui to the latest version for enhanced functionality.
    • Removed unnecessary CSS import to streamline layout.

Copy link

changeset-bot bot commented Nov 11, 2024

🦋 Changeset detected

Latest commit: 51ee45a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
create-llama Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

coderabbitai bot commented Nov 11, 2024

Walkthrough

The pull request introduces a new patch titled "create-llama" that updates the chat user interface (UI) components. Key changes include replacing the DocumentPreview component with DocumentInfo in the chat input, modifying how message keys are assigned in chat messages, updating type handling in the chat tools component, and enhancing the ChatMessageContent component with new loading and message appending functionalities. These updates aim to improve the overall chat interface while maintaining the core logic.

Changes

File Path Change Summary
.changeset/wet-pears-matter.md New patch added: "create-llama"
templates/types/streaming/nextjs/app/components/ui/chat/chat-input.tsx Replaced DocumentPreview with DocumentInfo, updated prop structure for DocumentInfo, added className prop for styling.
templates/types/streaming/nextjs/app/components/ui/chat/chat-messages.tsx Changed key prop assignment from message.id to index in messages.map.
templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx Introduced getArtifactVersion function, updated ChatTools to use artifactVersion, modified ToolAnnotations to pass the new version.
templates/types/streaming/nextjs/app/components/ui/chat/chat-message-content.tsx Added useChatUI hook, destructured isLoading and append, and updated return statement to include these props in ChatMessage.Content.
templates/types/streaming/nextjs/package.json Updated dependency version of @llamaindex/chat-ui from 0.0.5 to 0.0.7.
templates/types/streaming/nextjs/app/layout.tsx Removed import statement for ./markdown.css.
templates/types/streaming/nextjs/app/markdown.css Deleted file containing styles for rendering chat message markdown.

Possibly related PRs

Suggested reviewers

  • marcusschiesser

Poem

🐰 In the meadow where chats do bloom,
A llama's grace dispels the gloom.
With tools and messages, all in line,
Our chat's a garden, oh so fine!
DocumentInfo takes the stage,
As we hop along, page by page! 🌼


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ea5c28e and 51ee45a.

📒 Files selected for processing (2)
  • templates/types/streaming/nextjs/app/layout.tsx (0 hunks)
  • templates/types/streaming/nextjs/app/markdown.css (0 hunks)
💤 Files with no reviewable changes (2)
  • templates/types/streaming/nextjs/app/layout.tsx
  • templates/types/streaming/nextjs/app/markdown.css

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 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.

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (3)
templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (3)

3-3: LGTM! Consider adding type documentation.

The distinction between Message types through aliasing improves type safety. However, it would be helpful to add a brief comment explaining the difference between these types for future maintainers.

Add a comment above the imports:

// Message from chat-ui is used for component props
// AiMessage from ai library is used for message processing

Also applies to: 8-8


70-70: Consider a more type-safe approach for version mapping.

The type assertion (message as AiMessage).id follows the same pattern as above, but we could make this more robust.

Consider creating a type guard:

function isAiMessage(message: Message | AiMessage): message is AiMessage {
  return 'id' in message;
}

// Then use it like:
version={isAiMessage(message) ? artifactVersionMap.get(message.id) : undefined}

Line range hint 1-90: Consider architectural improvements for better maintainability.

A few suggestions to enhance the codebase:

  1. Extract the version mapping logic into a custom hook (e.g., useArtifactVersions)
  2. Consider implementing a registry pattern for tool renderers instead of switch-case
  3. Add documentation for adding new tool renderers (referenced in TODO)

Example hook extraction:

function useArtifactVersions(messages: Message[]) {
  return useMemo(() => {
    const map = new Map<string, number>();
    let versionIndex = 1;
    
    (messages as AiMessage[]).forEach((m) => {
      // ... version mapping logic
    });
    
    return map;
  }, [messages]);
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2b712ce and 07e19ae.

📒 Files selected for processing (4)
  • .changeset/wet-pears-matter.md (1 hunks)
  • templates/types/streaming/nextjs/app/components/ui/chat/chat-input.tsx (2 hunks)
  • templates/types/streaming/nextjs/app/components/ui/chat/chat-messages.tsx (1 hunks)
  • templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/wet-pears-matter.md
🧰 Additional context used
📓 Path-based instructions (3)
templates/types/streaming/nextjs/app/components/ui/chat/chat-input.tsx (1)

Pattern templates/**: For files under the templates folder, do not report 'Missing Dependencies Detected' errors.

templates/types/streaming/nextjs/app/components/ui/chat/chat-messages.tsx (1)

Pattern templates/**: For files under the templates folder, do not report 'Missing Dependencies Detected' errors.

templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (1)

Pattern templates/**: For files under the templates folder, do not report 'Missing Dependencies Detected' errors.

🔇 Additional comments (3)
templates/types/streaming/nextjs/app/components/ui/chat/chat-input.tsx (2)

4-4: LGTM: Import statement updated correctly

The replacement of DocumentPreview with DocumentInfo aligns with the latest chat UI requirements.


59-62: Verify the empty sources array usage

The sources array is being initialized as empty. Please verify if this is intentional or if document sources should be populated from the file metadata.

Let's check the DocumentInfo component's usage in other parts of the codebase:

✅ Verification successful

Empty sources array is intentional in this context

The empty sources array is correct in this usage. The DocumentInfo component is being used from @llamaindex/chat-ui/widgets (an external package) in the file upload preview context, where document sources are not yet available. This matches the pattern seen in other parts of the codebase where sources are initialized as empty arrays and populated later during processing.

Key evidence:

  • Component is imported from external package @llamaindex/chat-ui/widgets
  • Recent changelog entry indicates work on URL handling: "DocumentInfo working with relative URLs"
  • Usage is consistent with document preview before processing, where sources wouldn't be available yet
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other DocumentInfo usages to verify if sources are typically populated
rg -A 3 "DocumentInfo.*sources" 

Length of output: 33


Script:

#!/bin/bash
# Let's first find all DocumentInfo usages
rg -A 5 "<DocumentInfo"

# Also check the DocumentInfo component implementation
fd "DocumentInfo" --exec cat {}

Length of output: 705


Script:

#!/bin/bash
# Let's find the DocumentInfo component definition
fd -e tsx -e ts -e jsx -e js --exec ast-grep --pattern 'interface DocumentInfoProps {
  $$$
}'

# Also search for any type definitions related to document sources
rg -A 5 "sources.*\[\]"

Length of output: 2998


Script:

#!/bin/bash
# Let's find the actual DocumentInfo component implementation
fd -e tsx -e ts -e jsx -e js --exec ast-grep --pattern 'const DocumentInfo = ({$$$}: DocumentInfoProps) => {
  $$$
}'

# Also search for any documentation or comments about DocumentInfo
rg -B 2 -A 2 "DocumentInfo"

Length of output: 1490

templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (1)

30-30: Verify type casting safety.

The type assertion messages as AiMessage[] assumes all messages are AI messages. This could lead to runtime errors if the assumption doesn't hold.

Let's verify this assumption by checking the message types in the codebase:

✅ Verification successful

Type casting is safe in this context

The type assertion messages as AiMessage[] is safe because:

  1. The component uses both useChatUI() from "@llamaindex/chat-ui" and imports Message as AiMessage from "ai"
  2. The cast is only used to iterate messages for building an artifact version map
  3. The code defensively checks for optional chaining (m.annotations?.forEach) and type guards (typeof annotation === "object") after the cast
  4. Even if a message isn't an AiMessage, the code won't break as it only accesses common properties (id, annotations) that exist on both types
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how messages are created/used to verify type safety
# Look for message creation/manipulation patterns
rg -A 3 "messages\s*=|messages\.push|messages\[" --type typescript

# Look for useChatUI usage to understand message types
rg -A 3 "useChatUI" --type typescript

Length of output: 176


Script:

#!/bin/bash
# Search for message type definitions and usage
rg -t ts -t tsx "messages\s*=|messages\.push|messages\["

# Look for useChatUI hook usage
rg -t ts -t tsx "useChatUI"

# Search for AiMessage type definition and usage
rg -t ts -t tsx "AiMessage"

# Look at the specific component's full implementation
cat "templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx"

Length of output: 2780

@thucpn
Copy link
Collaborator Author

thucpn commented Nov 11, 2024

TODO: use latest chat-ui

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5bad605 and a3db073.

📒 Files selected for processing (1)
  • templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (1)

Pattern templates/**: For files under the templates folder, do not report 'Missing Dependencies Detected' errors.

🔇 Additional comments (2)
templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (2)

31-37: LGTM! Clean implementation of version handling.

The ChatTools component has been properly updated to handle the artifact version, with appropriate TypeScript types and clean prop passing.

Also applies to: 59-59


13-19: Consider addressing the TODO comment with a more robust solution.

The current implementation of artifact version tracking is acknowledged as a temporary solution. Consider moving the version tracking to the tool call itself and storing it in CodeArtifact for better maintainability.

The useMemo optimization is well implemented, but this logic could be simplified if the version was stored directly in the artifact data.

Let's check if there are other similar patterns in the codebase:

✅ Verification successful

Verified: No other instances of artifact version tracking patterns found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar version tracking patterns
rg -g '*.{ts,tsx}' "getArtifactVersion|artifactVersion" --type-add 'tsx:*.{ts,tsx}'

Length of output: 902

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (2)

13-14: Address technical debt in artifact versioning.

The TODO comment indicates that the current versioning approach is a temporary solution. Consider implementing a more robust solution by storing the version in CodeArtifact directly.


81-101: Enhance robustness and performance of version calculation.

The version calculation logic has several areas for improvement:

  1. No validation for unique message IDs
  2. Repeated type checking for message ID
  3. Potential performance impact with large message lists

Consider this improved implementation:

 function getArtifactVersion(
   messages: Message[],
   message: Message,
 ): number | undefined {
   const messageId = "id" in message ? message.id : undefined;
   if (!messageId) return undefined;
+
+  // Create a Set of message IDs to ensure uniqueness
+  const messageIds = new Set(messages.filter(m => "id" in m).map(m => m.id));
+  if (!messageIds.has(messageId)) return undefined;
+
   let versionIndex = 1;
   for (const m of messages) {
+    if (!("id" in m)) continue;
+
     const toolData = m.annotations
       ? (getAnnotationData(m.annotations, "tools") as unknown as ToolData[])
       : null;

     if (toolData?.some((t) => t.toolCall.name === "artifact")) {
-      if ("id" in m && m.id === messageId) {
+      if (m.id === messageId) {
         return versionIndex;
       }
       versionIndex++;
     }
   }
   return undefined;
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a3db073 and 41cec08.

📒 Files selected for processing (1)
  • templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (1)

Pattern templates/**: For files under the templates folder, do not report 'Missing Dependencies Detected' errors.

🔇 Additional comments (1)
templates/types/streaming/nextjs/app/components/ui/chat/tools/chat-tools.tsx (1)

31-37: LGTM! Clean implementation of artifact versioning.

The changes to ChatTools component are well-structured with proper typing and the version is correctly passed to the Artifact component.

Also applies to: 59-59

Comment on lines 22 to 24
const toolData = annotations
? (getAnnotationData(annotations, "tools") as unknown as ToolData[])
: null;
Copy link

@coderabbitai coderabbitai bot Nov 13, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety in toolData casting.

The double type casting through unknown is a code smell and could lead to runtime errors.

Consider this safer approach:

-const toolData = annotations
-  ? (getAnnotationData(annotations, "tools") as unknown as ToolData[])
-  : null;
+const toolData = annotations
+  ? getAnnotationData<ToolData[]>(annotations, "tools")
+  : null;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const toolData = annotations
? (getAnnotationData(annotations, "tools") as unknown as ToolData[])
: null;
const toolData = annotations
? getAnnotationData<ToolData[]>(annotations, "tools")
: null;

Copy link
Collaborator

Choose a reason for hiding this comment

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

@thucpn I think that would also work

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, this requires typing update in getAnnotationData function of chat-ui

@marcusschiesser marcusschiesser merged commit 6925676 into main Nov 14, 2024
46 checks passed
@marcusschiesser marcusschiesser deleted the feat/use-latest-chat-ui branch November 14, 2024 03:48
@coderabbitai coderabbitai bot mentioned this pull request Nov 29, 2024
@coderabbitai coderabbitai bot mentioned this pull request Dec 27, 2024
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