Skip to content

improvement: updated ai21 integration #1228

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 2 commits into
base: main
Choose a base branch
from

Conversation

Utkarsh-0304
Copy link
Contributor

@Utkarsh-0304 Utkarsh-0304 commented Jul 17, 2025

Description

Updated Chat Completions API endpoint, and also modified API configs and response interface

Motivation

This updates the existing outdated ai21 integration and fixes #1215

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Related Issues

Fixes #1215

Copy link

matter-code-review bot commented Jul 17, 2025

Code Quality bug detected new feature

Description

Summary By MatterAI MatterAI logo

🔄 What Changed

This Pull Request updates the integration with the AI21 Chat Completions API. Key changes include:

  • Removal of the SYSTEM_MESSAGE_ROLES import, indicating a shift in how system messages are handled.
  • Refactoring of the messages parameter transformation to support multi-modal content, extracting textContent from array-based message content.
  • Introduction of a new documents parameter transformation, which extracts non-textual content from messages (e.g., images, files) and sends them as separate documents to the AI21 API.
  • Removal of the documents parameter from the top-level AI21ChatCompleteConfig as its logic is now handled within the transform function.

🔍 Impact of the Change

These changes enable the system to send more complex, multi-modal chat messages to the AI21 API, including both text and non-textual content. This aligns the integration with potentially new capabilities of the AI21 API, allowing for richer interactions and data handling.

📁 Total Files Changed

  • src/providers/ai21/chatComplete.ts: Modified the message and document processing logic for AI21 chat completions.

🧪 Test Added

N/A (No explicit tests mentioned in PR description.)

🔒Security Vulnerabilities

No new security vulnerabilities detected.

Motivation

Updated Chat Completions API endpoint, and also modified API configs and response interface.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)

How Has This Been Tested?

  • Unit Tests
  • Integration Tests
  • Manual Testing

Screenshots (if applicable)

N/A

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Tip

Quality Recommendations

  1. The current textContent extraction for multi-modal messages only captures the last text part. It should concatenate all text parts to ensure complete message content is sent.

  2. The logic for the documents parameter is inverted. If documents are present, it sends undefined, and if empty, it sends []. This should be corrected to send the documents when present and undefined (or omit the parameter) when empty, aligning with typical API expectations.

  3. Consider adding unit tests for the new message and document transformation logic to ensure all edge cases (e.g., empty content, mixed content types, no documents) are handled correctly.

  4. Add comments or update existing documentation for the AI21ChatCompleteConfig to explain the new messages and documents transformation logic, especially regarding multi-modal content handling.

Tanka Poem ♫

New data flows,
Messages now multi-modal,
AI's mind expands.
Documents, a fresh new path,
Knowledge blossoms, code refined. 🚀

Sequence Diagram

sequenceDiagram
    actor Client
    Client->>AI21ChatCompleteConfig: Call chatComplete with Params
    AI21ChatCompleteConfig->>messages.transform: Process params.messages
    messages.transform-->>AI21ChatCompleteConfig: Returns transformed messages (role, content)
    AI21ChatCompleteConfig->>documents.transform: Process params.messages for documents
    documents.transform->>documents.transform: Extract non-text content (c.type !== 'text')
    documents.transform-->>AI21ChatCompleteConfig: Returns documents array or undefined
    AI21ChatCompleteConfig->>AI21 API: Send transformed messages and documents
    AI21 API-->>AI21ChatCompleteConfig: ChatCompletionResponse | ErrorResponse
    AI21ChatCompleteConfig-->>Client: Return response
Loading

max_tokens: {
param: 'maxTokens',
default: 16,
documents: {
Copy link
Collaborator

Choose a reason for hiding this comment

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

you would need to handle mapping from user message content parts containing files/images or audio (whichever is supported by ai21) to the documents field

Image

so for the fixed mapping you need to move this inside the messages object like this

  messages: [{param: 'messages'...}, {param: 'documents' ...}]

Copy link
Collaborator

Choose a reason for hiding this comment

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

in the new ai21 spec, there is no separate field for 'system', so you can remove this code block

    {
      param: 'system',
      required: false,
      transform: (params: Params) => {
        if (
          params.messages?.[0]?.role &&
          SYSTEM_MESSAGE_ROLES.includes(params.messages?.[0]?.role)
        ) {
          return params.messages?.[0].content;
        }
      },
    },

Copy link
Collaborator

Choose a reason for hiding this comment

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

also remove this chunk from the messages object

if (
          params.messages?.[0]?.role &&
          SYSTEM_MESSAGE_ROLES.includes(params.messages?.[0]?.role)
        ) {
          inputMessages = params.messages.slice(1);

Copy link
Collaborator

Choose a reason for hiding this comment

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

you will also need to map the text content part into the user and system messages from openai to ai21 format
in openai, a user can send user message like this

{
"role": "user",
"content" : [{"type": "text", "text": "abc"}, ..multiple parts]
}

but ai21 only accepts a string, so you will need to handle that

Copy link
Contributor Author

@Utkarsh-0304 Utkarsh-0304 Aug 5, 2025

Choose a reason for hiding this comment

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

Thanks for your review! I'm working on the requested changes and will update the pull request soon.

Also, could you please send me the link for the above-attached image for reference? As in the official API reference for AI21 Chat completions, parameters are defined similarly to the ones in my commit.

Copy link

Important

PR Review Skipped

PR review skipped as per the configuration setting. Run a manually review by commenting /matter review

💡Tips to use Matter AI

Command List

  • /matter summary: Generate AI Summary for the PR
  • /matter review: Generate AI Reviews for the latest commit in the PR
  • /matter review-full: Generate AI Reviews for the complete PR
  • /matter release-notes: Generate AI release-notes for the PR
  • /matter : Chat with your PR with Matter AI Agent
  • /matter remember : Generate AI memories for the PR
  • /matter explain: Get an explanation of the PR
  • /matter help: Show the list of available commands and documentation
  • Need help? Join our Discord server: https://discord.gg/fJU5DvanU3

@Utkarsh-0304 Utkarsh-0304 requested a review from narengogi August 6, 2025 07:36
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.

Update ai21 integration
2 participants