LangChain Integration¶
langchain-akasicdb는 LangChain에서 AkasicDB를 사용하기 위한 integration package입니다. AkasicDB 기반 LangChain VectorStore 구현과 AkasicDB graph에 Cypher query를 실행하는 graph wrapper를 제공합니다.
요구 사항¶
- Python 3.11 이상
- 실행 중인 AkasicDB instance
- 대상 database에 활성화된 AkasicDB extension
- LangChain
Embeddingsinterface를 구현한 embedding model
먼저 Quick Start를 참고하여 AkasicDB를 실행합니다.
설치¶
LangChain integration package를 설치합니다.
이 package는 akasicdb[sdk], langchain-core, psycopg, numpy에 의존합니다.
Import Path¶
langchain_akasicdb package를 사용합니다.
Connection URL¶
AkasicDBVector는 내부에서 AkasicDB Python SDK를 사용하므로 SQLAlchemy-style PostgreSQL URL을 사용합니다.
AkasicDBGraph는 Psycopg로 graph query를 직접 실행하므로 Psycopg-style PostgreSQL URL을 사용합니다.
Vector Store¶
AkasicDBVector는 LangChain VectorStore interface를 구현합니다. Document text, metadata, embedding을 AkasicDB collection에 저장합니다.
from langchain_akasicdb import AkasicDBVector
vector_store = AkasicDBVector(
embedding=embeddings,
dimension=1536,
db_url="postgresql+psycopg://postgres:mysecretpassword@localhost:5432/postgres",
collection_name="docs",
new_table=True,
)
Constructor argument는 다음과 같습니다.
| Argument | 설명 |
|---|---|
embedding |
LangChain Embeddings 구현체 |
dimension |
Embedding vector dimension |
db_url |
SQLAlchemy-style AkasicDB connection URL |
collection_name |
AkasicDB collection 이름. 기본값은 langchain |
new_table |
True이면 collection table을 새로 생성 |
Text 또는 Document로 생성¶
Content 추가와 collection 생성을 한 번에 수행하려면 from_texts() 또는 from_documents()를 사용합니다. Embedding dimension은 embedding으로부터 자동으로 감지됩니다.
from langchain_core.documents import Document
from langchain_akasicdb import AkasicDBVector
docs = [
Document(page_content="AkasicDB supports vector search.", metadata={"source": "manual"}),
Document(page_content="LangChain can use AkasicDB as a VectorStore.", metadata={"source": "manual"}),
]
vector_store = AkasicDBVector.from_documents(
documents=docs,
embedding=embeddings,
db_url="postgresql+psycopg://postgres:mysecretpassword@localhost:5432/postgres",
collection_name="docs",
)
Document 추가와 삭제¶
LangChain 표준 add_texts(), add_documents(), delete() method를 사용합니다.
ids = vector_store.add_texts(
["hello akasicdb", "hello langchain"],
metadatas=[{"topic": "db"}, {"topic": "llm"}],
)
vector_store.delete(ids=[ids[0]])
Similarity Search¶
Document만 필요하면 similarity_search()를 사용하고, score가 필요하면 similarity_search_with_score()를 사용합니다.
docs = vector_store.similarity_search(
"How do I store embeddings?",
k=3,
filter={"topic": "db"},
)
docs_with_scores = vector_store.similarity_search_with_score(
"How do I store embeddings?",
k=3,
)
지원하는 distance_func 값은 다음과 같습니다.
| Value | AkasicDB operator | 의미 |
|---|---|---|
sqrt_euclid |
<-> |
L2 distance |
neg_dot_prod |
<#> |
Negative dot product |
ned_cos |
<=> |
Cosine distance |
Maximal Marginal Relevance¶
Similarity와 diversity를 함께 고려한 결과가 필요하면 MMR search를 사용합니다.
docs = vector_store.max_marginal_relevance_search(
"graph vector search",
k=4,
fetch_k=20,
lambda_mult=0.5,
)
MMR은 sqrt_euclid, ned_cos distance function을 지원합니다.
Retriever¶
AkasicDBVector는 as_retriever()를 통해 LangChain retriever로 사용할 수 있습니다.
retriever = vector_store.as_retriever(
search_type="similarity",
search_kwargs={"k": 4},
)
docs = retriever.invoke("What is AkasicDB?")
Graph Wrapper¶
AkasicDBGraph는 AkasicDB graph query를 위한 LangChain-compatible graph wrapper입니다. Graph는 AkasicDB에 미리 정의 및 생성되어 있어야 합니다.
from langchain_akasicdb import AkasicDBGraph
graph = AkasicDBGraph(
db_url="postgresql://postgres:mysecretpassword@localhost:5432/postgres",
graph_name="retail_graph",
)
rows = graph.query("""
MATCH (c:v_customer)-[:buy]->(i:v_item)
RETURN c.first_name AS customer, i.name AS item
""")
Constructor argument는 다음과 같습니다.
| Argument | 설명 |
|---|---|
db_url |
Psycopg-style AkasicDB connection URL |
graph_name |
AkasicDB graph 이름 |
refresh_schema |
초기화 시 schema metadata를 로드합니다. 기본값은 True |
Query Parameter¶
params로 parameter를 전달합니다. Cypher query에서는 $name 형태로 참조합니다.
rows = graph.query(
"""
MATCH (c:v_customer)
WHERE c.first_name = $name
RETURN c.last_name AS last_name
""",
params={"name": "Margaret"},
)
Schema Introspection¶
AkasicDBGraph는 사람이 읽을 수 있는 schema string과 structured dictionary를 제공합니다.
Graph definition을 다시 생성하거나 변경한 뒤에는 refresh_schema()를 호출합니다.
Compatibility Notes¶
- 현재 package에서
AkasicDBVector.get_by_ids()는 구현되어 있지 않습니다. - Vector store는 AkasicDB Python SDK를 통해 AkasicDB collection table을 생성합니다.
- Graph wrapper는 기존 AkasicDB graph에 Cypher를 실행합니다. Graph definition을 생성하지는 않습니다.