Kinetica는 벡터 유사도 검색을 통합 지원하는 데이터베이스입니다지원 기능:
- 정확한 최근접 이웃 검색 및 근사 최근접 이웃 검색
- L2 거리, 내적, 코사인 거리
Kinetica)를 사용하는 방법을 보여줍니다.
이를 위해서는 Kinetica 인스턴스가 필요하며, 다음 지침에 따라 쉽게 설정할 수 있습니다 - 설치 지침.
Copy
# Pip install necessary package
pip install -qU langchain-openai langchain-community
pip install "gpudb>=7.2.2.0"
pip install -qU tiktoken
OpenAIEmbeddings를 사용하려면 OpenAI API Key를 가져와야 합니다.
Copy
import getpass
import os
if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
Copy
## Loading Environment Variables
from dotenv import load_dotenv
load_dotenv()
Copy
False
Copy
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import (
Kinetica,
KineticaSettings,
)
from langchain_openai import OpenAIEmbeddings
Copy
embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
Copy
# Kinetica needs the connection to the database.
# This is how to set it up.
HOST = os.getenv("KINETICA_HOST", "http://127.0.0.1:9191")
USERNAME = os.getenv("KINETICA_USERNAME", "")
PASSWORD = os.getenv("KINETICA_PASSWORD", "")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
def create_config() -> KineticaSettings:
return KineticaSettings(host=HOST, username=USERNAME, password=PASSWORD)
Copy
from uuid import uuid4
from langchain_core.documents import Document
document_1 = Document(
page_content="I had chocolate chip pancakes and scrambled eggs for breakfast this morning.",
metadata={"source": "tweet"},
)
document_2 = Document(
page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
metadata={"source": "news"},
)
document_3 = Document(
page_content="Building an exciting new project with LangChain - come check it out!",
metadata={"source": "tweet"},
)
document_4 = Document(
page_content="Robbers broke into the city bank and stole $1 million in cash.",
metadata={"source": "news"},
)
document_5 = Document(
page_content="Wow! That was an amazing movie. I can't wait to see it again.",
metadata={"source": "tweet"},
)
document_6 = Document(
page_content="Is the new iPhone worth the price? Read this review to find out.",
metadata={"source": "website"},
)
document_7 = Document(
page_content="The top 10 soccer players in the world right now.",
metadata={"source": "website"},
)
document_8 = Document(
page_content="LangGraph is the best framework for building stateful, agentic applications!",
metadata={"source": "tweet"},
)
document_9 = Document(
page_content="The stock market is down 500 points today due to fears of a recession.",
metadata={"source": "news"},
)
document_10 = Document(
page_content="I have a bad feeling I am going to get deleted :(",
metadata={"source": "tweet"},
)
documents = [
document_1,
document_2,
document_3,
document_4,
document_5,
document_6,
document_7,
document_8,
document_9,
document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]
Euclidean Distance를 사용한 유사도 검색 (기본값)
Copy
# The Kinetica Module will try to create a table with the name of the collection.
# So, make sure that the collection name is unique and the user has the permission to create a table.
COLLECTION_NAME = "langchain_example"
connection = create_config()
db = Kinetica(
connection,
embeddings,
collection_name=COLLECTION_NAME,
)
db.add_documents(documents=documents, ids=uuids)
Copy
['05e5a484-0273-49d1-90eb-1276baca31de',
'd98b808f-dc0b-4328-bdbf-88f6b2ab6040',
'ba0968d4-e344-4285-ae0f-f5199b56f9d6',
'a25393b8-6539-45b5-993e-ea16d01941ec',
'804a37e3-1278-4b60-8b02-36b159ee8c1a',
'9688b594-3dc6-41d2-a937-babf8ff24c2f',
'40f7b8fe-67c7-489a-a5a5-7d3965e33bba',
'b4fc1376-c113-41e9-8f16-f9320517bedd',
'4d94d089-fdde-442b-84ab-36d9fe0670c8',
'66fdb79d-49ce-4b06-901a-fda6271baf2a']
Copy
# query = "What did the president say about Ketanji Brown Jackson"
# docs_with_score = db.similarity_search_with_score(query)
Copy
print()
print("Similarity Search")
results = db.similarity_search(
"LangChain provides abstractions to make working with LLMs easy",
k=2,
filter={"source": "tweet"},
)
for res in results:
print(f"* {res.page_content} [{res.metadata}]")
print()
print("Similarity search with score")
results = db.similarity_search_with_score(
"Will it be hot tomorrow?", k=1, filter={"source": "news"}
)
for res, score in results:
print(f"* [SIM={score:3f}] {res.page_content} [{res.metadata}]")
Copy
Similarity Search
* Building an exciting new project with LangChain - come check it out! [{'source': 'tweet'}]
* LangGraph is the best framework for building stateful, agentic applications! [{'source': 'tweet'}]
Similarity search with score
* [SIM=0.945397] The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees. [{'source': 'news'}]
vectorstore 작업하기
위에서는 vectorstore를 처음부터 생성했습니다. 그러나 종종 기존 vectorstore를 사용하고 싶을 때가 있습니다. 이를 위해 직접 초기화할 수 있습니다.Copy
store = Kinetica(
collection_name=COLLECTION_NAME,
config=connection,
embedding_function=embeddings,
)
문서 추가하기
기존 vectorstore에 문서를 추가할 수 있습니다.Copy
store.add_documents([Document(page_content="foo")])
Copy
['68c4c679-c4d9-4f2d-bf01-f6c4f2181503']
Copy
docs_with_score = db.similarity_search_with_score("foo")
Copy
docs_with_score[0]
Copy
(Document(metadata={}, page_content='foo'), 0.0015394920483231544)
Copy
docs_with_score[1]
Copy
(Document(metadata={'source': 'tweet'}, page_content='Building an exciting new project with LangChain - come check it out!'),
1.2609431743621826)
vectorstore 덮어쓰기
기존 collection이 있는 경우,from_documents를 수행하고 pre_delete_collection = True로 설정하여 덮어쓸 수 있습니다
Copy
db = Kinetica.from_documents(
documents=documents,
embedding=embeddings,
collection_name=COLLECTION_NAME,
config=connection,
pre_delete_collection=True,
)
Copy
docs_with_score = db.similarity_search_with_score("foo")
Copy
docs_with_score[0]
Copy
(Document(metadata={'source': 'tweet'}, page_content='Building an exciting new project with LangChain - come check it out!'),
1.260920763015747)
VectorStore를 Retriever로 사용하기
Copy
retriever = store.as_retriever()
Copy
print(retriever)
Copy
tags=['Kinetica', 'OpenAIEmbeddings'] vectorstore=<langchain_community.vectorstores.kinetica.Kinetica object at 0x7a48142b2230> search_kwargs={}
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.