OpenAI functions 메타데이터 태거 통합

OpenAI functions 메타데이터 태거 통합

LangChain JavaScript로 OpenAI functions 메타데이터 태거 문서 변환기와 통합하는 방법을 안내할게요.

출처: 문서

본문

수집된 문서에 제목, 톤, 문서 길이 같은 구조화된 메타데이터를 태깅하면 나중에 더 정확한 유사도 검색을 할 수 있어서 유용한 경우가 많아요. 하지만 문서 수가 많으면 이 라벨링 과정을 수동으로 수행하는 것은 지루할 수 있어요.

MetadataTagger 문서 변환기는 제공된 스키마에 따라 각 문서에서 메타데이터를 추출해 이 과정을 자동화해요. 내부적으로 구성 가능한 OpenAI Functions 기반 체인을 사용하므로, 커스텀 LLM 인스턴스를 전달한다면 functions 지원이 있는 OpenAI 모델이어야 해요.

주: 이 문서 변환기는 완전한 문서에서 가장 잘 동작하므로, 다른 분할이나 처리를 하기 전에 전체 문서로 먼저 실행하는 것이 가장 좋아요!

사용법

예를 들어 영화 리뷰 세트를 인덱싱하려 한다고 해볼게요. 문서 변환기를 다음과 같이 초기화할 수 있어요:

import * as z from "zod";
import { createMetadataTaggerFromZod } from "@langchain/classic/document_transformers/openai_functions";
import { ChatOpenAI } from "@langchain/openai";
import { Document } from "@langchain/core/documents";

const zodSchema = z.object({
  movie_title: z.string(),
  critic: z.string(),
  tone: z.enum(["positive", "negative"]),
  rating: z
    .optional(z.number())
    .describe("The number of stars the critic rated the movie"),
});

const metadataTagger = createMetadataTaggerFromZod(zodSchema, {
  llm: new ChatOpenAI({ model: "gpt-3.5-turbo" }),
});

const documents = [
  new Document({
    pageContent:
      "Review of The Bee Movie\nBy Roger Ebert\nThis is the greatest movie ever made. 4 out of 5 stars.",
  }),
  new Document({
    pageContent:
      "Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.",
    metadata: { reliable: false },
  }),
];
const taggedDocuments = await metadataTagger.transformDocuments(documents);

console.log(taggedDocuments);

/*
  [
    Document {
      pageContent: 'Review of The Bee Movie\n' +
        'By Roger Ebert\n' +
        'This is the greatest movie ever made. 4 out of 5 stars.',
      metadata: {
        movie_title: 'The Bee Movie',
        critic: 'Roger Ebert',
        tone: 'positive',
        rating: 4
      }
    },
    Document {
      pageContent: 'Review of The Godfather\n' +
        'By Anonymous\n' +
        '\n' +
        'This movie was super boring. 1 out of 5 stars.',
      metadata: {
        movie_title: 'The Godfather',
        critic: 'Anonymous',
        tone: 'negative',
        rating: 1,
        reliable: false
      }
    }
  ]
*/

유효한 JSON Schema 객체도 받아들이는 추가 createMetadataTagger 메서드도 있어요.

사용자 지정

두 번째 옵션 매개변수에서 기본 태깅 체인에 표준 LLMChain 인자를 전달할 수 있어요. 예를 들어 LLM이 입력 문서의 특정 세부 사항에 집중하도록 하거나 특정 스타일로 메타데이터를 추출하도록 하려면 커스텀 프롬프트를 전달할 수 있어요:

import * as z from "zod";
import { createMetadataTaggerFromZod } from "@langchain/classic/document_transformers/openai_functions";
import { ChatOpenAI } from "@langchain/openai";
import { Document } from "@langchain/core/documents";
import { PromptTemplate } from "@langchain/core/prompts";

const taggingChainTemplate = `Extract the desired information from the following passage.
Anonymous critics are actually Roger Ebert.

Passage:
{input}
`;

const zodSchema = z.object({
  movie_title: z.string(),
  critic: z.string(),
  tone: z.enum(["positive", "negative"]),
  rating: z
    .optional(z.number())
    .describe("The number of stars the critic rated the movie"),
});

const metadataTagger = createMetadataTaggerFromZod(zodSchema, {
  llm: new ChatOpenAI({ model: "gpt-3.5-turbo" }),
  prompt: PromptTemplate.fromTemplate(taggingChainTemplate),
});

const documents = [
  new Document({
    pageContent:
      "Review of The Bee Movie\nBy Roger Ebert\nThis is the greatest movie ever made. 4 out of 5 stars.",
  }),
  new Document({
    pageContent:
      "Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.",
    metadata: { reliable: false },
  }),
];
const taggedDocuments = await metadataTagger.transformDocuments(documents);

console.log(taggedDocuments);

/*
  [
    Document {
      pageContent: 'Review of The Bee Movie\n' +
        'By Roger Ebert\n' +
        'This is the greatest movie ever made. 4 out of 5 stars.',
      metadata: {
        movie_title: 'The Bee Movie',
        critic: 'Roger Ebert',
        tone: 'positive',
        rating: 4
      }
    },
    Document {
      pageContent: 'Review of The Godfather\n' +
        'By Anonymous\n' +
        '\n' +
        'This movie was super boring. 1 out of 5 stars.',
      metadata: {
        movie_title: 'The Godfather',
        critic: 'Roger Ebert',
        tone: 'negative',
        rating: 1,
        reliable: false
      }
    }
  ]
*/

[Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers. [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/document_transformers/openai_metadata_tagger.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).

더 알아보기