utils.ts
Overview
The utils.ts file contains a set of utility functions primarily designed to support operations related to conversations, messages, and references in a chat application context. These utilities facilitate tasks such as validating conversation IDs, extracting document IDs from conversation references, building message reference objects, and performing text replacements for legacy indexing formats.
This file acts as a helper layer, simplifying and standardizing common data manipulations and checks that interact with conversation and message data structures used across the chat system.
Functions
isConversationIdExist
export const isConversationIdExist = (conversationId: string) => boolean;
Purpose:
Checks whether a given conversation ID is valid and exists, i.e., it is neither an empty string nor a predefined empty conversation ID constant.
Parameters:
conversationId(string): The conversation ID to validate.
Returns:boolean — true if the conversation ID is valid and exists; false otherwise.
Usage example:
if (isConversationIdExist(convoId)) {
// proceed with conversation-related logic
}
getDocumentIdsFromConversionReference
export const getDocumentIdsFromConversionReference = (data: IConversation) => string;
Purpose:
Extracts and concatenates unique document IDs from a conversation's reference data.
Parameters:
data(IConversation): A conversation object containing an array of references (reference), each having aggregated document info.
Returns:string — A comma-separated string of unique document IDs found in the conversation references.
Detailed behaviour:
Iterates over all references in the conversation.
For each reference, it accesses
doc_aggs(document aggregations).Extracts
doc_idfrom each aggregation.Collects unique document IDs (avoiding duplicates).
Joins them into a single string separated by commas.
Usage example:
const docIds = getDocumentIdsFromConversionReference(conversation);
console.log(docIds); // Output: "doc1,doc2,doc3"
buildMessageItemReference
export const buildMessageItemReference = (
conversation: { message: IMessage[]; reference: IReference[] },
message: IMessage,
) => IReference;
Purpose:
Constructs or retrieves the appropriate reference object for a given message within a conversation context.
Parameters:
conversation({ message: IMessage[]; reference: IReference[] }): An object containing the conversation's messages and references.message(IMessage): The message for which the reference is to be built or retrieved.
Returns:IReference — The reference object associated with the message. If no reference is found, returns a default empty reference object { doc_aggs: [], chunks: [], total: 0 }.
Detailed behaviour:
Filters the conversation messages to get all assistant role messages except the first one.
Finds the index of the provided message in the filtered assistant messages.
Retrieves the reference either directly from the message if it exists or from the conversation's references using the found index.
Returns the found reference or a default empty reference if none is available.
Usage example:
const ref = buildMessageItemReference(conversation, message);
console.log(ref.doc_aggs);
replaceTextByOldReg
export const replaceTextByOldReg = (text: string) => string;
Purpose:
Transforms text containing legacy index markers into the current index format to maintain compatibility.
Parameters:
text(string): The input text containing old-style index markers.
Returns:string — The text with old index markers replaced by the new format.
Detailed behaviour:
Uses a regular expression to find all occurrences of the old index marker pattern
##<number>$$.Replaces each match with the new format
[ID:<number>].
Example:
const oldText = "Reference ##123$$ is here";
const newText = replaceTextByOldReg(oldText);
console.log(newText); // "Reference [ID:123] is here"
Constants and Regex
oldReg— A regex pattern to match the old index format:/#{2}\d+${2}/gcurrentReg— A regex pattern to match the current index format:/[ID:(\d+)]/g
These regex patterns are used primarily for text replacement and parsing tasks related to message references.
Important Implementation Details
Uniqueness in Document IDs:
ThegetDocumentIdsFromConversionReferencefunction uses an array and.every()method to ensure document IDs are unique before adding them. This avoids duplicates in the final comma-separated string.Reference Retrieval Logic:
ThebuildMessageItemReferencefunction smartly matches messages with references by filtering assistant messages and using their indices. It falls back gracefully if no direct reference is attached to a message.Backward Compatibility:
ThereplaceTextByOldRegfunction supports maintaining legacy data formats by converting old message reference markers to the new standardized format.
Interaction with Other Parts of the System
Imports:
MessageTypefrom@/constants/chat: Provides constants to identify message roles (e.g., Assistant).Interfaces
IConversation,IReference, andIMessagedefine the shape of conversation, reference, and message objects.EmptyConversationIdconstant from./constantsis used to check for invalid conversation IDs.isEmptyfromlodashis used to check the presence of references.
Usage Context:
These utilities are likely used wherever conversation data and messages are processed — e.g., in chat UI components, backend services for chat management, or message rendering logic. They help ensure consistent handling of conversation references and message IDs, aiding in the retrieval and display of related documents or metadata linked to messages.
Mermaid Diagram: Utility Functions Flowchart
flowchart TD
A[isConversationIdExist] -->|validates| B[Conversation ID]
C[getDocumentIdsFromConversionReference] -->|extracts unique doc IDs| D[Conversation.reference]
E[buildMessageItemReference] -->|uses| F[Conversation.message]
E -->|uses| G[Conversation.reference]
E -->|returns| H[Message Reference]
I[replaceTextByOldReg] -->|replaces old index format| J[Text String]
subgraph Inputs
B
D
F
G
J
end
subgraph Outputs
H
end
Summary
The utils.ts file provides essential utility functions that streamline the handling of conversations and messages, particularly focusing on references and IDs. It handles validation, data extraction, backward compatibility, and data structuring in a reusable manner supporting a chat application's data flow and rendering logic.