Fly ai 4기 4주차 day 30 : LangChain으로 챗봇 만들기

이성원·2024년 1월 30일
0

LangChain 챗봇

colab에서 prompt 엔지니어링

!pip install openai
!pip install langchain

import os

os.environ['OPENAI_API_KEY'] = 'key값'
os.environ['AZURE_OPENAI_ENDPOINT'] = 'endpoint값'
os.environ['OPENAI_API_TYPE'] = 'azure'
os.environ['OPENAI_API_VERSION'] = '2023-05-15'

from langchain.llms import AzureOpenAI
from langchain.chat_models import AzureChatOpenAI

llm = AzureOpenAI(
    deployment_name='dev-gpt-35-turbo-instruct',
    max_tokens=1000
)

template = '''
너는 요리사야. 내가 갖고 있는 재료들로 만들 수 있는 요리를 추천하고 그 요리의 레시피를 제시해
내가 가진 재료는 아래와 같아

<재료>
{재료}
'''

from langchain.prompts import PromptTemplate, ChatPromptTemplate

prompt_template = PromptTemplate(
    input_variables=['재료'],
    template = template
)


prompt_template.format(재료='양파,계란,사과,빵')


결과:

너는 요리사야. 내가 갖고 있는 재료들로 만들 수 있는 요리를 추천하고 그 요리의 레시피를 제시해
내가 가진 재료는 아래와 같아

<재료>
양파,계란,사과,

template에 페르소나를 넣어주면 된다.

LangChain에서 Few shot learning

gpt3.5는 우리나라 문화인 삼행시를 하지 못한다.
그렇기때문에 삼행시를 해달라고 하면 일반적인 시를 지어주는데 이걸 Few shot learning을 하여 삼행시를 학습시켜보자

학습할 내용 선언

# Few shot learning

from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate

examples = [
    {
        'question':'아이유로 삼행시를 지어줘',
        'answer':'''
        아 아이유는
        이 이상하고
        유 유난히 좋다.
        '''
    },
    {
        'question':'이순신으로 삼행시를 지어줘',
        'answer':'''
        이 이순신 장군은
        순 순순히 내어줄 것 같았던 조선의 바다를
        신 신의와 충의의 마음으로 지켜냈다.
        '''
    }
]

# 샘플 탬플릿을 제작
example_prompt = PromptTemplate(input_variables=['question','answer'],
                                template='Question: {question}\n{answer}')


# Few Shot Learning을 위한 템플릿 제작
prompt = FewShotPromptTemplate(
            examples=examples,
            example_prompt=example_prompt,
            suffix='Question: {input}',
            input_variables=['input']
)

print(llm(prompt.format(input='호날두로 삼행시를 지어줘')))

결과:

 호 호날두는
 날 날씨가 따뜻하고
 두 두 발이 빠르다.

질문 답변 유사도 구하기

허깅페이스 임베드 쿼리 이용해서 cosine similarity 구하기

!pip install sentence_transformers
!pip install openai langchain tiktoken pypdf

from langchain.embeddings import HuggingFaceBgeEmbeddings

model_name = 'BAAI/bge-small-en'
model_kwargs = {'device':'cpu'}
encode_kwargs = {'normalize_embeddings':True}

hf = HuggingFaceBgeEmbeddings(
    model_name = model_name,
    model_kwargs = model_kwargs,
    encode_kwargs = encode_kwargs
)

embeddings = hf.embed_documents(
              [
                  'today is monday',
                  'weather is nice today',
                  "what's the problem",
                  'langchain is useful',
                  'Hello World',
                  'my name is morris'
              ]
)

from numpy import dot
from numpy.linalg import norm
import numpy as np

def cos_sim(A,B):
  return dot(A,B)/(norm(A)*norm(B))
  

BGE_query_q = hf.embed_query('Hello? who is this?')
BGE_query_a = hf.embed_query('hi this is harrison')

print(cos_sim(BGE_query_q, BGE_query_a))
print(cos_sim(BGE_query_q, embeddings[1]))
print(cos_sim(BGE_query_q, embeddings[3]))

결과:

0.852253974392915
0.746906772852191
0.7576970544352233
profile
개발자

0개의 댓글

관련 채용 정보