곽은철 파트너님이 내주신 과제를 하며 정리해본 내용입니다.
너무 간단해서 공유하기 민망하지만 올려봅니다!
왜 🦜⛓️?
앵무새는 언어 모델이나 자연어 처리 모델이 주어진 입력을 그대로 따라하거나 반복하는 것을 비유적으로 나타내는 용어
앵무새(모델)를 연결하거나 조합(chain)해서 유용한 출력물을 얻기위한 것을 의미
1-1 . langchain으로 openai gpt-3.5모델에게 객체에 대한 개발자식 농담을 하라고 하기
[ 사전 준비 ]
랭체인 설치
pip install langchain
랭체인-openAI 통합 패키지 설치
pip install langchain-openai
openAI API Key 발급 받기
https://platform.openai.com/api-keys
크레딧을 충전해야 사용이 가능하다.
크레딧 충전 후 인식 반영 지연이 있을 수 있다. (바로 안되고 요청 시 아래 에러 발생)
RateLimitError: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: <https://platform.openai.com/docs/guides/error-codes/api-errors.'>, 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}
API Key 환경변수 설정하기
export OPENAI_API_KEY="...”
모델 초기화
from langchain_openai import ChatOpenAI #llm = ChatOpenAI() llm_model = "gpt-3.5-turbo" llm = ChatOpenAI(temperature=0.9, model=llm_model)
temperature : 모델이 다음 단어나 토큰을 생성할 때의 무작위성을 조절하는 매개변수
낮은 temperature(0.2 이하) - 확실한 예측, 정보 검색 / 과학적 문서 생성 같은 정확한 결과가 필요할 때
높은 temperature(1.5 이상) - 다양한 예측, 예술적/창의적 아이디어가 필요할 때
0.8~0.9 → 상대적으로 다양한 출력 생성
model : GPT-3.5 Turbo 모델을 사용하도록 설정
프롬프트 템플릿을 활용해서 LLM이 특정 맥락이나 역할에 맞게 응답을 생성하도록 유도
예시 : 당신은 프로그래밍과 기술에 관해서 특히 유머 감각이 뛰어난 경험 많은 소프트웨어 엔지니어입니다. 동료들은 코딩 조언뿐만 아니라 좋은 웃음을 위해서도 자주 당신에게 찾아옵니다. 오늘, 당신은 자신의 유머를 공유하고 싶은 기분입니다.
→ ChatGPT에 “개발자식 농담에 대한 응답을 잘 할 수 있도록 발화자를 설정하는 프롬프트를 작성해줘.” 라고 요청해서 받은 프롬프트 문.
from langchain_core.prompts import ChatPromptTemplate prompt = ChatPromptTemplate.from_messages([ ("system", "You are an experienced software engineer with a great sense of humor, especially when it comes to programming and technology. Your colleagues often come to you not just for coding advice but also for a good laugh. Today, you're in the mood to share some of your humor."), ("user", "{input}") ])
메시지 객체에서 문자열로 변환하는 Parser 추가
from langchain_core.output_parsers import StrOutputParser output_parser = StrOutputParser()
LLM chain으로 결합하기 - 한 모듈의 출력을 다른 모듈의 입력으로 연결하여 결합해줌
prompt는 사용자 입력을 받아 언어 모델이 이해하기 쉬운 형태로 변환하여 llm에 전달
llm은 학습된 모델을 기반으로 입력데이터에 대한 출력 생성
output_parser가 모델의 출력을 문자열로 변환
chain = prompt | llm | output_parser
chain 호출해서 개발자식 농담 해달라고 하기
chain.invoke({"input": "Please generate a developer-themed joke that combines humor with programming concepts. The joke should be easy to understand for someone with a background in software development and should cleverly incorporate elements from coding, technology, or software engineering."})
응답 : "Sure, here's a classic developer-themed joke for you:\\n\\nWhy do programmers prefer dark mode?\\n\\nBecause light attracts bugs!"
왜 프로그래머들은 다크 모드를 선호하는가? 빛이 버그를 끌어들이기 때문이다!
1-2. Prompt Templates - [객체, 함수, 절차]에 대한 개발자식 농담을 하라고 하기
chain.invoke({"input": "Tell me a joke about objects, functions, and procedures."})
응답 : "Why did the object go to therapy?\\n\\nBecause it had an identity crisis, couldn't decide whether it wanted to be a function or a procedure!"
왜 객체가 치료를 받으러 갔나요? 신원 위기(identity crisis)를 겪고 있어서, 자신이 함수가 되고 싶은지 절차가 되고 싶은지 결정할 수 없었기 때문입니다!
1-3. Output parsers - 배열[ 0, 1, 2, 3 …] 형태로 10개의 과일 이름을 묻고 이를 리스트에 저장하기.
prompt = ChatPromptTemplate.from_messages([("system", "You are a fruit expert."),
("user", "{input}")])
chain = prompt | llm | output_parser
response = chain.invoke({"input" : "Give me a list of 10 fruit names."})
lines = response.split('\\n')
fruit_names = [line.split('. ')[1] for line in lines]
print(fruit_names)
['Apple', 'Banana', 'Orange', 'Mango', 'Strawberry', 'Grapefruit', 'Pineapple', 'Watermelon', 'Kiwi', 'Pear']
이상입니다~!☺️
#9기 랭체인