AIㆍML / 개발자

구글 팜(PaLM) API를 이용해 챗봇 만들기

Janakiram MSV | InfoWorld 2023.07.19
구글 팜(PaLM) API를 이용해 블로그 콘텐츠를 자동으로 만드는 방법에 이어, 이번에는 구글 클라우드 버텍스 AI에서 팜 2 API를 이용해 챗봇을 만들어 보자. 기본적인 환경과 SDK 설정은 앞선 예제와 같다. 그다음 과정부터 살펴본다. vertexai.preview.language_models 라이브러리에는 ChatModel, TextEmbedding, TextGenerationModel 등 다양한 클래스가 포함돼 있다. 여기서는 팜 모델이 질문에 답변하는 물리 선생님 역할을 할 수 있도록 ChatModel 라이브러리를 주로 사용한다.

먼저, 라이브러리에서 적절한 클래스를 불러온다.
 
from vertexai.preview.language_models import ChatModel, InputOutputTextPair

ChatModel 클래스는 프롬프트를 받아들이고 답변을 출력하는 역할을 한다. InputOutputTextPair가 질문과 답변을 쉽게 만들어 챗봇에 제공하는 과정을 도와준다. 이후에는 미리 훈련된 모델인 chat-bison@001을 기반으로 객체를 초깃값을 산출한 후 채팅 방식의 대화에 최적화한다.
 
model = ChatModel.from_pretrained("chat-bison@001") 

다음 단계는 입력된 프롬프트를 받아들이고 모델이 생성한 답변을 내보내는 함수를 설정하는 것이다.
 
def get_completion(msg):
   
    ctx="My name is Jani. You are a physics teacher, knowledgeable about the gravitational theory"   
   
    exp=[
        InputOutputTextPair(
            input_text="How you define gravity?",
            output_text="Gravity is a force that attracts a body towards the centre of the earth or any other physical body having mass."
        ),
    ]   
    chat = model.start_chat(context=ctx,examples=exp)

    response = chat.send_message(msg,max_output_tokens=256,temperature=0.2)

    return response

이 과정이 챗봇을 만드는 핵심이다. 의미 있고 적절한 답변을 만들려면 다음 3가지 요소가 필요하다.
 
  • Context : 챗 모델의 행동을 맞춤 설정한다. 모델에 대화의 핵심 토픽이나 테마를 알려주기 위해 추가 문맥 정보를 추구하는 데 사용한다. 부가 정보이지만, 정확한 답변을 생성하는 데 중요한 역할을 한다.
  • Examples : 주어진 질문에 대해 전형적인 모델 답변을 보여주는 입출력 쌍의 AI 리스트로 대표적인 것이 챗 프롬프트다. 이를 이용해 특정 질문에 대해 답변하는 방법을 바꿀 수 있다.
  • Messages : 챗 프롬프트의 저자-콘텐츠 쌍 리스트다. 모델은 가장 최근 메시지에 답변하는데, 이것이 메시지 리스트의 마지막 쌍이 된다. 챗 세션 히스토리는 선행하는 쌍들로 구성된다.

주목해야 할 것은 context와 examples를 정의하는 방법이다. 여기서는 중력 이론에 특화된 물리학 챗봇을 만드는 것이므로, context와 examples 모두 이 주제를 참조해야 한다. 팜 모델은 토큰이라는 크기 단위를 통해 프롬프트와 답변을 인식한다. 1개 토큰은 약 4글자이므로, 토큰 100개가 60~80단어 정도 된다. 여기서는 max_output_tokens 파라미터를 250으로 지정한다. 각자 원하는 대로 이를 늘리면 된다. 토큰의 한계에 따라 얼마나 많은 메시지를 챗 세션 히스토리에 포함할지 결정된다.

모델의 독창성은 temperature에 따라 결정된다. 토큰을 선택할 때 얼마나 무작위로 할 것인지를 의미한다. 0~1까지인데, 이 값이 낮을수록 더 일반적인 답변이 돌아온다. 이 값이 크면 더 독특하고 창의적인 답변이 반환된다. 여기서는 정확성 높은 대답을 얻기 위해 0.2로 설정한다.

메서드 작업이 끝났으므로 프롬프트를 만들 차례다.
 
prompt="What is the relationship between gravity and weight?"

Invoke the method by passing the prompt.
response=get_completion(prompt)
print(response)
response=get_completion(prompt)

중력과 관련된 다른 질문을 해 보자.
 
prompt="What is gravity according to Einstein?" response=get_completion(prompt) print(response.text)

전체 코드는 다음과 같다.
 
from vertexai.preview.language_models import ChatModel, InputOutputTextPair

model = ChatModel.from_pretrained("chat-bison@001")

def get_completion(msg):
   
    ctx="My name is Jani. You are a physics teacher, knowledgeable about the gravitational theory"   

    exp=[
        InputOutputTextPair(
            input_text="How you define gravity?",
            output_text="Gravity is a force that attracts a body towards the centre of the earth or any other physical body having mass."
        ),
    ]   
    chat = model.start_chat(context=ctx,examples=exp)

    response = chat.send_message(msg,max_output_tokens=256,temperature=0.2)

    return response

prompt="What is the relationship between gravity and weight?"
response=get_completion(prompt)
print(response.text)

prompt="What is gravity according to Einstein?"
response=get_completion(prompt)
print(response.text)

editor@itworld.co.kr
 Tags Palm 챗봇
Sponsored

회사명 : 한국IDG | 제호: ITWorld | 주소 : 서울시 중구 세종대로 23, 4층 우)04512
| 등록번호 : 서울 아00743 등록발행일자 : 2009년 01월 19일

발행인 : 박형미 | 편집인 : 박재곤 | 청소년보호책임자 : 한정규
| 사업자 등록번호 : 214-87-22467 Tel : 02-558-6950

Copyright © 2024 International Data Group. All rights reserved.