@genkit-ai/ai
Version:
Genkit AI framework generative AI APIs.
102 lines • 3.02 kB
JavaScript
import { extractJson } from "./extract";
class Message {
role;
content;
metadata;
parser;
static parseData(lenientMessage, defaultRole = "user") {
if (typeof lenientMessage === "string") {
return { role: defaultRole, content: [{ text: lenientMessage }] };
}
return {
...lenientMessage,
content: Message.parseContent(lenientMessage.content)
};
}
static parse(lenientMessage) {
return new Message(Message.parseData(lenientMessage));
}
static parseContent(lenientPart) {
if (typeof lenientPart === "string") {
return [{ text: lenientPart }];
} else if (Array.isArray(lenientPart)) {
return lenientPart.map((p) => typeof p === "string" ? { text: p } : p);
} else {
return [lenientPart];
}
}
constructor(message, options) {
this.role = message.role;
this.content = message.content;
this.metadata = message.metadata;
this.parser = options?.parser;
}
/**
* Attempts to parse the content of the message according to the supplied
* output parser. Without a parser, returns `data` contained in the message or
* tries to parse JSON from the text of the message.
*
* @returns The structured output contained in the message.
*/
get output() {
return this.parser?.(this) || this.data || extractJson(this.text);
}
toolResponseParts() {
const res = this.content.filter((part) => !!part.toolResponse);
return res;
}
/**
* Concatenates all `text` parts present in the message with no delimiter.
* @returns A string of all concatenated text parts.
*/
get text() {
return this.content.map((part) => part.text || "").join("");
}
/**
* Returns the first media part detected in the message. Useful for extracting
* (for example) an image from a generation expected to create one.
* @returns The first detected `media` part in the message.
*/
get media() {
return this.content.find((part) => part.media)?.media || null;
}
/**
* Returns the first detected `data` part of a message.
* @returns The first `data` part detected in the message (if any).
*/
get data() {
return this.content.find((part) => part.data)?.data;
}
/**
* Returns all tool request found in this message.
* @returns Array of all tool request found in this message.
*/
get toolRequests() {
return this.content.filter(
(part) => !!part.toolRequest
);
}
/**
* Returns all tool requests annotated with interrupt metadata.
* @returns Array of all interrupt tool requests.
*/
get interrupts() {
return this.toolRequests.filter((t) => !!t.metadata?.interrupt);
}
/**
* Converts the Message to a plain JS object.
* @returns Plain JS object representing the data contained in the message.
*/
toJSON() {
let out = {
role: this.role,
content: [...this.content]
};
if (this.metadata) out.metadata = this.metadata;
return out;
}
}
export {
Message
};
//# sourceMappingURL=message.mjs.map