LangGraph๋ LangChain ์ํ๊ณ์ ์ผ๋ถ๋ก, ๋ณต์กํ AI ์ํฌํ๋ก์ฐ๋ฅผ ๊ตฌ์ถํ๊ธฐ ์ํ ๊ฐ๋ ฅํ ํ๋ ์์ํฌ
์ ์ฐํ๊ณ ํ์ฅ ๊ฐ๋ฅํ AI ์ ํ๋ฆฌ์ผ์ด์
์ ๋น๊ต์ ์ฝ๊ฒ ๋ง๋ค ์ ์์
from typing import TypedDict, Annotated, Sequence, List
from langchain_core.documents.base import Document
class AgentState(TypedDict):
actions: str
context: Sequence[Document]
answer: str
question: str
groundness_status: str
AgentState
๋ ์ํฌํ๋ก์ฐ์ ๊ฐ ๋จ๊ณ์์ ์ฌ์ฉ๋๋ ๋ฐ์ดํฐ๋ฅผ ์ ์def extract_actions(state: AgentState) -> AgentState:
"""์ก์
์ถ์ถ"""
actions = "์ง๋ฌธ์์ ์ถ์ถ๋ ์ก์
๋ค"
return AgentState(actions=actions)
def is_exist_actions(state: AgentState) -> str:
"""์ก์
์กด์ฌ ์ฌ๋ถ ์ฒดํฌ"""
# is_exist_actions, is_not_exist_actions
is_exist_actions = "is_exist_actions"
return is_exist_actions
def is_exist_docs(state: AgentState) -> str:
"""๊ฒ์ ๋ฌธ์ ์กด์ฌ ์ฌ๋ถ ์ฒดํฌ"""
# is_exist_docs, is_not_exist_docs
is_exist_docs = "is_exist_docs"
return is_exist_docs
def retrieve(state: AgentState) -> AgentState:
"""๋ฌธ์ ๊ฒ์"""
docs = [Document(page_content="๊ฒ์๋ ๋ฌธ์ 1"), Document(page_content="๊ฒ์๋ ๋ฌธ์ 2")]
return AgentState(context=docs)
def invoke_llm_with_context(state: AgentState) -> AgentState:
"""context์ ํจ๊ป LLM ํธ์ถ"""
answer = "LLM ๋ต๋ณ"
return AgentState(answer=answer)
def invoke_llm(state: AgentState) -> AgentState:
"""LLM ํธ์ถ"""
answer = "LLM ๋ต๋ณ"
return AgentState(answer=answer)
def check_groundedness(state: AgentState) -> AgentState:
"""๊ฒ์ ๋ฌธ์์ LLM ๋ต๋ณ์ ์ ํฉ์ฑ ํ์ธ"""
# grounded, notGrounded, notSure
groundness_status = "grounded"
return AgentState(groundness_status=groundness_status)
def judgement(state: AgentState) -> str:
"""๋
ธ๋ ์ฌํธ์ถ ํน์ ์ข
๋ฃ ํ๋จ"""
# retry_retrieve, retry_invoke_llm_with_context, END
judgement = END
return judgement
from langgraph.graph import StateGraph
workflow = StateGraph(AgentState)
workflow.add_node("extract_actions", extract_actions)
workflow.add_node("retrieve", retrieve)
workflow.add_node("invoke_llm", invoke_llm)
workflow.add_node("invoke_llm_with_context", invoke_llm_with_context)
workflow.add_node("check_groundedness", check_groundedness)
workflow.add_conditional_edges(
"extract_actions",
is_exist_actions,
{
"is_exist_actions": "retrieve",
"is_not_exist_actions": "invoke_llm",
}
)
workflow.add_conditional_edges(
"retrieve",
is_exist_docs,
{
"is_exist_docs": "invoke_llm_with_context",
"is_not_exist_docs": "invoke_llm",
}
)
workflow.add_edge("invoke_llm_with_context", "check_groundedness")
workflow.add_edge("invoke_llm", END)
workflow.add_conditional_edges(
"check_groundedness",
judgement,
{
"retry_retrieve": "retrieve",
"retry_invoke_llm_with_context": "invoke_llm_with_context",
END: END
}
)
workflow.set_entry_point("extract_actions")
app = workflow.compile()
app.invoke(AgentState(question="๋ด ์ง๋ฌธ"))