# Set up for Unit 15: free tiers on Microsoft, AWS and Google, and one shared SAP tool

> Know what Microsoft, AWS and Google give free for agent work in November 2026, install the Unit 15 libraries, and build the one SAP tool all of them call.

- Course: Orchestrate, Unit 15 · SAP AI next to other platforms
- Page: https://erpfde.com/topics/set-up-for-unit-15/
- Updated: 2026-11-30
- Reading time: Foundational 8 min, Deep 35 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

Unit 15 is about SAP next to other agent platforms. Most SAP customers also run Microsoft, AWS or Google, and agents built there want SAP data. The unit compares how each one reaches SAP and where an agent should live.

To compare fairly, every platform calls **the same SAP tool**: read one sales order and say what's wrong with it. You build that tool in this setup, with a contract that later topics translate into each platform's format.

The platforms themselves cost money beyond a free allowance, and each free offer works differently. As of 24 November 2026:

- **Microsoft Azure** gives a $200 credit for 30 days. **Copilot Studio** has its own trial, which needs a work or school account.
- **AWS** gives up to $200 in credits on a free plan that ends after 6 months.
- **Google Cloud** gives $300 for 90 days, but since 16 November 2026 that credit no longer pays for Google's agent and model platform. The Gemini API has a separate free tier.

So this setup installs the libraries, builds the shared tool, and teaches you to start each account only when its topic needs it. Setup takes about 30 minutes and costs nothing.

### Why it matters to the business

Calder Pumpworks, the course's fictional company, is typical. Its CRM, HR system and collaboration tools come from other vendors. Sales asks for an assistant in Microsoft Teams. The data team runs on a hyperscaler. Each wants an agent that reads SAP.

The questions a leader faces are practical. Which platform owns the agent? Who pays for the model calls? Whose identity does SAP see when the agent reads an order? A team can only answer them well if it has tried more than one platform on the same task.

Free tiers make that possible, but they differ in ways that matter to budget and risk:

| Platform | Free offer (as read 24 Nov 2026) | Watch out for |
| --- | --- | --- |
| Microsoft Azure | $200 credit within 30 days, plus free monthly amounts of some services ([Azure free account](https://azure.microsoft.com/en-us/free/)) | A card and phone number are needed; after 30 days you move to pay-as-you-go or the account is disabled |
| Copilot Studio | Individual trial ([Microsoft Learn](https://learn.microsoft.com/en-us/microsoft-copilot-studio/requirements-licensing-subscriptions)) | Needs a work or school account; your IT can block self sign-up; a trial agent can't be published |
| AWS | $100 at sign-up and up to $100 more for using services such as Amazon Bedrock; free plan for up to 6 months ([AWS](https://aws.amazon.com/about-aws/whats-new/2025/07/aws-free-tier-credits-month-free-plan)) | The free plan covers only some services; the account is suspended at the end and erased if not upgraded within 90 days |
| Google Cloud | $300 credit for 90 days ([Google Cloud](https://docs.cloud.google.com/free/docs/free-cloud-features)) | For sign-ups from 16 November 2026, the credit can't pay for Gemini platform (formerly Vertex AI) services or the Gemini API |

The business lesson: a free tier is a way to learn a platform's shape, not a way to run a pilot. A pilot needs a company account with a budget, an owner and your data rules.

### How SAP does it

SAP publishes reference architectures for exactly this situation. As of its 26 October 2026 update, the SAP Architecture Center shows a [Copilot Studio agent reaching SAP through the MCP Gateway in SAP Integration Suite](https://architecture.learning.sap.com/docs/ref-arch/d2e34e), with the user's identity flowing from Microsoft Entra ID to SAP Cloud Identity Services. It needs a customer-managed SAP subaccount with Integration Suite and the MCP Gateway capability.

A second page, [A2A and MCP for AI agent interoperability](https://architecture.learning.sap.com/docs/ref-arch/76ec36), names Google Vertex AI, Microsoft Copilot Studio and AWS Bedrock AgentCore as platforms that interoperate with SAP agents. When it was last updated, it said two-way traffic between SAP's Agent Gateway and third-party agents was not yet supported. Each Unit 15 topic checks the current status.

None of this is open to a learner without a customer system. The course uses local stand-ins instead: the MCP gateway from [the Integration Suite MCP gateway topic](https://erpfde.com/topics/integration-suite-mcp-gateway-hands-on/) and the A2A server from [A2A for SAP agents](https://erpfde.com/topics/a2a-for-sap-agents/). The shared tool you build here reads Calder's made-up orders, or SAP's public sandbox with the key you already have.

### What this unit adds

| Item | What it is | Cost | Used in |
| --- | --- | --- | --- |
| `boto3` | AWS's Python library | Free | The AWS topic |
| `azure-ai-projects`, `azure-identity` | Microsoft's Python libraries for Foundry projects and sign-in | Free | The Microsoft topic |
| `google-adk` | Google's Agent Development Kit, already added in [Choosing an agent SDK](https://erpfde.com/topics/choosing-an-agent-sdk/) | Free | [The Google topic](https://erpfde.com/topics/google-vertex-and-agentspace-with-sap/) |
| `unit15/calder_tool.py` | The shared SAP tool and its contract | Free | Every Unit 15 topic |
| Account dates in `.env` | One line per account you start | Free | Every Unit 15 topic with an account |
| `check_unit15.py` | Checks libraries, the tool and account clocks | Free | Before every Unit 15 topic |

> **Note** **For functional consultants:** nothing in your configuration changes in this setup. What changes is the question you ask in a workshop where another platform's agent wants SAP data: which SAP API it calls, whose identity SAP sees, and which role decides what it may read.

### Time and money

- **Time:** about 30 minutes now, plus 15 minutes to open each account when its topic comes up.
- **Money for a learner:** nothing for this setup. Each account's free offer is described above, and each later topic says what it would cost beyond that.
- **Clocks:** 30 days of Azure credit, about 6 months for the AWS free plan, 90 days for Google Cloud. Start them one at a time.
- **Money for a company:** model calls, agent runtimes and SAP's own gateway services are all charged. SAP's side needs Integration Suite and its own entitlements.

### Questions to ask

Ask IT before you open any account:

- May I open personal cloud accounts for learning, or does the company have a sandbox subscription I should use?
- May I use my work account for a Copilot Studio trial, or is self-service sign-up turned off here?
- Which SAP systems may an agent on another platform read, and through which gateway?

Ask a platform vendor or SAP when you plan a real agent:

- Which identity does SAP see when your agent reads an order: the user's or a technical user's?
- What does a month of model calls and agent runtime cost at our volume?
- Which parts of the SAP integration are generally available today, and which are planned?

### Common misconceptions

- **"Google's $300 credit covers Vertex AI."** Not for sign-ups from 16 November 2026, according to Google's trial page.
- **"A Copilot Studio trial lets us pilot with users."** A trial agent can be built and tested, but not published.
- **"Free plans just stop when they end."** AWS suspends the account and erases it if you don't upgrade within 90 days. Azure disables the account and its services.
- **"Every platform needs its own SAP connection to compare them."** One shared tool and one contract is fairer, and cheaper.
- **"If the reference architecture exists, it's generally available."** SAP's own pages flagged parts as not yet GA when last updated.

### Key terms

- **Hyperscaler:** a very large public cloud provider, here Microsoft Azure, AWS and Google Cloud.
- **Free tier:** monthly allowances that are free within limits; **credit:** money the provider gives you to spend for a limited time.
- **Tool contract:** a written description of one tool: its name, what it does and the inputs it accepts.
- **Copilot Studio:** Microsoft's low-code tool for building agents.
- **Amazon Bedrock:** AWS's managed service for model calls; **AgentCore** is its agent runtime family.
- **Agent Development Kit (ADK):** Google's open-source library for building agents in code.
- **MCP Gateway:** the capability in SAP Integration Suite that exposes SAP APIs to agents as tools under SAP's policies.

### Check yourself

1. Why does Unit 15 give every platform the same SAP tool?
   - A. SAP licenses one tool per customer across all platforms
   - B. So differences come from the platform, not the backend
   - C. Because the hyperscalers can only call one SAP API each
   - D. So the free tiers can share one set of credits between them

   Answer: B. Comparing platforms is only fair when each calls the same tool on the same data. One contract, translated into each platform's format, keeps the backend constant.

2. A colleague signs up for Google Cloud today to try Vertex AI on the $300 credit. What should you tell them?
   - A. The credit covers Vertex AI for the full 90 days
   - B. The credit covers Vertex AI only for the first 30 days
   - C. For sign-ups since 16 November 2026 it doesn't cover it
   - D. Vertex AI is free forever on Google's always-free tier

   Answer: C. Google's trial page says the $300 credit can't pay for Gemini platform services (formerly Vertex AI) for sign-ups from 16 November 2026. The Gemini API has its own free tier instead.

3. Sales wants five users to try a Copilot Studio agent on the trial. What is the main limit?
   - A. The trial allows only one user per agent
   - B. The trial runs only inside Microsoft Excel
   - C. The trial needs a separate SAP license per user
   - D. A trial agent can be tested but not published

   Answer: D. Microsoft's licensing page says the trial lets you create and test agents in the test chat, but not publish them. Reaching users needs a paid plan.

4. Your team's AWS free plan is ending and nobody upgraded. What happens to what they built?
   - A. The account is suspended, then erased after 90 days
   - B. It keeps running and is billed to the card on file
   - C. It moves to the always-free tier automatically
   - D. It is copied to an SAP BTP trial account

   Answer: A. AWS's FAQ says the account is suspended at the end of the free plan and erased if it isn't upgraded within 90 days. Plan to delete or export what you built before then.

5. What does SAP's reference architecture for Copilot Studio require on the SAP side?
   - A. Nothing beyond a Copilot Studio trial and an SAP user name
   - B. A Google Cloud project with Vertex AI switched on
   - C. A customer subaccount with Integration Suite and MCP Gateway
   - D. An S/4HANA system with a copy of the Copilot Studio agent

   Answer: C. SAP's Architecture Center lists a customer-managed subaccount with SAP Integration Suite and the MCP Gateway capability. That is why learners use the course's local stand-ins instead.

6. Before a real pilot of an agent on another platform, which question matters most?
   - A. Which free tier lasts longest, so the pilot can run on it
   - B. Whether the agent can skip the gateway to save latency
   - C. Whose identity SAP sees, and what the month will cost
   - D. Whether the platform's logo can appear in Fiori

   Answer: C. Identity decides what the agent may read in SAP, and cost decides whether it scales. Free tiers are for learning a platform's shape, not for running a pilot.

## Deep layer

### Mental model: one socket, three plugs

Think of SAP as a wall socket and each platform as a plug from a different country. You don't rewire the wall for every visitor. You agree on one socket shape and give each visitor an adapter.

In this unit the socket is one tool contract: `get_sales_order`, read only, one input. Each platform topic writes the adapter: a Copilot Studio tool, a Bedrock tool definition, an ADK function. When an agent misbehaves, you know the problem is in the adapter or the platform, because the socket never changed.

Three rules follow:

- **The tool is read only.** Every agent in this unit reads. None changes SAP data.
- **The contract is the source of truth.** Platforms translate it; they don't redefine it.
- **Accounts are short-lived.** Start one per topic, finish the topic, delete what you built.

### How it works

```mermaid
flowchart LR
  subgraph Laptop
    C[tool_contract.json] --> T[calder_tool.py<br/>get_sales_order]
    T --> S[Calder sample<br/>orders 1000002-7]
    K[check_unit15.py]
  end
  T -- --sandbox --> H[SAP sandbox<br/>API_SALES_ORDER_SRV]
  M[Microsoft agent] -.adapter.-> C
  A[AWS agent] -.adapter.-> C
  G[Google agent] -.adapter.-> C
```

> **Note** There is nothing to download. You create `calder_tool.py` in [Step 3](#d-step-3-write-the-shared-sap-tool) below, and it writes `tool_contract.json` for you in [Step 4](#d-step-4-write-the-contract-and-call-the-tool).

The tool runs on your laptop. It reads Calder's six open orders from [order to cash](https://erpfde.com/topics/order-to-cash-end-to-end/) without any key, or one order from SAP's public sandbox with the `SAP_API_KEY` from [Set up your computer](https://erpfde.com/topics/set-up-your-computer/). The SAP Developers tutorial describes the hub as a site to discover, explore and test SAP APIs, with a sandbox you use while logged on ([SAP Developers](https://developers.sap.com/tutorials/hcp-abh-getting-started.html)).

#### The free offers, read on 24 November 2026

Each Unit 15 topic re-checks its own platform. This is what the run found today.

| Platform | What you get | What it needs | When it ends |
| --- | --- | --- | --- |
| Azure free account | $200 credit to use within 30 days; free monthly amounts of 20+ services for 12 months and 65+ always free | Phone, credit or debit card, Microsoft or GitHub account | After 30 days or when the credit is used: move to pay-as-you-go, or the account and services are disabled |
| Copilot Studio trial | Build and test agents in the test chat | Work or school account; IT may have turned off self sign-up | Length not stated on the page; can be extended by 30 days; agents keep working up to 90 days after |
| AWS free plan | $100 credit at sign-up, up to $100 more for activities in the console | Payment method not required for most new customers | 6 months or when credits run out; suspended, then erased after 90 days without upgrade |
| Google Cloud Free Trial | $300 credit for 90 days | Payment method at sign-up; a temporary authorization of up to $1 | 90 days or when the credit is used; 30-day grace, then resources are deleted |
| Gemini API | A free tier, which Google's trial page points to | A Google account and an API key from Google AI Studio | Not checked in this run |

Three details change what you can do:

- **Model calls on Azure.** The free account page lists free monthly amounts for several services, but this run found no free amount for model inference in Foundry. Plan on model calls drawing on the credit.
- **Bedrock on AWS.** The July 2025 announcement names Amazon Bedrock among the services that earn extra credits. The FAQ doesn't say which services the free plan includes. Bedrock's pricing page lists on-demand prices per million input and output tokens, by model and region, and describes no general free tier ([Bedrock pricing](https://aws.amazon.com/bedrock/pricing/)). AWS's FAQ also gives credit expiry as 6 months in some answers and 12 in others; your console's credits page is the one to trust.
- **Vertex AI on Google.** Google's trial page says that for sign-ups or upgrades from 16 November 2026, the $300 credit can't pay for Gemini platform services (formerly Gemini Enterprise Agent Platform, Vertex AI), and can't pay for the Gemini API in AI Studio. It suggests the Gemini API free tier or a prepay plan. The course's Google route therefore uses ADK on your laptop with a Gemini API key.

#### The libraries

| Library | Version pinned | Needs Python | What it is for |
| --- | --- | --- | --- |
| `boto3` | 1.44.10 | 3.10 or newer | Calling AWS services, including Bedrock, from Python |
| `azure-ai-projects` | 2.11.0 | 3.10 or newer | Working with a Foundry project from Python |
| `azure-identity` | 1.27.0 | 3.10 or newer | Signing in to Azure from Python |
| `google-adk` | 2.14.1 | 3.11 or newer | Google's agent kit; already added in [Choosing an agent SDK](https://erpfde.com/topics/choosing-an-agent-sdk/) |

The versions are the ones the run installed and imported. The course keeps `google-adk` at 2.14.1, as pinned in Unit 8, although 2.15.0 is newer, so both topics run the same code. The Google library underneath ADK reads a key from `GOOGLE_API_KEY` (or `GEMINI_API_KEY`), and uses Vertex AI instead when `GOOGLE_GENAI_USE_VERTEXAI` is set; the run read this in the installed library's source.

### Build it yourself: the shared tool, the check and the clocks

You will install the Unit 15 libraries, write the shared SAP tool and its contract, add the check, and learn the routine for opening an account later. Everything here is free and needs no new account.

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/). It installs Python and VS Code and creates your `orchestrate-course` folder with its `.venv`, `.env` and `SAP_API_KEY`. This walkthrough doesn't repeat those steps. [Choosing an agent SDK](https://erpfde.com/topics/choosing-an-agent-sdk/) added `google-adk`; if you skipped it, Step 2 adds it.

```mermaid
flowchart LR
  S1[Step 1<br/>open folder] --> S2[Step 2<br/>libraries]
  S2 --> S3[Step 3<br/>the tool]
  S3 --> S4[Step 4<br/>contract and call]
  S4 --> S5[Step 5<br/>the check]
  S5 --> S6[Step 6<br/>save in Git]
```

> **Note** New words in this walkthrough:
> - **Tool:** a function an agent may call, described so a model knows when and how to call it.
> - **JSON Schema:** a standard way to describe the shape of JSON data, such as "one field, a string of digits". Most agent platforms describe tool inputs this way.
> - **Read only:** the tool reads data and never changes it.
> - **Sandbox:** SAP's public test system on the Business Accelerator Hub. It returns sample data, not Calder's.

#### What you need

- Your course folder from Unit 2.
- About 30 minutes.
- Cost: free. No new account.

> **Warning** Don't open the Azure, AWS or Google accounts yet. Each runs on a clock, and Google's needs a payment method. Each Unit 15 topic tells you when to open its account and how to stay within the free offer.

#### Step 1: Open your course folder and turn on the virtual environment

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. Create the folder for this unit:

   ```bash
   mkdir unit15
   ```

#### Step 2: Add the libraries

1. Open `requirements.txt` and add these lines at the end. If `google-adk==2.14.1` is already there from Unit 8, don't add it twice.

   ```text
   boto3==1.44.10
   azure-ai-projects==2.11.0
   azure-identity==1.27.0
   google-adk==2.14.1
   ```

2. Save the file and install. The same command works in PowerShell and macOS/Linux:

   ```bash
   pip install -r requirements.txt
   ```

**What success looks like:** the install ends with a `Successfully installed ...` line listing new packages, or with `Requirement already satisfied` lines if you had them. It can take a few minutes; these libraries bring others with them.

#### Step 3: Write the shared SAP tool

1. In VS Code, create `unit15/calder_tool.py`, paste the code below and save.

```python
"""Unit 15: one SAP tool that every agent platform in this unit calls.

The tool is get_sales_order: read one sales order and say what is wrong with it.
Microsoft, AWS and Google agents in later topics all call this same function and this
same contract, so you compare the platforms, not five different backends.

Run it from your course folder, with .venv turned on:
    python unit15/calder_tool.py contract            write unit15/tool_contract.json
    python unit15/calder_tool.py call 1000002        read a Calder order (made-up data, no key)
    python unit15/calder_tool.py call --sandbox      read the first order in SAP's sandbox (SAP_API_KEY)
    python unit15/calder_tool.py call --sandbox 1    read a sandbox order by its number

The Calder orders are fictional. Problem and Owner are course fields, not SAP API fields.
"""
import argparse
import json
import os
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
CONTRACT_FILE = HERE / "tool_contract.json"
SANDBOX = "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_SALES_ORDER_SRV"
FIELDS = ["SalesOrder", "SoldToParty", "DistributionChannel", "RequestedDeliveryDate",
          "TotalNetAmount", "TransactionCurrency", "DeliveryBlockReason",
          "HeaderBillingBlockReason", "OverallSDProcessStatus"]

# One contract, written once. Later topics translate it into each platform's own tool format.
CONTRACT = {
    "contract_version": "1",
    "tools": [{
        "name": "get_sales_order",
        "description": ("Read one sales order by its number and return the customer, value, "
                        "requested date, and any problem that stops it. Read only."),
        "parameters": {
            "type": "object",
            "properties": {"sales_order": {"type": "string", "pattern": "^[0-9]{1,10}$",
                                           "description": "Sales order number, for example 1000002"}},
            "required": ["sales_order"],
            "additionalProperties": False,
        },
        "read_only": True,
    }],
}

# Calder's open orders from the order-to-cash topic (fictional, USD). 1000005 has no price yet.
CALDER_ORDERS = {
    "1000002": ("10000002", "Hallam Fluid Systems", "20", "2026-10-30", "24288.00", "credit block", "Credit analyst"),
    "1000003": ("10000001", "Brennock Water Utility", "10", "2026-11-02", "12300.00", "billing data incomplete", "Sales order team"),
    "1000004": ("10000001", "Brennock Water Utility", "10", "2026-10-27", "24600.00", "partly confirmed", "Order fulfillment"),
    "1000005": ("10000002", "Hallam Fluid Systems", "30", "2026-10-28", "", "price missing", "Pricing team"),
    "1000006": ("10000001", "Brennock Water Utility", "10", "2026-10-20", "4200.00", "billing block", "Billing clerk"),
    "1000007": ("10000001", "Brennock Water Utility", "10", "2026-11-09", "8400.00", "delivery block", "Customer service"),
}


class ToolError(Exception):
    """The order can't be read: not found, no key, no network, or an unexpected answer."""


def calder_order(sales_order: str) -> dict:
    """Read a made-up Calder order. No key and no network needed."""
    if sales_order not in CALDER_ORDERS:
        raise ToolError(f"order {sales_order} not found in the Calder sample (try 1000002 to 1000007)")
    party, name, channel, date, value, problem, owner = CALDER_ORDERS[sales_order]
    return {"source": "calder-sample", "sales_order": sales_order, "sold_to_party": party,
            "customer_name": name, "distribution_channel": channel, "requested_delivery_date": date,
            "net_value": value or None, "currency": "USD", "problem": problem, "owner": owner}


def sandbox_order(sales_order: str | None, api_key: str, timeout: float = 30) -> dict:
    """Read one order from SAP's public sandbox. With no number, read the first one it returns."""
    import requests   # imported here so the sample path works even without the library

    if sales_order:
        url, params = f"{SANDBOX}/A_SalesOrder('{sales_order}')", {"$select": ",".join(FIELDS)}
    else:
        url, params = f"{SANDBOX}/A_SalesOrder", {"$top": "1", "$select": ",".join(FIELDS)}
    try:
        response = requests.get(url, params=params, timeout=timeout,
                                headers={"APIKey": api_key, "Accept": "application/json"})
    except requests.RequestException as error:   # no network, proxy, DNS, timeout
        raise ToolError(f"could not reach SAP ({type(error).__name__})") from error
    if response.status_code == 404:
        raise ToolError(f"order {sales_order} not found in the sandbox")
    if response.status_code != 200:
        raise ToolError(f"SAP answered HTTP {response.status_code}")
    try:
        body = response.json()["d"]
        record = body["results"][0] if "results" in body else body   # list or single record
    except (ValueError, KeyError, IndexError, TypeError) as error:
        raise ToolError("SAP answered, but not with the expected OData JSON") from error
    blocks = [label for field, label in (("DeliveryBlockReason", "delivery block"),
                                         ("HeaderBillingBlockReason", "billing block"))
              if record.get(field)]
    return {"source": "sap-sandbox", "sales_order": record.get("SalesOrder"),
            "sold_to_party": record.get("SoldToParty"), "customer_name": None,
            "distribution_channel": record.get("DistributionChannel"),
            "requested_delivery_date": record.get("RequestedDeliveryDate"),
            "net_value": record.get("TotalNetAmount"), "currency": record.get("TransactionCurrency"),
            "problem": ", ".join(blocks) or "none found", "owner": None}


def get_sales_order(sales_order: str | None = None, sandbox: bool = False) -> dict:
    """The tool every platform calls. Read only: it never changes anything in SAP."""
    if sales_order is not None and not (sales_order.isdigit() and len(sales_order) <= 10):
        raise ToolError("a sales order number is 1 to 10 digits")
    if not sandbox:
        return calder_order(sales_order or "1000002")
    from dotenv import load_dotenv

    load_dotenv()
    api_key = os.environ.get("SAP_API_KEY")
    if not api_key:
        raise ToolError("SAP_API_KEY is not in .env (see Set up your computer, Step 6)")
    return sandbox_order(sales_order, api_key)


def main() -> None:
    parser = argparse.ArgumentParser(description="Calder's shared SAP tool for Unit 15.")
    sub = parser.add_subparsers(dest="command", required=True)
    sub.add_parser("contract", help="write unit15/tool_contract.json")
    call = sub.add_parser("call", help="call get_sales_order")
    call.add_argument("sales_order", nargs="?", help="order number (default: 1000002, or the first sandbox order)")
    call.add_argument("--sandbox", action="store_true", help="read SAP's sandbox instead of the Calder sample")
    args = parser.parse_args()

    if args.command == "contract":
        CONTRACT_FILE.write_text(json.dumps(CONTRACT, indent=2) + "\n", encoding="utf-8", newline="\n")
        print(f"Wrote {CONTRACT_FILE.name}: {len(CONTRACT['tools'])} tool(s): "
              + ", ".join(t["name"] for t in CONTRACT["tools"]))
        return
    try:
        print(json.dumps(get_sales_order(args.sales_order, args.sandbox), indent=2))
    except ToolError as error:
        sys.exit(f"Tool error: {error}")


if __name__ == "__main__":
    main()
```

> **Note** Calder Pumpworks and its orders are fictional. The six orders and their problems come from [order to cash](https://erpfde.com/topics/order-to-cash-end-to-end/). `problem` and `owner` are course fields; the sandbox path reads real field names of SAP's sales order API, as in [Calling your first SAP API](https://erpfde.com/topics/calling-your-first-sap-api/).

#### Step 4: Write the contract and call the tool

1. Write the contract:

   ```bash
   python unit15/calder_tool.py contract
   ```

   **What success looks like:**

   ```text
   Wrote tool_contract.json: 1 tool(s): get_sales_order
   ```

2. Call the tool on a Calder order:

   ```bash
   python unit15/calder_tool.py call 1000002
   ```

   **What success looks like:** the same answer on every computer, because the data is fixed:

   ```text
   {
     "source": "calder-sample",
     "sales_order": "1000002",
     "sold_to_party": "10000002",
     "customer_name": "Hallam Fluid Systems",
     "distribution_channel": "20",
     "requested_delivery_date": "2026-10-30",
     "net_value": "24288.00",
     "currency": "USD",
     "problem": "credit block",
     "owner": "Credit analyst"
   }
   ```

3. Try an order that doesn't exist, to see a clean tool error instead of a crash:

   ```bash
   python unit15/calder_tool.py call 1000009
   ```

   ```text
   Tool error: order 1000009 not found in the Calder sample (try 1000002 to 1000007)
   ```

4. Optional: read one order from SAP's sandbox. This needs `SAP_API_KEY` in `.env` and a network that reaches `sandbox.api.sap.com`:

   ```bash
   python unit15/calder_tool.py call --sandbox
   ```

   **What success looks like:** a JSON answer with `"source": "sap-sandbox"`. The order number, customer and amount are SAP's sample data, not Calder's, and they can change when SAP refreshes the sandbox. `"problem": "none found"` is a valid answer: it means the order has no delivery or billing block.

#### Step 5: Add the Unit 15 check and run it

1. In the course folder (not in `unit15`), create `check_unit15.py`, paste the code below and save.

```python
"""Check that your course folder is ready for Unit 15 (SAP AI next to other platforms).

Run it from your course folder:  python check_unit15.py
Pretend today is another date (to test the account clocks):  python check_unit15.py --today 2027-01-10

It uses built-in Python only, reads .env and the files in unit15/, changes nothing
and sends nothing anywhere. It never contacts Microsoft, AWS, Google or SAP.
"""
import argparse
import datetime
import importlib.metadata
import json
import os
import subprocess
import sys
from pathlib import Path

# (library, version pinned in requirements.txt, Unit 15 topic that uses it)
LIBRARIES = [
    ("boto3", "1.44.10", "AWS Bedrock and AgentCore with SAP"),
    ("azure-ai-projects", "2.11.0", "Microsoft Copilot Studio and Azure with SAP"),
    ("azure-identity", "1.27.0", "Microsoft Copilot Studio and Azure with SAP"),
    ("google-adk", "2.14.1", "Google Vertex and Agentspace with SAP"),
]
# (line in .env, account, length in days or None if the provider doesn't state one, what ends)
CLOCKS = [
    ("AZURE_FREE_START", "Azure free account credit", 30, "the $200 credit"),
    ("COPILOT_STUDIO_TRIAL_START", "Copilot Studio trial", None, "the trial (length shown in the product)"),
    ("AWS_FREE_START", "AWS free plan", 182, "the free plan (6 months, or when credits run out)"),
    ("GCP_TRIAL_START", "Google Cloud Free Trial", 90, "the $300 credit"),
]
WARN_DAYS = 7   # warn when an account clock has fewer days left than this

problems = 0


def report(ok: bool, label: str, fix: str = "", optional: bool = False) -> None:
    """Print one line: OK, MISSING (must fix) or LATER (optional for now)."""
    global problems
    if ok:
        print(f"  OK       {label}")
    elif optional:
        print(f"  LATER    {label}  ->  {fix}")
    else:
        problems += 1
        print(f"  MISSING  {label}  ->  {fix}")


def read_env(path: str = ".env") -> dict:
    """Read KEY=value lines from .env without any library. Ignores comments and blank lines."""
    values = {}
    if not os.path.exists(path):
        return values
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                key, value = line.split("=", 1)
                values[key.strip()] = value.strip().strip('"').strip("'")
    return values


parser = argparse.ArgumentParser(description="Check your Unit 15 setup.")
parser.add_argument("--today", help="pretend today is this date (YYYY-MM-DD)")
options = parser.parse_args()
today = datetime.date.fromisoformat(options.today) if options.today else datetime.date.today()
env = read_env()

print("\n1. Python")
v = sys.version_info
report(v >= (3, 11), f"Python {v.major}.{v.minor}.{v.micro}", "the course needs Python 3.11 or newer")
report(sys.prefix != sys.base_prefix, "virtual environment is active", "activate .venv (Step 1)")
report(os.path.exists(".env"), ".env in this folder", "run this from your course folder")

print("\n2. Platform libraries")
for name, pinned, topic in LIBRARIES:
    try:
        found = importlib.metadata.version(name)
    except importlib.metadata.PackageNotFoundError:
        report(False, f"{name} not installed", "add the Step 2 lines to requirements.txt and pip install")
        continue
    report(found == pinned, f"{name} {found}", f"the course pins {pinned}; run pip install -r requirements.txt")

print("\n3. The shared SAP tool")
tool = Path("unit15") / "calder_tool.py"
contract = Path("unit15") / "tool_contract.json"
report(tool.exists(), "unit15/calder_tool.py", "create it (Step 3)")
names = []
if contract.exists():
    try:
        names = [t["name"] for t in json.loads(contract.read_text(encoding="utf-8"))["tools"]]
    except (ValueError, KeyError, TypeError):
        names = []
report(bool(names), f"tool contract: {len(names)} tool(s) {', '.join(names)}".rstrip(),
       "run python unit15/calder_tool.py contract (Step 4)")
if tool.exists():
    run = subprocess.run([sys.executable, str(tool), "call", "1000002"],
                         capture_output=True, text=True, timeout=60)
    try:
        answer = json.loads(run.stdout)
    except ValueError:
        answer = {}
    report(answer.get("problem") == "credit block",
           "sample call: order 1000002 has a credit block",
           (run.stderr.strip().splitlines() or ["no output"])[-1])

print("\n4. Keys (each only when its topic needs it)")
report(bool(env.get("SAP_API_KEY")), "SAP_API_KEY (from Set up your computer)",
       "needed for --sandbox calls; the Calder sample works without it", optional=True)
report(bool(env.get("GOOGLE_API_KEY") or env.get("GEMINI_API_KEY")), "GOOGLE_API_KEY (Gemini API)",
       "add it when the Google topic asks you to", optional=True)

print(f"\n5. Account clocks (today {today})")
for name, label, days, what in CLOCKS:
    raw = env.get(name, "")
    if not raw:
        report(False, f"{label}: not started", "start it only when its topic needs it", optional=True)
        continue
    try:
        started = datetime.date.fromisoformat(raw)
    except ValueError:
        report(False, f"{label}: '{raw}' is not a date", f"write {name}=YYYY-MM-DD in .env")
        continue
    if days is None:
        report(False, f"{label}: started {(today - started).days} day(s) ago",
               f"check {what}", optional=True)
        continue
    ends = started + datetime.timedelta(days=days)
    left = (ends - today).days
    if left < 0:
        report(False, f"{label}: {what} ended {ends}", "stop or delete what you built there",
               optional=True)
    else:
        report(left >= WARN_DAYS, f"{label}: {left} day(s) left (ends about {ends})",
               f"finish its topic and delete what you built before {ends}", optional=True)

print()
if problems:
    print(f"{problems} item(s) to fix before Unit 15.")
    sys.exit(1)
print("Ready for Unit 15. LATER lines are keys and accounts you add only when a topic needs them.")
```

2. Run it:

   ```bash
   python check_unit15.py
   ```

**What success looks like:** every library and tool line is `OK`; the Google key and the four accounts are `LATER` because you haven't started them. Your Python version and the date will differ.

```text
1. Python
  OK       Python 3.12.7
  OK       virtual environment is active
  OK       .env in this folder

2. Platform libraries
  OK       boto3 1.44.10
  OK       azure-ai-projects 2.11.0
  OK       azure-identity 1.27.0
  OK       google-adk 2.14.1

3. The shared SAP tool
  OK       unit15/calder_tool.py
  OK       tool contract: 1 tool(s) get_sales_order
  OK       sample call: order 1000002 has a credit block

4. Keys (each only when its topic needs it)
  OK       SAP_API_KEY (from Set up your computer)
  LATER    GOOGLE_API_KEY (Gemini API)  ->  add it when the Google topic asks you to

5. Account clocks (today 2026-11-24)
  LATER    Azure free account credit: not started  ->  start it only when its topic needs it
  LATER    Copilot Studio trial: not started  ->  start it only when its topic needs it
  LATER    AWS free plan: not started  ->  start it only when its topic needs it
  LATER    Google Cloud Free Trial: not started  ->  start it only when its topic needs it

Ready for Unit 15. LATER lines are keys and accounts you add only when a topic needs them.
```

The script ends with exit code 0 when nothing is `MISSING`, and 1 otherwise.

3. When a later topic has you open an account, add its start date to `.env` the day you open it, for example `AZURE_FREE_START=2026-12-01`, and run the check again. To see how the warnings look later, pretend it's another day:

   ```bash
   python check_unit15.py --today 2026-12-27
   ```

   With `AZURE_FREE_START=2026-12-01`, the Azure line then reads:

   ```text
     LATER    Azure free account credit: 4 day(s) left (ends about 2026-12-31)  ->  finish its topic and delete what you built before 2026-12-31
   ```

The end dates are estimates from the lengths the providers state. Each provider's own billing page shows your real dates and remaining credit; trust that over the check.

#### Step 6: Save your work in Git

1. Check what Git sees:

   ```bash
   git status
   ```

   You should see `requirements.txt`, `check_unit15.py` and the `unit15` folder. You must **not** see `.env`.

2. Save:

   ```bash
   git add requirements.txt check_unit15.py unit15
   git commit -m "Set up Unit 15: shared SAP tool and platform check"
   ```

#### How the code works

| Part | What it does |
| --- | --- |
| `CONTRACT` | The tool's name, description and input as JSON Schema; written to `tool_contract.json` for later topics to translate |
| `CALDER_ORDERS` | The six fictional open orders, with the problem and the team that owns it |
| `calder_order()` | Answers from the Calder sample; no key, no network |
| `sandbox_order()` | Reads one order from SAP's sandbox with the `APIKey` header, and turns block fields into a problem text |
| `get_sales_order()` | The one function every platform calls; checks the input first, then picks the source |
| `ToolError` | Turns every failure into one short message, which an agent can pass on instead of crashing |
| `LIBRARIES`, `CLOCKS` | What the check expects: pinned versions, and each account's `.env` line and stated length |
| `subprocess.run(...)` | The check runs the tool once on order `1000002` and expects a credit block |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` is not recognized, or `command not found` | Python isn't installed, or the terminal can't find it | Windows: repeat Unit 2, Step 1, then open a new terminal. macOS/Linux: use `python3` until `.venv` is active |
| `MISSING virtual environment is active` | `.venv` isn't turned on | Run Step 1, item 3, then run the check again |
| `MISSING boto3 not installed` (or another library) | Step 2 wasn't run in this `.venv` | Check for `(.venv)` in the prompt, then `pip install -r requirements.txt` |
| `MISSING google-adk 2.15.0` | A newer ADK was installed outside the course pin | Set the line to `google-adk==2.14.1` and run `pip install -r requirements.txt` |
| `pip` stops with `Could not find a version` or a connection error | Network, proxy or an older Python | Use Python 3.11 or newer; on a company network ask IT to allow `pypi.org` |
| `MISSING tool contract: 0 tool(s)` | The contract file is missing or was edited | Run `python unit15/calder_tool.py contract` again |
| `Tool error: SAP_API_KEY is not in .env` | The sandbox path needs your key | Add `SAP_API_KEY="..."` as in Set up your computer, Step 6, or drop `--sandbox` |
| `Tool error: SAP answered HTTP 401` | The key is wrong or expired | Copy a fresh key from the Business Accelerator Hub into `.env` |
| `Tool error: could not reach SAP (ProxyError)` or `ConnectionError` | A network, proxy or firewall blocks `sandbox.api.sap.com` | Try another network or ask IT; the Calder sample still works |
| `ModuleNotFoundError: No module named 'dotenv'` | `python-dotenv` from Unit 2 is missing | `pip install -r requirements.txt`; it is in the Unit 2 lines |

### Where this shows up in SAP

On a customer project, the shared tool becomes an SAP API exposed through a gateway, and the adapter becomes the platform's own connector. The table shows where a learner's practice stops.

| Need | Learn with (this setup) | On a customer project |
| --- | --- | --- |
| The SAP tool | `calder_tool.py`, sample or sandbox | A released SAP API, exposed through the MCP Gateway in SAP Integration Suite or an API proxy |
| The agent | A free account, one topic at a time | The company's tenant on the chosen platform, with a budget and an owner |
| Identity | None; the sandbox key is shared by everyone | The user's identity passed from the platform's identity provider to SAP Cloud Identity Services, as in SAP's [Copilot Studio reference architecture](https://architecture.learning.sap.com/docs/ref-arch/d2e34e) |
| Agent to agent | The local A2A server from [A2A for SAP agents](https://erpfde.com/topics/a2a-for-sap-agents/) | SAP's Agent Gateway, with the status SAP states at the time ([A2A and MCP at SAP](https://architecture.learning.sap.com/docs/ref-arch/76ec36)) |

What SAP's API policy allows a third-party agent to do is its own question; [SAP's API policy and third-party agents](https://erpfde.com/topics/sap-api-policy-and-third-party-agents/) covers it.

### Production concerns

- **Spending.** The day you open an account, find out how its console warns you about spending, set a warning below the free credit if it offers one, and delete resources when a topic ends.
- **Keys.** Cloud keys go in `.env` only, never in code or in a chat with a model. Revoke a key when you close an account.
- **Data.** Free accounts and free model tiers are personal learning tools. Never send company, customer or employee data to them; use Calder's made-up values.
- **Identity.** The sandbox key identifies you, not a business user. A real agent must carry the user's identity into SAP, or a technical user whose roles someone owns; see [agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/).
- **Read only first.** The shared tool reads. Any later tool that changes SAP data needs a person's approval in the flow, not just in the prompt.

### Pitfalls

- **Opening every account on day one.** The Azure credit lasts 30 days; it's gone before its topic.
- **Assuming Google's credit covers Vertex AI.** Not for sign-ups since 16 November 2026.
- **Forgetting an AWS account at the end of the free plan.** It is suspended, then erased after 90 days.
- **Letting each platform redefine the tool.** Change the contract once, then regenerate each adapter.
- **Reading sandbox output as Calder's.** The sandbox returns SAP's sample data.
- **Upgrading a pinned library on a whim.** Change the pin, rerun the check, and say why in your commit.

### Exercise

Add a second read-only tool to the contract so later platform topics can list Calder's problem orders, not just read one.

1. Open `unit15/calder_tool.py`.
2. In `CONTRACT["tools"]`, the list ends with `}],` after `"read_only": True,`. Change that `}],` to `},`, paste the entry below on the next line, and close the list with `],` after it:

   ```python
       {
           "name": "list_problem_orders",
           "description": "List Calder's open sales orders that have a problem, optionally for one customer. Read only.",
           "parameters": {
               "type": "object",
               "properties": {"sold_to_party": {"type": "string", "pattern": "^[0-9]{8}$",
                                                "description": "Customer number, for example 10000001"}},
               "required": [],
               "additionalProperties": False,
           },
           "read_only": True,
       },
   ```

3. Below `calder_order()`, add the function:

   ```python
   def list_problem_orders(sold_to_party: str | None = None) -> list:
       """List the sample orders with a problem, optionally for one customer."""
       return [calder_order(number) for number, row in CALDER_ORDERS.items()
               if sold_to_party in (None, row[0])]
   ```

4. Run `python unit15/calder_tool.py contract`. It now reports `2 tool(s): get_sales_order, list_problem_orders`.
5. Try the function from Python:

   ```bash
   python -c "import sys; sys.path.insert(0, 'unit15'); import calder_tool as t; print([o['sales_order'] for o in t.list_problem_orders('10000001')])"
   ```

   You should see Brennock's four orders: `['1000003', '1000004', '1000006', '1000007']`.

6. Run `python check_unit15.py` and commit with the message `Unit 15: add list_problem_orders to the tool contract`.

**Done when:** the check prints `OK       tool contract: 2 tool(s) get_sales_order, list_problem_orders` and still ends with `Ready for Unit 15.` The Microsoft, AWS and Google topics can then give each platform's agent both tools, so it can find a customer's stuck orders and read each one.

### Check yourself

1. What does `check_unit15.py` do when `AWS_FREE_START` is missing from `.env`?
   - A. It stops with MISSING, because every account must be open first
   - B. It prints LATER, because you open each account only when needed
   - C. It opens an AWS account for you through the AWS console
   - D. It reads your sign-up date from AWS over the network

   Answer: B. Accounts are optional until their topic, so the check reports them as LATER and never fails on them. It contacts no provider; it only reads `.env` and counts days.

2. Why does `calder_tool.py` turn every failure into a `ToolError` with a short message?
   - A. So SAP can log the error in the sales order's change history
   - B. So an agent gets a clear message it can pass on, not a crash
   - C. So the free tiers don't count failed calls against the credit
   - D. So the contract file is rewritten after every failed call

   Answer: B. An agent calling a tool needs an answer it can reason about, such as "order not found". A crash or a raw stack trace gives the model nothing useful and hides the cause from the user.

3. The Microsoft topic's agent answers differently from the Google topic's on order 1000002. Where do you look first?
   - A. In `tool_contract.json`, because each platform edits its own copy
   - B. In the Calder sample, because it changes with every call
   - C. In each platform's adapter and model, since the tool is the same
   - D. In the SAP sandbox, because both agents read it by default

   Answer: C. Both agents call the same tool on the same fixed data, so the backend isn't the difference. The adapter, the model or the platform's instructions are where the answers diverge.

4. You signed up for Google Cloud on 20 November 2026 and want to run the Google topic. Which route does this setup prepare?
   - A. Vertex AI paid for from the $300 credit for 90 days
   - B. ADK on your laptop with a Gemini API key from AI Studio
   - C. The SAP Agent Gateway on your own SAP subaccount
   - D. A Copilot Studio trial calling Gemini through Azure

   Answer: B. Google's trial page says the $300 credit can't pay for Gemini platform or Gemini API costs for sign-ups from 16 November 2026, and points to the Gemini API free tier. The course runs ADK locally with `GOOGLE_API_KEY`.

5. `python unit15/calder_tool.py call --sandbox` prints `Tool error: could not reach SAP (ProxyError)`. What does that mean?
   - A. The SAP key in `.env` has expired and needs a new one
   - B. Order 1000002 doesn't exist in SAP's sandbox system
   - C. The tool contract has the wrong input shape for SAP
   - D. A network or proxy blocks `sandbox.api.sap.com`

   Answer: D. A ProxyError is raised before SAP answers at all, so neither the key nor the order is at fault. Try another network or ask IT; the Calder sample works without the network.

6. A teammate wants to add a tool that releases credit blocks to the contract. What should come with it?
   - A. Nothing extra, since the contract is only for learning
   - B. A higher `contract_version`, which tells SAP to allow writes
   - C. A person's approval in the flow before anything changes in SAP
   - D. A second sandbox key so writes and reads use different keys

   Answer: C. Every tool in this setup is read only. A tool that changes SAP data needs a person's approval enforced in the flow, and an identity whose SAP roles someone owns, not a version number or a key.

## Sources

- [Azure free account (azure.microsoft.com)](https://azure.microsoft.com/en-us/free/): $200 credit to use within 30 days; free monthly amounts of 20+ services for 12 months and 65+ always-free services; phone, credit or debit card and a Microsoft or GitHub account; card not charged unless you move to pay-as-you-go; otherwise account and services are disabled
- [Copilot Studio licensing and trial (Microsoft Learn, updated 2026-10-27)](https://learn.microsoft.com/en-us/microsoft-copilot-studio/requirements-licensing-subscriptions): individual trial with a work or school account; IT can disable self-service sign-up; extend by 30 days when it expires; agents keep working up to 90 days after; a trial can't publish agents; trial length not stated on the page
- [AWS Free Tier now offers $200 in credits and 6-month free plan (AWS What's New, 16 July 2025)](https://aws.amazon.com/about-aws/whats-new/2025/07/aws-free-tier-credits-month-free-plan): $100 at sign-up plus up to $100 more for using services such as Amazon EC2 and Amazon Bedrock; the free plan ends 6 months after sign-up or when credits run out
- [AWS Free Tier FAQs (aws.amazon.com, updated 2026-11-17)](https://aws.amazon.com/free/free-tier-faqs/): free plan covers a subset of services; payment method not required for most new customers; account suspended at the end, erased if not upgraded within 90 days; credit expiry given as 6 months in some answers and 12 in others
- [Amazon Bedrock pricing (aws.amazon.com, updated 2026-11-20)](https://aws.amazon.com/bedrock/pricing/): on-demand inference priced per million input and output tokens by model and region; no general free tier described
- [Free Google Cloud features and trial offer (Google Cloud documentation)](https://docs.cloud.google.com/free/docs/free-cloud-features): $300 credit valid for 90 days; payment method required at sign-up; no automatic upgrade; can't be paused or extended; from 16 November 2026 the credit can't pay for Gemini platform (formerly Vertex AI) services or the Gemini API in AI Studio, which has its own free tier
- [Copilot Studio with MCP Gateway in SAP Integration Suite (SAP Architecture Center, updated 2026-10-26)](https://architecture.learning.sap.com/docs/ref-arch/d2e34e): Copilot Studio as MCP client through the MCP Gateway; Entra ID trusted by SAP Cloud Identity Services; needs a customer-managed subaccount with Integration Suite and the MCP Gateway capability; notes the Agent Gateway was not yet GA when written
- [A2A and MCP for AI Agent Interoperability at SAP (SAP Architecture Center, updated 2026-10-26)](https://architecture.learning.sap.com/docs/ref-arch/76ec36): A2A preferred for external interoperability; names Google Vertex AI, Microsoft Copilot Studio and AWS Bedrock AgentCore; bidirectional Agent Gateway traffic with third-party agents not yet supported when written
- [Get started with SAP Business Accelerator Hub (SAP Developers tutorial)](https://developers.sap.com/tutorials/hcp-abh-getting-started.html): the hub is a website to discover, explore and test SAP APIs; the sandbox needs you to be logged on; Try Out and Run
