본문 바로가기
📚도서 공부/LangChain으로 구현하는 LLM

4-2-1(정보요약, 기본 프롬프팅) Langchain 비서 구축

by Majestyblue 2024. 4. 22.

2. 정보 요약

빠르게 변화하는 요즘 환경에서는 지속적으로 증가하는 정보 양에 대응하는 것이 어렵다. 특히 컴퓨터 과학 및 AI 분야는 더욱 그렇다. 수 많은 논문을 읽고 이해하는 것에 시간이 너무 많이 소요된다. 이 때 자동화가 중요한 역할을 한다. LLM은 강력한 언어 이해 능력을 통해 텍스트를 간추리는 데 뛰어나다. LangChain을 사용해 요약 기술을 더욱 정교한 수준으로 탐색해 보자.

1. 기본 프롬프팅(데코레이터 사용하기)

몇 문장을 요약할 때는 기본 프롬프팅이 잘 작동한다. 원하는 길이를 지정하고 텍스트를 제공하면 된다.

# <https://en.wikipedia.org/wiki/Pluto>
text = "Pluto (minor-planet designation: 134340 Pluto) is a dwarf planet in the Kuiper belt, a ring of bodies beyond the orbit of Neptune. It is the ninth-largest and tenth-most-massive known object to directly orbit the Sun. It is the largest known trans-Neptunian object by volume, by a small margin, but is less massive than Eris. Like other Kuiper belt objects, Pluto is made primarily of ice and rock and is much smaller than the inner planets. Pluto has roughly one-sixth the mass of Earth's moon, and one-third its volume. Pluto has a moderately eccentric and inclined orbit, ranging from 30 to 49 astronomical units (4.5 to 7.3 billion kilometers; 2.8 to 4.6 billion miles) from the Sun. Light from the Sun takes 5.5 hours to reach Pluto at its orbital distance of 39.5 AU (5.91 billion km; 3.67 billion mi). Pluto's eccentric orbit periodically brings it closer to the Sun than Neptune, but a stable orbital resonance prevents them from colliding. Pluto has five known moons: Charon, the largest, whose diameter is just over half that of Pluto; Styx; Nix; Kerberos; and Hydra. Pluto and Charon are sometimes considered a binary system because the barycenter of their orbits does not lie within either body, and they are tidally locked. The New Horizons mission was the first spacecraft to visit Pluto and its moons, making a flyby on July 14, 2015, and taking detailed measurements and observations.Pluto was discovered in 1930 by Clyde W. Tombaugh, making it by far the first known object in the Kuiper belt. It was immediately hailed as the ninth planet, but it was always the odd object out,[14]: 27  and its planetary status was questioned when it was found to be much smaller than expected. These doubts increased following the discovery of additional objects in the Kuiper belt starting in the 1990s, and particularly the more massive scattered disk object Eris in 2005. In 2006, the International Astronomical Union (IAU) formally redefined the term planet to exclude dwarf planets such as Pluto. Many planetary astronomers, however, continue to consider Pluto and other dwarf planets to be planets."
from langchain.llms import GPT4All
#위에서 선언하였음.
#model = "E:\\GPT4ALL\\Download Models\\mistral-7b-instruct-v0.2.Q4_0.gguf"
#llm = GPT4All(model=model, device='gpu')

prompt = """
Summerize this text in one sentene:

{text}
"""
summary = llm(prompt.format(text=text))
print(summary)

<출력결과>
Pluto is a small, icy dwarf planet in the Kuiper Belt with five known moons, discovered in 1930 but reclassified as a dwarf planet by the International Astronomical Union in 2006.

명왕성은 카이퍼 벨트에 있는 작고 얼음처럼 차가운 소행성으로, 1930년에 발견되었지만 2006년 국제천문연맹에 의해 왜행성으로 재분류되었습니다.

Langchian의 decorators 라이브러리는 기본 LangChain과 비교해 프롬프트를 정의하고 실행하는데 더 파이썬 형식에 가까운 인터페이스를 제공한다. 함수 데코레이터는 프롬프트 문서를 실행 가능한 코드로 변환해 여러 줄의 정의와 자연스러운 코드 흐름을 가능하게 한다. (비공식 애드온이다.)

※ 데코레이터(decorator)란 기존 함수를 입력 받아서 기능이 추가된 새로운 함수 객체로 만들어주는 역할을 하는 것이다. 자세한 내용은 아래 링크 참고

 

01) 데코레이터 - 레벨업 파이썬 (wikidocs.net)

 

01) 데코레이터

[TOC] ## 데코레이터 영어 사전에서 decorator를 찾아보면 '장식하는 사람'이라는 뜻을 갖고 있습니다. 파이썬의 데코레이터 역시 동일한 의미로 사용됩니다. 어떤 …

wikidocs.net

[파이썬/Python] 이해하기 쉬운 데코레이터 원리 (tistory.com)

 

[파이썬/Python] 이해하기 쉬운 데코레이터 원리

데코레이터(Decorator)란? 함수/메서드의 기능을 확장하거나 변경해 주는 특별한 문법 파이썬 코드를 공부하다 보면, '@' 골뱅이가 붙은 특이한 이름을 보신 적이 있으실 겁니다. 파이썬에서 골뱅이

kevinitcoding.tistory.com

 

 

아래 코드는 llm_prompt라는 데코레이터를 이용하는건데… 로컬 모델로는 안되나 보다. 계속 openai api key를 요구한다.

from langchain.llms import GPT4All
from langchain_decorators import llm_prompt

#위에서 선언하였음.
#model = "E:\\GPT4ALL\\Download Models\\mistral-7b-instruct-v0.2.Q4_0.gguf"
#llm = GPT4All(model=model, device='gpu')

@llm_promt
def summarize(text:srt, length="short", llm=[llm]) -> str:
    """
    Summarize this text {text} to {length} length.

    {text}
    """
    return

summary = summarize(text=text)

<출력결과>
ValidationError: 1 validation error for ChatOpenAI
__root__
  Did not find openai_api_key, please add an environment variable `OPENAI_API_KEY` which contains it, or pass `openai_api_key` as a named parameter. (type=value_error)

 

음… 이거 렝체인 레딧에 올려볼가?

langchain-decorators/src/langchain_decorators/prompt_decorator.py at main · ju-bezdek/langchain-decorators · GitHub

 

langchain-decorators/src/langchain_decorators/prompt_decorator.py at main · ju-bezdek/langchain-decorators

syntactic sugar 🍭 for langchain. Contribute to ju-bezdek/langchain-decorators development by creating an account on GitHub.

github.com

아니 쉬밤 여기서는 llm:옵션에 내 llm 넣으면 안되나? (아시는분?)