UNPKG

@mastra/core

Version:
198 lines • 8.44 kB
import type { MastraDBMessage } from '../agent/message-list/state/types.js'; import type { MastraVector } from '../vector/index.js'; /** * Average characters per English token. Chunking measures characters because no single * tokenizer matches every embedder, so token limits are converted with this ratio. * * @internal */ export declare const MESSAGE_EMBEDDING_CHARS_PER_TOKEN = 4; /** * Default ceiling, in characters, for one chunk of message text sent to the embedder. * About 4096 English tokens, which fits `openai/text-embedding-3-small` (8191 tokens). * * @internal */ export declare const DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS: number; /** * Optional, Mastra-specific property an embedding model can carry to declare the most tokens it * embeds from one input. The AI SDK model interfaces have no such field, so integrations that know * their window (for example `@mastra/fastembed`) set it on the model object. */ export interface MessageEmbeddingModelLimits { /** Largest number of tokens the model embeds from a single input before truncating or failing. */ maxInputTokens?: number; } /** * Metadata stored on every message vector row. Recall resolves rows back to messages through * `message_id`, and edits and deletes find rows through it, so it is always set. * * @internal */ export type MessageVectorMetadata = Record<string, unknown> & { message_id: string; thread_id: string | undefined; resource_id: string | undefined; role: string; /** Full embedded text of the message, repeated on each of its chunk rows. */ content: string; created_at: string; }; /** * One message to embed. * * @internal */ export interface MessageEmbeddingItem { message: MastraDBMessage; /** * Text to embed instead of the text read from `message`. `Memory.updateMessages` passes the * projected text of an edit here, because the stored row it reads metadata from still holds * the old text. */ text?: string | null; } /** * Embeds chunk texts, one embedding per chunk in the same order. Each writer passes its own, so * embedding keeps its existing call path, retries and cache. * * @internal */ export type MessageChunkEmbedder = (chunks: string[]) => Promise<{ embeddings: number[][]; usage?: { tokens?: number; }; }>; /** * Options for {@link buildMessageEmbeddingRows}. * * @internal */ export interface BuildMessageEmbeddingRowsOptions { items: MessageEmbeddingItem[]; /** * Produces the vectors. When omitted the rows carry `documents` instead, for vector stores that * embed text themselves. */ embed?: MessageChunkEmbedder; /** * Called when embedding one message fails. When given, that message is left out of the rows * (and of the record) and the others are still written; when omitted, the failure rejects the * whole build. */ onEmbedError?: (error: unknown, message: MastraDBMessage) => void; /** Character ceiling per chunk. Resolve it with {@link resolveMaxChunkChars}. */ maxChunkChars: number; /** * Loads the metadata of the given threads, spread under the fixed fields so * `semanticRecall.filter` can match thread attributes. Called only when at least one message * still needs rows, so a write that skips everything costs no storage read. */ loadThreadMetadata?: (threadIds: string[]) => Promise<Map<string, Record<string, unknown>>>; /** * Thread and resource used when a message does not carry its own. Agent runs pass the run's * thread and resource, because resource-scoped recall filters rows by `resource_id`. */ defaults?: { threadId?: string; resourceId?: string; }; /** * The run's record of messages already embedded, from `MessageList.getEmbeddedMessages()`. * Messages recorded for the same index with the same text are skipped. */ embeddedMessages?: Map<string, string>; /** * Index the rows are written to. Required with `embeddedMessages`: the record is kept per * index, because the `SemanticRecall` processor and `Memory` can write to different indexes * (a custom `semanticRecall.indexName`) and each must still receive every message. */ indexName?: string; } /** * Rows ready for {@link upsertMessageVectors}. Every array lines up index by index. * * @internal */ export interface MessageEmbeddingRows { /** Row ids from {@link messageVectorId}. Always set, so a repeated write replaces the same rows. */ ids: string[]; /** Embeddings, set when an embedder was given. */ vectors?: number[][]; /** Chunk texts, set for vector stores that embed text themselves. */ documents?: string[]; metadata: MessageVectorMetadata[]; /** Embedding length, set when an embedder was given and at least one row was produced. */ dimension?: number; /** Tokens the embedder reported for these rows. */ usage?: { tokens: number; }; /** * `[recordKey, textHash]` pairs for the messages these rows embed. {@link upsertMessageVectors} * adds them to the run's record only after the write succeeds. */ embeddedEntries: Array<[string, string]>; } /** * Text of a message as semantic recall embeds it, or `null` when the message is not embedded. * System messages and transient signals are never stored, working-memory tags are removed, * and text parts are joined with a space. * * @internal */ export declare function extractMessageEmbeddingText(message: MastraDBMessage): string | null; /** * Splits text into chunks of at most `maxChars` characters, breaking on whitespace where it can. * A single word longer than the ceiling (base64, minified code, unbroken CJK text) is split by * character count, so every chunk fits. * * @internal */ export declare function chunkMessageText(text: string, maxChars: number): string[]; /** * Character ceiling per chunk: the explicit `maxChunkChars` option, else the embedder's declared * `maxInputTokens` converted to characters, else {@link DEFAULT_MESSAGE_EMBEDDING_MAX_CHUNK_CHARS}. * * @internal */ export declare function resolveMaxChunkChars({ maxChunkChars, embedder, }: { maxChunkChars?: number; embedder?: unknown; }): number; /** * Vector row id for one chunk of a message. Chunk 0 keeps the message id when it is a UUID (the * default) or a small unsigned integer: that is the id the `SemanticRecall` processor has always * written, so existing rows are replaced instead of duplicated. Every other chunk, and chunk 0 of * a message with any other id (custom id generators, client-supplied ids), gets a UUIDv8 derived * from the message id and chunk index. Derived ids are stable across writers and retries, and are * UUIDs because some stores (Qdrant) reject any other string id. * * @internal */ export declare function messageVectorId(messageId: string, chunkIndex: number): Promise<string>; /** * Builds the vector rows for messages. The `SemanticRecall` processor and `Memory` both write * through it, so a message gets the same rows whichever writer reaches it. * * Messages with no embeddable text, and messages already in `embeddedMessages` for this index with * the same text, produce no rows. When a message is written again with fewer chunks, rows for the * extra chunks stay until the message is updated or deleted, both of which remove rows by * `message_id`. * * @throws When a message has no id. Ids are assigned when messages enter a `MessageList`, so a * missing id means a caller skipped that step; a row without `message_id` could never be * recalled or deleted. * @internal */ export declare function buildMessageEmbeddingRows({ items, embed, onEmbedError, maxChunkChars, loadThreadMetadata, defaults, embeddedMessages, indexName, }: BuildMessageEmbeddingRowsOptions): Promise<MessageEmbeddingRows>; /** * Writes message rows built by {@link buildMessageEmbeddingRows}, always with their ids, then * records the embedded messages in `embeddedMessages`. Recording happens only after the write * succeeds, so a writer that fails leaves the message for the next writer to embed. * * @internal */ export declare function upsertMessageVectors(vector: MastraVector, indexName: string, rows: MessageEmbeddingRows, embeddedMessages?: Map<string, string>): Promise<void>; //# sourceMappingURL=message-embeddings.d.ts.map