> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Recipes

> One job per recipe: the scopes it needs, its steps with code, and what comes back.

The SDK packages are being released to the public registries. Until the install commands are shown in the [quickstart](/docs/quickstart.md), do not install a package of these names from anywhere else. The cURL samples run as written against a sandbox, with a test key in `INSIGHTCHAIN_API_KEY`; the quickstart sets both up. The TypeScript and Python samples run as written once the SDK is installed.

* [Push your purchase orders, get stockout risk back](#push-your-purchase-orders-get-stockout-risk-back)
* [Check what a tariff costs before you buy](#check-what-a-tariff-costs-before-you-buy)
* [Act on a recommendation](#act-on-a-recommendation)
* [Get told when something changes](#get-told-when-something-changes)
* [Keep your keys healthy](#keep-your-keys-healthy)
* [Find a failed call](#find-a-failed-call)
* [Connect an agent](#connect-an-agent)

## Push your purchase orders, get stockout risk back

Send the purchase orders you have open and read back which are at risk, and where stock runs out first.

**Scopes:** `ingest`, `read`

`ingest` writes and reads nothing back, so the reads need `read` on the same key or on a second one.

**Step 1.** Push the orders. A record is matched on `external_id`, so sending it again updates it, and an `Idempotency-Key` makes a retry safe. The sample sends one order that is already late, for an item, a supplier and a location of the sandbox's demo data. With your own data, push `suppliers`, `items` and `locations` the same way first.

```bash cURL theme={null}
curl -X POST "https://api.insightchain.ai/v1/ingest/records" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: recipe-orders-0001-curl" \
  -d '{
    "connection": "recipes",
    "entities": {
      "purchase_orders": [
        {
          "external_id": "RECIPE-PO-0001",
          "supplier_external_id": "VEND-000001",
          "status": "open",
          "currency": "USD",
          "order_date": "2026-10-01",
          "expected_delivery_date": "2026-11-01",
          "lines": [
            { "line_number": 1, "item_external_id": "MAT-00000001", "location_external_id": "1002", "quantity": 200, "unit_price": 120 }
          ]
        }
      ]
    }
  }'
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const result = await client.ingestRecords(
  {
    body: {
      connection: "recipes",
      entities: {
        purchase_orders: [
          {
            external_id: "RECIPE-PO-0001",
            supplier_external_id: "VEND-000001",
            status: "open",
            currency: "USD",
            order_date: "2026-10-01",
            expected_delivery_date: "2026-11-01",
            lines: [
              { line_number: 1, item_external_id: "MAT-00000001", location_external_id: "1002", quantity: 200, unit_price: 120 },
            ],
          },
        ],
      },
    },
  },
  { idempotencyKey: "recipe-orders-0001" },
);
console.log(result.status, result.results.purchase_orders, "errors:", result.error_count);
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

result = client.ingest_records(
    body={
        "connection": "recipes",
        "entities": {
            "purchase_orders": [
                {
                    "external_id": "RECIPE-PO-0001",
                    "supplier_external_id": "VEND-000001",
                    "status": "open",
                    "currency": "USD",
                    "order_date": "2026-10-01",
                    "expected_delivery_date": "2026-11-01",
                    "lines": [
                        {
                            "line_number": 1,
                            "item_external_id": "MAT-00000001",
                            "location_external_id": "1002",
                            "quantity": 200,
                            "unit_price": 120,
                        }
                    ],
                }
            ]
        },
    },
    options={"idempotency_key": "recipe-orders-0001-py"},
)
print(result["status"], result["results"]["purchase_orders"], "errors:", result["error_count"])
```

**Step 2.** Read the risk of each open order for that item: a score, what drives it, and what to do about it (`expedite`, `monitor` or `on_track`).

```bash cURL theme={null}
curl "https://api.insightchain.ai/v1/inventory/purchase_order_risks?item=MAT-00000001&limit=10" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const risks = await client.listPurchaseOrderRisks({ item: "MAT-00000001", limit: 10 });
for (const po of risks.data) {
  console.log(po.purchase_order, po.risk_score, po.recommended_action, po.expected_delivery_date);
  for (const factor of po.factors) console.log("  ", factor.factor, factor.points, factor.detail);
}
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

risks = client.list_purchase_order_risks(item="MAT-00000001", limit=10)
for po in risks["data"]:
    print(po["purchase_order"], po["risk_score"], po["recommended_action"], po["expected_delivery_date"])
    for factor in po["factors"]:
        print("  ", factor["factor"], factor["points"], factor["detail"])
```

**Step 3.** Read when the item runs out at each location, with the inbound orders counted in.

```bash cURL theme={null}
curl "https://api.insightchain.ai/v1/inventory/stockout_projections?item=MAT-00000001&limit=10" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const projections = await client.listStockoutProjections({ item: "MAT-00000001", limit: 10 });
for (const row of projections.data) {
  console.log(row.item, row.location, "on hand", row.on_hand, "runs out in", row.stockout_in_days, "days;", row.rescued_by_inbound ? "inbound arrives in time" : "nothing arrives in time");
}
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

projections = client.list_stockout_projections(item="MAT-00000001", limit=10)
for row in projections["data"]:
    covered = "inbound arrives in time" if row["rescued_by_inbound"] else "nothing arrives in time"
    print(row["item"], row["location"], "on hand", row["on_hand"], "runs out in", row["stockout_in_days"], "days;", covered)
```

**Step 4.** List what is proposed. A sandbox lists the proposals it was loaded with.

```bash cURL theme={null}
curl "https://api.insightchain.ai/v1/recommendations?status=proposed&limit=5" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const proposed = await client.listRecommendations({ status: "proposed", limit: 5 });
for (const rec of proposed.data) {
  console.log(rec.id, rec.kind, rec.priority, rec.item?.external_id ?? "");
}
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

proposed = client.list_recommendations(status="proposed", limit=5)
for rec in proposed["data"]:
    item = rec["item"]["external_id"] if rec["item"] else ""
    print(rec["id"], rec["kind"], rec["priority"], item)
```

**What comes back.** The push answers with a count per entity (`received`, `upserted`, `failed`) and the records it refused. A risk row carries `purchase_order`, `risk_score`, `recommended_action` and the `factors` behind the score. A projection carries `on_hand`, `stockout_in_days` and whether inbound stock arrives in time (`rescued_by_inbound`).

## Check what a tariff costs before you buy

Price an import before you place the order: the duty on the tariff line, then the full landed cost.

**Scopes:** `read`

**Step 1.** Check the duty on the tariff line from the country you would buy from. Send `item_description` in place of `hs_code` when you do not have the code.

```bash cURL theme={null}
curl -X POST "https://api.insightchain.ai/v1/tariff_checks" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"hs_code": "8471.30.0100", "origin_country": "CN", "destination_country": "US"}'
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const check = await client.createTariffCheck({
  body: { hs_code: "8471.30.0100", origin_country: "CN", destination_country: "US" },
});
console.log(check.hs_code, "effective rate:", check.effective_rate);
for (const duty of check.additional_duties) console.log("  ", duty.type, duty.rate);
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

check = client.create_tariff_check(
    body={"hs_code": "8471.30.0100", "origin_country": "CN", "destination_country": "US"},
)
print(check["hs_code"], "effective rate:", check["effective_rate"])
for duty in check["additional_duties"]:
    print("  ", duty["type"], duty["rate"])
```

**Step 2.** Price the shipment: duty, fees and import tax on top of the goods, freight and insurance, in total and per unit.

```bash cURL theme={null}
curl -X POST "https://api.insightchain.ai/v1/landed_costs" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "hs_code": "8471.30.0100",
    "origin_country": "CN",
    "destination_country": "US",
    "goods_value": 50000,
    "freight_cost": 2500,
    "insurance_cost": 500,
    "quantity": 10
  }'
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const cost = await client.createLandedCost({
  body: {
    hs_code: "8471.30.0100", origin_country: "CN", destination_country: "US",
    goods_value: 50000,
    freight_cost: 2500,
    insurance_cost: 500,
    quantity: 10,
  },
});
console.log("duty:", cost.cost_breakdown.duty_amount, "fees:", cost.cost_breakdown.total_fees);
console.log("total:", cost.total_landed_cost, cost.currency, "per unit:", cost.per_unit_landed_cost);
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

cost = client.create_landed_cost(
    body={
        "hs_code": "8471.30.0100", "origin_country": "CN", "destination_country": "US",
        "goods_value": 50000,
        "freight_cost": 2500,
        "insurance_cost": 500,
        "quantity": 10,
    },
)
print("duty:", cost["cost_breakdown"]["duty_amount"], "fees:", cost["cost_breakdown"]["total_fees"])
print("total:", cost["total_landed_cost"], cost["currency"], "per unit:", cost["per_unit_landed_cost"])
```

**Step 3.** Compare the countries you could buy from: the same shipment, one call per origin.

```bash cURL theme={null}
for origin in CN VN MX; do
  curl -X POST "https://api.insightchain.ai/v1/landed_costs" \
    -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"hs_code": "8471.30.0100", "origin_country": "'"$origin"'", "destination_country": "US", "goods_value": 50000, "quantity": 10}'
  echo
done
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

for (const origin of ["CN", "VN", "MX"]) {
  const cost = await client.createLandedCost({
    body: { hs_code: "8471.30.0100", origin_country: origin, destination_country: "US", goods_value: 50000, quantity: 10 },
  });
  console.log(origin, `duty ${cost.cost_breakdown.duty_rate_percent}%`, "per unit:", cost.per_unit_landed_cost);
}
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

for origin in ["CN", "VN", "MX"]:
    cost = client.create_landed_cost(
        body={"hs_code": "8471.30.0100", "origin_country": origin, "destination_country": "US", "goods_value": 50000, "quantity": 10},
    )
    print(origin, "duty", cost["cost_breakdown"]["duty_rate_percent"], "%", "per unit:", cost["per_unit_landed_cost"])
```

**What comes back.** The tariff check returns the base rate, every additional duty with its source, and the `effective_rate`. The landed cost returns a `cost_breakdown` (duty, fees, import tax), `total_landed_cost` and `per_unit_landed_cost`.

## Act on a recommendation

Read what is proposed and why, then approve it or turn it down.

**Scopes:** `read`, `execute`, `approve`

`read` lists and explains. `execute` decides a recommendation and proposes an order. `approve` approves or rejects an order: only an organization admin can put it on a key, and it is held by someone other than the proposer.

**Step 1.** List what is waiting for a decision, highest priority first.

```bash cURL theme={null}
curl "https://api.insightchain.ai/v1/recommendations?status=proposed&limit=10" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const proposed = await client.listRecommendations({ status: "proposed", limit: 10 });
for (const rec of proposed.data) {
  console.log(rec.id, rec.kind, "priority", rec.priority, "quantity", rec.quantity);
}
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

proposed = client.list_recommendations(status="proposed", limit=10)
for rec in proposed["data"]:
    print(rec["id"], rec["kind"], "priority", rec["priority"], "quantity", rec["quantity"])
```

**Step 2.** Read why it was proposed: the evidence, the numbers behind it and how confident it is.

```bash cURL theme={null}
# RECOMMENDATION_ID: the id of a recommendation listed in step 1.
curl -X POST "https://api.insightchain.ai/v1/explanations" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"recommendation_id": "'"$RECOMMENDATION_ID"'", "use_ai": false}'
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listRecommendations({ status: "proposed", limit: 1 });
const rec = data[0];
if (!rec) throw new Error("Nothing is proposed.");

const explanation = await client.createExplanation({ body: { recommendation_id: rec.id, use_ai: false } });
console.log(explanation.evidence.headline);
console.log("confidence:", explanation.evidence.confidence);
console.log(explanation.narrative);
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

rec = client.list_recommendations(status="proposed", limit=1)["data"][0]

explanation = client.create_explanation(body={"recommendation_id": rec["id"], "use_ai": False})
print(explanation["evidence"]["headline"])
print("confidence:", explanation["evidence"]["confidence"])
print(explanation["narrative"])
```

**Step 3.** Decide. Approving needs the `execute` scope and is recorded for the person who created the key. To turn it down, call `dismissRecommendation` (`dismiss_recommendation`) the same way.

```bash cURL theme={null}
# RECOMMENDATION_ID: the id of a recommendation listed in step 1.
curl -X POST "https://api.insightchain.ai/v1/recommendations/$RECOMMENDATION_ID/approve" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listRecommendations({ status: "proposed", limit: 1 });
const rec = data[0];
if (!rec) throw new Error("Nothing is proposed.");

const { recommendation } = await client.approveRecommendation({ id: rec.id });
console.log(recommendation.id, recommendation.status, recommendation.status_changed_at);
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

rec = client.list_recommendations(status="proposed", limit=1)["data"][0]

recommendation = client.approve_recommendation(rec["id"])["recommendation"]
print(recommendation["id"], recommendation["status"], recommendation["status_changed_at"])
```

**Step 4.** Where the recommendation is an order (a transfer, a purchase, an expedite, a markdown), propose the order with `execute`. A second organization admin then approves or rejects it with a key that holds `approve`: send `action: "approve"` or `"reject"` with the order's id as `order_id`. The person who proposed an order cannot approve it. A recommendation that is a task for a person is refused here, and the sample prints why.

```bash cURL theme={null}
# RECOMMENDATION_ID: the id of a recommendation listed in step 1.
# One that is a task for a person is refused: the answer is the error object, and error.code says why.
curl -X POST "https://api.insightchain.ai/v1/orders/actions" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"action": "propose", "recommendation_id": "'"$RECOMMENDATION_ID"'"}'
```

```typescript TypeScript theme={null}
import { InsightChain, InvalidRequestError } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listRecommendations({ status: "proposed", limit: 1 });
const rec = data[0];
if (!rec) throw new Error("Nothing is proposed.");

try {
  const { order } = await client.createOrderAction({
    body: { action: "propose", recommendation_id: rec.id },
  });
  console.log("order", order?.id, order?.status);
} catch (err) {
  if (!(err instanceof InvalidRequestError)) throw err;
  console.log("not an order:", err.code, err.message);
}
```

```python Python theme={null}
import insightchain

client = insightchain.InsightChain()

rec = client.list_recommendations(status="proposed", limit=1)["data"][0]

try:
    order = client.create_order_action(body={"action": "propose", "recommendation_id": rec["id"]})["order"]
    print("order", order["id"], order["status"])
except insightchain.InvalidRequestError as err:
    print("not an order:", err.code, err.message)
```

**What comes back.** A recommendation carries its `kind`, `priority`, `quantity`, the item and locations, and its `status`. The explanation carries the `evidence` (headline, drivers, cost and benefit, confidence) and a `narrative`. A decision returns the recommendation with its new status; a proposed order returns the order with status `proposed`.

## Get told when something changes

Receive a signed request at your own address when something changes, and check that it came from us.

**Scopes:** `approve`

The key's creator must be an organization admin. A webhook registered with a test key receives test events only.

**Step 1.** Register the address that will receive events, and the kinds it wants. The signing secret is in this answer only: store it where your receiver reads it. Set `WEBHOOK_URL` to a public `https` address of your own before running the samples of this recipe.

```bash cURL theme={null}
# The answer carries the signing secret (whsec_...) once: store it. Keep webhook.id for the next steps.
curl -X POST "https://api.insightchain.ai/v1/webhooks" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "'"$WEBHOOK_URL"'", "events": ["recommendation", "disruption"]}'
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const url = process.env.WEBHOOK_URL;
if (!url) throw new Error("Set WEBHOOK_URL to a public https address of your own.");

const { webhook, secret } = await client.createWebhook({
  body: { url, events: ["recommendation", "disruption"] },
});
// `secret` (whsec_...) is shown once. Store it now; this sample does not print it.
console.log("webhook", webhook.id, webhook.events, "secret received:", secret.startsWith("whsec_"));
```

```python Python theme={null}
import os

from insightchain import InsightChain

client = InsightChain()

created = client.create_webhook(
    body={"url": os.environ["WEBHOOK_URL"], "events": ["recommendation", "disruption"]},
)
# created["secret"] (whsec_...) is shown once. Store it now; this sample does not print it.
print("webhook", created["webhook"]["id"], created["webhook"]["events"], "secret received:", created["secret"].startswith("whsec_"))
```

**Step 2.** In your receiver, check `X-InsightChain-Signature-V2` against the raw body before you trust it: `t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`, keyed with the secret. Refuse a timestamp more than 300 seconds from your clock. The sample runs on its own.

```typescript TypeScript theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";

function verifyWebhook(secret, rawBody, header, nowSeconds = Math.floor(Date.now() / 1000)) {
  const pairs = String(header ?? "").split(",").map((part) => part.trim().split("="));
  const t = Number(pairs.find(([name]) => name === "t")?.[1]);
  // Older than five minutes, or from the future: refuse it (a replayed request).
  if (!Number.isInteger(t) || Math.abs(nowSeconds - t) > 300) return false;
  const expected = Buffer.from(createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex"));
  // While a rotated secret overlaps there are two v1 values: accept the delivery when any matches.
  return pairs
    .filter(([name]) => name === "v1")
    .some(([, value]) => {
      const given = Buffer.from(String(value ?? ""));
      return given.length === expected.length && timingSafeEqual(given, expected);
    });
}

// Try it: sign a body the way a delivery is signed, then check it.
const secret = "whsec_example";
const body = JSON.stringify({ type: "insightchain.test", data: { test: true } });
const t = Math.floor(Date.now() / 1000);
const v1 = createHmac("sha256", secret).update(`${t}.${body}`).digest("hex");
console.log(verifyWebhook(secret, body, `t=${t},v1=${v1}`)); // true
console.log(verifyWebhook("whsec_another", body, `t=${t},v1=${v1}`)); // false
```

```python Python theme={null}
import hashlib
import hmac
import json
import time


def verify_webhook(secret, raw_body, header, now=None):
    t = None
    signatures = []
    for part in (header or "").split(","):
        name, _, value = part.strip().partition("=")
        if name == "t":
            t = value
        elif name == "v1":
            signatures.append(value)
    # Older than five minutes, or from the future: refuse it (a replayed request).
    if t is None or not t.isascii() or not t.isdigit():
        return False
    if abs((time.time() if now is None else now) - int(t)) > 300:
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest().encode()
    # While a rotated secret overlaps there are two v1 values: accept the delivery when any matches.
    return any(hmac.compare_digest(expected, given.encode()) for given in signatures)


# Try it: sign a body the way a delivery is signed, then check it.
secret = "whsec_example"
body = json.dumps({"type": "insightchain.test", "data": {"test": True}}).encode()
t = str(int(time.time()))
v1 = hmac.new(secret.encode(), t.encode() + b"." + body, hashlib.sha256).hexdigest()
print(verify_webhook(secret, body, f"t={t},v1={v1}"))  # True
print(verify_webhook("whsec_another", body, f"t={t},v1={v1}"))  # False
```

**Step 3.** Send a test event. It is signed like any delivery, sent once, and the answer says how your receiver replied.

```bash cURL theme={null}
# WEBHOOK_ID: webhook.id of the answer in step 1.
curl -X POST "https://api.insightchain.ai/v1/webhooks/$WEBHOOK_ID/test" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listWebhooks();
const hook = data.find((w) => w.url === process.env.WEBHOOK_URL);
if (!hook) throw new Error("Register the webhook first (step 1).");

const { test } = await client.testWebhook({ id: hook.id });
console.log("delivered:", test.delivered, "outcome:", test.outcome, "your answer:", test.last_status);
```

```python Python theme={null}
import os

from insightchain import InsightChain

client = InsightChain()

hook = next(w for w in client.list_webhooks()["data"] if w["url"] == os.environ["WEBHOOK_URL"])

test = client.test_webhook(hook["id"])["test"]
print("delivered:", test["delivered"], "outcome:", test["outcome"], "your answer:", test["last_status"])
```

**Step 4.** Read the delivery log: one row per attempt for the last 30 days, with what your receiver answered and how long it took.

```bash cURL theme={null}
# WEBHOOK_ID: webhook.id of the answer in step 1.
curl "https://api.insightchain.ai/v1/webhooks/$WEBHOOK_ID/deliveries?limit=10" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listWebhooks();
const hook = data.find((w) => w.url === process.env.WEBHOOK_URL);
if (!hook) throw new Error("Register the webhook first (step 1).");

const log = await client.listWebhookDeliveries({ id: hook.id, limit: 10 });
for (const attempt of log.data) {
  console.log(attempt.attempted_at, attempt.event_type, attempt.trigger, attempt.outcome, attempt.status, `${attempt.duration_ms} ms`);
}
```

```python Python theme={null}
import os

from insightchain import InsightChain

client = InsightChain()

hook = next(w for w in client.list_webhooks()["data"] if w["url"] == os.environ["WEBHOOK_URL"])

log = client.list_webhook_deliveries(hook["id"], limit=10)
for attempt in log["data"]:
    print(attempt["attempted_at"], attempt["event_type"], attempt["trigger"], attempt["outcome"], attempt["status"], attempt["duration_ms"], "ms")
```

**Step 5.** Send a failed delivery again once your receiver is fixed. `delivery_id` is the `X-InsightChain-Delivery` header your receiver got. A delivery still being retried answers 409 `delivery_pending`. A sandbox sends test events only, and a test event is sent once, so there the sample finds nothing to send again.

```bash cURL theme={null}
# WEBHOOK_ID: webhook.id of the answer in step 1.
# The failed attempts
curl "https://api.insightchain.ai/v1/webhooks/$WEBHOOK_ID/deliveries?outcome=failed&limit=20" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"

# DELIVERY_ID: delivery_id of a failed attempt in that answer whose trigger is not "test".
curl -X POST "https://api.insightchain.ai/v1/webhooks/$WEBHOOK_ID/deliveries/$DELIVERY_ID/redeliver" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listWebhooks();
const hook = data.find((w) => w.url === process.env.WEBHOOK_URL);
if (!hook) throw new Error("Register the webhook first (step 1).");

const failures = await client.listWebhookDeliveries({ id: hook.id, outcome: "failed", limit: 20 });
const failed = failures.data.find((attempt) => attempt.trigger !== "test");

if (!failed) {
  console.log("No failed delivery to send again.");
} else {
  const { attempt } = await client.redeliverWebhookDelivery({ id: hook.id, delivery_id: failed.delivery_id });
  console.log("delivered:", attempt.delivered, "your answer:", attempt.status);
}
```

```python Python theme={null}
import os

from insightchain import InsightChain

client = InsightChain()

hook = next(w for w in client.list_webhooks()["data"] if w["url"] == os.environ["WEBHOOK_URL"])

failures = client.list_webhook_deliveries(hook["id"], outcome="failed", limit=20)
failed = next((a for a in failures["data"] if a["trigger"] != "test"), None)

if failed is None:
    print("No failed delivery to send again.")
else:
    attempt = client.redeliver_webhook_delivery(hook["id"], failed["delivery_id"])["attempt"]
    print("delivered:", attempt["delivered"], "your answer:", attempt["status"])
```

**Step 6.** Rotate the secret without dropping a delivery. With `overlap_seconds` the old secret keeps signing beside the new one until the window ends: the header carries two `v1` values, the new secret's first, and the check above accepts either. Deploy the new secret to your receiver inside the window.

```bash cURL theme={null}
# WEBHOOK_ID: webhook.id of the answer in step 1. The answer carries the new secret once: store it.
curl -X POST "https://api.insightchain.ai/v1/webhooks/$WEBHOOK_ID/rotate_secret" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"overlap_seconds": 86400}'
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listWebhooks();
const hook = data.find((w) => w.url === process.env.WEBHOOK_URL);
if (!hook) throw new Error("Register the webhook first (step 1).");

const rotated = await client.rotateWebhookSecret({ id: hook.id, body: { overlap_seconds: 86400 } });
// rotated.secret is the new secret, shown once. Store it now.
console.log("the old secret signs until", rotated.previous_secret_expires_at);
```

```python Python theme={null}
import os

from insightchain import InsightChain

client = InsightChain()

hook = next(w for w in client.list_webhooks()["data"] if w["url"] == os.environ["WEBHOOK_URL"])

rotated = client.rotate_webhook_secret(hook["id"], body={"overlap_seconds": 86400})
# rotated["secret"] is the new secret, shown once. Store it now.
print("the old secret signs until", rotated["previous_secret_expires_at"])
```

**What comes back.** Registering returns the webhook and its `secret`, once. A test returns `delivered`, the `outcome` and your receiver's status. The delivery log returns one row per attempt: `event_type`, `trigger`, `outcome`, `status`, `duration_ms` and, for an attempt that will be retried, `next_attempt_at`.

## Keep your keys healthy

See which keys are in use, give each an expiry, and rotate one without downtime.

**Scopes:** `keys`, `read`

Only an organization admin can put `keys` on a key, and the key works while its creator is still an admin. It manages keys of its own environment: a test key the sandbox's keys, a live key the live ones.

**Step 1.** List the keys: what each may do, when it was last used and when it expires. A key that has not been used for months is one to revoke.

```bash cURL theme={null}
curl "https://api.insightchain.ai/v1/api_keys" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const keys = await client.listApiKeys();
for (const key of keys.data) {
  console.log(key.name, key.key_hint, key.scopes.join(","), "last used:", key.last_used_at ?? "never", "expires:", key.expires_at ?? "never");
}
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

keys = client.list_api_keys()
for key in keys["data"]:
    print(key["name"], key["key_hint"], ",".join(key["scopes"]), "last used:", key["last_used_at"] or "never", "expires:", key["expires_at"] or "never")
```

**Step 2.** Create a key for one job, with only the scopes the job needs and a date it stops working. A key can hand out only scopes it holds itself, so this call needs `read` as well as `keys`.

```bash cURL theme={null}
# expires_at: any time in the future. The answer carries the key itself (secret) once: store it. Keep key.id for the next steps.
curl -X POST "https://api.insightchain.ai/v1/api_keys" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "recipe-reporting", "scopes": ["read"], "expires_at": "2027-06-30T00:00:00Z"}'
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const in90Days = new Date(Date.now() + 90 * 86_400_000).toISOString();
const created = await client.createApiKey({
  body: { name: "recipe-reporting", scopes: ["read"], expires_at: in90Days },
});
// created.secret is the key itself, shown once. Store it now.
console.log(created.key.id, created.key.key_hint, created.key.environment, "expires", created.key.expires_at);
```

```python Python theme={null}
from datetime import datetime, timedelta, timezone

from insightchain import InsightChain

client = InsightChain()

in_90_days = (datetime.now(timezone.utc) + timedelta(days=90)).isoformat(timespec="seconds")
created = client.create_api_key(
    body={"name": "recipe-reporting", "scopes": ["read"], "expires_at": in_90_days},
)
# created["secret"] is the key itself, shown once. Store it now.
print(created["key"]["id"], created["key"]["key_hint"], created["key"]["environment"], "expires", created["key"]["expires_at"])
```

**Step 3.** Rotate it with a 24-hour overlap: the new secret works at once and the old one keeps working until the window ends, so you can deploy the new one without a gap. Without `overlap_seconds` the old secret stops at once.

```bash cURL theme={null}
# KEY_ID: key.id of the answer in step 2. The answer carries the new secret once: store it.
curl -X POST "https://api.insightchain.ai/v1/api_keys/$KEY_ID/rotate" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"overlap_seconds": 86400}'
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listApiKeys();
const key = data.find((k) => k.name === "recipe-reporting");
if (!key) throw new Error("Create the key first (step 2).");

const rotated = await client.rotateApiKey({ id: key.id, body: { overlap_seconds: 86400 } });
// rotated.secret is the new secret, shown once. Store it now.
console.log(rotated.key.key_hint, "the old secret works until", rotated.previous_secret_expires_at);
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

key = next(k for k in client.list_api_keys()["data"] if k["name"] == "recipe-reporting")

rotated = client.rotate_api_key(key["id"], body={"overlap_seconds": 86400})
# rotated["secret"] is the new secret, shown once. Store it now.
print(rotated["key"]["key_hint"], "the old secret works until", rotated["previous_secret_expires_at"])
```

**Step 4.** Change when it expires. Past `expires_at` the key answers 401 `api_key_expired`. Send `null` for a key that does not expire.

```bash cURL theme={null}
# KEY_ID: key.id of the answer in step 2. expires_at: any time in the future, or null.
curl -X PATCH "https://api.insightchain.ai/v1/api_keys/$KEY_ID" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"expires_at": "2027-03-31T00:00:00Z"}'
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listApiKeys();
const key = data.find((k) => k.name === "recipe-reporting");
if (!key) throw new Error("Create the key first (step 2).");

const in30Days = new Date(Date.now() + 30 * 86_400_000).toISOString();
const updated = await client.updateApiKey({ id: key.id, body: { expires_at: in30Days } });
console.log(updated.key.name, "expires", updated.key.expires_at);
```

```python Python theme={null}
from datetime import datetime, timedelta, timezone

from insightchain import InsightChain

client = InsightChain()

key = next(k for k in client.list_api_keys()["data"] if k["name"] == "recipe-reporting")

in_30_days = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat(timespec="seconds")
updated = client.update_api_key(key["id"], body={"expires_at": in_30_days})
print(updated["key"]["name"], "expires", updated["key"]["expires_at"])
```

**Step 5.** Revoke a key you no longer need. It stops working at once.

```bash cURL theme={null}
# KEY_ID: key.id of the answer in step 2.
curl -X DELETE "https://api.insightchain.ai/v1/api_keys/$KEY_ID" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const { data } = await client.listApiKeys();
const key = data.find((k) => k.name === "recipe-reporting");
if (!key) throw new Error("Create the key first (step 2).");

const revoked = await client.revokeApiKey({ id: key.id });
console.log("revoked:", revoked.deleted, revoked.id);
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

key = next(k for k in client.list_api_keys()["data"] if k["name"] == "recipe-reporting")

revoked = client.revoke_api_key(key["id"])
print("revoked:", revoked["deleted"], revoked["id"])
```

**What comes back.** Every key comes back without its secret: `name`, `key_hint` (the prefix and last four characters), `scopes`, `environment`, `last_used_at` (to the minute), `expires_at` and `requests_today`. Creating and rotating also return `secret`, once. Every change is in your audit trail.

## Find a failed call

Trace one call from your own logs to ours, and see what failed lately.

**Scopes:** `read`

**Step 1.** Send your own id with the call, as `X-Request-ID` (1 to 128 visible characters). The answer keeps ours in `X-Request-ID` and echoes yours as `X-Client-Request-ID`. The sample asks for a recommendation that does not exist, so the call fails.

```bash cURL theme={null}
curl -i "https://api.insightchain.ai/v1/recommendations/00000000-0000-0000-0000-000000000000" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY" \
  -H "X-Request-ID: recipe-trace-0001"
```

```typescript TypeScript theme={null}
import { InsightChain, InsightChainError } from "@insightchain/sdk";

const client = new InsightChain();

try {
  await client.getRecommendation(
    { id: "00000000-0000-0000-0000-000000000000" },
    { headers: { "X-Request-ID": "recipe-trace-0001" } },
  );
} catch (err) {
  if (!(err instanceof InsightChainError)) throw err;
  console.log("failed:", err.status, err.code, "request_id:", err.requestId);
}
```

```python Python theme={null}
import insightchain

client = insightchain.InsightChain()

try:
    client.get_recommendation(
        "00000000-0000-0000-0000-000000000000",
        options={"headers": {"X-Request-ID": "recipe-trace-0001"}},
    )
except insightchain.InsightChainError as err:
    print("failed:", err.status, err.code, "request_id:", err.request_id)
```

**Step 2.** Find the call by your id. An entry appears a moment after its answer has left.

```bash cURL theme={null}
curl "https://api.insightchain.ai/v1/request_logs?client_request_id=recipe-trace-0001" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const log = await client.listRequestLogs({ client_request_id: "recipe-trace-0001" });
for (const entry of log.data) {
  console.log(entry.created_at, entry.method, entry.route, entry.status, entry.error_code, `${entry.latency_ms} ms`, entry.request_id);
}
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

log = client.list_request_logs(client_request_id="recipe-trace-0001")
for entry in log["data"]:
    print(entry["created_at"], entry["method"], entry["route"], entry["status"], entry["error_code"], entry["latency_ms"], "ms", entry["request_id"])
```

**Step 3.** Or list what failed lately. Filter by `outcome`, `status`, `method`, `api_key_id`, or a time range with `since` and `until`.

```bash cURL theme={null}
curl "https://api.insightchain.ai/v1/request_logs?outcome=error&limit=20" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const failures = await client.listRequestLogs({ outcome: "error", limit: 20 });
for (const entry of failures.data) {
  console.log(entry.created_at, entry.method, entry.route, entry.status, entry.error_code, "via", entry.via);
}
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

failures = client.list_request_logs(outcome="error", limit=20)
for entry in failures["data"]:
    print(entry["created_at"], entry["method"], entry["route"], entry["status"], entry["error_code"], "via", entry["via"])
```

**Step 4.** See how much of each key's daily quota is used, and requests and failures per key and day.

```bash cURL theme={null}
curl "https://api.insightchain.ai/v1/usage?days=7" \
  -H "Authorization: Bearer $INSIGHTCHAIN_API_KEY"
```

```typescript TypeScript theme={null}
import { InsightChain } from "@insightchain/sdk";

const client = new InsightChain();

const usage = await client.getUsage({ days: 7 });
for (const key of usage.keys) {
  console.log(key.name, `${key.requests_today} of ${key.daily_limit} today,`, key.remaining_today, "left");
}
for (const day of usage.daily) {
  console.log(day.day, "requests:", day.requests, "client errors:", day.client_errors, "server errors:", day.server_errors);
}
```

```python Python theme={null}
from insightchain import InsightChain

client = InsightChain()

usage = client.get_usage(days=7)
for key in usage["keys"]:
    print(key["name"], key["requests_today"], "of", key["daily_limit"], "today,", key["remaining_today"], "left")
for day in usage["daily"]:
    print(day["day"], "requests:", day["requests"], "client errors:", day["client_errors"], "server errors:", day["server_errors"])
```

**What comes back.** A log entry carries `request_id`, your `client_request_id`, the key, `method`, the `route` as a template, `status`, `error_code`, `latency_ms` and whether it came over `http` or `mcp`. It never carries a body, a query value or an id from the path. Entries are kept 30 days. Calls made without a valid key are not logged.

## Connect an agent

An assistant can call the same operations as tools: add the server to the client your team already uses and sign in with your account, or give a script an API key. Setup for each client, and the tools by the question they answer, are on their own page. See [Connect an AI client](/docs/agents.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.