Skip to content
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

Add embedding model setting #100

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

Conversation

Royal-lobster
Copy link
Owner

@Royal-lobster Royal-lobster commented Dec 16, 2024

Related to #99


For more details, open the Copilot Workspace session.

Summary by CodeRabbit

  • New Features

    • Introduced a new section in Chat Settings for selecting an "Embedding Model."
    • Users can now choose from available embedding models in the settings interface.
  • Bug Fixes

    • Enhanced the configurability of the embedding model in the vector store retrieval process.
  • Documentation

    • Updated type definitions to include a new property for embeddingModel in the settings configuration.

Copy link

stackblitz bot commented Dec 16, 2024

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link

changeset-bot bot commented Dec 16, 2024

⚠️ No Changeset found

Latest commit: bc7a92f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

The pull request introduces an enhancement to the chat settings by adding support for selecting an embedding model. This modification spans across three files: ChatSettings.tsx, settings/index.ts, and getMatchedContent.ts. The changes enable users to choose a specific embedding model for vector operations, with a default fallback to 'text-embedding-ada-002'. The implementation maintains the existing settings structure while providing more flexibility in configuration.

Changes

File Change Summary
src/components/Settings/Sections/ChatSettings.tsx Added new FieldWrapper for embedding model selection with dropdown
src/config/settings/index.ts Introduced embeddingModel as a nullable string in Settings type and defaultSettings
src/lib/getMatchedContent.ts Updated getContextVectorStore to dynamically use embedding model from settings

Sequence Diagram

sequenceDiagram
    participant User
    participant ChatSettings
    participant Settings
    participant VectorStore
    
    User->>ChatSettings: Select Embedding Model
    ChatSettings->>Settings: Update embeddingModel
    Settings-->>VectorStore: Provide Selected Model
    VectorStore->>VectorStore: Initialize with Model
Loading

Poem

🐰 A rabbit's tale of models bright,
Embedding choices now in sight!
From settings new, a dropdown gleams,
Configuring AI's vector dreams 🌟
Flexibility hops into the code! 🚀

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request.


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.

@Royal-lobster Royal-lobster marked this pull request as draft December 16, 2024 04:06
Copy link
Contributor

@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: 2

🧹 Nitpick comments (1)
src/components/Settings/Sections/ChatSettings.tsx (1)

Line range hint 1-188: Consider improving settings management architecture

Suggestions for better architecture:

  1. Create a centralized settings validation layer
  2. Use TypeScript enums or constants for valid model types
  3. Separate chat and embedding model management
  4. Add error boundaries for settings-related failures

This will improve type safety and maintainability.

Example implementation:

// types/models.ts
export enum EmbeddingModel {
  Ada002 = 'text-embedding-ada-002',
  // Add other models
}

// validation/settings.ts
export function validateSettings(settings: Settings): ValidationResult {
  return {
    isValid: true,
    errors: [],
    // Add validation logic
  }
}

// hooks/useEmbeddingModels.ts
export function useEmbeddingModels() {
  return {
    models: Object.values(EmbeddingModel).map(id => ({
      id,
      name: formatModelName(id)
    })),
    // Add other embedding-specific logic
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 838475e and bc7a92f.

📒 Files selected for processing (3)
  • src/components/Settings/Sections/ChatSettings.tsx (1 hunks)
  • src/config/settings/index.ts (2 hunks)
  • src/lib/getMatchedContent.ts (2 hunks)
🔇 Additional comments (1)
src/config/settings/index.ts (1)

27-27: LGTM! Type definition and default value are consistent

The embeddingModel field follows the same pattern as other similar fields in the settings, maintaining type consistency.

Also applies to: 46-46

@@ -3,6 +3,7 @@ import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter'
import { MemoryVectorStore } from 'langchain/vectorstores/memory'
import { createSHA256Hash } from './createSHA256Hash'
import { readStorage, setStorage } from '../hooks/useStorage'
import { useSettings } from '../hooks/useSettings'
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Invalid React hooks usage in non-React context

The useSettings hook is being used incorrectly:

  1. React hooks can only be used inside React components
  2. Hooks cannot be called inside regular functions like getContextVectorStore

This will cause runtime errors.

Consider refactoring to pass the embedding model as a parameter:

-import { useSettings } from '../hooks/useSettings'

 export const getMatchedContent = async (
   query: string,
   context: string,
   apiKey: string,
   baseURL: string,
+  embeddingModel?: string,
 ) => {
-  const vectorStore = await getContextVectorStore(context, apiKey, baseURL)
+  const vectorStore = await getContextVectorStore(context, apiKey, baseURL, embeddingModel)
   const retriever = vectorStore.asRetriever()
   const relevantDocs = await retriever.getRelevantDocuments(query)
   return relevantDocs.map((doc) => doc.pageContent).join('\n')
 }

 const getContextVectorStore = async (
   context: string,
   apiKey: string,
   baseURL: string,
+  embeddingModel?: string,
 ) => {
-  const [settings] = useSettings()
-  const embeddingModel = settings.chat.embeddingModel || 'text-embedding-ada-002'
+  const modelName = embeddingModel || 'text-embedding-ada-002'
   const embeddings = new OpenAIEmbeddings({
     openAIApiKey: apiKey,
-    modelName: embeddingModel,
+    modelName,
     configuration: {
       baseURL: baseURL,
     },
   })

Also applies to: 25-26, 29-29

Comment on lines +164 to +188
<FieldWrapper
title="Embedding Model"
description="Choose between available embedding models"
row={true}
>
<select
value={chatSettings.embeddingModel || ''}
className="input cdx-w-44"
onChange={(e) => {
setSettings({
...settings,
chat: {
...chatSettings,
embeddingModel: e.target.value,
},
})
}}
>
{models.map((model) => (
<option key={model.id} value={model.id}>
{model.id}
</option>
))}
</select>
</FieldWrapper>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Incorrect reuse of chat models for embeddings

The implementation has several issues:

  1. Chat models (like GPT-3.5, GPT-4) are different from embedding models (like text-embedding-ada-002)
  2. No validation to ensure selected model supports embeddings
  3. UI doesn't distinguish between chat and embedding models

This could lead to runtime errors if incompatible models are selected.

Consider maintaining a separate list of embedding models:

+const EMBEDDING_MODELS = [
+  { id: 'text-embedding-ada-002', name: 'Ada 002' },
+  // Add other supported embedding models
+]

 <FieldWrapper
   title="Embedding Model"
   description="Choose between available embedding models"
   row={true}
 >
   <select
     value={chatSettings.embeddingModel || ''}
     className="input cdx-w-44"
     onChange={(e) => {
       setSettings({
         ...settings,
         chat: {
           ...chatSettings,
           embeddingModel: e.target.value,
         },
       })
     }}
   >
-    {models.map((model) => (
+    {EMBEDDING_MODELS.map((model) => (
       <option key={model.id} value={model.id}>
-        {model.id}
+        {model.name}
       </option>
     ))}
   </select>
 </FieldWrapper>

Committable suggestion skipped: line range outside the PR's diff.

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

Successfully merging this pull request may close these issues.

1 participant