{"version":3,"file":"translator.cjs","names":["BaseTranslator","Operators","Comparators","func: Operator | Comparator","operation: Operation","comparison: Comparison","result: WeaviateComparisonResult","query: StructuredQuery","defaultFilter: FilterValue | undefined","generatedFilter: FilterValue | undefined","merged: WeaviateOperationResult"],"sources":["../src/translator.ts"],"sourcesContent":["import {\n  isFilterEmpty,\n  isString,\n  isInt,\n  isFloat,\n  BaseTranslator,\n  type Comparator,\n  Comparators,\n  Comparison,\n  type NOT,\n  Operation,\n  type Operator,\n  Operators,\n  StructuredQuery,\n  Visitor,\n} from \"@langchain/core/structured_query\";\nimport { FilterValue } from \"weaviate-client\";\nimport { WeaviateStore } from \"./vectorstores.js\";\n\ntype AllowedOperator = Exclude<Operator, NOT>;\n\ntype WeaviateOperatorValues = {\n  value: string | number | boolean;\n};\n\ntype WeaviateOperatorKeys = keyof WeaviateOperatorValues;\n\ntype ExclusiveOperatorValue = {\n  [L in WeaviateOperatorKeys]: {\n    [key in L]: WeaviateOperatorValues[key];\n  } & Omit<{ [key in WeaviateOperatorKeys]?: never }, L>;\n}[WeaviateOperatorKeys];\n\nexport type WeaviateVisitorResult =\n  | WeaviateOperationResult\n  | WeaviateComparisonResult\n  | WeaviateStructuredQueryResult;\n\nexport type WeaviateOperationResult = {\n  operator: string;\n  filters: WeaviateVisitorResult[];\n  value: null;\n};\nexport type WeaviateComparisonResult = {\n  target: { property: string };\n  operator: string;\n} & ExclusiveOperatorValue;\n\nexport type WeaviateStructuredQueryResult = {\n  filter?: WeaviateComparisonResult | WeaviateOperationResult;\n};\n\n/**\n * A class that translates or converts data into a format that can be used\n * with Weaviate, a vector search engine. It extends the `BaseTranslator`\n * class and provides specific implementation for Weaviate.\n * @example\n * ```typescript\n * const selfQueryRetriever = new SelfQueryRetriever({\n *   llm: new ChatOpenAI({ model: \"gpt-4o-mini\" }),\n *   vectorStore: new WeaviateStore(),\n *   documentContents: \"Brief summary of a movie\",\n *   attributeInfo: [],\n *   structuredQueryTranslator: new WeaviateTranslator(),\n * });\n *\n * const relevantDocuments = await selfQueryRetriever.getRelevantDocuments(\n *   \"Which movies are rated higher than 8.5?\",\n * );\n * ```\n */\nexport class WeaviateTranslator<\n  T extends WeaviateStore\n> extends BaseTranslator<T> {\n  declare VisitOperationOutput: WeaviateOperationResult;\n\n  declare VisitComparisonOutput: WeaviateComparisonResult;\n\n  allowedOperators: Operator[] = [Operators.and, Operators.or];\n\n  allowedComparators: Comparator[] = [\n    Comparators.eq,\n    Comparators.ne,\n    Comparators.lt,\n    Comparators.lte,\n    Comparators.gt,\n    Comparators.gte,\n  ];\n\n  /**\n   * Formats the given function into a string representation. Throws an\n   * error if the function is not a known comparator or operator, or if it\n   * is not allowed.\n   * @param func The function to format, which can be an Operator or Comparator.\n   * @returns A string representation of the function.\n   */\n  formatFunction(func: Operator | Comparator): string {\n    if (func in Comparators) {\n      if (\n        this.allowedComparators.length > 0 &&\n        this.allowedComparators.indexOf(func as Comparator) === -1\n      ) {\n        throw new Error(\n          `Comparator ${func} not allowed. Allowed operators: ${this.allowedComparators.join(\n            \", \"\n          )}`\n        );\n      }\n    } else if (func in Operators) {\n      if (\n        this.allowedOperators.length > 0 &&\n        this.allowedOperators.indexOf(func as Operator) === -1\n      ) {\n        throw new Error(\n          `Operator ${func} not allowed. Allowed operators: ${this.allowedOperators.join(\n            \", \"\n          )}`\n        );\n      }\n    } else {\n      throw new Error(\"Unknown comparator or operator\");\n    }\n    const dict = {\n      and: \"And\",\n      or: \"Or\",\n      eq: \"Equal\",\n      ne: \"NotEqual\",\n      lt: \"LessThan\",\n      lte: \"LessThanEqual\",\n      gt: \"GreaterThan\",\n      gte: \"GreaterThanEqual\",\n    };\n    return dict[func as Comparator | AllowedOperator];\n  }\n\n  /**\n   * Visits an operation and returns a WeaviateOperationResult. The\n   * operation's arguments are visited and the operator is formatted.\n   * @param operation The operation to visit.\n   * @returns A WeaviateOperationResult.\n   */\n  visitOperation(operation: Operation): this[\"VisitOperationOutput\"] {\n    const args = operation.args?.map((arg) => arg.accept(this as Visitor)) as (\n      | WeaviateComparisonResult\n      | WeaviateOperationResult\n    )[];\n\n    return {\n      operator: this.formatFunction(operation.operator), // Usually 'And' or 'Or'\n      filters: args,\n      value: null,\n    };\n  }\n\n  /**\n   * Visits a comparison and returns a WeaviateComparisonResult. The\n   * comparison's value is checked for type and the comparator is formatted.\n   * Throws an error if the value type is not supported.\n   * @param comparison The comparison to visit.\n   * @returns A WeaviateComparisonResult.\n   */\n  visitComparison(comparison: Comparison): WeaviateComparisonResult {\n    const result: WeaviateComparisonResult = {\n      operator: this.formatFunction(comparison.comparator),\n      target: { property: comparison.attribute },\n      value: \"\",\n    };\n\n    if (typeof comparison.value === \"string\") {\n      if (isString(comparison.value)) {\n        result.value = comparison.value;\n      } else if (isInt(comparison.value)) {\n        result.value = parseInt(comparison.value, 10);\n      } else if (isFloat(comparison.value)) {\n        result.value = parseFloat(comparison.value as string);\n      } else {\n        throw new Error(\"Value type is not supported\");\n      }\n    } else {\n      result.value = comparison.value;\n    }\n    return result;\n  }\n\n  /**\n   * Visits a structured query and returns a WeaviateStructuredQueryResult.\n   * If the query has a filter, it is visited.\n   * @param query The structured query to visit.\n   * @returns A WeaviateStructuredQueryResult.\n   */\n  visitStructuredQuery(\n    query: StructuredQuery\n  ): this[\"VisitStructuredQueryOutput\"] {\n    let nextArg = {};\n    if (query.filter) {\n      nextArg = {\n        filter: query.filter.accept(this as Visitor),\n      };\n    }\n    return nextArg;\n  }\n\n  /**\n   * Merges two filters into one. If both filters are empty, returns\n   * undefined. If one filter is empty or the merge type is 'replace',\n   * returns the other filter. If the merge type is 'and' or 'or', returns a\n   * new filter with the merged results. Throws an error for unknown merge\n   * types.\n   * @param defaultFilter The default filter to merge.\n   * @param generatedFilter The generated filter to merge.\n   * @param mergeType The type of merge to perform. Can be 'and', 'or', or 'replace'. Defaults to 'and'.\n   * @returns A merged FilterValue, or undefined if both filters are empty.\n   */\n  mergeFilters(\n    defaultFilter: FilterValue | undefined,\n    generatedFilter: FilterValue | undefined,\n    mergeType = \"and\"\n  ): FilterValue | undefined {\n    if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) {\n      return undefined;\n    }\n    if (isFilterEmpty(defaultFilter) || mergeType === \"replace\") {\n      if (isFilterEmpty(generatedFilter)) {\n        return undefined;\n      }\n      return generatedFilter;\n    }\n    if (isFilterEmpty(generatedFilter)) {\n      if (mergeType === \"and\") {\n        return undefined;\n      }\n      return defaultFilter;\n    }\n    const merged: WeaviateOperationResult = {\n      operator: \"And\",\n      filters: [\n        defaultFilter as WeaviateVisitorResult,\n        generatedFilter as WeaviateVisitorResult,\n      ],\n      value: null,\n    };\n\n    if (mergeType === \"or\") {\n      merged.operator = \"Or\";\n    }\n    const temp = {\n      operator: merged.operator,\n      operands: merged.filters,\n      value: null,\n    } as FilterValue;\n    return temp;\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,qBAAb,cAEUA,iDAAkB;CAK1B,mBAA+B,CAACC,4CAAU,KAAKA,4CAAU,EAAG;CAE5D,qBAAmC;EACjCC,8CAAY;EACZA,8CAAY;EACZA,8CAAY;EACZA,8CAAY;EACZA,8CAAY;EACZA,8CAAY;CACb;;;;;;;;CASD,eAAeC,MAAqC;AAClD,MAAI,QAAQD,+CACV;OACE,KAAK,mBAAmB,SAAS,KACjC,KAAK,mBAAmB,QAAQ,KAAmB,KAAK,GAExD,OAAM,IAAI,MACR,CAAC,WAAW,EAAE,KAAK,iCAAiC,EAAE,KAAK,mBAAmB,KAC5E,KACD,EAAE;EAEN,WACQ,QAAQD,6CACjB;OACE,KAAK,iBAAiB,SAAS,KAC/B,KAAK,iBAAiB,QAAQ,KAAiB,KAAK,GAEpD,OAAM,IAAI,MACR,CAAC,SAAS,EAAE,KAAK,iCAAiC,EAAE,KAAK,iBAAiB,KACxE,KACD,EAAE;EAEN,MAED,OAAM,IAAI,MAAM;EAElB,MAAM,OAAO;GACX,KAAK;GACL,IAAI;GACJ,IAAI;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