Metadata-Version: 2.5
Name: intelligence-cloud
Version: 0.2.0
Summary: Python client for the Intelligence Cloud partner API: customer lifecycle and conversation intelligence.
Project-URL: Homepage, https://docs.intelligence.cloud
Project-URL: Documentation, https://docs.intelligence.cloud/api
Project-URL: Source, https://github.com/tresic-cloud/intelligence-cloud-sdk-python
Author: Tresic
License: Intelligence Cloud SDK Licence
        
        Copyright (c) 2026 Creo Solutions, Inc. d/b/a Tresic
        
        Permission is granted to Intelligence Cloud partners, their customers, and contractors working for
        either, to use, copy, modify and distribute this software, in source or compiled form and as part of
        their own applications, solely to access Intelligence Cloud services under an agreement with Tresic
        or an authorised Tresic partner. Keep this notice in copies of the source.
        
        Use of the Intelligence Cloud API, with or without this software, is governed by the Intelligence
        Cloud API and SDK Terms (https://docs.intelligence.cloud/terms/api) and by your
        agreement with Tresic or with your provider.
        
        This licence grants no right in any Tresic patent or patent application, trademark, or the
        Intelligence Cloud service, other than the right to use this software as provided. This licence ends
        when your right to access Intelligence Cloud ends.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
        WITHOUT LIMITATION THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
        NON-INFRINGEMENT. CREO SOLUTIONS, INC. D/B/A TRESIC IS NOT LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
        SOFTWARE OR ITS USE.
License-File: LICENSE
Classifier: License :: Other/Proprietary License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Description-Content-Type: text/markdown

# Intelligence Cloud Python SDK

Python client for the Intelligence Cloud partner API. It covers both jobs:

- **Customers** with an administrator login: the account layer (`client.accounts`) creates and maintains a customer on Base User and Base Manager licenses, beside one method per API operation (companies, locations, users, products, connectors, First Alert, Insights Hub).
- **Conversations** with a user login: the conversation layer (`client.conversations`) gives a signed-in person their own calls, tasks and alerts; `client.intelligence` reads calls, transcripts, recordings, alerts, tasks and insights; and the After Call and First Alert webhooks.

Version 0.2.0. Python 3.10 or later. One dependency: `httpx` (0.27 or later).

The API reference is at https://docs.intelligence.cloud/reference.html, built from https://docs.intelligence.cloud/openapi.yaml.

## Install

```bash
pip install intelligence-cloud          # or: uv add intelligence-cloud
```

The import name is `intelligence_cloud`.

Alternative, from the source download:

```bash
unzip python.zip && cd python
pip install .            # or: uv pip install .
```

To run the examples without installing: `uv run --with httpx --with-editable . python examples/whoami.py`.

## Credentials

Today every integration signs in with the email and password of a **dedicated integration user**. Turn MFA off for that user's company (`mfa_off=True` in `create_customer`, or `PATCH /companies/{id}` with `mfa_enforced: false`). **API keys arrive in December 2026.**

Use one client per credential:

| Credential | Role | Use it for |
|---|---|---|
| Admin | `reseller_admin` | `client.accounts`, `client.companies`, `client.users`, ... |
| Frontline | `frontline_user` | `client.conversations` and `client.intelligence` (calls, alerts, tasks, insights) |

Admin logins get empty lists from the conversation-data endpoints by design. `client.intelligence` checks the role once and raises `FrontlineRequiredError` instead of returning empty data. `client.conversations` raises `WrongLoginError` for an administrator login, and `client.accounts` raises it for a user login.

Keep credentials out of source code. Read them from your secret store or environment. Send secrets to Tresic only through **security@tresic.cloud**, and report security issues there too.

```python
import os
from intelligence_cloud import Client

admin = Client(email=os.environ["IC_ADMIN_EMAIL"], password=os.environ["IC_ADMIN_PASSWORD"])
data = Client(email=os.environ["IC_DATA_EMAIL"], password=os.environ["IC_DATA_PASSWORD"])
```

`Client(base_url="https://app.intelligence.cloud/api/v1", email, password, token_store=None, timeout=30)`; also `user_agent=` (prefixed to the SDK's own), `max_retries=3`, `login_rate_limit_wait=60` (seconds; `0` raises `RateLimitError` at once, better inside a web request) and `keep_unknown_fields=False` (see "Rules the SDK applies for you"), `mask_numbers=True` and `app_url="https://app.intelligence.cloud"` (see "Conversation layer"). `base_url` must be `https://` (`http://` only for `localhost`). If you pass your own `transport=`, keep certificate verification on.

### Sign-in, tokens and sign-out

- The client signs in on first use and keeps the access and refresh tokens in memory.
- Sign-in is limited to 5 per minute per IP. Sign in once per job and reuse the client. On a 429 at sign-in the client waits `login_rate_limit_wait` seconds (60) once.
- On a 401 the client renews the token once and retries. Refresh tokens are single-use: the new pair is stored before it is used and an old refresh token is never sent again. Renewal is serialised with a lock, so threads sharing a client renew once. A 429 on renewal is waited out and the same refresh token is sent again; it never turns into a sign-in.
- To keep tokens across runs, pass a `token_store` with `get()` and `set(tokens)`. Store tokens like passwords.
- **Several processes, one integration user** (workers, serverless, a cron job next to a web app): use one shared store that also has `lock()`, a context manager holding a lock across processes. The client signs in and renews inside it and re-reads the store first, so two processes never send the same refresh token (a replayed refresh token ends the session everywhere). `FileTokenStore(path)` does this for processes on one machine (file mode 0600, lock file beside it). Never create a client per request.
- `client.close()` closes connections. It does **not** sign out.
- `client.logout()` signs out and **ends every session of that user, including the web app**. The SDK never calls it by itself.
- Sign-in returning `mfa_required` raises `MfaRequiredError`: "Integration users need MFA off for their company. API keys arrive in December 2026."

## Account layer: `client.accounts` (admin)

A customer is one company with one or more **teams** (each a location in the API) and a **Management** location named `<Company> - Management`.

- Each team has a connector to the phone system, five groups (Customer Threats, Upset Customers, Low Sentiment Calls, Insights Hub Access, Insights Hub Weekly Reports) and three alerts, each routed to its group: Customer Threat (priority high, sentiment below -20 and its phrases), Upset Customer (medium, below -20 and its phrases) and Low Sentiment (low, below -40).
- Management has its own connector, which captures the managers' own lines, and the Insights Hub Weekly Reports group for the company-wide reports. It has no alerts.
- A **Base User** has After Call on their own line at one team. A **Base Manager** has all three products, their own line at Management, every Base User line of the teams they run, and those teams' groups.

```python
from intelligence_cloud import (AlertSetting, AlertSettings, Client, ConnectorSpec, CustomerSpec,
                                PersonSpec, TeamSpec)

admin = Client(email=..., password=...)
phone_system = ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2", "riverbend.example.com",
                                        api_key=phone_system_key)

customer = admin.accounts.create_customer(CustomerSpec(
    company_id=saved_company_id,              # None the first time; store customer.company_id and pass it on re-runs
    company_name="Riverbend Dental",
    admin=PersonSpec("pat.lee@example.com", "Pat", "Lee", phone_number="+15555550100"),
    team=TeamSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", state="IL",
                  country="US", zipcode="62701", vertical="<vertical id or key>"),
    connector=phone_system,                   # used for the team and for Management
    alerts=AlertSettings(customer_threat=AlertSetting(phrases=threat_phrases),
                         upset_customer=AlertSetting(phrases=upset_phrases)),
    mfa_off=True,                             # the company has an integration user
))
team = customer.teams[0]

admin.accounts.add_base_user(customer, PersonSpec("sam.ortiz@example.com", "Sam", "Ortiz"), team=team, line="2101")
admin.accounts.add_base_manager(customer, PersonSpec("dana.cho@example.com", "Dana", "Cho"),
                                teams=[team], line="2001")
admin.accounts.activate_alerts(customer)    # once each team has a manager in its alert groups
```

- **Phrase lists come from you.** The SDK holds none; ask your Tresic contact for them. A customer can be created without them: Low Sentiment and every group are created, `customer.pending` lists `"customer_threat"` and `"upset_customer"`, and `set_alerts` creates those alerts when the lists arrive.
- **Safe to re-run.** Every helper finds what exists before it writes; a second run with the same input writes nothing. A company is never adopted by its name alone: pass `company_id` from the first run. Without it, a same-named company is used only when its primary contact email is `admin.email`; otherwise `ConflictError` (code `company_name_conflict`) is raised before anything is written.
- **Stops are reported.** A helper that fails part-way raises `AccountError` with `.step`, `.result` (so far) and `.cause`. Run it again with the same input to continue; `change_license` and `move_user` also recognise a person they left part-way. A connector that does not become active stops `create_customer`, `add_team` and `set_connector` at the end, once everything else is built: `.step` is `"connectors"` and `.cause` is `ConnectorTimeoutError` or `ConnectorError` (with `state_reason`).
- **Existing people keep their license.** `add_base_user`, `add_base_manager` and `add_integration_user` refuse (`InvalidRequestError`, before any write) a person already set up with another license; use `change_license`.
- **Alerts start switched off.** `activate_alerts` switches them on for every team. A team does not need a manager: its alerts then show in the app only, and the result lists it.
- **Alert email is off** for every person the helpers create, managers included. People switch it on in their own settings.
- **Insights Hub "monitor all numbers" stays off.** The helpers never switch it on and switch it off where they find it on.
- **Invitations go last.** People are created without one; it is emailed once their products, groups and lines are in place (`invite=False` holds it back; `send_invitations` sends it later).
- **Connectors.** `ConnectorSpec(type, config, name=None, timeout=600)` takes the phone platform as the API names it and that platform's own settings; `ConnectorSpec.netsapiens(api_url, domain, api_key)` is the shortcut for the documented one. Give the key in full each time: it is sent when a connector is created or repaired and is never kept, logged or shown when the object is printed (any setting whose name contains key, secret, token, password, pwd, credential or auth is hidden, at any depth). A new connector is checked every 10 seconds until it settles; its status is recorded on the team (`connector_status`, `connector_state_reason`). A re-run with a corrected key repairs a connector in `error`; it never creates a second one.

| Helper | Does | Returns |
|---|---|---|
| `create_customer(spec)` | Company with all three products, SSO domain claim (optional), first team and Management, connector on each (if given), groups, alerts (switched off), Insights Hub | `Customer` |
| `get_customer(company_id)` | Reads the layout back; a layout it does not recognise is listed in `pending` | `Customer` |
| `add_team(customer, team, connector, *, alerts=None)` | A further team with its connector, groups, alerts (copying the first team's phrases and levels unless `alerts` sets them) and Insights Hub | `Team` |
| `set_alerts(customer, alerts, *, team=None)` | Phrases and sentiment levels on one team or all; `None` keeps what is there; alerts keep their on or off state | rule ids changed |
| `set_connector(customer, connector, *, team=None)` | Attaches a phone system to the named team, or the first team and Management; refuses where an active one exists | `list[Team]` |
| `add_base_user(customer, person, *, team, line, invite=True)` | After Call, their line on the team's connector, First Alert and Insights Hub lists and the team's managers | `Member` |
| `add_base_manager(customer, person, *, teams, line=None, company_reports=False, invite=True)` | All three products on each team and Management, own line at Management, the teams' lines and groups; `company_reports=True` adds the company-wide reports group | `Member` |
| `add_integration_user(customer, person)` | A data-reading user across every team: password sign-in, tagged `department: "integration"`, every line | `Member` |
| `change_license(customer, user_id, to, *, teams=None, line=None)` | `"base_manager"` or `"base_user"`, moving their own line between the team and Management | `Member` |
| `move_user(customer, user_id, *, from_team, to_team)` | Moves a Base User's membership and line, or swaps one of a manager's teams; call history stays with the old team | `Member` |
| `change_line(customer, user_id, old, new)` | A Base User's line: their mapping and the team's lists (a line another Base User still holds stays listed). A manager's own line at Management only | `Member` |
| `remove_user(customer, user_id, *, keep_lines=False)` | Clears groups and lines, then deactivates; `notes` names teams left with no manager in an alert group (alerts are not changed) | summary |
| `activate_alerts(customer, *, team=None)` | Switches alerts on for every team. Returns a dict: `switched_on` (rule ids) and `no_manager` (teams whose alert groups have no manager, so their alerts show in the app only) | `{"switched_on", "no_manager"}` |
| `send_invitations(customer, *, user_ids=None)` | Sends invitations not yet sent or expired; re-sends to `user_ids` | user ids |
| `list_members(customer, *, license=None, team=None)` | Everyone, with license (`base_user`, `base_manager`, `integration`, `other`), teams and lines | `list[Member]` |
| `license_report(customer)` | People by license and the number of teams (Management not counted) | counts and members |
| `sync_lines(customer, *, dry_run=False)` | Makes every line list match the people. Someone with After Call and one line who reads back as `other` keeps their line and is listed under `other` | changes |
| `offboard_customer(customer, *, deactivate_company=True)` | Pauses webhooks, stops every connector, deactivates integration users and the company | summary |

Every helper that takes `customer` also takes a company id. `team` is a `Team`, its location id or its name. Lines need an **active** connector: a refused mapping raises `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only: a clash raises `ConflictError` with the message "Extension is already monitored at another location."

## Conversation layer: `client.conversations` (user login)

Sign in as the person. The platform decides what each call returns: a Base User gets their own calls, a Base Manager their teams'.

```python
me = Client(email=..., password=...)

for brief in me.conversations.calls():               # today, newest first
    print(brief)                                     # CallBrief(id=..., when=...): no content
history = me.conversations.caller_history("5555550142", limit=5)
detail = me.conversations.brief(call_id)             # summary, key points, tasks, sentiment, topics, alerts
tasks = me.conversations.open_tasks()
board = me.conversations.team_view(team_id)          # for a manager: counts, alerts, open tasks, briefs
```

| Helper | Returns | Limits |
|---|---|---|
| `me()`, `teams()` | Who is signed in and the teams they can see. `me().lines` is `None`: the API gives a user login no way to read its own lines | |
| `calls(*, day=None, since=None, until=None, team=None, number=None, search=None, limit=50)` | `list[CallBrief]`, newest first; default today | window at most 31 days, `limit` at most 200 |
| `brief(call_id)` | One `CallBrief` with key points, tasks, topics and the alerts it raised (read from one page of that day's alerts, so a day with more than 100 alerts can miss some) | no transcript, no recording |
| `transcript(call_id)` | The transcript of one call | one call per request |
| `recording_link(call_id)` | A `RecordingLink` that expires; the SDK never downloads the audio | |
| `caller_history(number, *, limit=10)` | Recent briefs for one caller (last 31 days) | `limit` at most 50 |
| `open_tasks(*, due=None, team=None)` | Open tasks with the id of the call each came from | up to 200 |
| `alerts(*, since=None, until=None, team=None, limit=50)` | `list[AlertBrief]` on this person's teams. `status=` raises `InvalidRequestError` and `holder` is `None`: the API has no alert status or holder yet | as `calls` |
| `alert(alert_id)` | One alert with its call brief | |
| `team_view(team, *, day=None, since=None, until=None)` | Counts, alerts, open tasks and briefs for one team | as `calls` |
| `topics(*, since=None, until=None, team=None)` | Topic volumes and rising topics (default last 7 days) | needs Insights Hub access |
| `reference(call_or_alert)` | The id and its page in the app, to pass to another system in place of content | |
| `parse_first_alert_event(payload)` | A `FirstAlertEvent` | |

- **Caller numbers are masked** to their last four digits (`***0142`) unless the client was created with `mask_numbers=False`, also where a number appears in a name. Extensions are shown as they are.
- **Links**: `CallBrief.link`, `AlertBrief.link` and `reference()` give the page in the app, `<app>/after-call-copilot/calls/<id>` or `<app>/first-alert-copilot/alerts/<id>`; they carry only the id.
- `<app>` is `https://app.intelligence.cloud` unless you pass your own address: `Client(app_url="https://...")`.
- **Limits are checked before any request**: a longer window, a larger limit, `number` with `search`, or a date without a time zone raises `InvalidRequestError`. "Today" and `day=` are midnight to midnight in this machine's time zone, daylight saving included.
- **Nothing is logged.** Printing a brief shows its id and time only. Keep summaries, names and numbers out of your own logs too.
- An administrator login raises `WrongLoginError`. There is no helper that walks every call; for a bounded daily job use `client.intelligence.iter_calls`.

## Quick start: conversation intelligence (frontline)

```python
from datetime import datetime, timedelta, timezone
from intelligence_cloud import Client

data = Client(email=..., password=...)
since = datetime.now(timezone.utc) - timedelta(days=1)

for call in data.intelligence.iter_calls(date_from=since, sentiment="negative"):
    detail = data.intelligence.get_call(call["id"])
    transcript = data.intelligence.get_transcript(call["id"])

for alert in data.intelligence.iter_alerts(alert_name="Upset Customer", date_from=since):
    print(alert["id"], alert["call_id"])
```

- `phone` and `text` both search the one search field (names, numbers, summary and transcript text). Pass one or the other.
- Without `date_from`, calls and alerts start at 00:00 UTC seven days ago.
- Dates accept time-zone-aware `datetime` objects or full RFC 3339 strings and are sent in UTC. A date alone (`2026-11-01`) and a `datetime` without a time zone are refused: use `2026-11-01T00:00:00Z` or `datetime.now(timezone.utc)`.
- `alert_name` is the exact, case-sensitive rule name.
- Calls and alerts as they happen arrive on the After Call and First Alert [webhooks](#webhooks). Don't poll the API for new data: read it when a person asks for something or when a webhook tells you to fetch details, and run scheduled jobs (exports, digests) at most once a day over a bounded date window.

### Recordings

```python
link = data.intelligence.get_recording_url(call_id)
if link:
    audio = httpx.get(link.url)   # WAV; no Authorization header; Range requests work
```

The link is signed and valid for 120 minutes (`link.expires_at`). Anyone with the link can download the audio: treat it as a secret, never log it, and fetch a new one when it expires. Returns `None` when the call has no recording.

## Method list

Every API operation is a method named after its `operationId` in snake case, grouped by reference section. Path ids are positional; filters are keyword arguments; request bodies are a `dict` with the field names from the reference.

- List methods return a `Page` (`items`, `next_cursor`, `has_more`, `total`, `raw`). `items` holds the records with the `type`/`attributes` wrapper removed.
- Each list method has an `iter_*` twin that follows cursors 100 at a time.
- Single reads and writes return the response body as documented (`intelligence_cloud.unwrap(body)` returns the record inside).

| Namespace | Methods |
|---|---|
| `client.resellers` | `get_reseller_branding`, `update_reseller_branding`, `get_reseller_smtp_settings`, `save_reseller_smtp_settings`, `delete_reseller_smtp_settings` |
| `client.companies` | `list_companies` / `iter_companies`, `create_company`, `get_companies_mfa_summary`, `get_company`, `update_company`, `deactivate_company`, `reactivate_company`, `get_company_branding`, `update_company_branding`; helpers `add_products`, `remove_products`, `find_company`, `find_companies` |
| `client.sso` | `list_company_domains`, `claim_company_domain`, `remove_company_domain`, `list_domain_verifications`, `verify_domain`, `get_identity_provider`, `connect_identity_provider`, `disconnect_identity_provider`, `test_identity_provider` |
| `client.products` | `list_products`, `list_company_products`, `list_user_products`, `enable_user_product`, `disable_user_product` |
| `client.locations` | `list_verticals`, `list_company_locations` / `iter_company_locations`, `create_location`, `get_location`, `update_location`, `deactivate_location`, `reactivate_location`; helpers `add_products`, `remove_products`, `find_location` |
| `client.groups` | `list_user_groups` / `iter_user_groups`, `create_user_group`, `get_user_group`, `update_user_group`, `delete_user_group`, `get_user_group_membership`, `set_user_group_membership`; helpers `add_members`, `remove_members`, `add_user_to_groups`, `remove_user_from_groups`, `user_group_ids`, `find_group` |
| `client.connectors` | `list_connector_types`, `test_connector`, `list_location_connectors` / `iter_location_connectors`, `create_connector`, `get_connector`, `update_connector`, `deactivate_connector`, `reactivate_connector`, `list_company_connectors` / `iter_company_connectors`; helpers `wait_for_status`, `find_connector` |
| `client.first_alert` | `list_alert_rules` / `iter_alert_rules`, `create_alert_rule`, `get_alert_rule`, `update_alert_rule`, `delete_alert_rule`, `duplicate_alert_rule`, `get_first_alert_config`, `save_first_alert_config`, `test_first_alert_webhook`, `get_alert_notification_preferences`, `set_alert_email_preferences`, `set_alert_digest_preferences`; helpers `add_monitored_numbers`, `remove_monitored_numbers`, `set_monitored_numbers`, `add_rule_groups`, `remove_rule_groups`, `find_rule` |
| `client.insights_hub` | `get_insights_hub_setup`, `save_insights_hub_setup`, `update_insights_hub_setup`, `get_insights_hub_config`, `update_insights_hub_config`, `get_user_insights_hub_access`; helpers `add_numbers`, `remove_numbers`, `set_numbers`, `add_groups`, `remove_groups` |
| `client.users` | `list_company_users` / `iter_company_users`, `create_company_user`, `get_company_user`, `update_company_user`, `deactivate_company_user`, `reactivate_company_user`, `resend_invitation`, `reset_password`, `get_user_number_mappings`, `set_user_number_mappings`, `list_location_users` / `iter_location_users`, `get_location_user`; helpers `find_user_by_email`, `add_locations`, `remove_locations`, `user_numbers`, `add_numbers`, `remove_numbers`, `set_numbers` |
| `client.after_call_settings` | `get_user_after_call_settings`, `update_user_after_call_settings` |
| `client.account` | `get_me`, `list_visible_locations` / `iter_visible_locations` |
| `client.calls` | `list_calls` / `iter_calls`, `get_call`, `get_call_transcript` |
| `client.alerts` | `list_alerts` / `iter_alerts`, `get_alerts_dashboard` |
| `client.tasks` | `list_tasks` / `iter_tasks` |
| `client.insights` | `get_insights_dashboard`, `list_topic_calls` / `iter_topic_calls` |
| `client.webhooks` | `get_after_call_webhook`, `save_after_call_webhook`, `test_after_call_webhook` |
| `client.intelligence` | `whoami`, `require_frontline`, `search_calls` / `iter_calls`, `get_call`, `get_transcript`, `get_recording_url`, `search_alerts` / `iter_alerts`, `get_alert(alert_id, with_call=False)`, `get_alerts_dashboard`, `list_tasks` / `iter_tasks`, `get_insights_dashboard`, `list_topic_calls` / `iter_topic_calls`, `get_after_call_webhook`, `set_after_call_webhook`, `test_after_call_webhook`, `get_first_alert_webhook`, `set_first_alert_webhook`, `test_first_alert_webhook` |
| `client.accounts` | see "Account layer" |
| `client.conversations` | see "Conversation layer" |
| `client` | `login`, `logout`, `close` |

Module level: `parse_after_call_event`, `parse_first_alert_event`, `UnknownEvent`, `MAX_EVENT_BYTES`, `mask_number`, `Deduplicator`, `FileTokenStore`, `unwrap`, `Page`, the error classes and the spec dataclasses.

### Rules the SDK applies for you

- **Filters:** list methods accept only the filters the API supports. The API ignores unknown parameters silently, so the SDK refuses them before sending (`TypeError` for an unknown keyword, `InvalidRequestError` for a bad value). Enums are checked; `numbers` takes up to 25 entries and strips `+`, `-`, spaces and brackets, and sends a North American number as its last 10 digits (`+1 555-555-0142` becomes `5555550142`, which also matches records stored without the 1); `location_id` lists take up to 50 ids.
- **Full-replacement writes** (group members, a user's groups, number mappings, First Alert monitored numbers, Insights Hub numbers and groups, company and location products, rule groups) have `add_*` / `remove_*` helpers that read, merge and write. The First Alert helpers always resend the webhook URL so it is not cleared.
- **User create** always sends an `Idempotency-Key` (reused on retries). If the create returns 422 but left the user behind, the SDK finds the user by email and applies `location_ids`.
- **Connectors:** `create_connector`, `reactivate_connector` and `deactivate_connector` wait for the final status, checking every 10 seconds for up to 10 minutes (`timeout=` in seconds; `wait=False` to return at once). An `error` raises `ConnectorError` with `state_reason`; no final status in time raises `ConnectorTimeoutError`.
- **Responses** carry only the fields in the published reference. Anything else is dropped. With `Client(keep_unknown_fields=True)` new fields the reference does not list yet are kept on the customer-lifecycle (admin) reads; `get_me`, sign-in and every conversation-data read (calls, transcripts, alerts, tasks, insights) always keep only the documented fields. Either way, the one-time sign-in link a user create can return is never passed through or logged.
- **Test endpoints** (connector dry run, webhook tests) report only success and the HTTP status.
- **Retries:** 429 and 5xx are retried up to 3 times with backoff and jitter, honouring `Retry-After` up to 60 seconds. A longer `Retry-After` is not waited out: `RateLimitError` is raised at once with `.retry_after`. 5xx is retried only for reads, updates, deletes and user create, never for other creates.

## Error handling

```python
from intelligence_cloud import ApiError, NotFoundError, ConflictError, ValidationError

try:
    admin.companies.get_company(company_id)
except NotFoundError:
    ...  # also returned for records outside this login's scope
except ApiError as e:
    log.warning("Intelligence Cloud error %s %s request_id=%s", e.status, e.code, e.request_id)
```

Log `status`, `code` and `request_id`, not exception text or response bodies. `str(error)` carries only the status, code and request id, plus text the SDK wrote itself (such as "Extension is already monitored at another location."). The server's own text is on `e.message`: it can echo numbers or names from the request, so keep it out of logs.

| Error | When |
|---|---|
| `ApiError` | Any API error: `status`, `code`, `message`, `request_id` |
| `NetworkError` | The request did not complete (no connection, a timeout, an unreadable response): `status` 0, `code` `network_error` or `timeout`, `kind`. The HTTP library's own error is not attached, because it holds the request |
| `AuthError` (401), `PasswordExpiredError` | Sign-in failed, or the token could not be renewed |
| `NotFoundError` (404) | Not found, or outside what this login can see |
| `ConflictError` (409) | Duplicate name or email, already active or inactive, extension already monitored (`.extensions`) |
| `ValidationError` (400, 422) | Malformed request or refused value |
| `RateLimitError` (429) | Still rate limited after retries (`.retry_after`) |
| `InvalidRequestError` | Bad input, refused by the SDK before sending |
| `MfaRequiredError` | The integration user's company has MFA on |
| `FrontlineRequiredError` | `client.intelligence` conversation data asked for with an admin login |
| `WrongLoginError` | An account helper with a user login, or a conversation helper with an administrator login; the message says which login to use |
| `AccountError` | An account helper stopped part-way (`.step`, `.result`, `.cause`); run it again to continue |
| `ConnectorError`, `ConnectorTimeoutError` | A connector ended in `error`, or a new connector did not settle in time |
| `ExtensionMappingError` | A helper could not map numbers (`.user_id`, `.cause`); the `.cause` of an `AccountError` |
| `WebhookPayloadError` | A webhook body is not JSON, or is a malformed After Call or First Alert event (answer 400) |
| `PayloadTooLargeError` | A webhook body is over `max_bytes` (256 KB; answer 413) |

All derive from `IntelligenceCloudError`.

## Webhooks

Webhooks are how your integration hears about new calls and alerts: the After Call webhook for every call, the First Alert webhook for each alert as it fires. Subscribe to them; don't poll the API for new data.

### Configure (admin)

```python
admin.intelligence.set_after_call_webhook(location_id, f"https://hooks.example.com/ic/after-call/{path_token}")
admin.intelligence.test_after_call_webhook(location_id)      # WebhookTestResult(success, http_status)

admin.intelligence.set_first_alert_webhook(location_id, f"https://hooks.example.com/ic/alerts/{alert_path_token}")
admin.intelligence.test_first_alert_webhook(location_id)
```

- The After Call webhook sends **every call at the location**. One URL per location. Pause it with `enabled=False`; there is no delete.
- The First Alert location webhook is set in the location's First Alert configuration. `set_first_alert_webhook` keeps the monitored numbers.

### Receive

- Use HTTPS and put a token of at least 32 random characters in the path, one per location, read from your secret store: `python -c "import secrets; print(secrets.token_urlsafe(32))"`. Compare it in constant time (`hmac.compare_digest` on bytes). Requests are not signed: treat the URL as a secret and keep it out of proxy, load balancer and APM logs.
- Answer 2xx within 2 seconds and do the work afterwards. Redirects count as failures. Delivery is tried 3 times, then dropped.
- `parse_after_call_event` refuses bodies over 256 KB (`PayloadTooLargeError`: answer 413) and returns `UnknownEvent` for event types it doesn't handle: answer 2xx and ignore them. Answer 400 only for a body that isn't JSON or a malformed After Call event, and 404 for a wrong token.
- Treat an event as a notification. Before you write anything from it into another system, read the call with `get_call(event.call.id)` using your frontline integration user; a `NotFoundError` means drop the event.
- Expect repeats of the same `call.id` (retries, and calls with several legs); a later one can carry newer data. Store events durably before acknowledging, and upsert on `call.id`.
- To test locally, post the sample event: `curl -X POST http://localhost:8080/ic/after-call/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`, or run `python examples/webhook_receiver.py --self-test`.

FastAPI:

```python
import hmac
import os

from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
from intelligence_cloud import (AfterCallEvent, Deduplicator, PayloadTooLargeError, WebhookPayloadError,
                                parse_after_call_event)

app = FastAPI()
dedup = Deduplicator()
PATH_TOKEN = os.environ["IC_WEBHOOK_TOKEN"]  # from your secret store
if len(PATH_TOKEN) < 32:
    raise SystemExit("IC_WEBHOOK_TOKEN must be at least 32 characters")

@app.post("/ic/after-call/{token}")
async def after_call(token: str, request: Request, background: BackgroundTasks):
    if not hmac.compare_digest(token.encode(), PATH_TOKEN.encode()):
        raise HTTPException(status_code=404)
    try:
        event = parse_after_call_event(await request.body())
    except PayloadTooLargeError:
        raise HTTPException(status_code=413)
    except WebhookPayloadError:
        raise HTTPException(status_code=400)
    if isinstance(event, AfterCallEvent) and not event.is_test and not dedup.is_duplicate(event):
        background.add_task(handle, event.call.id)   # read the call with get_call, then upsert on its id
    return {"ok": True}
```

Flask:

```python
import hmac

from flask import Flask, abort, request
from intelligence_cloud import AfterCallEvent, PayloadTooLargeError, WebhookPayloadError, parse_after_call_event

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 262_144

@app.post("/ic/after-call/<token>")
def after_call(token):
    if not hmac.compare_digest(token.encode(), PATH_TOKEN.encode()):
        abort(404)
    try:
        event = parse_after_call_event(request.get_data())
    except PayloadTooLargeError:
        abort(413)
    except WebhookPayloadError:
        abort(400)
    if isinstance(event, AfterCallEvent) and not event.is_test:
        durable_queue.put_once(event.call.id)   # a persistent queue keyed on call.id; process outside the request
    return {"ok": True}
```

`Deduplicator.is_duplicate(...)` returns True for a repeat (the same name and meaning in all three SDKs: `isDuplicate` in PHP and TypeScript). It keeps the last 10,000 call ids in memory. With several workers, pass a shared `store` whose `add(key)` returns True only for a new key (for example a shared cache's set-if-absent with an expiry). Use it to skip repeat work, not to drop updates: when you keep a copy of the call, upsert on `call.id`.

### Receive First Alert

The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. `parse_first_alert_event` returns a `FirstAlertEvent` (`alert_id`, and `rule`, `location_id`, `call_id`, `timestamp` when the delivery carries them). Take the alert id, answer 2xx at once, then fetch the alert and its call with a frontline integration user in every alert group:

```python
@app.post("/ic/alerts/{token}")
async def first_alert(token: str, request: Request, background: BackgroundTasks):
    if not hmac.compare_digest(token.encode(), ALERT_TOKEN.encode()):   # IC_ALERT_WEBHOOK_TOKEN, 32+ characters
        raise HTTPException(status_code=404)
    try:
        alert_id = parse_first_alert_event(await request.body()).alert_id
    except PayloadTooLargeError:
        raise HTTPException(status_code=413)
    except WebhookPayloadError:
        raise HTTPException(status_code=400)
    if not alert_dedup.is_duplicate(alert_id):          # a second Deduplicator, keyed on the alert id
        background.add_task(handle_alert, alert_id)
    return {"ok": True}

def handle_alert(alert_id: str):
    alert = data.intelligence.get_alert(alert_id, with_call=True)   # None when this login can't see it
    if alert:
        page_on_call_manager(alert["id"], alert["call_id"])          # ids only; never log the summary
```

If your receiver was unavailable, read the window you missed once and skip alerts you have already handled:

```python
for alert in data.intelligence.iter_alerts(date_from=went_down - timedelta(minutes=30), date_to=came_back):
    if not alert_dedup.is_duplicate(alert["id"]):
        handle_alert(alert["id"])
```

Alerts are dated by their call, so start the window 30 minutes before the receiver went down.

## Examples

| File | Shows | Credential |
|---|---|---|
| `examples/whoami.py` | Sign in and print the role | any |
| `examples/export_calls.py` | Export yesterday's calls to CSV (ids, dates, sentiment, duration) | frontline |
| `examples/create_customer.py` | Create a customer, add a Base User and a Base Manager, switch the alerts on (dry run unless `--apply`; phrase lists from the files in `IC_THREAT_PHRASES_FILE` and `IC_UPSET_PHRASES_FILE`, optional) | admin |
| `examples/my_day.py` | A person's day: today's call briefs, open tasks and alerts, with masked numbers and no content in logs | frontline (the person's own login) |
| `examples/webhook_receiver.py` | A dependency-free After Call webhook receiver: 256 KB cap, a persistent queue keyed on `call.id`, a worker that reads each call (`--self-test` to try it offline) | frontline (worker) |
| `examples/after-call-sample.json` | A sample After Call event for local tests | none |
| `examples/alert_webhook_receiver.py` | A dependency-free First Alert webhook receiver that fetches each alert and its call (`--self-test` to try it offline) | frontline |

The admin examples read `IC_ADMIN_EMAIL` and `IC_ADMIN_PASSWORD`; the frontline examples read `IC_DATA_EMAIL` and `IC_DATA_PASSWORD`. `whoami.py` uses whichever pair is set.

## Regenerating from the spec

`src/intelligence_cloud/_generated.py` and `data/spec.json` are generated from `openapi.yaml` (download it from https://docs.intelligence.cloud/openapi.yaml):

```bash
uv run --with pyyaml python tools/generate.py openapi.yaml          # rewrite both files
uv run --with pyyaml python tools/generate.py openapi.yaml --check  # exit 1 if either is out of date
```

## License

Intelligence Cloud SDK Licence. Copyright (c) 2026 Creo Solutions, Inc. d/b/a Tresic. Partners, their customers and contractors working for either may use, copy, modify and distribute the SDK solely to access Intelligence Cloud. Use of the API is governed by the Intelligence Cloud API and SDK Terms (https://docs.intelligence.cloud/terms/api) and your agreement with Tresic or your provider. Provided as is. See `LICENSE`.
