function assignRoleToPartsAndValidateSendMessageRequest()

in src/requests/request-helpers.ts [78:112]


function assignRoleToPartsAndValidateSendMessageRequest(
  parts: Part[],
): Content {
  const userContent: Content = { role: "user", parts: [] };
  const functionContent: Content = { role: "function", parts: [] };
  let hasUserContent = false;
  let hasFunctionContent = false;
  for (const part of parts) {
    if ("functionResponse" in part) {
      functionContent.parts.push(part);
      hasFunctionContent = true;
    } else {
      userContent.parts.push(part);
      hasUserContent = true;
    }
  }

  if (hasUserContent && hasFunctionContent) {
    throw new GoogleGenerativeAIError(
      "Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.",
    );
  }

  if (!hasUserContent && !hasFunctionContent) {
    throw new GoogleGenerativeAIError(
      "No content is provided for sending chat message.",
    );
  }

  if (hasUserContent) {
    return userContent;
  }

  return functionContent;
}