-
Notifications
You must be signed in to change notification settings - Fork 439
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add Weaviate memory adapter #95
Open
zainhas
wants to merge
12
commits into
meta-llama:main
Choose a base branch
from
zainhas:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
49763c4
add Weaviate memory adapter
zainhas 2fc9bd9
Refactor Weaviate config to remove unused api_key field
zainhas ba8044d
Refactor Weaviate config to include cluster URL in memory adapter
zainhas 619b03b
Merge branch 'meta-llama:main' into main
zainhas a138b48
addressed the PR comments
zainhas af1710a
Merge branch 'main' of https://github.com/zainhas/weaviate-memory-ada…
zainhas 38bc150
Merge branch 'meta-llama:main' into main
zainhas aca4a4d
Refactor WeaviateMemoryAdapter initialization and client handling
zainhas 3eb03da
Merge branch 'main' of https://github.com/zainhas/weaviate-memory-ada…
zainhas 3ee415d
Merge branch 'meta-llama:main' into main
zainhas c13b2f0
Merge branch 'meta-llama:main' into main
zainhas ed84641
remove prints
zainhas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
from .config import WeaviateConfig | ||
|
||
async def get_adapter_impl(config: WeaviateConfig, _deps): | ||
from .weaviate import WeaviateMemoryAdapter | ||
|
||
impl = WeaviateMemoryAdapter(config) | ||
await impl.initialize() | ||
return impl |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the terms described in the LICENSE file in | ||
# the root directory of this source tree. | ||
|
||
from llama_models.schema_utils import json_schema_type | ||
from pydantic import BaseModel, Field | ||
|
||
class WeaviateRequestProviderData(BaseModel): | ||
# if there _is_ provider data, it must specify the API KEY | ||
# if you want it to be optional, use Optional[str] | ||
weaviate_api_key: str | ||
weaviate_cluster_url: str | ||
|
||
@json_schema_type | ||
class WeaviateConfig(BaseModel): | ||
collection: str = Field(default="MemoryBank") |
192 changes: 192 additions & 0 deletions
192
llama_stack/providers/adapters/memory/weaviate/weaviate.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,192 @@ | ||
import json | ||
import uuid | ||
from typing import List, Optional, Dict, Any | ||
from numpy.typing import NDArray | ||
|
||
import weaviate | ||
import weaviate.classes as wvc | ||
from weaviate.classes.init import Auth | ||
|
||
from llama_stack.apis.memory import * | ||
from llama_stack.distribution.request_headers import get_request_provider_data | ||
from llama_stack.providers.utils.memory.vector_store import ( | ||
BankWithIndex, | ||
EmbeddingIndex, | ||
) | ||
|
||
from .config import WeaviateConfig, WeaviateRequestProviderData | ||
|
||
class WeaviateIndex(EmbeddingIndex): | ||
def __init__(self, client: weaviate.Client, collection: str): | ||
self.client = client | ||
self.collection = collection | ||
|
||
async def add_chunks(self, chunks: List[Chunk], embeddings: NDArray): | ||
assert len(chunks) == len(embeddings), f"Chunk length {len(chunks)} does not match embedding length {len(embeddings)}" | ||
|
||
data_objects = [] | ||
for i, chunk in enumerate(chunks): | ||
|
||
data_objects.append(wvc.data.DataObject( | ||
properties={ | ||
"chunk_content": chunk, | ||
}, | ||
vector = embeddings[i].tolist() | ||
)) | ||
|
||
# Inserting chunks into a prespecified Weaviate collection | ||
assert self.collection is not None, "Collection name must be specified" | ||
my_collection = self.client.collections.get(self.collection) | ||
|
||
await my_collection.data.insert_many(data_objects) | ||
|
||
|
||
async def query(self, embedding: NDArray, k: int) -> QueryDocumentsResponse: | ||
assert self.collection is not None, "Collection name must be specified" | ||
|
||
my_collection = self.client.collections.get(self.collection) | ||
|
||
results = my_collection.query.near_vector( | ||
near_vector = embedding.tolist(), | ||
limit = k, | ||
return_meta_data = wvc.query.MetadataQuery(distance=True) | ||
) | ||
|
||
chunks = [] | ||
scores = [] | ||
for doc in results.objects: | ||
try: | ||
chunk = doc.properties["chunk_content"] | ||
chunks.append(chunk) | ||
scores.append(1.0 / doc.metadata.distance) | ||
|
||
except Exception as e: | ||
import traceback | ||
traceback.print_exc() | ||
print(f"Failed to parse document: {e}") | ||
|
||
return QueryDocumentsResponse(chunks=chunks, scores=scores) | ||
|
||
|
||
class WeaviateMemoryAdapter(Memory): | ||
def __init__(self, config: WeaviateConfig) -> None: | ||
self.config = config | ||
self.client = None | ||
self.cache = {} | ||
|
||
def _get_client(self) -> weaviate.Client: | ||
request_provider_data = get_request_provider_data() | ||
|
||
if request_provider_data is not None: | ||
assert isinstance(request_provider_data, WeaviateRequestProviderData) | ||
|
||
# Connect to Weaviate Cloud | ||
return weaviate.connect_to_weaviate_cloud( | ||
cluster_url = request_provider_data.weaviate_cluster_url, | ||
auth_credentials = Auth.api_key(request_provider_data.weaviate_api_key), | ||
) | ||
|
||
async def initialize(self) -> None: | ||
try: | ||
self.client = self._get_client() | ||
|
||
# Create collection if it doesn't exist | ||
if not self.client.collections.exists(self.config.collection): | ||
self.client.collections.create( | ||
name = self.config.collection, | ||
vectorizer_config = wvc.config.Configure.Vectorizer.none(), | ||
properties=[ | ||
wvc.config.Property( | ||
name="chunk_content", | ||
data_type=wvc.config.DataType.TEXT, | ||
), | ||
] | ||
) | ||
|
||
except Exception as e: | ||
import traceback | ||
traceback.print_exc() | ||
raise RuntimeError("Could not connect to Weaviate server") from e | ||
|
||
async def shutdown(self) -> None: | ||
self.client = self._get_client() | ||
|
||
if self.client: | ||
self.client.close() | ||
|
||
async def create_memory_bank( | ||
self, | ||
name: str, | ||
config: MemoryBankConfig, | ||
url: Optional[URL] = None, | ||
) -> MemoryBank: | ||
bank_id = str(uuid.uuid4()) | ||
bank = MemoryBank( | ||
bank_id=bank_id, | ||
name=name, | ||
config=config, | ||
url=url, | ||
) | ||
self.client = self._get_client() | ||
|
||
# Store the bank as a new collection in Weaviate | ||
self.client.collections.create( | ||
name=bank_id | ||
) | ||
|
||
index = BankWithIndex( | ||
bank=bank, | ||
index=WeaviateIndex(cleint = self.client, collection = bank_id), | ||
) | ||
self.cache[bank_id] = index | ||
return bank | ||
|
||
async def get_memory_bank(self, bank_id: str) -> Optional[MemoryBank]: | ||
bank_index = await self._get_and_cache_bank_index(bank_id) | ||
if bank_index is None: | ||
return None | ||
return bank_index.bank | ||
|
||
async def _get_and_cache_bank_index(self, bank_id: str) -> Optional[BankWithIndex]: | ||
|
||
self.client = self._get_client() | ||
|
||
if bank_id in self.cache: | ||
return self.cache[bank_id] | ||
|
||
collections = await self.client.collections.list_all().keys() | ||
|
||
for collection in collections: | ||
if collection == bank_id: | ||
bank = MemoryBank(**json.loads(collection.metadata["bank"])) | ||
index = BankWithIndex( | ||
bank=bank, | ||
index=WeaviateIndex(self.client, collection), | ||
) | ||
self.cache[bank_id] = index | ||
return index | ||
|
||
return None | ||
|
||
async def insert_documents( | ||
self, | ||
bank_id: str, | ||
documents: List[MemoryBankDocument], | ||
) -> None: | ||
index = await self._get_and_cache_bank_index(bank_id) | ||
if not index: | ||
raise ValueError(f"Bank {bank_id} not found") | ||
|
||
await index.insert_documents(documents) | ||
|
||
async def query_documents( | ||
self, | ||
bank_id: str, | ||
query: InterleavedTextMedia, | ||
params: Optional[Dict[str, Any]] = None, | ||
) -> QueryDocumentsResponse: | ||
index = await self._get_and_cache_bank_index(bank_id) | ||
if not index: | ||
raise ValueError(f"Bank {bank_id} not found") | ||
|
||
return await index.query_documents(query, params) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
provider data isn't present at this point -- it is only provided at the time of the request. you should initialize the client on every client call and if we need a cache of clients then, we'd need to build that.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
modified the method to return an initialized client. following this I initialize the client on every client call using the method.