Skip to content

Secure Dot Product Tutorial

Estimated Time to Complete: 20-30 minutes

Expected Outcome

By completing this tutorial, you will:

  • Build a complete privacy-preserving dot product computation system with three agents
  • Implement AP3 commitments to advertise data structures without revealing values
  • Configure agent cards with AP3 extensions for discovery and compatibility checking
  • Use Privacy Intent and Result Directives to structure secure computations

Use Case: FMCG Quality Evaluation

In the Fast-Moving Consumer Goods (FMCG) industry, a manufacturer needs to evaluate whether a supplier's product meets quality thresholds. However, both parties want to keep their proprietary information private:

  • Supplier: Holds private product quality metrics (detergency, foaming levels)
  • Manufacturer: Holds private evaluation criteria (quality factors, threshold)

Challenge: Compute the dot product supplier_values × manufacturer_factors and compare it to a threshold without revealing either party's private values.

System Architecture

The system consists of three agents:

  1. Supplier Agent (ap3_receiver)
    1. Role: Receives and processes dot product protocol requests
    2. Holds: Product quality parameters (DETERGENCY, FOAMING)
  2. Manufacturer Agent (ap3_initiator)
    1. Role: Initiates secure dot product computations
    2. Holds: Evaluation factors (DETERGENCY_FACTOR, FOAMING_FACTOR, THRESHOLD)
  3. Host Agent (Routing Agent)
    1. Role: Coordinates agent discovery and protocol initiation
    2. Provides: AP3 compatibility checking and user interface

Prerequisites

Before starting, ensure you have:

  1. Python 3.10+ installed
  2. Google AI Studio API Key - Create one here
  3. Git installed (to clone the repository)
  4. Basic terminal/command line knowledge

Tutorial Steps

Step 1: Clone and Set Up the Project

# Clone the repository
git clone https://github.com/silence-laboratories/ap3.git
cd ap3/examples/dot-product

# Set your Google API key
export GOOGLE_API_KEY=<your-api-key>

# Install dependencies
uv sync && source .venv/bin/activate

Environment Setup

Make sure to activate the virtual environment in each new terminal window when running multiple agents.

Step 2: Define AP3 Commitments

Both agents need to advertise their data structure using AP3 commitments. Let's implement this:

2.1 Supplier Agent Commitment

In supplier_agent/supplier_agent.py, you'll create a commitment like this:

from ap3.types.core import (
    CommitmentMetadata,
    DataStructure,
    DataFormat,
    DataFreshness,
    Industry,
)

# Supplier Commitment
supplier_commitment = CommitmentMetadata(
    commitment_id="fmcg_supplier_product_quality_v1",
    data_structure=DataStructure.PRODUCT_CATALOG,
    data_format=DataFormat.STRUCTURED,
    entry_count=2,  # Two quality parameters: detergency and foaming
    data_freshness=DataFreshness.REAL_TIME,
    industry=Industry.MANUFACTURING,
)

What this does:

  • Advertises that the supplier has 2 product quality parameters
  • Uses structured data format (can be JSON/CSV)
  • Indicates real-time data freshness
  • Belongs to the manufacturing industry
  • Does NOT reveal the actual detergency or foaming values

2.2 Manufacturer Agent Commitment

Similarly, in manufacturer_agent/manufacturer_agent.py:

# Manufacturer Commitment
manufacturer_commitment = CommitmentMetadata(
    commitment_id="fmcg_manufacturer_evaluation_criteria_v1",
    data_structure=DataStructure.PRODUCT_CATALOG,
    data_format=DataFormat.STRUCTURED,
    entry_count=3,  # Three evaluation parameters: factors + threshold
    data_freshness=DataFreshness.REAL_TIME,
    industry=Industry.MANUFACTURING,
)

Step 3: Extend Agent Cards with AP3 Parameters

Both agents include AP3 extension parameters in their agent cards:

3.1 Supplier Agent Card Extension

# Supplier Agent Card Extension
supplier_ap3_extension = {
    "uri": "https://github.com/silence-laboratories/ap3/tree/main",
    "params": {
        "roles": ["ap3_receiver"],  # This agent receives computation requests
        "supported_operations": ["SFE"],  # Secure Function Evaluation
        "commitments": [supplier_commitment]
    }
}

3.2 Manufacturer Agent Card Extension

# Manufacturer Agent Card Extension
manufacturer_ap3_extension = {
    "uri": "https://github.com/silence-laboratories/ap3/tree/main",
    "params": {
        "roles": ["ap3_initiator"],  # This agent initiates computations
        "supported_operations": ["SFE"],
        "commitments": [manufacturer_commitment]
    }
}

Key Points:

  • Roles must be compatible: ap3_receiver + ap3_initiator pairs work together
  • Operations must match: Both must support SFE for Secure Function Evaluation
  • Commitments enable discovery: They help agents find suitable partners

Step 4: Implement AP3 Discovery

The host agent uses AP3DiscoveryService to:

  1. Fetch agent cards from both supplier and manufacturer
  2. Extract AP3 extension parameters from each card
  3. Calculate compatibility score based on:
  4. Role compatibility (receiver + initiator = compatible)
  5. Common operations (both support SFE)
  6. Commitment alignment (data structure, format, industry)

4.1 Run the Host Agent

cd host_agent
uv run .

The host agent will start on http://0.0.0.0:8000

4.2 Check Compatibility

The host agent provides an endpoint or interface to check compatibility:

from ap3.discovery import AP3DiscoveryService

ap3_discovery = AP3DiscoveryService()

# Host Agent - Compatibility Check
is_compatible, score, explanation, details = await ap3_discovery.check_compatibility(
    supplier_url="http://localhost:10001",
    manufacturer_url="http://localhost:10002"
)

print(f"Compatible: {is_compatible}")
print(f"Score: {score}/100")
print(f"Explanation: {explanation}")

Expected Output: - is_compatible: True (if roles and operations match) - score: 100 (if all checks pass) - Explanation of why they're compatible

Step 5: Use Privacy Directives

5.1 Privacy Intent Directive

When initiating the dot product protocol, the manufacturer creates a PrivacyIntentDirective:

from ap3.types.directive import PrivacyIntentDirective
from datetime import datetime, timedelta
import uuid

session_id = str(uuid.uuid4())
expiry_time = datetime.utcnow() + timedelta(hours=1)

privacy_intent = PrivacyIntentDirective(
    ap3_session_id=session_id,
    operation_type="SFE",
    participants=["http://localhost:10001", "http://localhost:10002"],
    expiry=expiry_time.isoformat(),
)

What this does: - Establishes a session for the computation - Declares the operation type (SFE = Secure Function Evaluation) - Lists all participating agents - Sets an expiry time for security

5.2 Validate Privacy Intent

The supplier validates this directive before processing:

from common.ap3_directives import validate_privacy_intent_directive

is_valid, error_msg = validate_privacy_intent_directive(
    directive=privacy_intent,
    expected_operation_type="SFE"
)

if not is_valid:
    raise ValueError(f"Invalid privacy intent: {error_msg}")

5.3 Privacy Result Directive

Upon completion, the supplier creates a PrivacyResultDirective with the encrypted result:

from ap3.types.directive import PrivacyResultDirective, ResultData, OperationProofs

privacy_result = PrivacyResultDirective(
    ap3_session_id=session_id,
    result_data=ResultData(
        encrypted_result=encrypted_dot_product,
        result_hash=result_hash,
        metadata={
            "threshold": threshold,
            "pass_fail": "PASS" if result >= threshold else "FAIL"
        }
    ),
    proofs=OperationProofs(
        correctness_proof=correctness_proof,
        privacy_proof=privacy_proof,
        verification_proof=verification_proof
    )
)

Step 6: Run the Complete System

6.1 Terminal 1: Start Supplier Agent

cd supplier_agent
export GOOGLE_API_KEY=<your-api-key>
uv run .

The supplier agent will start on http://localhost:10001

6.2 Terminal 2: Start Manufacturer Agent

cd manufacturer_agent
export GOOGLE_API_KEY=<your-api-key>
uv run .

The manufacturer agent will start on http://localhost:10002

6.3 Terminal 3: Start Host Agent

cd host_agent
uv run .

The host agent will start on http://0.0.0.0:8000

6.4 Initiate the Computation

Use the host agent's interface to:

  1. Check compatibility between supplier and manufacturer agents
  2. Initiate the dot product computation
  3. Observe the 20-round protocol execution
  4. View the final result (PASS/FAIL) without seeing the actual values

Expected Flow:

  1. Host agent checks compatibility
  2. Manufacturer creates PrivacyIntentDirective → Sends to supplier
  3. Supplier validates directive
  4. Both agents execute 20 rounds of secure computation
  5. Supplier creates PrivacyResultDirective with result
  6. Result shows PASS or FAIL (without revealing values)

Step 7: Understand the Protocol Flow

The dot product protocol consists of 20 rounds of cryptographic computation:

  1. Round 1 (Initiation):
    1. Manufacturer generates session ID and cryptographic setup
    2. Creates PrivacyIntentDirective
    3. Sends initial message with directive to supplier
  2. Round 2-19 (Computation):
    1. Both parties exchange messages using secure multi-party computation
    2. Values remain encrypted throughout
    3. Supplier's values: [detergency, foaming]
    4. Manufacturer's factors: [detergency_factor, foaming_factor]
    5. Each round performs a piece of the dot product computation
  3. Round 20 (Finalization):
    1. Both parties compute secret shares of the dot product
    2. Shares are combined: dot_product = share_cb + share_ob
    3. Result compared to threshold: result >= threshold ? PASS : FAIL
    4. Supplier creates PrivacyResultDirective with result

Key Insight:

  • Neither party ever sees the other's private values
  • The computation happens on encrypted/shared data
  • Only the final comparison result is revealed

Summary

In this tutorial, you:

  • Set up a three-agent system for privacy-preserving dot product computation
  • Implemented AP3 commitments to advertise data structures
  • Configured agent cards with AP3 extensions
  • Used discovery service to check agent compatibility
  • Implemented Privacy Intent and Result Directives
  • Executed a secure dot product computation over 20 rounds