Skip to content
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

New user features #17

Merged
merged 2 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 51 additions & 10 deletions docs/3_add_items_and_interactions.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# Adding Items and User Interactions

## Overview
This guide explains how to add items to your recommender system and record user interactions using the `WeaviateRecommendClient`.

This guide explains how to add items to your recommender system, record user interactions, and manage user data using the `WeaviateRecommendClient`.

## Prerequisites

- Established connection to the Recommender Service (see `1_connection.md`)
- Created recommender schema (see `2_create_schema.md`)

Expand Down Expand Up @@ -45,13 +47,37 @@ response = client.item.add_batch(items)
print(response)
```

## Recording User Interactions
## Managing User Data

### Creating a New User

To record a single user interactions with an item:
To create a new user in the recommender system:

```python
from weaviate_recommend.models.data import UserInteraction
from weaviate_recommend.models.data import User

new_user = User(id="user123", properties={"name": "John Doe", "age": 30})
response = client.user.create_user(new_user)
print(response)
```

### Retrieving User Information

To get all properties for a user by ID:

```python
user_id = "user123"
user = client.user.get_user(user_id)
print(user)
```

## Recording User Interactions

### Adding a Single User Interaction

To record a single user interaction with an item:

```python
user_id = "user123"
item_id = "item456"
interaction_type = "purchase" # Or "like", "view", etc. as defined in your schema
Expand All @@ -71,22 +97,37 @@ print(response)
For bulk addition of user interactions:

```python
from weaviate_recommend.models.data import UserInteraction

interactions = [
UserInteraction(user_id="user1", "item_id": "1", "interaction_property_name": "purchase", "weight": 1.0},
UserInteraction(user_id="user1", "item_id": "4", "interaction_property_name": "purchase", "weight": 0.5},
# add more items as needed
UserInteraction(user_id="user1", item_id="1", interaction_property_name="purchase", weight=1.0),
UserInteraction(user_id="user1", item_id="4", interaction_property_name="purchase", weight=0.5),
# add more interactions as needed
]

client.user.add_interactions(interactions)
response = client.user.add_interactions(interactions)
print(response)
```

### Retrieving User Interactions

To get all interactions for a specific user:

```python
user_id = "user123"
interactions = client.user.get_user_interactions(user_id)
for interaction in interactions:
print(f"Item: {interaction.item_id}, Type: {interaction.interaction_property_name}, Weight: {interaction.weight}")
```

## Best Practices

1. Ensure all required properties are included when adding items.
1. Ensure all required properties are included when adding items or creating users.
2. Use batch operations for adding multiple items or user interactions efficiently.
3. Choose appropriate weights for user interactions to reflect their importance.
4. Regularly add user interactions to keep the recommender system up-to-date.
5. Use the `get_user` and `get_user_interactions` methods to retrieve and analyze user data as needed.

## Next Steps

After adding items and user interactions, you can train your recommender system to generate personalized recommendations. See `4_train.md` for information on training the system.
After adding items, managing user data, and recording user interactions, you can train your recommender system to generate personalized recommendations. See `4_train.md` for information on training the system.
5 changes: 5 additions & 0 deletions weaviate_recommend/models/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,8 @@ class UserInteraction(BaseModel):
interaction_property_name: str
weight: float = 1.0
created_at: Union[str, None] = None


class User(BaseModel):
id: Union[str, UUID]
properties: Dict[str, Any]
4 changes: 4 additions & 0 deletions weaviate_recommend/models/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,7 @@ class AddUserInteractionResponse(BaseModel):
class AddUserInteractionsResponse(BaseModel):
message: str
num_interactions_added: int


class CreateUserResponse(BaseModel):
message: str
53 changes: 50 additions & 3 deletions weaviate_recommend/services/data/user.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from typing import TYPE_CHECKING, Union
from typing import TYPE_CHECKING, List, Union
from uuid import UUID

import requests

from weaviate_recommend.exceptions import RecommendApiException
from weaviate_recommend.models.data import UserInteraction
from weaviate_recommend.models.data import User, UserInteraction
from weaviate_recommend.models.responses import (
AddUserInteractionResponse,
AddUserInteractionsResponse,
CreateUserResponse,
)
from weaviate_recommend.utils import get_auth_header, get_datetime

Expand Down Expand Up @@ -54,7 +55,7 @@ def add_interaction(
return AddUserInteractionResponse.model_validate(response.json())

def add_interactions(
self, interactions: list[UserInteraction]
self, interactions: List[UserInteraction]
) -> AddUserInteractionsResponse:
"""
Add multiple user interactions.
Expand All @@ -71,3 +72,49 @@ def add_interactions(
if response.status_code != 200:
raise RecommendApiException(response.text)
return AddUserInteractionsResponse.model_validate(response.json())

def get_user_interactions(self, user_id: Union[str, UUID]) -> List[UserInteraction]:
"""
Get all interactions for a user.
"""
if isinstance(user_id, UUID):
user_id = str(user_id)

response = requests.get(
f"{self.endpoint_url}interactions/{user_id}",
headers=get_auth_header(self.client._api_key),
)
if response.status_code != 200:
raise RecommendApiException(response.text)
return [
UserInteraction.model_validate(interaction)
for interaction in response.json()
]

def create_user(self, user: User) -> CreateUserResponse:
"""
Create a new user in the recommender with the given properties, not including interactions.
"""
response = requests.post(
f"{self.endpoint_url}create",
json=user.model_dump(),
headers=get_auth_header(self.client._api_key),
)
if response.status_code != 200:
raise RecommendApiException(response.text)
return CreateUserResponse.model_validate(response.json())

def get_user(self, user_id: Union[str, UUID]) -> User:
"""
Get all properties for a user by ID.
"""
if isinstance(user_id, UUID):
user_id = str(user_id)

response = requests.get(
f"{self.endpoint_url}{user_id}",
headers=get_auth_header(self.client._api_key),
)
if response.status_code != 200:
raise RecommendApiException(response.text)
return User.model_validate(response.json())
Loading