.from_template vs. _from_messages

샤워실의 바보·2025년 2월 5일

GPT

목록 보기
11/11
  1. .from_template 사용 방식:

    • 단일 문자열 템플릿을 인자로 받아 프롬프트 객체를 생성합니다.
    • 템플릿 내에 있는 변수(예: {question}, {topic} 등)를 나중에 입력 값으로 채워 넣을 수 있습니다.
    • 주로 일반 텍스트 기반 프롬프트를 만들 때 사용됩니다.
  2. .from_messages 사용 방식:

    • 여러 메시지를 포함하는 리스트를 인자로 받아, 대화(chat) 형식의 프롬프트 객체를 생성합니다.
    • 각 메시지는 역할(예: 시스템, 사용자, AI 등)을 구분하여 작성할 수 있어, 실제 대화와 유사한 형태의 프롬프트를 만듭니다.
    • 대화형 모델에 적합한 프롬프트를 구성할 때 사용됩니다.
  3. 예시 코드:

    • .from_template 예시:

      from langchain.prompts import PromptTemplate
      
      prompt = PromptTemplate.from_template("Human: {question}\nAI:")
      result = prompt.format(question="What is the capital of Germany?")
      # result는 "Human: What is the capital of Germany?\nAI:"와 같은 문자열을 생성합니다.
    • .from_messages 예시:

      from langchain.prompts.chat import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
      
      chat_prompt = ChatPromptTemplate.from_messages([
          SystemMessagePromptTemplate.from_template("You are a helpful assistant."),
          HumanMessagePromptTemplate.from_template("Tell me about {topic}.")
      ])
      result = chat_prompt.format(topic="Germany")
      # result는 여러 메시지를 포함하는 채팅 대화 형식의 프롬프트를 생성합니다.
  4. 결론:

    • .from_template: 단일 텍스트 템플릿에서 프롬프트를 만들 때 사용되며, 단순한 문자열 치환 방식으로 동작합니다.
    • .from_messages: 대화형 모델에 적합하도록, 여러 메시지를 역할별로 구성한 프롬프트를 만들 때 사용됩니다.
profile
공부하는 개발자

0개의 댓글