LangChain Academy
LangChain Academy에 오신 것을 환영합니다!
배경
LangChain에서 저희는 LLM 애플리케이션을 쉽게 구축할 수 있도록 하는 것을 목표로 합니다. 구축할 수 있는 LLM 애플리케이션 중 하나는 에이전트입니다. 에이전트는 이전에는 불가능했던 광범위한 작업을 자동화할 수 있기 때문에 에이전트 구축에 대한 많은 관심이 있습니다.
하지만 실제로는 이러한 작업을 안정적으로 실행하는 시스템을 구축하는 것은 매우 어렵습니다. 사용자들과 함께 에이전트를 프로덕션에 투입하면서, 더 많은 제어가 종종 필요하다는 것을 배웠습니다. 에이전트가 항상 특정 도구를 먼저 호출하거나 상태에 따라 다른 프롬프트를 사용해야 할 수도 있습니다.
이 문제를 해결하기 위해 저희는 LangGraph를 구축했습니다 — 에이전트 및 멀티 에이전트 애플리케이션을 구축하기 위한 프레임워크입니다. LangChain 패키지와는 별개로, LangGraph의 핵심 설계 철학은 개발자가 실제 시스템의 복잡성에 적합한 에이전트 워크플로우에 더 나은 정밀도와 제어를 추가하도록 돕는 것입니다.
강좌 구조
강좌는 일련의 모듈로 구성되어 있으며, 각 모듈은 LangGraph와 관련된 특정 주제에 중점을 둡니다. 각 모듈에 대한 폴더를 볼 수 있으며, 여기에는 일련의 노트북이 포함되어 있습니다. 개념을 안내하는 데 도움이 되는 비디오가 각 노트북과 함께 제공되지만, 노트북은 독립적이기도 합니다. 즉, 설명이 포함되어 있어 비디오와 독립적으로 볼 수 있습니다. 각 모듈 폴더에는 studio 폴더도 포함되어 있으며, 여기에는 LangGraph 애플리케이션 구축을 위한 IDE인 LangGraph Studio에 로드할 수 있는 그래프 세트가 포함되어 있습니다.
설정
시작하기 전에 README의 지침에 따라 환경을 생성하고 종속성을 설치해주세요.
Chat 모델
이 강좌에서는 Chat Models을 사용할 것입니다. 이는 메시지 시퀀스를 입력으로 받아 채팅 메시지를 출력으로 반환하는 몇 가지 작업을 수행합니다. LangChain은 Chat Models을 호스팅하지 않으며, 대신 타사 통합에 의존합니다. 여기에 LangChain 내의 타사 채팅 모델 통합 목록이 있습니다! 기본적으로 강좌는 인기가 많고 성능이 좋기 때문에 ChatOpenAI를 사용합니다. 언급한 바와 같이, OPENAI_API_KEY가 있는지 확인해주세요.
OPENAI_API_KEY가 설정되어 있는지 확인해보고, 설정되어 있지 않다면 입력하라는 메시지가 표시됩니다.
%%capture --no-stderr
%pip install --quiet -U langchain_openai langchain_core langchain_community tavily-pythonimport os
import getpass
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")여기에 채팅 모델로 할 수 있는 모든 것에 대한 유용한 가이드가 있지만, 아래에서 몇 가지 하이라이트를 보여드리겠습니다. README에서 언급한 대로 pip install -r requirements.txt를 실행했다면, langchain-openai 패키지를 설치한 것입니다. 이를 통해 ChatOpenAI 모델 객체를 인스턴스화할 수 있습니다. API에 처음 가입하는 경우, 모든 모델에 적용할 수 있는 무료 크레딧을 받게 됩니다. 여기에서 다양한 모델의 가격을 확인할 수 있습니다. 노트북은 품질, 가격, 속도의 좋은 균형이기 때문에 기본적으로 gpt-4o를 사용합니다(자세히 보기), 하지만 더 저렴한 gpt-3.5 시리즈 모델을 선택할 수도 있습니다.
채팅 모델에서 설정할 수 있는 몇 가지 표준 매개변수가 있습니다. 가장 일반적인 두 가지는 다음과 같습니다:
model: 모델의 이름temperature: 샘플링 온도
Temperature는 모델 출력의 임의성 또는 창의성을 제어합니다. 낮은 온도(0에 가까운)는 더 결정적이고 집중된 출력을 생성합니다. 이는 정확성이나 사실적 응답이 필요한 작업에 좋습니다. 높은 온도(1에 가까운)는 창의적인 작업이나 다양한 응답 생성에 좋습니다.
from langchain_openai import ChatOpenAI
gpt4o_chat = ChatOpenAI(model="gpt-4o", temperature=0)
gpt35_chat = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)LangChain의 채팅 모델에는 여러 기본 메서드가 있습니다. 대부분의 경우 다음을 사용할 것입니다:
stream: 응답의 청크를 스트림으로 반환invoke: 입력에 대해 체인을 호출
그리고 앞서 언급했듯이, 채팅 모델은 메시지를 입력으로 받습니다. 메시지는 역할(누가 메시지를 말하는지 설명)과 콘텐츠 속성을 가집니다. 이에 대해서는 나중에 더 자세히 다루겠지만, 여기서는 기본 사항만 보여드리겠습니다.
from langchain_core.messages import HumanMessage
# Create a message
msg = HumanMessage(content="Hello world", name="Lance")
# Message list
messages = [msg]
# Invoke the model with a list of messages
gpt4o_chat.invoke(messages)AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 11, 'total_tokens': 20, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_eb3c3cb84d', 'id': 'chatcmpl-CP8VHAoBrlnD5EmNJzfS7QRDjXHRz', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='run--896307a0-8b8c-4e47-9c34-53245b63c563-0', usage_metadata={'input_tokens': 11, 'output_tokens': 9, 'total_tokens': 20, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})
AIMessage 응답을 받습니다. 또한 문자열로 채팅 모델을 호출할 수도 있습니다. 문자열이 입력으로 전달되면, HumanMessage로 변환된 후 기본 모델에 전달됩니다.
gpt4o_chat.invoke("hello world")AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 9, 'total_tokens': 18, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_eb3c3cb84d', 'id': 'chatcmpl-CP8VI0wql0C945oEgGCCbad4aTrkT', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='run--1b3a3057-ff50-4cdd-947c-c82f34684c4c-0', usage_metadata={'input_tokens': 9, 'output_tokens': 9, 'total_tokens': 18, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})
gpt35_chat.invoke("hello world")AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 9, 'prompt_tokens': 9, 'total_tokens': 18, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'id': 'chatcmpl-CP8VJklq7VdcWYOSh7Wv4KsAue7Bk', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='run--1f053fec-1713-4259-a81a-e27960d5ffc7-0', usage_metadata={'input_tokens': 9, 'output_tokens': 9, 'total_tokens': 18, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})
인터페이스는 모든 채팅 모델에서 일관되며, 모델은 일반적으로 각 노트북 시작 시 한 번 초기화됩니다.
따라서 다른 공급자에 대한 강한 선호가 있다면 다운스트림 코드를 변경하지 않고도 모델 간에 쉽게 전환할 수 있습니다.
검색 도구
README에서 Tavily도 볼 수 있습니다. 이는 LLM과 RAG에 최적화된 검색 엔진으로, 효율적이고 빠르며 지속적인 검색 결과를 목표로 합니다. 언급했듯이 가입이 쉽고 관대한 무료 계층을 제공합니다. 일부 강의(모듈 4)에서는 기본적으로 Tavily를 사용하지만, 물론 코드를 직접 수정하려면 다른 검색 도구를 사용할 수도 있습니다.
_set_env("TAVILY_API_KEY")from langchain_community.tools.tavily_search import TavilySearchResults
tavily_search = TavilySearchResults(max_results=3)
search_docs = tavily_search.invoke("What is LangGraph?")/var/folders/z8/xfx3ln6x16x1fy6q7kpf1tzh0000gn/T/ipykernel_5047/1344879509.py:3: LangChainDeprecationWarning: The class `TavilySearchResults` was deprecated in LangChain 0.3.25 and will be removed in 1.0. An updated version of the class exists in the :class:`~langchain-tavily package and should be used instead. To use it run `pip install -U :class:`~langchain-tavily` and import as `from :class:`~langchain_tavily import TavilySearch``.
tavily_search = TavilySearchResults(max_results=3)
search_docs[{'title': 'What is LangGraph? - GeeksforGeeks',
'url': 'https://www.geeksforgeeks.org/machine-learning/what-is-langgraph/',
'content': 'LangGraph is an open-source framework built by LangChain that streamlines the creation and management of AI agent workflows. At its core, LangGraph combines large language models (LLMs) with graph-based architectures allowing developers to map, organize and optimize how AI agents interact and make decisions.',
'score': 0.9527197},
{'title': 'LangGraph Overview - Docs by LangChain',
'url': 'https://docs.langchain.com/oss/python/langgraph/overview',
'content': 'Trusted by companies shaping the future of agents - including Klarna, Replit, Elastic, and more - LangGraph is a low-level orchestration framework for building, managing, and deploying long-running, stateful agents.LangGraph is very low-level, and focused entirely on agent orchestration. Before using LangGraph, it is recommended you familiarize yourself with some of the components used to build agents, starting with models and tools. We will commonly use LangChain components throughout the',
'score': 0.9492242},
{'title': 'What is LangGraph? - Analytics Vidhya',
'url': 'https://www.analyticsvidhya.com/blog/2024/07/langgraph-revolutionizing-ai-agent/',
'content': 'To sum up, LangGraph is a major advancement in the development of AI agents. It enables developers to push the limits of what’s possible with AI agents by eliminating the shortcomings of earlier systems and offering a flexible, graph-based framework for agent construction and execution. LangGraph is positioned to influence the direction of artificial intelligence significantly in the future. [...] LangGraph is a library built on top of Langchain that is designed to facilitate the creation of cyclic graphs for large language model (LLM) – based AI agents.\n It views agent Objective Points about LangGraph and workflows as cyclic graph topologies, allowing for more variable and nuanced agent behaviors than linear execution models. [...] Frameworks such as LangGraph are becoming increasingly important as AI develops. LangGraph is making the next generation of AI applications possible by offering a versatile and strong framework for developing and overseeing AI agents.',
'score': 0.947386}]