-
Notifications
You must be signed in to change notification settings - Fork 5
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
Updating the swarm sample, to include actual product data. #7
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,73 +1,99 @@ | ||
import json | ||
import os | ||
import sys | ||
import uuid | ||
from typing import List, Optional | ||
|
||
import azure_open_ai | ||
from azure.cosmos import ContainerProxy, CosmosClient, PartitionKey, exceptions | ||
|
||
# Initialize CosmosDB Client | ||
|
||
from azure.cosmos import CosmosClient, PartitionKey, exceptions | ||
COSMOS_DB_URL = os.getenv("COSMOS_DB_URL") | ||
COSMOS_DB_KEY = os.getenv("COSMOS_DB_KEY") | ||
AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY") | ||
DATABASE_NAME = "ProductAssistant" | ||
PRODUCTS_CONTAINER = "Products" | ||
USERS_CONTAINER = "Users" | ||
PURCHASE_HISTORY_CONTAINER = "PurchaseHistory" | ||
|
||
# Initialize the Cosmos client | ||
# reference environment variables for the values of these variables | ||
endpoint = os.environ['AZURE_COSMOSDB_ENDPOINT'] | ||
key = os.environ['AZURE_COSMOSDB_KEY'] | ||
client = CosmosClient(endpoint, key) | ||
client = CosmosClient(COSMOS_DB_URL, COSMOS_DB_KEY) | ||
client.create_database_if_not_exists(DATABASE_NAME) | ||
database = client.get_database_client(DATABASE_NAME) | ||
|
||
# Database and container names | ||
database_name = "MultiAgentDemoDB" | ||
users_container_name = "Users" | ||
purchase_history_container_name = "PurchaseHistory" | ||
products_container_name = "Products" | ||
|
||
# Create database and containers if they don't exist | ||
def create_database(): | ||
# Create Containers with Vector and Full-Text Indexing Policies | ||
def create_containers(): | ||
try: | ||
database = client.create_database_if_not_exists(id=database_name) | ||
users_container = database.create_container_if_not_exists( | ||
id=users_container_name, | ||
id=USERS_CONTAINER, | ||
partition_key=PartitionKey(path="/user_id"), | ||
offer_throughput=400 | ||
offer_throughput=400, | ||
) | ||
|
||
print( | ||
f"Container {USERS_CONTAINER} created." | ||
) | ||
|
||
purchase_history_container = database.create_container_if_not_exists( | ||
id=purchase_history_container_name, | ||
id=PURCHASE_HISTORY_CONTAINER, | ||
partition_key=PartitionKey(path="/user_id"), | ||
offer_throughput=400 | ||
) | ||
|
||
print( | ||
f"Container {PURCHASE_HISTORY_CONTAINER} created." | ||
) | ||
|
||
vector_embedding_policy = { | ||
"vectorEmbeddings": [ | ||
{ | ||
"path": "/product_description_vector", | ||
"path": "/embedding", | ||
"dataType": "float32", | ||
"dimensions": 1536, | ||
"distanceFunction": "cosine", | ||
"dimensions": 1536 | ||
}, | ||
} | ||
] | ||
} | ||
diskann_indexing_policy = { | ||
"includedPaths": [ | ||
{"path": "/*"} | ||
], | ||
"excludedPaths": [ | ||
{"path": "/\"_etag\"/?"} | ||
], | ||
"vectorIndexes": [ | ||
|
||
full_text_policy = { | ||
"defaultLanguage": "en-US", | ||
"fullTextPaths": [ | ||
{ | ||
"path": "/product_description_vector", | ||
"type": "diskANN", | ||
"path": "/product_description", | ||
"language": "en-US", | ||
} | ||
] | ||
} | ||
|
||
indexing_policy = { | ||
"indexingMode": "consistent", | ||
"includedPaths": [{"path": "/*"}], | ||
"excludedPaths": [{"path": '/"_etag"/?'}], | ||
"vectorIndexes": [{"path": "/embedding", "type": "diskANN"}], | ||
"fullTextIndexes": [{"path": "/product_description"}], | ||
} | ||
|
||
products_container = database.create_container_if_not_exists( | ||
id=products_container_name, | ||
partition_key=PartitionKey(path="/product_id"), | ||
id=PRODUCTS_CONTAINER, | ||
partition_key=PartitionKey(path="/category"), | ||
offer_throughput=400, | ||
vector_embedding_policy=vector_embedding_policy, | ||
indexing_policy=diskann_indexing_policy | ||
full_text_policy=full_text_policy, | ||
indexing_policy=indexing_policy, | ||
) | ||
|
||
print( | ||
f"Container {PRODUCTS_CONTAINER} created with vector and full-text search indexing." | ||
) | ||
except exceptions.CosmosHttpResponseError as e: | ||
print(f"Database creation failed: {e}") | ||
print(f"Container creation failed: {e}") | ||
|
||
|
||
def add_user(user_id, first_name, last_name, email, phone): | ||
database = client.get_database_client(database_name) | ||
container = database.get_container_client(users_container_name) | ||
container = database.get_container_client(USERS_CONTAINER) | ||
user = { | ||
"id": str(user_id), | ||
"id": str(uuid.uuid4()), | ||
"user_id": user_id, | ||
"first_name": first_name, | ||
"last_name": last_name, | ||
|
@@ -79,29 +105,32 @@ def add_user(user_id, first_name, last_name, email, phone): | |
except exceptions.CosmosResourceExistsError: | ||
print(f"User with user_id {user_id} already exists.") | ||
|
||
def add_purchase(user_id, date_of_purchase, item_id, amount): | ||
database = client.get_database_client(database_name) | ||
container = database.get_container_client(purchase_history_container_name) | ||
|
||
def add_purchase(user_id, date_of_purchase, item_id, amount, product_name, category): | ||
container = database.get_container_client(PURCHASE_HISTORY_CONTAINER) | ||
purchase = { | ||
"id": f"{user_id}_{item_id}_{date_of_purchase}", | ||
"id": str(uuid.uuid4()), | ||
"user_id": user_id, | ||
"date_of_purchase": date_of_purchase, | ||
"item_id": item_id, | ||
"product_id": item_id, | ||
"product_name": product_name, | ||
"category": category, | ||
"amount": amount | ||
} | ||
try: | ||
container.create_item(body=purchase) | ||
except exceptions.CosmosResourceExistsError: | ||
print(f"Purchase already exists for user_id {user_id} on {date_of_purchase} for item_id {item_id}.") | ||
|
||
def add_product(product_id, product_name, product_description, price): | ||
database = client.get_database_client(database_name) | ||
container = database.get_container_client(products_container_name) | ||
|
||
def add_product(product_id, product_name, category, product_description, price): | ||
container = database.get_container_client(PRODUCTS_CONTAINER) | ||
product_description_vector = azure_open_ai.generate_embedding(product_description) | ||
product = { | ||
"id": str(product_id), | ||
"id": str(uuid.uuid4()), | ||
"product_id": product_id, | ||
"product_name": product_name, | ||
"category": category, | ||
"product_description": product_description, | ||
"product_description_vector": product_description_vector, | ||
"price": price | ||
|
@@ -111,72 +140,68 @@ def add_product(product_id, product_name, product_description, price): | |
except exceptions.CosmosResourceExistsError: | ||
print(f"Product with product_id {product_id} already exists.") | ||
|
||
def preview_table(container_name): | ||
database = client.get_database_client(database_name) | ||
container = database.get_container_client(container_name) | ||
items = container.query_items( | ||
query="SELECT * FROM c", | ||
enable_cross_partition_query=True | ||
|
||
def process_and_insert_data( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this could do with being parallelized and increasing default RU to 10000 for the container, or it takes quite a long time. |
||
filename: str, | ||
container: ContainerProxy, | ||
vector_field: Optional[str] = None, | ||
full_text_fields: Optional[List[str]] = None, | ||
): | ||
if not os.path.exists(filename): | ||
print(f"File {filename} not found.") | ||
return | ||
|
||
with open(filename, "r") as f: | ||
data = json.load(f) | ||
|
||
if len(data) > 300: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this logic means that some records are skipped if number of json docs in the file is greater than 300? What is this for? |
||
data = data[226:] | ||
|
||
for entry in data: | ||
if full_text_fields is not None: | ||
for field in full_text_fields: | ||
if field in entry and isinstance(entry[field], list): | ||
entry[field] = [", ".join(map(str, entry[field]))] | ||
|
||
# Generate vector embedding | ||
if vector_field and vector_field in entry and isinstance(entry[vector_field], str): | ||
entry["embedding"] = azure_open_ai.generate_embedding(entry[vector_field]) | ||
|
||
# Insert into CosmosDB | ||
entry["id"] = str(uuid.uuid4()) | ||
size = sys.getsizeof(json.dumps(entry)) | ||
if size > 2 * 1024 * 1024: # 2MB in bytes | ||
print(f"Document {entry['id']} is too large: {size} bytes") | ||
container.upsert_item(entry) | ||
|
||
print(f"Inserted data from {filename} into {container.id}.") | ||
|
||
|
||
def main(): | ||
# Create Containers | ||
create_containers() | ||
|
||
products_container = database.get_container_client(PRODUCTS_CONTAINER) | ||
users_container = database.get_container_client(USERS_CONTAINER) | ||
purchase_history_container = database.get_container_client(PURCHASE_HISTORY_CONTAINER) | ||
|
||
# Insert data into CosmosDB with embedding and indexing | ||
file_prefix = "/Users/aayushkataria/git/multi-agent-swarm/src/data/" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. hardcoded |
||
process_and_insert_data( | ||
file_prefix + "final_products.json", | ||
products_container, | ||
"product_description", | ||
["product_description"], | ||
) | ||
for item in items: | ||
if (container_name == products_container_name): | ||
# redact the product description vector | ||
item.pop("product_description_vector", None) | ||
print(item) | ||
|
||
# Initialize and load database | ||
def initialize_database(): | ||
create_database() | ||
|
||
# Add some initial users | ||
initial_users = [ | ||
(1, "Alice", "Smith", "alice@test.com", "123-456-7890"), | ||
(2, "Bob", "Johnson", "bob@test.com", "234-567-8901"), | ||
(3, "Sarah", "Brown", "sarah@test.com", "555-567-8901"), | ||
# Add more initial users here | ||
] | ||
|
||
for user in initial_users: | ||
add_user(*user) | ||
|
||
# Add some initial purchases | ||
initial_purchases = [ | ||
(1, "2024-01-01", 101, 99.99), | ||
(2, "2023-12-25", 100, 39.99), | ||
(3, "2023-11-14", 307, 49.99), | ||
] | ||
|
||
for purchase in initial_purchases: | ||
add_purchase(*purchase) | ||
|
||
initial_products = [ | ||
(7, "Hat", "A hat is a stylish and functional accessory designed to shield the " | ||
"head from the elements while adding a touch of personality to any outfit. " | ||
"Crafted from materials such as wool, cotton, straw, or synthetic blends, hats come " | ||
"in a variety of shapes and designs, from wide-brimmed sun hats to snug beanies and classic fedoras. " | ||
"They offer versatile use, providing protection from sun, rain, or cold while serving as a " | ||
"fashionable statement piece. Whether for outdoor adventures, formal occasions, " | ||
"or casual outings, a hat combines practicality and style, making it a " | ||
"timeless wardrobe essential", 19.99), | ||
(8, "Wool socks", "Wool socks are premium, cozy footwear accessories designed " | ||
"to provide exceptional warmth, comfort, and moisture-wicking properties. " | ||
"Made from natural wool fibers, they are ideal for keeping feet insulated in " | ||
"cold weather while remaining breathable in warmer conditions. These socks are soft, " | ||
"durable, and naturally odor-resistant, making them perfect for everyday wear, " | ||
"outdoor adventures, or lounging at home. With their ability to regulate " | ||
"temperature and cushion feet, wool socks offer unparalleled comfort, " | ||
"making them an essential addition to any wardrobe, whether for hiking, working, " | ||
"or simply relaxing.",29.99), | ||
(9, "Shoes","Shoes are versatile footwear designed to protect and comfort " | ||
"the feet while enabling effortless movement and style. They " | ||
"come in a wide range of designs, materials, and functions, catering " | ||
"to various activities, from formal occasions to rugged outdoor adventures. " | ||
"Crafted from durable materials such as leather, canvas, or synthetic blends, " | ||
"shoes provide support, cushioning, and stability through features like rubber soles, " | ||
"padded insoles, and secure fastenings. Available in diverse styles such as sneakers, boots, " | ||
"sandals, and dress shoes, they blend functionality with aesthetic appeal, making them a staple " | ||
"for every wardrobe",39.99), | ||
] | ||
|
||
for product in initial_products: | ||
add_product(*product) | ||
process_and_insert_data(file_prefix + "users.json", users_container) | ||
process_and_insert_data( | ||
file_prefix + "purchase_history.json", | ||
purchase_history_container) | ||
|
||
print( | ||
"Data successfully inserted into CosmosDB with embeddings, vector search, and full-text search indexing!" | ||
) | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
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.
You have added full_text_policy but I can't see full text search being used anywhere? If not being used, I would say better to remove it.