"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AIMessageChunk = exports.isAIMessage = exports.AIMessage = void 0;
const json_js_1 = require("../utils/json.cjs");
const base_js_1 = require("./base.cjs");
const tool_js_1 = require("./tool.cjs");
/**
 * Represents an AI message in a conversation.
 */
class AIMessage extends base_js_1.BaseMessage {
    get lc_aliases() {
        // exclude snake case conversion to pascal case
        return {
            ...super.lc_aliases,
            tool_calls: "tool_calls",
            invalid_tool_calls: "invalid_tool_calls",
        };
    }
    constructor(fields, 
    /** @deprecated */
    kwargs) {
        let initParams;
        if (typeof fields === "string") {
            initParams = {
                content: fields,
                tool_calls: [],
                invalid_tool_calls: [],
                additional_kwargs: kwargs ?? {},
            };
        }
        else {
            initParams = fields;
            const rawToolCalls = initParams.additional_kwargs?.tool_calls;
            const toolCalls = initParams.tool_calls;
            if (!(rawToolCalls == null) &&
                rawToolCalls.length > 0 &&
                (toolCalls === undefined || toolCalls.length === 0)) {
                console.warn([
                    "New LangChain packages are available that more efficiently handle",
                    "tool calling.\n\nPlease upgrade your packages to versions that set",
                    "message tool calls. e.g., `yarn add @langchain/anthropic`,",
                    "yarn add @langchain/openai`, etc.",
                ].join(" "));
            }
            try {
                if (!(rawToolCalls == null) && toolCalls === undefined) {
                    const [toolCalls, invalidToolCalls] = (0, tool_js_1.defaultToolCallParser)(rawToolCalls);
                    initParams.tool_calls = toolCalls ?? [];
                    initParams.invalid_tool_calls = invalidToolCalls ?? [];
                }
                else {
                    initParams.tool_calls = initParams.tool_calls ?? [];
                    initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? [];
                }
            }
            catch (e) {
                // Do nothing if parsing fails
                initParams.tool_calls = [];
                initParams.invalid_tool_calls = [];
            }
        }
        // Sadly, TypeScript only allows super() calls at root if the class has
        // properties with initializers, so we have to check types twice.
        super(initParams);
        // These are typed as optional to avoid breaking changes and allow for casting
        // from BaseMessage.
        Object.defineProperty(this, "tool_calls", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: []
        });
        Object.defineProperty(this, "invalid_tool_calls", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: []
        });
        if (typeof initParams !== "string") {
            this.tool_calls = initParams.tool_calls ?? this.tool_calls;
            this.invalid_tool_calls =
                initParams.invalid_tool_calls ?? this.invalid_tool_calls;
        }
    }
    static lc_name() {
        return "AIMessage";
    }
    _getType() {
        return "ai";
    }
}
exports.AIMessage = AIMessage;
function isAIMessage(x) {
    return x._getType() === "ai";
}
exports.isAIMessage = isAIMessage;
/**
 * Represents a chunk of an AI message, which can be concatenated with
 * other AI message chunks.
 */
class AIMessageChunk extends base_js_1.BaseMessageChunk {
    constructor(fields) {
        let initParams;
        if (typeof fields === "string") {
            initParams = {
                content: fields,
                tool_calls: [],
                invalid_tool_calls: [],
                tool_call_chunks: [],
            };
        }
        else if (fields.tool_call_chunks === undefined) {
            initParams = {
                ...fields,
                tool_calls: [],
                invalid_tool_calls: [],
                tool_call_chunks: [],
            };
        }
        else {
            const toolCalls = [];
            const invalidToolCalls = [];
            for (const toolCallChunk of fields.tool_call_chunks) {
                let parsedArgs = {};
                try {
                    parsedArgs = (0, json_js_1.parsePartialJson)(toolCallChunk.args ?? "{}") ?? {};
                    if (typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) {
                        throw new Error("Malformed tool call chunk args.");
                    }
                    toolCalls.push({
                        name: toolCallChunk.name ?? "",
                        args: parsedArgs,
                        id: toolCallChunk.id,
                    });
                }
                catch (e) {
                    invalidToolCalls.push({
                        name: toolCallChunk.name,
                        args: toolCallChunk.args,
                        id: toolCallChunk.id,
                        error: "Malformed args.",
                    });
                }
            }
            initParams = {
                ...fields,
                tool_calls: toolCalls,
                invalid_tool_calls: invalidToolCalls,
            };
        }
        // Sadly, TypeScript only allows super() calls at root if the class has
        // properties with initializers, so we have to check types twice.
        super(initParams);
        // Must redeclare tool call fields since there is no multiple inheritance in JS.
        // These are typed as optional to avoid breaking changes and allow for casting
        // from BaseMessage.
        Object.defineProperty(this, "tool_calls", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: []
        });
        Object.defineProperty(this, "invalid_tool_calls", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: []
        });
        Object.defineProperty(this, "tool_call_chunks", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: []
        });
        this.tool_call_chunks =
            initParams?.tool_call_chunks ?? this.tool_call_chunks;
        this.tool_calls = initParams?.tool_calls ?? this.tool_calls;
        this.invalid_tool_calls =
            initParams?.invalid_tool_calls ?? this.invalid_tool_calls;
    }
    get lc_aliases() {
        // exclude snake case conversion to pascal case
        return {
            ...super.lc_aliases,
            tool_calls: "tool_calls",
            invalid_tool_calls: "invalid_tool_calls",
            tool_call_chunks: "tool_call_chunks",
        };
    }
    static lc_name() {
        return "AIMessageChunk";
    }
    _getType() {
        return "ai";
    }
    concat(chunk) {
        const combinedFields = {
            content: (0, base_js_1.mergeContent)(this.content, chunk.content),
            additional_kwargs: (0, base_js_1._mergeDicts)(this.additional_kwargs, chunk.additional_kwargs),
            response_metadata: (0, base_js_1._mergeDicts)(this.response_metadata, chunk.response_metadata),
            tool_call_chunks: [],
        };
        if (this.tool_call_chunks !== undefined ||
            chunk.tool_call_chunks !== undefined) {
            const rawToolCalls = (0, base_js_1._mergeLists)(this.tool_call_chunks, chunk.tool_call_chunks);
            if (rawToolCalls !== undefined && rawToolCalls.length > 0) {
                combinedFields.tool_call_chunks = rawToolCalls;
            }
        }
        return new AIMessageChunk(combinedFields);
    }
}
exports.AIMessageChunk = AIMessageChunk;
