피드로 돌아가기
새로워지기·마흔의 생활코딩

LangGraph | Agentic RAG with LangChain

NS
normalstory
표지 이미지
YouTube 영상 미리보기YouTube
외부 미디어
YouTube 영상 미리보기YouTube
외부 미디어
YouTube 영상 미리보기YouTube
외부 미디어

영상 요약

  1. 요약이 아직 없습니다.

  2. 요약이 아직 없습니다.

  3. 요약이 아직 없습니다.

*참조 영상 2. LangGraph Crash Course with code examples

 

 

*노트

LangGraph is

랭그래프는 랭체인 위에 구축되었으며, 랭체인 생태계와 완벽하게 상호운용됩니다.
LangGraph is built on top of LangChain and completely interoperable with the LangChain ecosystem.

요약: LangGraph는 에이전트 런타임에 자주 필요한 '주기적 그래프'를 더 잘 생성할 수 있도록 LangChain 위에 구축된 모듈입니다.
TL;DR: LangGraph is module built on top of LangChain to better enable creation of cyclical graphs, often needed for agent runtimes.

주요 용도는 LLM 애플리케이션에 사이클을 추가하는 것입니다. 결정적으로, 이것은 DAG 프레임워크가 아닙니다. DAG를 구축하려면 LangChain 표현식 언어를 사용해야 합니다.
The main use is for adding cycles to your LLM application. Crucially, this is NOT a DAG framework. If you want to build a DAG, you should use just use LangChain Expression Language.

사이클은 에이전트와 같은 동작에 중요하며, LLM을 반복적으로 호출하여 다음에 수행할 작업을 요청합니다.
Cycles are important for agent-like behaviors, where you call an LLM in a loop, asking it what action to take next.

기본적으로 노드는 다음에 어떤 노드로 이동할 수 있지 결정을 내릴 수 있는 곳입니다.
This is basically where nodes can make decisions about which node they can go to next

이를 다른 방식으로 생각하면 그래프가 기본적으로 결정을 내리는 하나의 거대한 상태 머신과 같다고 할 수 있습니다, 
So another way of thinking about this is it's like a giant state machine that you're building, where the graph is basically the state machine that decides

A table showing our current mental model of cognitive architectures.

특정 체인을 실행하거나 특정 도구 등을 실행하기 위해 어떤 상태로 이동한 다음 어떻게 돌아올 것인가? 그리고 언제 그래프를 완성하거나 끝내야 하는지, 시퀀스를 끝내야 하는지 어떻게 알 수 있을까요? 
What state will you go to run a particular chain or to run a particular tool, et cetera? and then, how do you get back? And then also things like, how do you know when to complete or end the graph or end the sequence, in here? 

따라서 LangGraph는 'LangChain'를 사용하여 사용자 정의 에이전트를 더 쉽게 구축하고 단순한 체인 이상의 것을 구축할 수 있도록 하는 이러한 아이디어를 바탕으로 구축되었습니다. 
So LangGraph is built on these ideas of trying to make it easier for you to build, custom agents and to build, things that are more than just simple chains with 'LangChain'. 

 

Key Idea

따라서 여기에는 몇 가지 핵심적인 부분이 있습니다. So there are a number of key parts to this.

StateGraph

StateGraph라는 아이디어가 있습니다. 에이전트의 수명 주기 전반에 걸쳐 어떤 방식으로든 상태가 유지되도록 하는 곳입니다.
You've got this idea of a StateGraph. So this is where your state is being persisted in some way throughout the agent's life cycle.

StateGraph는 그래프를 나타내는 클래스입니다. 
StateGraph is a class that represents the graph. 

상태 정의를 전달하여 이 클래스를 초기화합니다. 이 상태 정의는 시간이 지남에 따라 업데이트되는 중앙 상태 객체를 나타냅니다. 
You initialize this class by passing in a state definition. This state definition represents a central state object that is updated over time. 

이 상태는 그래프의 노드에 의해 업데이트되며, 노드는 이 상태의 속성에 대한 연산(키-값 저장소 형태)을 반환합니다.
This state is updated by nodes in the graph, which return operations to attributes of this state (in the form of a key-value store).

- The attributes of this state can be updated in two ways. 

첫째, 속성을 완전히 재정의할 수 있습니다. 
이 방법은 노드가 속성의 새 값을 반환하도록 하려는 경우에 유용합니다. 
First, an attribute could be overridden completely. 
This is useful if you want to nodes to return the new value of an attribute. 

둘째, 속성의 값을 추가하여 속성을 업데이트할 수 있습니다. 
속성이 수행된 작업의 목록(또는 이와 유사한 것)인 경우 노드가 수행한 새로운 작업을 반환하고 해당 작업이 속성에 자동으로 추가되도록 하려는 경우에 유용합니다.
Second, an attribute could be updated by adding to its value. 
This is useful if an attribute is a list of actions taken (or something similar) and you want nodes to return new actions taken (and have those automatically added to the attribute).

- Define the agent state

LangGraph에서의 주요 그래프 유형은 StatefulGraph입니다. 이 그래프는 각 노드에 전달되는 상태 개체에 의해 매개변수화됩니다. 그러면 각 노드는 해당 상태를 업데이트하는 연산을 반환합니다. 
The main type of graph in LangGraph is the StatefulGraph. This graph is parameterized by a state object that it passes around to each node. Each node then returns operations to update that state. 

이러한 연산은 상태의 특정 속성을 설정하거나(예: 기존 값 덮어쓰기) 기존 속성에 추가할 수 있습니다. 설정 또는 추가 여부는 그래프를 구성하는 상태 객체에 주석을 달아 표시합니다.
These operations can either SET specific attributes on the state (e.g. overwrite the existing values) or ADD to the existing attribute. Whether to set or add is denoted by annotating the state object you construct the graph with.

Nodes

여기서 핵심이 되는 다음 부분은 노드의 전체 개념입니다. 그래프를 작성할 때 그래프에 노드를 추가하게 됩니다.
The next part, which is key to this, is the whole idea of nodes. As you build the graph, you want to add nodes to the graph.

StateGraph를 생성한 후 graph. add _node(이름, 값) 구문을 사용하여 노드를 추가합니다. 
After creating a StateGraph, you then add nodes with graph. add _node (name, value) syntax. 

'name' 매개변수는 에지를 추가할 때 노드를 참조하는 데 사용할 문자열이어야 합니다. 
The 'name' parameter should be a string that we will use to refer to the node when adding edges. 

'value' 매개변수는 호출할 함수 또는 실행 가능한 LCEL이어야 합니다. 
The 'value' parameter should be either a function or LCEL runnable that will be called. 

이 함수/LCEL은 상태 객체와 동일한 형식의 사전을 입력으로 받아들이고 업데이트할 상태 객체의 키가 포함된 사전을 출력해야 합니다.
This function/LCEL should accept a dictionary in the same form as the state object as input, and output a dictionary with keys of the state object to update.

이러한 노드를 체인처럼 생각할 수도 있고, 실제로는 실행 가능하므로 도구가 될 수도 있고 체인이 될 수도 있으며 다양한 노드를 가질 수 있습니다. 
And you can think of these nodes as being like chains, or actually. they're also runnables, so it could be a tool, it could be a chain, and you can have a variety of these different nodes. 

1. 에이전트: 취해야 할 조치(있는 경우)를 결정할 책임이 있습니다.
    The agent: responsible for deciding what (if any) actions to take.
2. 도구를 호출하는 함수: 에이전트가 작업을 수행하기로 결정하면 이 노드가 해당 작업을 실행합니다.
    A function to invoke tools: if the agent decides to take an action, this node will then execute that action.

이러한 노드는 에이전트의 구성 요소와 같아서 어떻게든 서로 연결해야 한다고 생각하면 됩니다. 따라서 노드는 실제 구성 요소입니다, 
And you think of these as being like the components of your agent that you need to somehow wire together. So while the nodes are the actual components, 

Edges

모든 것을 하나로 묶어주는 역할을 합니다. 그리고 엣지는 다양한 형태로 존재할 수 있습니다. 
what wires everything together. And the edges can come in different forms as well. 

1. Normal Edge: 
    도구가 호출된 후에는 항상 상담원에게 돌아가 다음에 수행할 작업을 결정해야 합니다.
    after the tools are invoked, it should always go back to the agent to decide what to do next

2. Conditional Edge: 
    조건부인 이유는 노드의 출력에 따라 여러 경로 중 하나가 선택될 수 있기 때문입니다. 어떤 경로가 선택될지는 해당 노드가 실행될 때까지 알 수 없습니다(LLM이 결정).
    The reason they are conditional is that based on the output of a node, one of several paths may be taken. The path that is taken is not known until that node is run (the LLM decides).

    에이전트가 호출된 후, 에이전트가 작업을 수행하라고 하면 도구를 호출하는 함수를 호출해야 합니다. 에이전트가 완료되었다고 하면 완료해야 합니다.
    after the agent is called, we should either: a. If the agent said to take an action, then the function to invoke tools should be called b. If the agent said that it was finished, then it should finish

    - To create Conditional Edges, you need to pass in three things:

    1. The upstream node: 이 노드의 출력을 살펴보고 다음에 수행할 작업을 결정합니다.
        the output of this node will be looked at to determine what to do next
    2. A function: 다음에 호출할 노드를 결정하기 위해 호출됩니다. 문자열을 반환해야 합니다.
        this will be called to determine which node to call next. It should return a string
    3. A mapping: 이 매핑은 (2)의 함수 출력을 다른 노드에 매핑하는 데 사용됩니다. 키는 (2)의 함수가 반환할 수 있는 가능한 값이어야 합니다. 값은 해당 값이 반환될 경우 이동할 노드의 이름이어야 합니다.
        this mapping will be used to map the output of the function in (2) to another node. The keys should be possible values that the function in (2) could return. The values should be names of nodes to go to if that value is returned.

Compiling the Graph

그래프는 일종의 표준 LangChain 런처블처럼 작동합니다. 따라서 호출을 실행하고 스트림 등을 실행할 수 있습니다. 
The Graph acts, just like a sort of standard LangChain runnable. So you can, run invoke on it, you can run stream, etc. 


(Set the entry point as 'agent')
이제 기본적으로 에이전트의 상태를 실행하고, '엔트리 포인트'를 제공하고, '엔트리 포인트'를 '엔트리 노드'로 정의합니다. 
it will now basically run the state of the agent for you, and, give you the 'entry point', you will define an 'entry point' as an 'entry node'. 

그리고 '엔드 포인트'를 제공합니다. 그리고 이런 것들을 서로 이어주는 일련의 작업들을 처리할 수 있게 됩니다.
and give you the sort of 'end point'. and it will be able to get through the whole sort of thing of wiring these things together.

이제 재사용 가능한 에이전트를 만들어서 그래프에 연결할 때 많이 사용할 수 있을 것 같습니다. Now I can see that there's going to be a lot of use for sort of making, reusable, sort of agents that you would then wire together on a graph. 

따라서 도구를 사용하기 위해 미리 만들어진 작은 것들이 많이 있을 수 있습니다.
So you might have lots of, little pre made things for using tools, that kind of thing.

이제 재사용 가능한 에이전트를 만들고 이를 그래프에 연결하는 데 많이 사용될 것임을 알 수 있습니다.
Now I can see that there's going to be a lot of use for sort of making, reusable, sort of agents that you would then wire together on a graph.

Agent Executor

저희는 LangGraph로 표준 LangChain 에이전트 실행자를 다시 만들었습니다. 이를 통해 기존 LangChain 에이전트를 사용할 수 있으면서도 '에이전트 실행기'의 내부를 보다 쉽게 수정할 수 있습니다.
We've recreated the canonical LangChain AgentExecutor with LangGraph. This will allow you to use existing LangChain agents, but allow you to more easily modify the internals of the 'Agent Executor'. 

이 그래프의 상태에는 기본적으로 입력, 채팅_역사, 중간_단계(그리고 가장 최근의 에이전트 결과를 나타내는 에이전트_결과) 등 LangChain 에이전트를 사용해본 적이 있다면 익숙할 개념이 포함되어 있습니다.
The state of this graph by default contains concepts that should be familiar to you if you've used LangChain agents: input, chat_history, intermediate_steps (and agent_outcome to represent the most recent agent outcome)

 

01. https://colab.research.google.com/drive/1jb_pz76PMhzphbsW-udjTZnSsXFuP_ZS#scrollTo=P4HwY9Ept0c2

case 01 

case 02

02. https://colab.research.google.com/drive/1g3WJIQ36zsR843VcRjuou5QZyundXmHt#scrollTo=2HoxaGZbkvi5

 

03. https://colab.research.google.com/drive/1CylOYFyQqBn4EDDHc6orcWm9Wgx70B9f#scrollTo=7r9pOg0B8qTy 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

*참조 영상 1. Agentic RAG with LangChain

개요
이 동영상에서는 언어 모델 내에서 추론과 행동의 패턴에 대해 구체적으로 논의하면서 에이전티브 RAG(추론 액션 루프) 동작의 개념을 살펴봅니다. 연사는 다양한 맥락에서 효과적으로 추론하고 행동할 수 있는 복잡한 AI 시스템을 구축하는 데 에이전티브 RAG가 어떻게 적용되는지 강조하면서 에이전티브 RAG의 세부 사항을 자세히 설명합니다.

섹션 1. 
Agents are a pattern, not a specific thing. 이는 복잡한 AI 시스템을 구축하는 방법을 이해하는 데 중요합니다. 연사는 에이전티브 RAG가 어떻게 고밀도 벡터 검색, 컨텍스트 내 학습 활용, 증강을 포함하는지 설명합니다. 이를 통해 RAG 시스템 내에서 에이전트를 사용하여 컨텍스트를 검색하고, 프롬프트를 보강하고, 응답을 생성할 수 있습니다.

섹션 2
이 동영상에서는 에이전트가 대규모 언어 모델(LLM)을 외부 도구에 연결하여 LL이 쿼리에 응답할 도구를 선택할 수 있도록 하는 함수 호출에 대해서도 다룹니다. 예를 들어 에이전트를 사용하여 검색에 비공개 데이터를 사용할지, 아카이브 문서를 사용할지, 아니면 DuckDuckGo를 사용할지 결정할 수 있습니다.

요점
이 동영상은 다양한 상황에서 효과적으로 추론하고 행동할 수 있는 복잡한 AI 시스템을 구축할 때 에이전티브 RAG 동작의 개념과 그 적용에 대한 인사이트를 제공합니다.

 

*노트 

> Agent 
먼저 Agent = Agent + Like = Agentic 와 같다. 그리고 '에이전트는 특별한 무엇이 아니라 패턴이다'라는 점을 강조하는 것으로 강의가 시작한다. 여기서 패턴은 '추론-행동 패턴' The Reasoning-Action pattern을 말한다. 

 

> RAG의 주요 기능
HALLUCINATIONS(Confident responses that are false) 방지를 목적으로 한다. 이를 위한 주요 기능은 크게 검색(문서에서 참조 찾기), 증강(프롬프트에 참조 추가), 생성(질문에 대한 답변을 개선하세요!)로 구성된다(RAG = Retrieval + Augmented + Generation). 
궁극적으로 RAG = 고밀도 벡터 검색 DENSE VECTOR RETRIEVAL + 상황별 학습 IN-CONTEXT LEARNING

 

> LangGraph
제품이 다이어그램을 작성할 수 있는 경우 공학은 그것을 정확하게 창조 할 수 있다.If I’m a builder... more intuitive, more modular. If Product can diagram it Engineering can create it exactly.(INTUITIVE)
LangGraph는 간단한 그래프 접근 방식을 사용합니다. LangGraph uses a simple graph approach. 그래프 graph( 연결된 개체의 모음 노드 가장자리)를 순환 그래프를 만듭니다. LangChain을 기반으로 주기적 그래프를 만들 수 있습니다. 이것은 우리가 LangChain에 구축 된 애플리케이션에 주기를 추가 할 수 있기 때문에 유용합니다. 물론 LangChain은 체인의 추상화로 시작되었습니다. LangGraph는 이를 가능하게 하는 것입니다. 

LangGraph는 상태 머신을 그래프로 지정 하여 생성하는 방법입니다. LangGraph is a way to create  state machines by specifying them as graphs.
특히 LangGraph가 하는 일은 각 노드의 상태를 그래프로 지정하여 일종의 상태를 추적하는 상태 머신을 만드는 것입니다.

 

 

COGNITIVE ARCHITECTURES 
1. LLM call
2. Chain of LLM calls
3. LLM as Router
4. State Machines
5. Agents

https://docs.google.com/presentation/d/1rPYL_Q8WF1-jqN0iLkwcW0UijEJbAYhoRzYhWBb3gWo/edit#slide=id.g2d249469c2a_0_64 

https://blog.langchain.dev/openais-bet-on-a-cognitive-architecture/

 

OpenAI's Bet on a Cognitive Architecture

Three weeks ago OpenAI held a highly anticipated developer day. They released a myriad of new features. The two most interesting to me were the Assistants API and GPTs. To me, these represent the same bet – on a particular, agent-like, closed “cognitiv

blog.langchain.dev

 

 

LangGraph

Nodes 
Function (e.g., an external tool) 
LCEL Runnable 실행 가능(e.g., a RAG chain) 

Edges 
“paths to take 가야 할 길(올바른 경로)” 
“where to pass our state object next 다음에 상태 개체를 전달할 위치”
*the agent scratch Pad
: what that is really tracking is it's tracking the state

 

 

LangChain v0.1.0

맥락 과 추론을 활용하는 LLM 애플리케이션 활성화 .Enabling LLM applications that leverage context and reasoning.

RAG

 

1. MODELS I/O : “Chat-Style” ::  Fine-tuned for chat Often instruction-tuned

2. PROMPTS

3. CREATE A VECTOR STORE
1) Load Docs
2) Split Text
3) Embed
4) Store Vectors

overview- 1

 

 

METARAG FLOW
1. Search ArXiv for top papers on RAG 
2. Papers --> embeddings -> Vector Store (FAISS)
3. Query RAG app about RAG!
4. Return answers to questions with sources

 

DATA

LangChain의 아카이브 로더를 사용하여 질문에 따라 아카이브에서 문서를 가져 와서이 벡터 저장소를 구축 할 수 있습니다.  we can use LangChain's archive loader to get papers from archive based on our question and build out this Vector store.

 

 

MODELS
Embedding Model : text-3-embedding-small 
Chat Model (e.g., LLM) : GPT-3.5-Turbo

 

overview- 2. ClassicMetaRAG 

code

 

 

overview- 3. RAG/Function Calling Build + Final Assembly

 

그래프는 한 방향으로만 흐르도록 허용합니다. 여기서 다음 항목으로 다음 항목으로 다음 항목으로 흐르는 것을 알 수 있습니다. LangGraph는 상태와 가장자리에 작용하는 노드나 단위 또는 상태를 다음에 어디로 가야하는지 알려주는 단위를 정의할 수 있는 유연성을 제공합니다. 따라서 이러한 구성 요소를 구체적으로 제어할 수 있으므로 LangGraph의 본질적인 아이디어는 상태를 중심으로 셰퍼링하고 작업을 수행한다는 것입니다. 

code 

 

 

 

CONCLUSION

Agents, RAG, Agentic RAG
These are all patterns, not things
이들은 모두 단순한 패턴이지 어떤 대상이 아닙니다.
Agent = Reasoning-Action pattern!

Classic (Meta)RAG via LCEL
LCEL을 통한 클래식 (메타)RAG
A single node in LangGraph
LangGraph의 단일 노드

LangGraph 
Shepherding state around, doing stuff
셰퍼링하는 상태를 중심으로 뭔가를 하는 상태

 

 

 

 

https://colab.research.google.com/drive/1cUj-jWDDpyHjDKqfIRAijXUWLSnxuy9W#scrollTo=R83jwrx8xKVf

 

Google Colab Notebook

Run, share, and edit Python notebooks

colab.research.google.com

 

 

https://www.youtube.com/watch?v=pBBe1pk8hf4

https://www.ted.com/talks/harrison_chase_the_magical_ai_assistants_of_the_future_and_the_engineering_behind_them

 

The magical AI assistants of the future — and the engineering behind them

What is it going to take to build the AI assistants of the future? Tech entrepreneur Harrison Chase details why large language models like ChatGPT are only one piece of the puzzle for creating tech capable of reasoning and understanding context, sharing fo

www.ted.com

https://medium.com/@szabokb/from-chat-bots-to-killer-bots-e71a20be2e2a

 

From Chat-bots to Killer-bots?

How memory, reasoning, and action-based learning transform AI agents from language processors to practical collaborators.

medium.com

https://www.agentx.so/post/what-is-ai-agent-2

 

AgentX - What is AI Agent ??

What is AI Agent ??

www.agentx.so

 

 

친절한 찰쓰씨
글쓴이
친절한 찰쓰씨
친절한 찰쓰씨 · 일상 UX 디자이너
기획·디자인·단상을 조용히 기록합니다.
작가 페이지에서 더 보기

이어서 읽기

새로워지기

꾸준히, 오래, 지치지 않고

Mar 31, 2026·8
새로워지기

테크 라이프 발란스

Feb 7, 2026·3
새로워지기

휴탈리티 박정렬

Feb 7, 2026·11