Amazon Neptune은 뛰어난 확장성과 가용성을 제공하는 고성능 그래프 분석 및 서버리스 데이터베이스입니다. 이 예제는 openCypher를 사용하여 Neptune 그래프 데이터베이스를 쿼리하고 사람이 읽을 수 있는 응답을 반환하는 QA chain을 보여줍니다. Cypher는 property graph에서 표현력 있고 효율적인 데이터 쿼리를 가능하게 하는 선언적 그래프 쿼리 언어입니다. openCypher는 Cypher의 오픈소스 구현입니다.

Neptune Open Cypher QA Chain

이 QA chain은 openCypher를 사용하여 Amazon Neptune을 쿼리하고 사람이 읽을 수 있는 응답을 반환합니다 LangChain은 create_neptune_opencypher_qa_chain을 통해 Neptune DatabaseNeptune Analytics 모두를 지원합니다. Neptune Database는 최적의 확장성과 가용성을 위해 설계된 서버리스 그래프 데이터베이스입니다. 초당 100,000개의 쿼리로 확장해야 하는 그래프 데이터베이스 워크로드, Multi-AZ 고가용성 및 다중 리전 배포를 위한 솔루션을 제공합니다. Neptune Database는 소셜 네트워킹, 사기 경고 및 Customer 360 애플리케이션에 사용할 수 있습니다. Neptune Analytics는 대량의 그래프 데이터를 메모리에서 빠르게 분석하여 인사이트를 얻고 트렌드를 찾을 수 있는 분석 데이터베이스 엔진입니다. Neptune Analytics는 기존 그래프 데이터베이스 또는 데이터 레이크에 저장된 그래프 데이터셋을 빠르게 분석하기 위한 솔루션입니다. 인기 있는 그래프 분석 알고리즘과 저지연 분석 쿼리를 사용합니다.

Neptune Database 사용하기

from langchain_aws.graphs import NeptuneGraph

host = "<neptune-host>"
port = 8182
use_https = True

graph = NeptuneGraph(host=host, port=port, use_https=use_https)

Neptune Analytics 사용하기

from langchain_aws.graphs import NeptuneAnalyticsGraph

graph = NeptuneAnalyticsGraph(graph_identifier="<neptune-analytics-graph-id>")

Neptune openCypher QA Chain 사용하기

이 QA chain은 openCypher를 사용하여 Neptune 그래프 데이터베이스를 쿼리하고 사람이 읽을 수 있는 응답을 반환합니다.
from langchain_aws import ChatBedrockConverse
from langchain_aws.chains import create_neptune_opencypher_qa_chain

MODEL_ID = "anthropic.claude-3-5-sonnet-20241022-v2:0"
llm = ChatBedrockConverse(
    model=MODEL_ID,
    temperature=0,
)

chain = create_neptune_opencypher_qa_chain(llm=llm, graph=graph)

result = chain.invoke("How many outgoing routes does the Austin airport have?")
print(result["result"].content)
Austin airport has 98 outgoing routes.

Message History 추가하기

Neptune openCypher QA chain은 RunnableWithMessageHistory로 래핑될 수 있는 기능을 가지고 있습니다. 이는 chain에 메시지 히스토리를 추가하여 여러 호출에 걸쳐 대화 상태를 유지하는 챗봇을 만들 수 있게 합니다. 시작하려면 메시지 히스토리를 저장하고 로드하는 방법이 필요합니다. 이를 위해 각 스레드는 InMemoryChatMessageHistory의 인스턴스로 생성되고, 반복적인 액세스를 위해 딕셔너리에 저장됩니다. (참고: python.langchain.com/docs/versions/migrating_memory/chat_history/#chatmessagehistory)
from langchain_core.chat_history import InMemoryChatMessageHistory

chats_by_session_id = {}


def get_chat_history(session_id: str) -> InMemoryChatMessageHistory:
    chat_history = chats_by_session_id.get(session_id)
    if chat_history is None:
        chat_history = InMemoryChatMessageHistory()
        chats_by_session_id[session_id] = chat_history
    return chat_history
이제 QA chain과 메시지 히스토리 저장소를 사용하여 새로운 RunnableWithMessageHistory를 생성할 수 있습니다. 기본 chain에서 예상하는 형식과 일치하도록 query를 input key로 설정해야 합니다.
from langchain_core.runnables.history import RunnableWithMessageHistory

runnable_with_history = RunnableWithMessageHistory(
    chain,
    get_chat_history,
    input_messages_key="query",
)
chain을 호출하기 전에 새로운 InMemoryChatMessageHistory가 기억할 대화를 위한 고유한 session_id를 생성해야 합니다.
import uuid

session_id = uuid.uuid4()
마지막으로 session_id와 함께 메시지 히스토리가 활성화된 chain을 호출합니다.
result = runnable_with_history.invoke(
    {"query": "How many destinations can I fly to directly from Austin airport?"},
    config={"configurable": {"session_id": session_id}},
)
print(result["result"].content)
You can fly directly to 98 destinations from Austin airport.
동일한 session_id로 chain이 계속 호출되면 대화의 이전 쿼리 컨텍스트에서 응답이 반환됩니다.
result = runnable_with_history.invoke(
    {"query": "Out of those destinations, how many are in Europe?"},
    config={"configurable": {"session_id": session_id}},
)
print(result["result"].content)
You can fly directly to 4 destinations in Europe from Austin airport.
result = runnable_with_history.invoke(
    {"query": "Give me the codes and names of those airports."},
    config={"configurable": {"session_id": session_id}},
)
print(result["result"].content)
The four European destinations you can fly to directly from Austin airport are:
- AMS (Amsterdam Airport Schiphol)
- FRA (Frankfurt am Main)
- LGW (London Gatwick)
- LHR (London Heathrow)

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I