/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var reasoning_exports = {};
__export(reasoning_exports, {
  REASONING_MAP_KEY: () => REASONING_MAP_KEY,
  ReasoningChatOpenAI: () => ReasoningChatOpenAI,
  collectReasoningMap: () => collectReasoningMap,
  getToolCallsKey: () => getToolCallsKey,
  patchRequestMessagesReasoning: () => patchRequestMessagesReasoning
});
module.exports = __toCommonJS(reasoning_exports);
var import_messages = require("@langchain/core/messages");
var import_openai = require("@langchain/openai");
const REASONING_MAP_KEY = "__nb_reasoning_map";
const getToolCallsKey = (toolCalls = []) => toolCalls.map((toolCall) => {
  var _a;
  const id = (toolCall == null ? void 0 : toolCall.id) ?? "";
  const name = (toolCall == null ? void 0 : toolCall.name) ?? ((_a = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _a.name) ?? "";
  return `${id}:${name}`;
}).join("|");
const collectReasoningMap = (messages) => {
  var _a, _b;
  const reasoningMap = /* @__PURE__ */ new Map();
  for (const message of messages ?? []) {
    if (!import_messages.AIMessage.isInstance(message)) {
      continue;
    }
    if (!((_a = message.tool_calls) == null ? void 0 : _a.length)) {
      continue;
    }
    const reasoningContent = (_b = message.additional_kwargs) == null ? void 0 : _b.reasoning_content;
    if (typeof reasoningContent !== "string" || !reasoningContent) {
      continue;
    }
    const key = getToolCallsKey(message.tool_calls);
    if (key) {
      reasoningMap.set(key, reasoningContent);
    }
  }
  return reasoningMap;
};
const patchRequestMessagesReasoning = (request, reasoningMap) => {
  if (!(reasoningMap == null ? void 0 : reasoningMap.size) || !Array.isArray(request == null ? void 0 : request.messages)) {
    return;
  }
  const lastMessage = request.messages.at(-1);
  if ((lastMessage == null ? void 0 : lastMessage.role) !== "tool") {
    return;
  }
  for (const message of request.messages) {
    if ((message == null ? void 0 : message.role) !== "assistant") {
      continue;
    }
    if (!Array.isArray(message.tool_calls) || message.tool_calls.length === 0) {
      continue;
    }
    if (message.reasoning_content) {
      continue;
    }
    const key = getToolCallsKey(message.tool_calls);
    const reasoningContent = key ? reasoningMap.get(key) : void 0;
    if (reasoningContent) {
      message.reasoning_content = reasoningContent;
    }
  }
};
class ReasoningChatOpenAI extends import_openai.ChatOpenAICompletions {
  async _generate(messages, options, runManager) {
    const reasoningMap = collectReasoningMap(messages);
    const nextOptions = {
      ...options || {},
      [REASONING_MAP_KEY]: reasoningMap
    };
    return super._generate(messages, nextOptions, runManager);
  }
  async *_streamResponseChunks(messages, options, runManager) {
    const reasoningMap = (options == null ? void 0 : options[REASONING_MAP_KEY]) instanceof Map ? options[REASONING_MAP_KEY] : collectReasoningMap(messages);
    const nextOptions = {
      ...options || {},
      [REASONING_MAP_KEY]: reasoningMap
    };
    yield* super._streamResponseChunks(messages, nextOptions, runManager);
  }
  _convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) {
    const messageChunk = super._convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole);
    if (delta == null ? void 0 : delta.reasoning_content) {
      messageChunk.additional_kwargs = {
        ...messageChunk.additional_kwargs || {},
        reasoning_content: delta.reasoning_content
      };
    }
    return messageChunk;
  }
  _convertCompletionsMessageToBaseMessage(message, rawResponse) {
    const langChainMessage = super._convertCompletionsMessageToBaseMessage(message, rawResponse);
    if (message == null ? void 0 : message.reasoning_content) {
      langChainMessage.additional_kwargs = {
        ...langChainMessage.additional_kwargs || {},
        reasoning_content: message.reasoning_content
      };
    }
    return langChainMessage;
  }
  async completionWithRetry(request, requestOptions) {
    const reasoningMap = requestOptions == null ? void 0 : requestOptions[REASONING_MAP_KEY];
    patchRequestMessagesReasoning(request, reasoningMap);
    if (request.stream) {
      return super.completionWithRetry(request, requestOptions);
    }
    return super.completionWithRetry(request, requestOptions);
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  REASONING_MAP_KEY,
  ReasoningChatOpenAI,
  collectReasoningMap,
  getToolCallsKey,
  patchRequestMessagesReasoning
});
