IT 이것저것

langchain(초보가이드)

김 Ai의 IT생활 2024. 8. 22. 17:34
728x90
반응형
SMALL

파트 1: 개념 소개

[LangChain]은 대규모 언어 모델(LLM)과 상호작용하는 데 필요한 도구와 라이브러리를 제공하는 Python 라이브러리입니다. 이를 통해 개발자는 LLM을 더 쉽게 활용할 수 있으며, 복잡한 작업을 수행할 수 있습니다. [LangChain]은 LLM의 출력을 구조화하고, 다른 데이터 소스와 통합하며, 여러 단계로 이루어진 작업을 구성할 수 있도록 도와줍니다.

코드:
```python
from langchain import OpenAI, PromptTemplate, LLMChain
```

파트 2: 기본 구조 및 문법 설명

[LangChain]의 핵심 구성 요소는 다음과 같습니다:

  • LLM (Large Language Model): 언어 모델 인스턴스를 나타냅니다. 예를 들어 OpenAI의 GPT-3와 같은 언어 모델을 사용할 수 있습니다.
  • Prompt: 언어 모델에 제공할 입력 텍스트를 나타냅니다.
  • Chain: 여러 단계로 이루어진 작업을 정의합니다. 각 단계는 입력을 받아 출력을 생성하는 방식으로 구성됩니다.
코드:
```python
# LLM 인스턴스 생성
llm = OpenAI(temperature=0.9)

# Prompt 템플릿 정의
prompt = PromptTemplate(
    input_variables=["product"],
    template="What is a good name for a company that makes {product}?",
)

# Chain 생성 및 실행
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run("colorful socks"))
```

파트 3: 상세 설명

[LangChain]은 다양한 유틸리티와 도구를 제공합니다:

  • Agents: 복잡한 작업을 수행하기 위한 지능형 에이전트를 구축할 수 있습니다.
  • Memory: 대화 이력이나 외부 데이터를 저장하고 활용할 수 있습니다.
  • Vectorstore: 문서를 벡터로 표현하고 유사도 검색을 수행할 수 있습니다.
코드:
```python
from langchain.agents import initialize_agent, Tool
from langchain.memory import ConversationBufferMemory

# Tool 정의
tools = [
    Tool(
        name="Wikipedia Search",
        func=lambda query: f"Wikipedia search results for '{query}'",
        description="Search Wikipedia for information related to the query"
    )
]

# Agent 초기화
memory = ConversationBufferMemory(memory_key="chat_history")
agent = initialize_agent(tools, memory=memory, agent="conversational-react-description", verbose=True)

# Agent 실행
agent.run("What is the capital of France?")
```

파트 4: 실제 예시

간단한 질문 답변 시스템을 만들어 봅시다.

코드:
```python
from langchain import OpenAI, PromptTemplate, LLMChain

# LLM 인스턴스 생성
llm = OpenAI(temperature=0.9)

# Prompt 템플릿 정의
prompt = PromptTemplate(
    input_variables=["question"],
    template="Answer the following question: {question}",
)

# Chain 생성 및 실행
chain = LLMChain(llm=llm, prompt=prompt)

question = "What is the capital of France?"
print(chain.run(question))
```

파트 5: 고급 활용법

[LangChain]은 외부 데이터 소스와 통합할 수 있습니다. 예를 들어, Pandas DataFrame에서 데이터를 읽어와 질문에 대한 답변을 생성할 수 있습니다.

코드:
```python
import pandas as pd
from langchain.llms import OpenAI
from langchain.agents import create_pandas_data_augmented_agent

# DataFrame 로드
df = pd.read_csv("data.csv")

# Agent 초기화
agent = create_pandas_data_augmented_agent(OpenAI(temperature=0), df)

# Agent 실행
agent.run("What is the average age of the people in the data?")

파트 6: 자주 발생하는 오류 및 해결 방법

1. **API 키 설정 오류**: OpenAI 인스턴스를 생성할 때 API 키를 제대로 설정하지 않으면 오류가 발생합니다.

잘못된 코드:
```python
from langchain import OpenAI

llm = OpenAI(temperature=0.9)  # API 키를 설정하지 않음
```

올바른 코드:
```python
import os
from langchain import OpenAI

os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
llm = OpenAI(temperature=0.9)
```

2. **인풋 형식 불일치 오류**: Prompt 템플릿의 입력 변수와 실제 입력의 형식이 일치하지 않으면 오류가 발생합니다.

잘못된 코드:
```python
prompt = PromptTemplate(input_variables=["product"], template="What is a good name for a company that makes {product}?")
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run(["colorful socks"]))  # 입력이 리스트 형태임
```

올바른 코드:
```python
prompt = PromptTemplate(input_variables=["product"], template="What is a good name for a company that makes {product}?")
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run("colorful socks"))  # 입력이 문자열 형태임
```

파트 7: 연습 문제

  1. OpenAI의 GPT-3 모델을 사용하여 간단한 문장 생성 작업을 수행해 보세요.
  2. 주어진 Pandas DataFrame에서 특정 열의 평균값을 계산하는 Agent를 만들어 보세요.
  3. Wikipedia 검색 도구를 사용하여 간단한 질문에 대한 답변을 생성하는 Agent를 구현해 보세요.
728x90
반응형
LIST

'IT 이것저것' 카테고리의 다른 글

LLM 모델 양자화 와 GGUF 파일  (0) 2024.08.23
LLM 파인튜닝에 대해 알아보자  (0) 2024.08.23
RAG 심층분석  (0) 2024.08.23
LLM 활용  (0) 2024.08.22
벡터데이터베이스  (0) 2024.08.22