diff --git a/.github/workflows/typescript-ci.yml b/.github/workflows/typescript-ci.yml index 897d392..24bf656 100644 --- a/.github/workflows/typescript-ci.yml +++ b/.github/workflows/typescript-ci.yml @@ -3,6 +3,7 @@ name: TypeScript SDK CI on: pull_request: paths: + - 'README.md' - 'typescript/**' - 'openapi/**' - 'scripts/**' @@ -17,6 +18,7 @@ on: push: branches: [main] paths: + - 'README.md' - 'typescript/**' - 'openapi/**' - 'scripts/**' diff --git a/README.md b/README.md index c1dd9f5..d536387 100644 --- a/README.md +++ b/README.md @@ -1,373 +1,90 @@ -# @zelinqa/sdk +# Zelinqa TypeScript SDK -Official TypeScript client for the [Zelinqa Engine](https://docs.zelinqa.ai) -V1 public API (`https://api.zelinqa.ai`). A [Python client](https://github.com/Zelinqa/zelinqa-sdk/blob/main/python/README.md) -is also available as `zelinqa`. +The official TypeScript client for Zelinqa. Configure a domain in +[Zelinqa Studio](https://client.zelinqa.ai), publish it, and let the API select +the next useful question for each conversation. -Zelinqa Engine keeps the canonical state of a conversation server-side and answers -one question: given what this conversation already told you, what should be -asked next? You configure objectives and a question bank in Zelinqa Studio, publish -an immutable version, and the API selects the next question from the session -state. +Node.js 22+ · ESM and CommonJS · Typed responses · No runtime dependencies -The SDK follows the versioned V1 contract. Field names on the wire are -`snake_case`. +## Install ```bash -pnpm add @zelinqa/sdk +npm install @zelinqa/sdk ``` -```ts -import { ZelinqaClient } from "@zelinqa/sdk"; - -const client = new ZelinqaClient({ apiKey: process.env.ZELINQA_API_KEY ?? "" }); -const conversation = await client.startSession({ client_reference: "demo-001" }); -let proposal = await conversation.next(); -// Ask proposal.candidates[0].text, then pass the visitor's answer: -proposal = await conversation.answer({ userText: "We need to qualify inbound requests" }); -``` +## Set your API key -The handle tracks the session and decision identifiers. See the -[TypeScript guide](https://github.com/Zelinqa/zelinqa-sdk/blob/main/typescript/README.md) -for choice answers, configuration, errors and retries. - -## SDKs - -| | Python | TypeScript | -|---|---|---| -| Package | `zelinqa` | `@zelinqa/sdk` | -| Version | 1.0.0 | 1.0.0 | -| Runtime | Python 3.11+ | Node ≥ 22 | -| Dependencies | `httpx`, `pydantic` v2 | none | -| Guide | [Python guide](https://github.com/Zelinqa/zelinqa-sdk/blob/main/python/README.md) | [TypeScript guide](https://github.com/Zelinqa/zelinqa-sdk/blob/main/typescript/README.md) | +Create a runtime API key for your published domain in Studio and set it on +your backend: ```bash -uv add zelinqa # or: pip install zelinqa -pnpm add @zelinqa/sdk # or: npm install / yarn add +export ZELINQA_API_KEY="YOUR_RUNTIME_API_KEY" ``` -## Two clients, two keys - -A Zelinqa key carries scopes, and Studio recommends one key per job. Both SDKs are -split the same way. - -| Client | Scope | What it does | -|---|---|---| -| `ZelinqaClient` (+ `AsyncZelinqaClient` in Python) | `runtime` | sessions, next question, out-of-turn events, state, feedback | -| `ZelinqaConfigurationClient` (+ async) | `configuration:read` · `configuration:write` · `configuration:publish` | read the corpus, edit the draft, publish, follow the compilation, read the audit log | - -Scope rules worth knowing: +Keep API keys out of browser code, mobile apps, logs and source control. -- A `runtime` key cannot read configuration. -- **Reading a draft requires both `configuration:read` and - `configuration:write`**. A read-only key receives `insufficient_scope`. -- Reading the audit log requires `configuration:publish`. -- The domain and tenant are derived from the API key; clients do not send them. +## Get a question and send the reply -## Runtime flow - -### Without technical identifiers - -```python -from zelinqa import ZelinqaClient - -with ZelinqaClient() as client: # ZELINQA_API_KEY, runtime scope - conversation = client.start_session(client_reference="demo-001") - proposal = conversation.next() - # Ask proposal.candidates[0].text, then pass the real reply: - proposal = conversation.answer("We need to qualify inbound requests") - conversation.submit_feedback(result="partial", label="demo_finished") -``` +This small console example asks one question and submits the person's reply. +For choice questions, enter one of the displayed labels exactly. ```ts +import { createInterface } from "node:readline/promises"; +import { stdin, stdout } from "node:process"; import { ZelinqaClient } from "@zelinqa/sdk"; -const client = new ZelinqaClient({ apiKey: process.env.ZELINQA_API_KEY ?? "" }); -const conversation = await client.startSession({ client_reference: "demo-001" }); -let proposal = await conversation.next(); -// Ask the question, then pass the real reply: -proposal = await conversation.answer({ userText: "We need to qualify inbound requests" }); -await conversation.submitFeedback({ result: "partial", label: "demo_finished" }); -``` - -The handle supplies session, version, decision and question IDs. Use -`candidate_rank` / `candidateRank` for the candidate actually asked (default 1). -`choice_labels` / `choiceLabels` maps exact displayed labels to choice IDs; -unknown, duplicate or ambiguous labels are rejected locally. Semi-open questions -respect `selection_mode`. `free_text` / `freeText` supplements a selected choice; -for an unlisted answer use `user_text` / `userText` instead. - -Answer rules (validated locally by `answer()` before any network request): - -- **Open question:** send the person's actual words in `user_text` / `userText`. - Text is analyzed by the engine. An outcome alone is not an open answer. -- **Closed or semi-open question:** choices alone require no model call. - For semi-open questions, `free_text` / `freeText` may supplement a selected - choice. Additional text is analyzed by the engine. -- **No answer or refusal:** `outcome="asked_no_answer"` or `outcome="refused"` - is accepted without text for every question type and requires no model call. - -These no-model paths assume no other text is supplied for analysis and an -unambiguous question. Initial `next()` and context-only updates are unchanged. - -Call mutations sequentially per handle. Persist `conversation.id` in your backend, -not the LLM prompt, to call `resume_session` / `resumeSession` after restart. -The helpers add no HTTP call to `/next` and keep no transcript cache. Free text -is not automatically marked complete, and conflicts are never silently replayed. - - -The session handle (`start_session` / `startSession`) tracks `state_version` for -you. Conflicts are never hidden. - -### Python - -```python -from zelinqa import ZelinqaClient - -with ZelinqaClient() as client: # api_key from ZELINQA_API_KEY - session = client.start_session(client_reference="crm-lead-8842", max_turns=15) - - decision = session.next() # first turn, nothing asked yet - candidate = decision.candidates[0] - - # …your agent asks the question, possibly reworded, and gets an answer… - decision = session.next( - previous_turn={ - "assistant_text": candidate.text, - "user_text": "Un canapé contemporain pour le salon, nous avons un chat.", - } - ) - - # Data the CRM already knows: no need to ask for it. - state = session.apply_events(client_updates={"data": [{"id": "annual_budget", "value": 2500}]}) - print(state.targets["annual_budget"].status) # confirmed - - state = session.refresh() # GET, authoritative state - session.submit_feedback(result="success", label="achat", metadata={"order_id": "SO-99120"}) -``` - -### TypeScript - -```ts -import { ZelinqaClient } from "@zelinqa/sdk"; - -const client = new ZelinqaClient({ apiKey: process.env.ZELINQA_RUNTIME_KEY ?? "" }); -const session = await client.startSession({ - client_reference: "crm-lead-8842", - max_turns: 15, -}); +const client = new ZelinqaClient({ apiKey: process.env.ZELINQA_API_KEY ?? "" }); +const session = await client.startSession({ client_reference: "demo-001" }); let decision = await session.next(); -const candidate = decision.candidates[0]; - -if (candidate !== undefined) { - decision = await session.next({ - previous_turn: { - assistant_text: candidate.text, - user_text: "Un canapé contemporain pour le salon, nous avons un chat.", - }, - }); +const question = decision.candidates[0]; + +if (decision.action === "ask" && question !== undefined) { + console.log(question.text); + for (const choice of question.choices) { + console.log(`- ${choice.label}`); + } + + const input = createInterface({ input: stdin, output: stdout }); + try { + const reply = await input.question("> "); + if (!reply.trim()) { + decision = await session.answer({ outcome: "asked_no_answer" }); + } else if (question.choices.length > 0) { + decision = await session.answer({ choiceLabels: [reply] }); + } else { + decision = await session.answer({ userText: reply }); + } + console.log(decision.action, decision.warnings); + } finally { + input.close(); + } } - -const state = await session.applyEvents({ - client_updates: { data: [{ id: "annual_budget", operation: "set", value: 2500 }] }, -}); -console.log(state.targets.annual_budget?.status); // confirmed - -await session.refresh(); -await session.submitFeedback({ - result: "success", - label: "achat", - metadata: { order_id: "SO-99120" }, -}); -``` - -Both handles expose the session id, the tracked state version, the last full -state and the pending decision, plus `next`, `apply_events`/`applyEvents`, -`refresh` and `submit_feedback`/`submitFeedback`. `resume_session` / -`resumeSession` rebuilds a handle from an existing session — after a crash, -re-reading the session is enough, there is no resume token to keep. Call the -client methods directly (`create_session`, `next`, `apply_events`, -`get_session`, `submit_feedback`) when you persist `state_version` yourself. - -Zelinqa never decides for you: `action == "ask"` means candidates are available, -ranked, rank 1 first; `action == "stop"` only happens when no identifiable -question is left. A reached turn limit or an achieved objective is reported in -`warnings` while the best question is still proposed. `degraded` / -`degraded_reasons` say the turn was understood in reduced mode — typically no -verbatim was sent. - -## Configuration flow - -Draft edits are atomic; nothing goes live until a publication has compiled. -Compilation runs outside the HTTP request, so `publish` returns `202` with a -compilation id. - -```python -with ZelinqaConfigurationClient() as studio: - draft = studio.get_configuration(state="draft") # needs read + write - print(draft.domain.name) # current Studio name - applied = studio.apply_changes(changes, expected_draft_revision=draft.draft_revision) - queued = studio.publish(expected_draft_revision=applied.draft_revision) - status = studio.wait_for_compilation(queued.compilation_id, poll_interval=3, timeout=900) -``` - -```ts -const draft = await studio.getConfiguration({ state: "draft" }); -console.log(draft.domain.name); // current Studio name, not objective.name -const applied = await studio.applyChanges({ - changes, - expected_draft_revision: draft.draft_revision ?? undefined, -}); -const queued = await studio.publish({ expected_draft_revision: applied.draft_revision }); -const status = await studio.waitForCompilation(queued.compilation_id, { - pollIntervalMs: 3_000, - timeoutMs: 900_000, -}); ``` -`wait_for_compilation` / `waitForCompilation` returns the terminal status — -a failed compilation is an editorial outcome, so inspect `status.error` instead -of catching an exception. Only running out of time raises -`ZelinqaCompilationTimeoutError`. Other configuration methods: `list_questions` / -`listQuestions`, `iter_questions` / `iterateQuestions` (cursor pagination), -`export_questions_csv` / `exportQuestionsCsv`, `list_audit` / `listAudit`, -`get_compilation` / `getCompilation`. - -## Errors - -The SDK-specific error classes have the same names in both languages. Python SDK -exceptions derive from `ZelinqaError`; TypeScript may also throw native errors -for invalid local arguments, choice labels, or caller cancellation. -The envelope `code` decides the type first, then the HTTP status when the body -is not a V1 envelope. - -| Class | When | Notable attributes | -|---|---|---| -| `ZelinqaConnectionError` | network failure or per-attempt timeout, after retries | | -| `ZelinqaCompilationTimeoutError` | the compilation wait ran out of time | compilation id, timeout | -| `ZelinqaAPIError` | base of every HTTP failure | status code, `code`, message, request id, details, retry after | -| `ZelinqaAuthenticationError` | `401` (no `Authorization` header) **or** `403` without an envelope | status code | -| `ZelinqaInsufficientScopeError` | `403` `insufficient_scope` — the service's dynamic check | required / granted scopes | -| `ZelinqaNotFoundError` | `404`, specialised as `ZelinqaUnknownSessionError`, `ZelinqaUnknownConfigurationError`, `ZelinqaUnknownCompilationError` | | -| `ZelinqaConflictError` | `409`, specialised as `ZelinqaStateVersionConflictError`, `ZelinqaIdempotencyKeyReusedError`, `ZelinqaCompilationInProgressError` | supplied / current state version · idempotency key · compilation id and status | -| `ZelinqaCompiledArtifactUnavailableError` | `410` `compiled_artifact_unavailable` | | -| `ZelinqaValidationError` | `422`, specialised as `ZelinqaInvalidPreviousTurnError`, `ZelinqaConstraintNoMatchError`, `ZelinqaInvalidChoiceError`, `ZelinqaConfigurationValidationError` | grouped `issues` | -| `ZelinqaRateLimitError` | `429`, retried automatically first | retry after | -| `ZelinqaIdempotencyContentionError` | `503` `idempotency_contention`, retried first | retry after | -| `ZelinqaServerError` | any other `5xx` | | - -Gateway semantics matter here: a missing `Authorization` header is `401` -`{"message":"Unauthorized"}`, while an invalid, revoked or expired key **and** a -key missing a scope required for the route both return the -same opaque `403 {"message":"Forbidden"}`. The SDKs do not pretend to tell those -two apart — both become `ZelinqaAuthenticationError`; read the status code to -separate a missing header from a refused key. `ZelinqaInsufficientScopeError` is -reserved for the `403` that carries a real V1 envelope. - -`str(error)` / `String(error)` reads `": -(request_id=…)"`. Quote the request id when you contact Zelinqa support; it -never contains a key or conversation content. - -## Retries, idempotency and timeouts - -- Every mutation sends `Idempotency-Key`. Without one, the SDK generates a - UUID v4 **once per logical call and reuses it across that call's retries**, so - a retry can never double a turn, an outcome, a feedback or a publication. - Same key + same body replays the original response; same key + different body - raises `ZelinqaIdempotencyKeyReusedError`. Server-side records expire after 24 h. -- Retried, up to `max_retries` / `maxRetries` (default 2), with exponential - backoff 0.5 s, 1 s, 2 s … capped at 10 s and jittered: connection errors, - timeouts, `429`, `500`, `502`, `503`, `504`, and the `idempotency_contention` - envelope. `GET` requests too. -- Never retried: `400`, `401`, `403`, `404`, `409`, `410`, `422`. -- `Retry-After` (seconds or HTTP date) and `details.retry_after_seconds` win - over the backoff, clamped to 30 s. -- The timeout (default 30 s) applies **per attempt**, combined with any - cancellation token you pass (`signal` in TypeScript). - -## Environment variables - -The Python SDK reads the environment; **the TypeScript SDK never does** — -`apiKey` is required and explicit. - -| Variable | Used by | Default | -|---|---|---| -| `ZELINQA_API_KEY` | both Python clients | — | -| `ZELINQA_CONFIGURATION_API_KEY` | Python configuration client, before `ZELINQA_API_KEY` | — | -| `ZELINQA_BASE_URL` | both Python clients | `https://api.zelinqa.ai` | +The session handle supplies session, decision, question and choice IDs for you. +Each `answer()` records the reply and returns the next decision; do not call +`next()` again just to retrieve that question. Use a session sequentially and +store `session.id` in your backend if you need to resume after a restart. -## Security +Open questions need the person's actual words. Choices alone need no model +call; free text is analyzed by the engine. Report a real refusal with +`outcome: "refused"`, or an empty reply with `outcome: "asked_no_answer"`. +Keep warnings visible and let your application decide when to finish. -**These are server-side clients.** A Zelinqa key is a bearer credential restricted -to its configured domain and scopes. Never -embed one in a browser, a mobile app or any client you do not control — proxy -Zelinqa through your own service instead. - -- The key lives in the HTTP client and nowhere else. No exception, message, - `repr`, `toString`, log line or returned value contains it. -- Use separate keys per scope, least privilege. A runtime key must not publish. -- `initial_history` is consumed once in memory to build the initial state; it is - never persisted, never logged, never returned. -- Keep keys out of the repository: `.env*` and `*.local` are git-ignored. -- No selection score, semantic evidence, embedding, prompt or compiled matrix is - ever exposed by the API or the SDKs. - -## Repository - -```text -openapi/ frozen V1 contract snapshot (source of truth, read-only) -python/ Python client, tests, live suite -typescript/ TypeScript client, generated types, tests, live suite -scripts/ version consistency and codegen utilities -``` - -## Development - -### TypeScript - -```bash -corepack enable -pnpm install --frozen-lockfile -pnpm generate:types # regenerate typescript/src/generated from the contract -pnpm check # lint + typecheck + tests + version consistency -pnpm build # ESM, CommonJS and type declarations -``` - -### Python - -```bash -uv sync --group dev -uv run ruff check python/src python/tests -uv run mypy python/src -uv run pytest # live tests excluded by default -``` - -`pnpm check:versions` asserts that `pyproject.toml`, -`python/src/zelinqa/_version.py`, `package.json` and `typescript/src/version.ts` -agree. Run it before every release. - -### Live tests - -Both live suites are opt-in, hit real staging and are skipped by default. They -need `ZELINQA_LIVE=1` plus `ZELINQA_LIVE_RUNTIME_KEY`, `ZELINQA_LIVE_CONFIG_READ_KEY`, -`ZELINQA_LIVE_CONFIG_WRITE_KEY`, `ZELINQA_LIVE_CONFIG_PUBLISH_KEY`, -`ZELINQA_LIVE_CONFIG_MANAGE_KEY` (read + write + publish, for draft reads) and -`ZELINQA_LIVE_REVOKED_KEY`; `ZELINQA_LIVE_BASE_URL` defaults to -`https://api.zelinqa.ai`. - -```bash -ZELINQA_LIVE=1 uv run pytest -m live python/tests/live -ZELINQA_LIVE=1 pnpm test:live -``` +## What you can do -They upsert a throwaway corpus so re-runs work, log only request ids and error -codes, and space their model-backed calls to respect service limits. In CI they -run only from the manual `live-tests.yml` workflow (`workflow_dispatch`, secrets -from the `staging-live` environment), never on a pull request. +- Run conversations, resume sessions, add context and record business feedback. +- Read questions, edit drafts and publish with `ZelinqaConfigurationClient` + and the corresponding configuration scopes. +- Handle typed errors, configure timeouts and retries, and cancel requests. -## Changelog +## Learn more -See the [changelog](https://github.com/Zelinqa/zelinqa-sdk/blob/main/CHANGELOG.md) for release history. +- [Documentation and API reference](https://docs.zelinqa.ai) +- [TypeScript guide: choices, configuration, errors and compiler setup](https://github.com/Zelinqa/zelinqa-sdk/blob/main/typescript/docs/usage.md) +- [Python SDK](https://github.com/Zelinqa/zelinqa-sdk/blob/main/python/README.md) — `pip install zelinqa` +- [Changelog](https://github.com/Zelinqa/zelinqa-sdk/blob/main/CHANGELOG.md) +- [Report an issue](https://github.com/Zelinqa/zelinqa-sdk/issues) ## License diff --git a/python/README.md b/python/README.md index 6795712..bd4db74 100644 --- a/python/README.md +++ b/python/README.md @@ -1,427 +1,81 @@ -# `zelinqa` — Python SDK for the Zelinqa Engine API V1 +# Zelinqa Python SDK -Official Python client for [Zelinqa Engine](https://docs.zelinqa.ai), the Zelinqa -conversational qualification platform. Zelinqa keeps the canonical state of a -conversation server-side and answers one question: given what this conversation -already told you, what should be asked next? +The official Python client for Zelinqa. Configure a domain in +[Zelinqa Studio](https://client.zelinqa.ai), publish it, and let the API select +the next useful question for each conversation. -The SDK follows `openapi/nbq-v1.openapi.yaml`, the frozen V1 contract. Field -names on the wire are `snake_case`, exactly as in the contract. +Python 3.11+ · Sync and async clients · Typed responses -- Python 3.11+ -- Sync and async clients, `httpx` transport, `pydantic` v2 models -- Fully typed (`py.typed`), strict `mypy` +## Install ```bash -uv add zelinqa # or: pip install zelinqa +pip install zelinqa ``` -## Two clients, two keys +## Set your API key -Use `session.answer("the actual reply")` after `session.next()` to avoid copying -technical IDs. Choices use `session.answer(choice_labels=["Exact label"])`. +Create a runtime API key for your published domain in Studio and set it on +your backend: -Open questions require the person's actual `user_text`; the engine analyzes -that text. Closed and semi-open questions accept choices alone without a model -call. Semi-open choices may include `free_text`, which is analyzed. An explicit -`outcome="asked_no_answer"` or `outcome="refused"` needs no text or model call -for any type. These no-model paths assume no other text needs analysis. -`answer()` rejects an open answer without text locally, before any HTTP request. -Async handles offer the same methods with `await`. Persist the session ID in -your backend to resume after a restart; use one handle sequentially. - - -A Zelinqa key carries scopes. Studio recommends one key per job, so the SDK is -split the same way. - -| Client | Scope | What it does | -|---|---|---| -| `ZelinqaClient` / `AsyncZelinqaClient` | `runtime` | drives conversations: sessions, next question, events, feedback | -| `ZelinqaConfigurationClient` / `AsyncZelinqaConfigurationClient` | `configuration:read`, `configuration:write`, `configuration:publish` | reads the question bank, edits the draft, publishes it | - -```python -from zelinqa import ZelinqaClient, ZelinqaConfigurationClient - -runtime = ZelinqaClient("YOUR_RUNTIME_KEY") # scope runtime -studio = ZelinqaConfigurationClient("YOUR_CONFIG_KEY") # management scopes -``` - -### Environment variables - -| Variable | Used by | Default | -|---|---|---| -| `ZELINQA_API_KEY` | both clients | — | -| `ZELINQA_CONFIGURATION_API_KEY` | configuration client, before `ZELINQA_API_KEY` | — | -| `ZELINQA_BASE_URL` | both clients | `https://api.zelinqa.ai` | - -```python -with ZelinqaClient() as client: # api_key from ZELINQA_API_KEY - ... -``` - -Both clients are context managers and expose `close()` (async: `aclose()`). -Their `repr()` and `str()` never contain the key. - -### Constructor options - -```python -ZelinqaClient( - api_key=None, # falls back to the environment - base_url=None, # absolute http(s), no credentials, no query - timeout=30.0, # seconds, per attempt - max_retries=2, - transport=None, # an httpx transport, for tests -) +```bash +export ZELINQA_API_KEY="YOUR_RUNTIME_API_KEY" ``` -## Runtime: one conversation +Keep API keys out of browser code, mobile apps, logs and source control. -### With a session handle (recommended) +## Get a question and send the reply -`start_session()` returns a `Session` that remembers `state_version` for you. +This small console example asks one question and submits the person's reply. +For choice questions, enter one of the displayed labels exactly. ```python from zelinqa import ZelinqaClient with ZelinqaClient() as client: - session = client.start_session(client_reference="crm-lead-8842", max_turns=15) - - decision = session.next() # first turn, nothing asked yet - candidate = decision.candidates[0] - print(candidate.question_id, candidate.text, candidate.type) - - # …your agent asks the question, possibly reworded, and gets an answer… - - decision = session.next( - previous_turn={ - "assistant_text": candidate.text, - "user_text": "Un canapé contemporain pour le salon, nous avons un chat.", - } - ) - print(decision.progress.objective.effective_status, decision.turns_remaining) - - # A choice question: answer with the ids, no LLM call on that path. - choice = decision.candidates[0] - if choice.choices: - decision = session.next( - previous_turn={ - "question_id": choice.question_id, - "structured_answer": {"choice_ids": [choice.choices[0].choice_id]}, - } - ) - - # Something the CRM already knows: no need to ask for it. - state = session.apply_events(client_updates={"data": [{"id": "annual_budget", "value": 2500}]}) - print(state.targets["annual_budget"].status) # confirmed - - # Messages exchanged outside Zelinqa. - session.apply_events( - context_update={"mode": "summary", "text": "Le visiteur emménage en mars."} - ) - - session.submit_feedback(result="success", label="achat", metadata={"order_id": "SO-99120"}) -``` - -`Session` exposes `id`, `state_version`, `state`, `pending_decision`, and -`next()`, `answer()`, `apply_events()`, `refresh()`, `submit_feedback()`. - -`answer(user_text)` submits an open answer to the pending decision. For a choice -question, pass `choice_labels=["Exact displayed label"]` instead. The handle -resolves the decision, question and choice IDs; it rejects unknown or ambiguous -labels locally. For a semi-open choice with an additional explanation, pass -`free_text` alongside `choice_labels`. It then requests the next decision. -The exported `answer_turn(pending_decision, user_text="...")` builds only the -`previous_turn` payload and makes no HTTP call. - -After a crash, read the session back — there is no resume token to keep: - -```python -session = client.resume_session("ses_01J8Z") -assert session.pending_decision is not None # the exact candidates, rehydrated -decision = session.next(previous_turn={"user_text": "…"}) -``` - -A conflict is never hidden. If another worker moved the session, `next()` raises -`ZelinqaStateVersionConflictError` and the handle is left untouched: you decide -whether to replay, refresh, or give up. - -```python -from zelinqa import ZelinqaStateVersionConflictError - -try: - session.next(previous_turn={"user_text": "…"}) -except ZelinqaStateVersionConflictError as error: - print(error.supplied_state_version, error.current_state_version) - session.refresh() # explicit, on your terms -``` - -### With explicit `state_version` - -If you keep the state yourself — a queue worker, a Lambda, a state machine — -call the client directly and pass the version you read. - -```python -state = client.create_session(client_reference="crm-lead-8842") -version = state.versions.state_version # 0 - -decision = client.next("ses_01J8Z", state_version=version) -version = decision.versions.state_version - -state = client.apply_events( - "ses_01J8Z", - state_version=version, - client_updates={"dimensions": [{"id": "so_livraison", "operation": "exclude"}]}, -) -state = client.get_session("ses_01J8Z") -client.submit_feedback("ses_01J8Z", result="partial") -``` - -### Async - -The async client has the same surface; `iter_questions` becomes an async -iterator. - -```python -from zelinqa import AsyncZelinqaClient - -async with AsyncZelinqaClient() as client: - session = await client.start_session() - decision = await session.next() -``` - -### Reading a decision - -`next()` returns a `NextResponse`. Zelinqa never decides for you: - -- `action == "ask"` → `decision_id` is set, `candidates` is non-empty, ranked, rank 1 first. -- `action == "stop"` → no identifiable question is left; `stop_reason` says why. -- `warnings` reports conditions that would justify stopping (`max_turns_reached`, - `objective_achieved`, `eligibility_exhausted_fallback`, `constraints_relaxed`) - while still proposing the best question available. The decision to stop is yours. -- `degraded` / `degraded_reasons` say the turn was understood in reduced mode — - typically because no `user_text` was provided. - -No selection score, semantic evidence, embedding or prompt is ever exposed. - -### Constraining one call - -```python -decision = session.next( - selection={ - "candidate_count": 2, - "allowed_question_types": ["single_choice", "multiple_choice"], - "dimensions": {"ids": ["so_besoin"], "mode": "restrict"}, - } -) -``` - -## Configuration: read, edit, publish - -```python -from zelinqa import ZelinqaConfigurationClient - -with ZelinqaConfigurationClient() as studio: - published = studio.get_configuration() # configuration:read - draft = studio.get_configuration(state="draft") # needs read + write - - page = studio.list_questions(dimension_id="so_besoin", type="single_choice", limit=50) - for question in studio.iter_questions(active=True): # follows the cursor - print(question.id, question.text) - - csv = studio.export_questions_csv() # raw text/csv - events = studio.list_audit(limit=20) # configuration:publish -``` - -`SuccessInformation` carries the collected value's JSON Schema. The contract -calls that field `schema`, which collides with a `pydantic` attribute, so the -Python attribute is `json_schema` and the wire name stays `schema`. - -```python -print(published.success_informations[0].json_schema) # {"type": "number", "minimum": 0} -``` - -### Editing the draft, then publishing - -Changes are applied atomically: either all of them land, or none does. Nothing -goes live until a publication has compiled. - -```python -from zelinqa import ZelinqaConfigurationClient - -with ZelinqaConfigurationClient() as studio: - draft = studio.get_configuration(state="draft") - - applied = studio.apply_changes( - [ - { - "entity": "question", - "operation": "create", - "question": { - "id": "q_delivery_window", - "text": "À quelle période souhaitez-vous être livré ?", - "type": "single_choice", - "dimension_id": "so_livraison", - "active": True, - "choices": [ - {"id": "choice_1m", "label": "Dans le mois", "maps_to_value": "dans_le_mois"}, - {"id": "choice_3m", "label": "Dans les trois mois", "maps_to_value": "trois_mois"}, - ], - }, - }, - { - "entity": "success_information", - "operation": "create", - "success_information": { - "id": "delivery_window", - "label": "Fenêtre de livraison souhaitée", - "primary_question_id": "q_delivery_window", - "schema": {"type": "string", "enum": ["dans_le_mois", "trois_mois"]}, - }, - }, - ], - expected_draft_revision=draft.draft_revision, # refuse to overwrite someone else - ) - print(applied.applied, applied.draft_revision) - - queued = studio.publish(expected_draft_revision=applied.draft_revision) - print(queued.compilation_id, queued.status) # cmp_… queued - - status = studio.wait_for_compilation(queued.compilation_id, poll_interval=3, timeout=900) - if status.status == "succeeded": - print("now active:", status.configuration_version) - else: - print("failed:", status.error.code, status.error.message) -``` - -Compilation runs outside the HTTP request: a large corpus needs several LLM -batches. `publish()` returns as soon as the job is accepted, and the previous -compiled version stays readable so sessions already using it can finish. - -`wait_for_compilation()` returns the terminal status — a failure is a normal -outcome, so inspect `status.error` rather than catching an exception. Only -running out of time raises `ZelinqaCompilationTimeoutError`. Typed models can be -passed instead of dicts: - -```python -from zelinqa import QuestionChange, QuestionPatch - -studio.apply_changes([QuestionChange(operation="update", question=QuestionPatch(id="q_style", active=False))]) -``` - -## Errors - -Every exception derives from `ZelinqaError`. The business envelope `code` decides -the type first; the HTTP status decides when the body is not a V1 envelope. - -| Raised | Status / code | Notable attributes | -|---|---|---| -| `ZelinqaAuthenticationError` | `401` (no `Authorization` header), or `403` with no envelope — invalid, revoked, expired, or missing the scope the gateway checks for that route | `status_code` | -| `ZelinqaInsufficientScopeError` | `403` `insufficient_scope` — the service-side check, today only `?state=draft` | `required_scopes`, `granted_scopes` | -| `ZelinqaUnknownSessionError` | `404` `unknown_session` | `details["session_id"]` | -| `ZelinqaUnknownConfigurationError` | `404` `unknown_configuration` | | -| `ZelinqaUnknownCompilationError` | `404` `unknown_compilation` | | -| `ZelinqaStateVersionConflictError` | `409` `state_version_conflict` | `supplied_state_version`, `current_state_version` | -| `ZelinqaIdempotencyKeyReusedError` | `409` `idempotency_key_reused` | `idempotency_key` | -| `ZelinqaCompilationInProgressError` | `409` `compilation_in_progress` | `compilation_id`, `status` | -| `ZelinqaCompiledArtifactUnavailableError` | `410` `compiled_artifact_unavailable` | | -| `ZelinqaInvalidPreviousTurnError` | `422` `invalid_previous_turn` | | -| `ZelinqaConstraintNoMatchError` | `422` `constraint_no_match` | | -| `ZelinqaInvalidChoiceError` | `422` `invalid_choice` | | -| `ZelinqaConfigurationValidationError` | `422` `configuration_validation_failed` | `issues: list[ConfigurationIssue]` | -| `ZelinqaRateLimitError` | `429` | `retry_after` | -| `ZelinqaIdempotencyContentionError` | `503` `idempotency_contention` | retried first, raised only when retries run out | -| `ZelinqaServerError` | other `5xx` | | -| `ZelinqaAPIError` | anything else | base of all of the above | -| `ZelinqaConnectionError` | network failure or timeout, after every retry | | -| `ZelinqaCompilationTimeoutError` | `wait_for_compilation` ran out of time | `compilation_id`, `timeout` | - -`ZelinqaAPIError` always carries `status_code`, `code`, `message`, `request_id`, -`details` and `retry_after`. `str(error)` reads -`": (request_id=…)"` — quote the `request_id` when -you contact Zelinqa support. - -Note that a `403` from the gateway is deliberately not split further: the -gateway answers the same opaque body for a revoked key and for a key missing a -route's scope, so the SDK does not pretend to know which it was. - -```python -from zelinqa import ZelinqaAPIError, ZelinqaConfigurationValidationError - -try: - studio.publish() -except ZelinqaConfigurationValidationError as error: - for issue in error.issues: - print(issue.code, issue.entity, issue.entity_id, issue.message) -except ZelinqaAPIError as error: - print(error.status_code, error.code, error.request_id) -``` - -`ConfigurationIssue.code` is a plain string on purpose: the contract does not -freeze that catalogue. Display `message`, and never assume you know every code. - -## Retries and idempotency - -Every mutation sends an `Idempotency-Key`. If you do not supply one, the SDK -generates a UUID v4 **once per logical call** and reuses it across that call's -retries — a retry can therefore never double a turn, an outcome, a feedback or -a publication. Supply your own when you want the replay to be idempotent across -processes too: - -```python -session.next(previous_turn={"user_text": "…"}, idempotency_key=f"next-{session.id}-turn-4") -``` - -Same key and same body replays the original response. Same key with a different -body raises `ZelinqaIdempotencyKeyReusedError`. - -Retried, up to `max_retries` (default 2), with exponential backoff (0.5 s, 1 s, -2 s… capped at 10 s, jittered): connection errors and timeouts, `429`, `500`, -`502`, `503`, `504`, and the `idempotency_contention` envelope. `Retry-After` -(seconds or HTTP date) and `details.retry_after_seconds` win over the backoff, -clamped to 30 s. `GET` requests are retried the same way. `400`, `401`, `403`, -`404`, `409`, `410` and `422` are never retried. `timeout` applies per attempt, -so the worst case is roughly `timeout × (max_retries + 1)` plus the backoff. - -## Security - -**These clients belong in a backend.** A Zelinqa key is restricted to its -configured domain and scopes. Never ship one to a browser, -a mobile app or any client you do not control; proxy Zelinqa through your own -service instead. - -- The key lives in the `httpx` client and nowhere else: no exception, message, - `repr`, log line or returned value contains it. -- Use separate keys per scope. A runtime key must not be able to publish. -- The tenant and domain are derived from the API key, not supplied by the client. -- `initial_history` is consumed once in memory to build the initial state. It - is never persisted, never logged, never returned. -- Keep keys out of the repository. `.env*` and `*.local` are git-ignored. - -## Development - -```bash -uv sync --group dev -uv run ruff check python/src python/tests -uv run ruff format --check python/src python/tests -uv run mypy python/src -uv run pytest # live tests excluded by default -``` - -The live suite runs against real staging keys and is opt-in: - -```bash -ZELINQA_LIVE=1 uv run pytest -m live python/tests/live -``` - -It needs `ZELINQA_LIVE_RUNTIME_KEY`, `ZELINQA_LIVE_CONFIG_READ_KEY`, -`ZELINQA_LIVE_CONFIG_WRITE_KEY`, `ZELINQA_LIVE_CONFIG_PUBLISH_KEY`, -`ZELINQA_LIVE_CONFIG_MANAGE_KEY` and `ZELINQA_LIVE_REVOKED_KEY`, and optionally -`ZELINQA_LIVE_BASE_URL`. In CI it only runs from the manual `live-tests` workflow, -with secrets from the `staging-live` environment. - -## Changelog - -See the [changelog](https://github.com/Zelinqa/zelinqa-sdk/blob/main/CHANGELOG.md) for release history. + session = client.start_session(client_reference="demo-001") + decision = session.next() + + if decision.action == "ask": + question = decision.candidates[0] + print(question.text) + for choice in question.choices: + print(f"- {choice.label}") + + reply = input("> ") + if not reply.strip(): + decision = session.answer(outcome="asked_no_answer") + elif question.choices: + decision = session.answer(choice_labels=[reply]) + else: + decision = session.answer(reply) + + print(decision.action) # "ask" for another question, or "stop" +``` + +The session handle supplies session, decision, question and choice IDs for you. +Each `answer()` records the reply and returns the next decision; do not call +`next()` again just to retrieve that question. Use a session sequentially and +store `session.id` in your backend if you need to resume after a restart. + +Open questions need the person's actual words. Choices alone need no model +call; free text is analyzed by the engine. Report a real refusal with +`outcome="refused"`, or an empty reply with `outcome="asked_no_answer"`. +Keep warnings visible and let your application decide when to finish. + +## What you can do + +- Run conversations, resume sessions, add context and record business feedback. +- Use `AsyncZelinqaClient` with `await` for asynchronous applications. +- Read questions, edit drafts and publish with `ZelinqaConfigurationClient` + and the corresponding configuration scopes. +- Handle typed errors, configure timeouts and retries, and provide idempotency keys. + +## Learn more + +- [Documentation and API reference](https://docs.zelinqa.ai) +- [Python guide: choices, async, configuration and errors](https://github.com/Zelinqa/zelinqa-sdk/blob/main/python/docs/usage.md) +- [Changelog](https://github.com/Zelinqa/zelinqa-sdk/blob/main/CHANGELOG.md) +- [Report an issue](https://github.com/Zelinqa/zelinqa-sdk/issues) ## License diff --git a/python/docs/usage.md b/python/docs/usage.md new file mode 100644 index 0000000..d579967 --- /dev/null +++ b/python/docs/usage.md @@ -0,0 +1,384 @@ +# Python SDK guide + +Detailed usage for the Zelinqa Python SDK. Start with the +[quickstart](https://github.com/Zelinqa/zelinqa-sdk/blob/main/python/README.md) +if you are integrating for the first time. + +## Two clients, two keys + +Use `session.answer("the actual reply")` after `session.next()` to avoid copying +technical IDs. Choices use `session.answer(choice_labels=["Exact label"])`. + +Open questions require the person's actual `user_text`; the engine analyzes +that text. Closed and semi-open questions accept choices alone without a model +call. Semi-open choices may include `free_text`, which is analyzed. An explicit +`outcome="asked_no_answer"` or `outcome="refused"` needs no text or model call +for any type. These no-model paths assume no other text needs analysis. +`answer()` rejects an open answer without text locally, before any HTTP request. +Async handles offer the same methods with `await`. Persist the session ID in +your backend to resume after a restart; use one handle sequentially. + + +A Zelinqa key carries scopes. Studio recommends one key per job, so the SDK is +split the same way. + +| Client | Scope | What it does | +|---|---|---| +| `ZelinqaClient` / `AsyncZelinqaClient` | `runtime` | drives conversations: sessions, next question, events, feedback | +| `ZelinqaConfigurationClient` / `AsyncZelinqaConfigurationClient` | `configuration:read`, `configuration:write`, `configuration:publish` | reads the question bank, edits the draft, publishes it | + +```python +from zelinqa import ZelinqaClient, ZelinqaConfigurationClient + +runtime = ZelinqaClient("YOUR_RUNTIME_KEY") # scope runtime +studio = ZelinqaConfigurationClient("YOUR_CONFIG_KEY") # management scopes +``` + +### Environment variables + +| Variable | Used by | Default | +|---|---|---| +| `ZELINQA_API_KEY` | both clients | — | +| `ZELINQA_CONFIGURATION_API_KEY` | configuration client, before `ZELINQA_API_KEY` | — | +| `ZELINQA_BASE_URL` | both clients | `https://api.zelinqa.ai` | + +```python +with ZelinqaClient() as client: # api_key from ZELINQA_API_KEY + ... +``` + +Both clients are context managers and expose `close()` (async: `aclose()`). +Their `repr()` and `str()` never contain the key. + +### Constructor options + +```python +ZelinqaClient( + api_key=None, # falls back to the environment + base_url=None, # absolute http(s), no credentials, no query + timeout=30.0, # seconds, per attempt + max_retries=2, + transport=None, # an httpx transport, for tests +) +``` + +## Runtime: one conversation + +### With a session handle (recommended) + +`start_session()` returns a `Session` that remembers `state_version` for you. + +```python +from zelinqa import ZelinqaClient + +with ZelinqaClient() as client: + session = client.start_session(client_reference="crm-lead-8842", max_turns=15) + + decision = session.next() # first turn, nothing asked yet + candidate = decision.candidates[0] + print(candidate.question_id, candidate.text, candidate.type) + + # …your agent asks the question, possibly reworded, and gets an answer… + + decision = session.next( + previous_turn={ + "assistant_text": candidate.text, + "user_text": "Un canapé contemporain pour le salon, nous avons un chat.", + } + ) + print(decision.progress.objective.effective_status, decision.turns_remaining) + + # A choice question: answer with the ids, no LLM call on that path. + choice = decision.candidates[0] + if choice.choices: + decision = session.next( + previous_turn={ + "question_id": choice.question_id, + "structured_answer": {"choice_ids": [choice.choices[0].choice_id]}, + } + ) + + # Something the CRM already knows: no need to ask for it. + state = session.apply_events(client_updates={"data": [{"id": "annual_budget", "value": 2500}]}) + print(state.targets["annual_budget"].status) # confirmed + + # Messages exchanged outside Zelinqa. + session.apply_events( + context_update={"mode": "summary", "text": "Le visiteur emménage en mars."} + ) + + session.submit_feedback(result="success", label="achat", metadata={"order_id": "SO-99120"}) +``` + +`Session` exposes `id`, `state_version`, `state`, `pending_decision`, and +`next()`, `answer()`, `apply_events()`, `refresh()`, `submit_feedback()`. + +`answer(user_text)` submits an open answer to the pending decision. For a choice +question, pass `choice_labels=["Exact displayed label"]` instead. The handle +resolves the decision, question and choice IDs; it rejects unknown or ambiguous +labels locally. For a semi-open choice with an additional explanation, pass +`free_text` alongside `choice_labels`. It then requests the next decision. +The exported `answer_turn(pending_decision, user_text="...")` builds only the +`previous_turn` payload and makes no HTTP call. + +After a crash, read the session back — there is no resume token to keep: + +```python +session = client.resume_session("ses_01J8Z") +assert session.pending_decision is not None # the exact candidates, rehydrated +decision = session.next(previous_turn={"user_text": "…"}) +``` + +A conflict is never hidden. If another worker moved the session, `next()` raises +`ZelinqaStateVersionConflictError` and the handle is left untouched: you decide +whether to replay, refresh, or give up. + +```python +from zelinqa import ZelinqaStateVersionConflictError + +try: + session.next(previous_turn={"user_text": "…"}) +except ZelinqaStateVersionConflictError as error: + print(error.supplied_state_version, error.current_state_version) + session.refresh() # explicit, on your terms +``` + +### With explicit `state_version` + +If you keep the state yourself — a queue worker, a Lambda, a state machine — +call the client directly and pass the version you read. + +```python +state = client.create_session(client_reference="crm-lead-8842") +version = state.versions.state_version # 0 + +decision = client.next("ses_01J8Z", state_version=version) +version = decision.versions.state_version + +state = client.apply_events( + "ses_01J8Z", + state_version=version, + client_updates={"dimensions": [{"id": "so_livraison", "operation": "exclude"}]}, +) +state = client.get_session("ses_01J8Z") +client.submit_feedback("ses_01J8Z", result="partial") +``` + +### Async + +The async client has the same surface; `iter_questions` becomes an async +iterator. + +```python +from zelinqa import AsyncZelinqaClient + +async with AsyncZelinqaClient() as client: + session = await client.start_session() + decision = await session.next() +``` + +### Reading a decision + +`next()` returns a `NextResponse`. Zelinqa never decides for you: + +- `action == "ask"` → `decision_id` is set, `candidates` is non-empty, ranked, rank 1 first. +- `action == "stop"` → no identifiable question is left; `stop_reason` says why. +- `warnings` reports conditions that would justify stopping (`max_turns_reached`, + `objective_achieved`, `eligibility_exhausted_fallback`, `constraints_relaxed`) + while still proposing the best question available. The decision to stop is yours. +- `degraded` / `degraded_reasons` say the turn was understood in reduced mode — + typically because no `user_text` was provided. + +### Constraining one call + +```python +decision = session.next( + selection={ + "candidate_count": 2, + "allowed_question_types": ["single_choice", "multiple_choice"], + "dimensions": {"ids": ["so_besoin"], "mode": "restrict"}, + } +) +``` + +## Configuration: read, edit, publish + +```python +from zelinqa import ZelinqaConfigurationClient + +with ZelinqaConfigurationClient() as studio: + published = studio.get_configuration() # configuration:read + draft = studio.get_configuration(state="draft") # needs read + write + + page = studio.list_questions(dimension_id="so_besoin", type="single_choice", limit=50) + for question in studio.iter_questions(active=True): # follows the cursor + print(question.id, question.text) + + csv = studio.export_questions_csv() # raw text/csv + events = studio.list_audit(limit=20) # configuration:publish +``` + +`SuccessInformation` carries the collected value's JSON Schema. The contract +calls that field `schema`, which collides with a `pydantic` attribute, so the +Python attribute is `json_schema` and the wire name stays `schema`. + +```python +print(published.success_informations[0].json_schema) # {"type": "number", "minimum": 0} +``` + +### Editing the draft, then publishing + +Changes are applied atomically: either all of them land, or none does. Nothing +goes live until a publication has compiled. + +```python +from zelinqa import ZelinqaConfigurationClient + +with ZelinqaConfigurationClient() as studio: + draft = studio.get_configuration(state="draft") + + applied = studio.apply_changes( + [ + { + "entity": "question", + "operation": "create", + "question": { + "id": "q_delivery_window", + "text": "À quelle période souhaitez-vous être livré ?", + "type": "single_choice", + "dimension_id": "so_livraison", + "active": True, + "choices": [ + {"id": "choice_1m", "label": "Dans le mois", "maps_to_value": "dans_le_mois"}, + {"id": "choice_3m", "label": "Dans les trois mois", "maps_to_value": "trois_mois"}, + ], + }, + }, + { + "entity": "success_information", + "operation": "create", + "success_information": { + "id": "delivery_window", + "label": "Fenêtre de livraison souhaitée", + "primary_question_id": "q_delivery_window", + "schema": {"type": "string", "enum": ["dans_le_mois", "trois_mois"]}, + }, + }, + ], + expected_draft_revision=draft.draft_revision, # refuse to overwrite someone else + ) + print(applied.applied, applied.draft_revision) + + queued = studio.publish(expected_draft_revision=applied.draft_revision) + print(queued.compilation_id, queued.status) # cmp_… queued + + status = studio.wait_for_compilation(queued.compilation_id, poll_interval=3, timeout=900) + if status.status == "succeeded": + print("now active:", status.configuration_version) + else: + print("failed:", status.error.code, status.error.message) +``` + +Compilation runs outside the HTTP request: a large corpus needs several LLM +batches. `publish()` returns as soon as the job is accepted, and the previous +compiled version stays readable so sessions already using it can finish. + +`wait_for_compilation()` returns the terminal status — a failure is a normal +outcome, so inspect `status.error` rather than catching an exception. Only +running out of time raises `ZelinqaCompilationTimeoutError`. Typed models can be +passed instead of dicts: + +```python +from zelinqa import QuestionChange, QuestionPatch + +studio.apply_changes([QuestionChange(operation="update", question=QuestionPatch(id="q_style", active=False))]) +``` + +## Errors + +Every exception derives from `ZelinqaError`. The business envelope `code` decides +the type first; the HTTP status decides when the body is not a V1 envelope. + +| Raised | Status / code | Notable attributes | +|---|---|---| +| `ZelinqaAuthenticationError` | `401` (no `Authorization` header), or `403` with no envelope — invalid, revoked, expired, or missing the scope the gateway checks for that route | `status_code` | +| `ZelinqaInsufficientScopeError` | `403` `insufficient_scope` — the service-side check, today only `?state=draft` | `required_scopes`, `granted_scopes` | +| `ZelinqaUnknownSessionError` | `404` `unknown_session` | `details["session_id"]` | +| `ZelinqaUnknownConfigurationError` | `404` `unknown_configuration` | | +| `ZelinqaUnknownCompilationError` | `404` `unknown_compilation` | | +| `ZelinqaStateVersionConflictError` | `409` `state_version_conflict` | `supplied_state_version`, `current_state_version` | +| `ZelinqaIdempotencyKeyReusedError` | `409` `idempotency_key_reused` | `idempotency_key` | +| `ZelinqaCompilationInProgressError` | `409` `compilation_in_progress` | `compilation_id`, `status` | +| `ZelinqaCompiledArtifactUnavailableError` | `410` `compiled_artifact_unavailable` | | +| `ZelinqaInvalidPreviousTurnError` | `422` `invalid_previous_turn` | | +| `ZelinqaConstraintNoMatchError` | `422` `constraint_no_match` | | +| `ZelinqaInvalidChoiceError` | `422` `invalid_choice` | | +| `ZelinqaConfigurationValidationError` | `422` `configuration_validation_failed` | `issues: list[ConfigurationIssue]` | +| `ZelinqaRateLimitError` | `429` | `retry_after` | +| `ZelinqaIdempotencyContentionError` | `503` `idempotency_contention` | retried first, raised only when retries run out | +| `ZelinqaServerError` | other `5xx` | | +| `ZelinqaAPIError` | anything else | base of all of the above | +| `ZelinqaConnectionError` | network failure or timeout, after every retry | | +| `ZelinqaCompilationTimeoutError` | `wait_for_compilation` ran out of time | `compilation_id`, `timeout` | + +`ZelinqaAPIError` always carries `status_code`, `code`, `message`, `request_id`, +`details` and `retry_after`. `str(error)` reads +`": (request_id=…)"` — quote the `request_id` when +you contact Zelinqa support. + +Note that a `403` from the gateway is deliberately not split further: the +gateway answers the same opaque body for a revoked key and for a key missing a +route's scope, so the SDK does not pretend to know which it was. + +```python +from zelinqa import ZelinqaAPIError, ZelinqaConfigurationValidationError + +try: + studio.publish() +except ZelinqaConfigurationValidationError as error: + for issue in error.issues: + print(issue.code, issue.entity, issue.entity_id, issue.message) +except ZelinqaAPIError as error: + print(error.status_code, error.code, error.request_id) +``` + +`ConfigurationIssue.code` is a plain string on purpose: the contract does not +freeze that catalogue. Display `message`, and never assume you know every code. + +## Retries and idempotency + +Every mutation sends an `Idempotency-Key`. If you do not supply one, the SDK +generates a UUID v4 **once per logical call** and reuses it across that call's +retries — a retry can therefore never double a turn, an outcome, a feedback or +a publication. Supply your own when you want the replay to be idempotent across +processes too: + +```python +session.next(previous_turn={"user_text": "…"}, idempotency_key=f"next-{session.id}-turn-4") +``` + +Same key and same body replays the original response. Same key with a different +body raises `ZelinqaIdempotencyKeyReusedError`. + +Retried, up to `max_retries` (default 2), with exponential backoff (0.5 s, 1 s, +2 s… capped at 10 s, jittered): connection errors and timeouts, `429`, `500`, +`502`, `503`, `504`, and the `idempotency_contention` envelope. `Retry-After` +(seconds or HTTP date) and `details.retry_after_seconds` win over the backoff, +clamped to 30 s. `GET` requests are retried the same way. `400`, `401`, `403`, +`404`, `409`, `410` and `422` are never retried. `timeout` applies per attempt, +so the worst case is roughly `timeout × (max_retries + 1)` plus the backoff. + +## Security + +**These clients belong in a backend.** A Zelinqa key is restricted to its +configured domain and scopes. Never ship one to a browser, +a mobile app or any client you do not control; proxy Zelinqa through your own +service instead. + +- The key lives in the `httpx` client and nowhere else: no exception, message, + `repr`, log line or returned value contains it. +- Use separate keys per scope. A runtime key must not be able to publish. +- The tenant and domain are derived from the API key, not supplied by the client. +- `initial_history` is consumed once in memory to build the initial state. It + is never persisted, never logged, never returned. +- Keep keys out of the repository. `.env*` and `*.local` are git-ignored. diff --git a/python/tests/test_readme.py b/python/tests/test_readme.py new file mode 100644 index 0000000..a1a3f11 --- /dev/null +++ b/python/tests/test_readme.py @@ -0,0 +1,97 @@ +"""Execute the published quickstart with the real SDK and synthetic HTTP replies.""" + +import copy +import re +from pathlib import Path + +import pytest +import zelinqa +from spec_examples import ARRET_SANS_QUESTION, DECISION_NORMALE, SESSION_NEUVE +from test_runtime_client import Recorder, json_response, sync_client + +README = Path(__file__).resolve().parents[1] / "README.md" + + +def quickstart(): + examples = re.findall(r"```python\n(.*?)\n```", README.read_text(), re.DOTALL) + assert len(examples) == 1, "Every executable README example must be tested" + return compile(examples[0], str(README), "exec") + + +def decision_for(kind): + decision = copy.deepcopy(DECISION_NORMALE) + candidate = decision["candidates"][0] + candidate["type"] = kind + candidate["selection_mode"] = None if kind == "open" else "single" + if kind == "multiple_choice": + candidate["selection_mode"] = "multiple" + candidate["choices"] = ( + [] if kind == "open" else [{"choice_id": "choice-email", "label": "Email"}] + ) + return decision + + +@pytest.mark.parametrize( + "kind,reply", + [ + ("open", "I need to qualify inbound requests."), + ("single_choice", "Email"), + ("multiple_choice", "Email"), + ("semi_open", "Email"), + ("open", ""), + ("open", " "), + ("single_choice", ""), + ], +) +def test_quickstart_submits_the_real_reply(monkeypatch, kind, reply): + decision = decision_for(kind) + recorder = Recorder( + json_response(201, SESSION_NEUVE), + json_response(200, decision), + json_response(200, ARRET_SANS_QUESTION), + ) + monkeypatch.setattr(zelinqa, "ZelinqaClient", lambda: sync_client(recorder)) + monkeypatch.setattr("builtins.input", lambda prompt: reply) + + exec(quickstart(), {}) + + assert len(recorder.requests) == 3 + assert recorder.body(0)["client_reference"] == "demo-001" + body = recorder.body() + assert body["state_version"] == decision["versions"]["state_version"] + previous = body["previous_turn"] + assert previous["decision_id"] == decision["decision_id"] + assert previous["question_id"] == decision["candidates"][0]["question_id"] + if not reply.strip(): + assert previous["outcome"] == "asked_no_answer" + assert previous.get("user_text") is None + assert previous.get("structured_answer") is None + elif kind == "open": + assert previous["user_text"] == reply + assert previous.get("structured_answer") is None + else: + assert previous["structured_answer"]["choice_ids"] == ["choice-email"] + assert previous.get("user_text") is None + + +def test_quickstart_does_not_ask_after_stop(monkeypatch): + recorder = Recorder(json_response(201, SESSION_NEUVE), json_response(200, ARRET_SANS_QUESTION)) + monkeypatch.setattr(zelinqa, "ZelinqaClient", lambda: sync_client(recorder)) + monkeypatch.setattr("builtins.input", lambda prompt: pytest.fail("No question is pending")) + + exec(quickstart(), {}) + + assert len(recorder.requests) == 2 + + +def test_quickstart_rejects_an_unknown_label_before_sending(monkeypatch): + recorder = Recorder( + json_response(201, SESSION_NEUVE), json_response(200, decision_for("single_choice")) + ) + monkeypatch.setattr(zelinqa, "ZelinqaClient", lambda: sync_client(recorder)) + monkeypatch.setattr("builtins.input", lambda prompt: "Not a displayed choice") + + with pytest.raises(ValueError, match="Unknown or ambiguous choice label"): + exec(quickstart(), {}) + + assert len(recorder.requests) == 2 diff --git a/typescript/README.md b/typescript/README.md index 823ce6e..d536387 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -1,351 +1,90 @@ -# `@zelinqa/sdk` — TypeScript SDK for Zelinqa Engine V1 +# Zelinqa TypeScript SDK -Official TypeScript client for the [Zelinqa Engine](https://docs.zelinqa.ai) V1 public -API (`https://api.zelinqa.ai`). Zelinqa Engine decides the **next best question** to -ask in a conversation: you configure objectives and a question bank in Zelinqa Studio, -publish an immutable version, and the API picks the next question from the session -state it keeps for you. +The official TypeScript client for Zelinqa. Configure a domain in +[Zelinqa Studio](https://client.zelinqa.ai), publish it, and let the API select +the next useful question for each conversation. -Zero runtime dependencies, ESM + CommonJS, full type declarations generated from -the OpenAPI contract. Node ≥ 22. TypeScript consumers need ES2022 and DOM type -libraries for `fetch`, `Request`, `URL` and `AbortSignal` (or equivalent Node -fetch types). +Node.js 22+ · ESM and CommonJS · Typed responses · No runtime dependencies ## Install -Use `await session.answer({ userText: "the actual reply" })` after -`session.next()`. Choices use `{ choiceLabels: ["Exact label"] }`. The handle -resolves technical IDs. Persist the session ID in your backend to resume after -a restart; use one handle sequentially. - -Open questions require the person's actual `userText`; the engine analyzes -that text. Closed and semi-open questions accept choices alone without a model -call. Semi-open choices may include `freeText`, which is analyzed. An explicit -`outcome: "asked_no_answer"` or `outcome: "refused"` needs no text or model call -for any type. These no-model paths assume no other text needs analysis. -`answer()` rejects an open answer without text locally, before any HTTP request. - - ```bash -pnpm add @zelinqa/sdk # or npm install / yarn add +npm install @zelinqa/sdk ``` -## Security — backend only - -A Zelinqa key is a bearer credential scoped to one domain and its permissions. **Never ship it to a -browser, a mobile bundle or any client-side code**, and never log it. The SDK -keeps the key in a private field, writes it to exactly one place — the -`Authorization` header — and never puts it in an error, a message, a stack trace -or the output of `toString()`. - -Use separate keys with least-privilege scopes: `runtime` for conversations, -`configuration:read` / `configuration:write` / `configuration:publish` for -management. Zelinqa Studio shows a raw key only once. +## Set your API key -## Two clients +Create a runtime API key for your published domain in Studio and set it on +your backend: -| Client | Scope | What it does | -|---|---|---| -| `ZelinqaClient` | `runtime` | create a session, get the next question, apply events, read the state, record the outcome | -| `ZelinqaConfigurationClient` | `configuration:*` | read the corpus, edit the draft, publish, follow the compilation, read the audit log | - -```ts -import { ZelinqaClient, ZelinqaConfigurationClient } from "@zelinqa/sdk"; - -const runtime = new ZelinqaClient({ apiKey: process.env.ZELINQA_RUNTIME_KEY ?? "" }); -const configuration = new ZelinqaConfigurationClient({ - apiKey: process.env.ZELINQA_CONFIGURATION_KEY ?? "", -}); +```bash +export ZELINQA_API_KEY="YOUR_RUNTIME_API_KEY" ``` -Constructor options (both clients): +Keep API keys out of browser code, mobile apps, logs and source control. -| Option | Default | Meaning | -|---|---|---| -| `apiKey` | — | required; the SDK never reads the environment for you | -| `baseUrl` | `https://api.zelinqa.ai` | absolute HTTP(S) origin, no credentials, query or fragment | -| `timeoutMs` | `30000` | per-attempt timeout | -| `maxRetries` | `2` | retries after the first attempt | -| `fetch` | global `fetch` | inject your own for tests or exotic runtimes | +## Get a question and send the reply -Every method takes an optional `{ idempotencyKey?, signal? }` as its last -argument. - -## Runtime: the conversation loop - -### With the `Session` handle (recommended) - -`startSession()` creates the session and returns a handle that remembers -`state_version` for you. +This small console example asks one question and submits the person's reply. +For choice questions, enter one of the displayed labels exactly. ```ts -const session = await runtime.startSession({ - client_reference: "crm-lead-8842", - max_turns: 15, -}); +import { createInterface } from "node:readline/promises"; +import { stdin, stdout } from "node:process"; +import { ZelinqaClient } from "@zelinqa/sdk"; -// First turn: no previous_turn yet. +const client = new ZelinqaClient({ apiKey: process.env.ZELINQA_API_KEY ?? "" }); +const session = await client.startSession({ client_reference: "demo-001" }); let decision = await session.next(); +const question = decision.candidates[0]; -while (decision.action === "ask") { - const candidate = decision.candidates[0]; - if (candidate === undefined) break; - - // Your agent is free to rephrase the published wording. - const assistantText = candidate.text; - const userText = await askTheVisitor(assistantText); - - decision = await session.next({ - previous_turn: { assistant_text: assistantText, user_text: userText }, - }); -} - -// Structured answer to a choice question: deterministic, no LLM call. -await session.next({ - previous_turn: { - question_id: "q_style", - structured_answer: { choice_ids: ["choice_contemporain"] }, - }, -}); - -// Data you already know, applied out of turn. -await session.applyEvents({ - client_updates: { data: [{ id: "annual_budget", operation: "set", value: 2500 }] }, -}); - -// Context that never went through Zelinqa. -await session.applyEvents({ - context_update: { mode: "summary", text: "The visitor moves in March." }, -}); - -const state = await session.refresh(); -console.log(state.progress.objective.effective_status, session.stateVersion); - -await session.submitFeedback({ - result: "success", - label: "purchase", - metadata: { order_id: "SO-99120" }, -}); -``` - -The handle exposes `id`, `stateVersion`, `state` (the last full `SessionState`), -and `pendingDecision`. `refresh()` re-reads the session — after a crash, that is -all you need: the pending decision comes back with its exact candidates, so no -resume token exists or is needed. - -`session.answer({ userText: "..." })` resolves the pending question's technical -identifiers and requests the next decision. For a choice question, use -`session.answer({ choiceLabels: ["Exact displayed label"] })`. A semi-open -choice can add `freeText`. Unknown, duplicate or ambiguous labels are rejected -locally. The exported `answerTurn(pendingDecision, answer)` builds only the -`previous_turn` payload and makes no HTTP call; use it when calling `next()` -directly. - -`resumeSession(sessionId)` builds a handle from an existing session. - -### With explicit `state_version` - -Every mutation carries the version you last read, as an optimistic lock. Use the -plain client when you persist the version yourself — in a queue message, a -workflow step or a database row. - -```ts -const created = await runtime.createSession({ client_reference: "crm-lead-8842" }); -let stateVersion = created.versions.state_version; // 0 - -const decision = await runtime.next("ses_01J8Z", { - state_version: stateVersion, - previous_turn: { user_text: "Around 2000 euros." }, -}); -stateVersion = decision.versions.state_version; - -const state = await runtime.applyEvents("ses_01J8Z", { - state_version: stateVersion, - client_updates: { dimensions: [{ id: "so_delivery", operation: "exclude" }] }, -}); -stateVersion = state.versions.state_version; -``` - -If the session moved in the meantime, the API answers `state_version_conflict` -and the SDK raises `ZelinqaStateVersionConflictError`. **It is never swallowed and -never auto-refreshed** — you decide whether to re-read and replay: - -```ts -import { ZelinqaStateVersionConflictError } from "@zelinqa/sdk"; - -try { - await session.next({ previous_turn: { user_text } }); -} catch (error) { - if (error instanceof ZelinqaStateVersionConflictError) { - console.warn("session moved", error.suppliedStateVersion, "→", error.currentStateVersion); - await session.refresh(); - } else { - throw error; +if (decision.action === "ask" && question !== undefined) { + console.log(question.text); + for (const choice of question.choices) { + console.log(`- ${choice.label}`); } -} -``` - -### Soft stops - -Zelinqa does not decide for you. When `max_turns` is reached, the objective is -already achieved, or normal eligibility is empty, `next` still returns the best -available question and says so in `warnings` -(`max_turns_reached`, `objective_achieved`, `eligibility_exhausted_fallback`, -`constraints_relaxed`). `action: "stop"` only happens when no identifiable -question is left; then `stop_reason` is set and `candidates` is empty. - -`degraded` / `degraded_reasons` tell you when the turn was understood in reduced -mode — typically `missing_user_text` when you sent no verbatim. - -## Configuration: edit, publish, compile - -```ts -// Read the published corpus. -const published = await configuration.getConfiguration(); - -// Read the draft — needs configuration:read AND configuration:write. -const draft = await configuration.getConfiguration({ state: "draft" }); - -// One page, or every page. -const page = await configuration.listQuestions({ limit: 50, type: "single_choice" }); -for await (const question of configuration.iterateQuestions({ active: true })) { - console.log(question.id, question.text); -} - -// Spreadsheet export includes selection_mode and source. -const csv = await configuration.exportQuestionsCsv({ dimension_id: "so_besoin" }); - -// Atomic, ordered draft edit. Pin the revision you read to avoid clobbering -// another editor's work. -const applied = await configuration.applyChanges({ - expected_draft_revision: draft.draft_revision ?? undefined, - changes: [ - { - entity: "question", - operation: "create", - question: { - id: "q_delivery_window", - text: "When would you like it delivered?", - type: "single_choice", - dimension_id: "so_livraison", - active: true, - choices: [ - { id: "choice_1m", label: "Within the month", maps_to_value: "dans_le_mois" }, - { id: "choice_3m", label: "Within three months", maps_to_value: "trois_mois" }, - ], - }, - }, - ], -}); - -// Publishing is asynchronous: it queues a compilation and returns 202. -const queued = await configuration.publish({ - expected_draft_revision: applied.draft_revision, -}); - -// Wait for it. Returns the terminal status — including `failed`. -const terminal = await configuration.waitForCompilation(queued.compilation_id, { - pollIntervalMs: 3_000, - timeoutMs: 900_000, -}); -if (terminal.status === "failed") { - console.error(terminal.error?.code, terminal.error?.message); -} else { - console.log("now active:", terminal.configuration_version); + const input = createInterface({ input: stdin, output: stdout }); + try { + const reply = await input.question("> "); + if (!reply.trim()) { + decision = await session.answer({ outcome: "asked_no_answer" }); + } else if (question.choices.length > 0) { + decision = await session.answer({ choiceLabels: [reply] }); + } else { + decision = await session.answer({ userText: reply }); + } + console.log(decision.action, decision.warnings); + } finally { + input.close(); + } } - -// Who changed what (configuration:publish). -const audit = await configuration.listAudit({ limit: 50, resource_type: "question" }); ``` -`waitForCompilation` raises `ZelinqaCompilationTimeoutError` only when the budget runs -out: a failed compilation is an editorial outcome, not an SDK failure, so inspect -`status.error` yourself. Pass a `signal` to cancel the wait. - -`applyChanges` and `publish` report blocking problems as -`ZelinqaConfigurationValidationError`, with every issue grouped in `error.issues` -(`code`, `message`, `entity`, `entity_id`, `change_index`) so a UI can show them -all at once. Display `message`; never assume you know every `code`. - -## Errors - -SDK HTTP, connection and compilation errors derive from `ZelinqaError`. -Invalid local arguments, choice labels and caller cancellation can instead -raise native JavaScript errors. - -| Class | When | -|---|---| -| `ZelinqaConnectionError` | network failure or per-attempt timeout, after retries | -| `ZelinqaCompilationTimeoutError` | `waitForCompilation` budget spent | -| `ZelinqaAPIError` | base of every HTTP failure: `statusCode`, `code`, `message`, `requestId`, `details`, `retryAfter` | -| `ZelinqaAuthenticationError` | `401` (no `Authorization` header) **or** `403` without a V1 envelope: key invalid, revoked, expired, or missing the scope the gateway requires for the route | -| `ZelinqaInsufficientScopeError` | `403` with `insufficient_scope`: the service's dynamic check — today only `?state=draft` without `configuration:write`. Carries `requiredScopes` / `grantedScopes` | -| `ZelinqaNotFoundError` | `404`; specialised as `ZelinqaUnknownSessionError`, `ZelinqaUnknownConfigurationError`, `ZelinqaUnknownCompilationError` | -| `ZelinqaConflictError` | `409`; specialised as `ZelinqaStateVersionConflictError` (`suppliedStateVersion`, `currentStateVersion`), `ZelinqaIdempotencyKeyReusedError`, `ZelinqaCompilationInProgressError` (`compilationId`, `compilationStatus`) | -| `ZelinqaCompiledArtifactUnavailableError` | `410`: the artifact pinned by the session is unreachable | -| `ZelinqaValidationError` | `422`; specialised as `ZelinqaInvalidPreviousTurnError`, `ZelinqaConstraintNoMatchError`, `ZelinqaInvalidChoiceError`, `ZelinqaConfigurationValidationError` (`issues`) | -| `ZelinqaRateLimitError` | `429`; retried automatically first | -| `ZelinqaIdempotencyContentionError` | `503 idempotency_contention`; retried automatically, raised only once retries are exhausted | -| `ZelinqaServerError` | any other `5xx` | - -The gateway cannot tell an invalid key from an under-scoped one — both are a bare -`403 {"message":"Forbidden"}` — so both become `ZelinqaAuthenticationError`. Read -`statusCode` to distinguish a missing header (`401`) from a refused key (`403`). - -`String(error)` renders as `": (request_id=…)"`. Quote -`error.requestId` when you open a support ticket. +The session handle supplies session, decision, question and choice IDs for you. +Each `answer()` records the reply and returns the next decision; do not call +`next()` again just to retrieve that question. Use a session sequentially and +store `session.id` in your backend if you need to resume after a restart. -## Retries, timeouts and idempotency +Open questions need the person's actual words. Choices alone need no model +call; free text is analyzed by the engine. Report a real refusal with +`outcome: "refused"`, or an empty reply with `outcome: "asked_no_answer"`. +Keep warnings visible and let your application decide when to finish. -- Every mutation sends `Idempotency-Key`. If you do not supply one, the SDK - generates a UUID v4 **once per logical call and reuses it across all retries**, - so a retry can never double a turn, an outcome, a feedback or a publication. - Same key + same body replays the original response; same key + different body - is `ZelinqaIdempotencyKeyReusedError`. Server-side records are purged after 24 h. -- Retried, up to `maxRetries`: connection errors, per-attempt timeouts, `429`, - `500`, `502`, `503`, `504`. `GET` requests too. -- Never retried: `400`, `401`, `403`, `404`, `409`, `410`, `422`. -- Backoff: 0.5 s, 1 s, 2 s … capped at 10 s, with jitter. `Retry-After` (seconds - or HTTP-date) and `details.retry_after_seconds` win, capped at 30 s. -- `timeoutMs` applies **per attempt**, via an `AbortController` combined with the - `signal` you pass. +## What you can do -```ts -const controller = new AbortController(); -setTimeout(() => controller.abort(), 5_000); - -await runtime.next("ses_01J8Z", { state_version: 4 }, { - idempotencyKey: "next-ses01J8Z-turn-4", // 8–128 characters - signal: controller.signal, -}); -``` - -## Custom `fetch` - -Any Fetch-compatible function works — useful for tests, tracing, proxies or a -runtime whose global `fetch` you would rather not use. - -```ts -const client = new ZelinqaClient({ - apiKey: process.env.ZELINQA_RUNTIME_KEY ?? "", - fetch: async (input, init) => { - const started = Date.now(); - const response = await fetch(input, init); - // Log the route and the status — never the headers. - console.log(new URL(String(input)).pathname, response.status, Date.now() - started); - return response; - }, -}); -``` +- Run conversations, resume sessions, add context and record business feedback. +- Read questions, edit drafts and publish with `ZelinqaConfigurationClient` + and the corresponding configuration scopes. +- Handle typed errors, configure timeouts and retries, and cancel requests. -## Types +## Learn more -All wire types are generated from `openapi/nbq-v1.openapi.yaml` and re-exported -under friendly names: `SessionState`, `NextResponse`, `Candidate`, -`Configuration`, `ConfiguredQuestion`, `CompilationStatus`, -`ConfigurationChange`, and so on. Field names are snake_case, exactly as on the -wire. Regenerate with `pnpm generate:types`. +- [Documentation and API reference](https://docs.zelinqa.ai) +- [TypeScript guide: choices, configuration, errors and compiler setup](https://github.com/Zelinqa/zelinqa-sdk/blob/main/typescript/docs/usage.md) +- [Python SDK](https://github.com/Zelinqa/zelinqa-sdk/blob/main/python/README.md) — `pip install zelinqa` +- [Changelog](https://github.com/Zelinqa/zelinqa-sdk/blob/main/CHANGELOG.md) +- [Report an issue](https://github.com/Zelinqa/zelinqa-sdk/issues) ## License diff --git a/typescript/docs/usage.md b/typescript/docs/usage.md new file mode 100644 index 0000000..56bc1fd --- /dev/null +++ b/typescript/docs/usage.md @@ -0,0 +1,352 @@ +# TypeScript SDK usage guide + +Official TypeScript client for the [Zelinqa Engine](https://docs.zelinqa.ai) V1 public +API (`https://api.zelinqa.ai`). Zelinqa Engine decides the **next best question** to +ask in a conversation: you configure objectives and a question bank in Zelinqa Studio, +publish an immutable version, and the API picks the next question from the session +state it keeps for you. + +Zero runtime dependencies, ESM + CommonJS, full type declarations generated from +the OpenAPI contract. Node ≥ 22. TypeScript consumers need ES2022 and DOM type +libraries for `fetch`, `Request`, `URL` and `AbortSignal` (or equivalent Node +fetch types). + +## Install + +Use `await session.answer({ userText: "the actual reply" })` after +`session.next()`. Choices use `{ choiceLabels: ["Exact label"] }`. The handle +resolves technical IDs. Persist the session ID in your backend to resume after +a restart; use one handle sequentially. + +Open questions require the person's actual `userText`; the engine analyzes +that text. Closed and semi-open questions accept choices alone without a model +call. Semi-open choices may include `freeText`, which is analyzed. An explicit +`outcome: "asked_no_answer"` or `outcome: "refused"` needs no text or model call +for any type. These no-model paths assume no other text needs analysis. +`answer()` rejects an open answer without text locally, before any HTTP request. + + +```bash +pnpm add @zelinqa/sdk # or npm install / yarn add +``` + +## Security — backend only + +A Zelinqa key is a bearer credential scoped to one domain and its permissions. **Never ship it to a +browser, a mobile bundle or any client-side code**, and never log it. The SDK +keeps the key in a private field, writes it to exactly one place — the +`Authorization` header — and never puts it in an error, a message, a stack trace +or the output of `toString()`. + +Use separate keys with least-privilege scopes: `runtime` for conversations, +`configuration:read` / `configuration:write` / `configuration:publish` for +management. Zelinqa Studio shows a raw key only once. + +## Two clients + +| Client | Scope | What it does | +|---|---|---| +| `ZelinqaClient` | `runtime` | create a session, get the next question, apply events, read the state, record the outcome | +| `ZelinqaConfigurationClient` | `configuration:*` | read the corpus, edit the draft, publish, follow the compilation, read the audit log | + +```ts +import { ZelinqaClient, ZelinqaConfigurationClient } from "@zelinqa/sdk"; + +const runtime = new ZelinqaClient({ apiKey: process.env.ZELINQA_RUNTIME_KEY ?? "" }); +const configuration = new ZelinqaConfigurationClient({ + apiKey: process.env.ZELINQA_CONFIGURATION_KEY ?? "", +}); +``` + +Constructor options (both clients): + +| Option | Default | Meaning | +|---|---|---| +| `apiKey` | — | required; the SDK never reads the environment for you | +| `baseUrl` | `https://api.zelinqa.ai` | absolute HTTP(S) origin, no credentials, query or fragment | +| `timeoutMs` | `30000` | per-attempt timeout | +| `maxRetries` | `2` | retries after the first attempt | +| `fetch` | global `fetch` | inject your own for tests or exotic runtimes | + +Every method takes an optional `{ idempotencyKey?, signal? }` as its last +argument. + +## Runtime: the conversation loop + +### With the `Session` handle (recommended) + +`startSession()` creates the session and returns a handle that remembers +`state_version` for you. + +```ts +const session = await runtime.startSession({ + client_reference: "crm-lead-8842", + max_turns: 15, +}); + +// First turn: no previous_turn yet. +let decision = await session.next(); + +while (decision.action === "ask") { + const candidate = decision.candidates[0]; + if (candidate === undefined) break; + + // Your agent is free to rephrase the published wording. + const assistantText = candidate.text; + const userText = await askTheVisitor(assistantText); + + decision = await session.next({ + previous_turn: { assistant_text: assistantText, user_text: userText }, + }); +} + +// Structured answer to a choice question: deterministic, no LLM call. +await session.next({ + previous_turn: { + question_id: "q_style", + structured_answer: { choice_ids: ["choice_contemporain"] }, + }, +}); + +// Data you already know, applied out of turn. +await session.applyEvents({ + client_updates: { data: [{ id: "annual_budget", operation: "set", value: 2500 }] }, +}); + +// Context that never went through Zelinqa. +await session.applyEvents({ + context_update: { mode: "summary", text: "The visitor moves in March." }, +}); + +const state = await session.refresh(); +console.log(state.progress.objective.effective_status, session.stateVersion); + +await session.submitFeedback({ + result: "success", + label: "purchase", + metadata: { order_id: "SO-99120" }, +}); +``` + +The handle exposes `id`, `stateVersion`, `state` (the last full `SessionState`), +and `pendingDecision`. `refresh()` re-reads the session — after a crash, that is +all you need: the pending decision comes back with its exact candidates, so no +resume token exists or is needed. + +`session.answer({ userText: "..." })` resolves the pending question's technical +identifiers and requests the next decision. For a choice question, use +`session.answer({ choiceLabels: ["Exact displayed label"] })`. A semi-open +choice can add `freeText`. Unknown, duplicate or ambiguous labels are rejected +locally. The exported `answerTurn(pendingDecision, answer)` builds only the +`previous_turn` payload and makes no HTTP call; use it when calling `next()` +directly. + +`resumeSession(sessionId)` builds a handle from an existing session. + +### With explicit `state_version` + +Every mutation carries the version you last read, as an optimistic lock. Use the +plain client when you persist the version yourself — in a queue message, a +workflow step or a database row. + +```ts +const created = await runtime.createSession({ client_reference: "crm-lead-8842" }); +let stateVersion = created.versions.state_version; // 0 + +const decision = await runtime.next("ses_01J8Z", { + state_version: stateVersion, + previous_turn: { user_text: "Around 2000 euros." }, +}); +stateVersion = decision.versions.state_version; + +const state = await runtime.applyEvents("ses_01J8Z", { + state_version: stateVersion, + client_updates: { dimensions: [{ id: "so_delivery", operation: "exclude" }] }, +}); +stateVersion = state.versions.state_version; +``` + +If the session moved in the meantime, the API answers `state_version_conflict` +and the SDK raises `ZelinqaStateVersionConflictError`. **It is never swallowed and +never auto-refreshed** — you decide whether to re-read and replay: + +```ts +import { ZelinqaStateVersionConflictError } from "@zelinqa/sdk"; + +try { + await session.next({ previous_turn: { user_text } }); +} catch (error) { + if (error instanceof ZelinqaStateVersionConflictError) { + console.warn("session moved", error.suppliedStateVersion, "→", error.currentStateVersion); + await session.refresh(); + } else { + throw error; + } +} +``` + +### Soft stops + +Zelinqa does not decide for you. When `max_turns` is reached, the objective is +already achieved, or normal eligibility is empty, `next` still returns the best +available question and says so in `warnings` +(`max_turns_reached`, `objective_achieved`, `eligibility_exhausted_fallback`, +`constraints_relaxed`). `action: "stop"` only happens when no identifiable +question is left; then `stop_reason` is set and `candidates` is empty. + +`degraded` / `degraded_reasons` tell you when the turn was understood in reduced +mode — typically `missing_user_text` when you sent no verbatim. + +## Configuration: edit, publish, compile + +```ts +// Read the published corpus. +const published = await configuration.getConfiguration(); + +// Read the draft — needs configuration:read AND configuration:write. +const draft = await configuration.getConfiguration({ state: "draft" }); + +// One page, or every page. +const page = await configuration.listQuestions({ limit: 50, type: "single_choice" }); +for await (const question of configuration.iterateQuestions({ active: true })) { + console.log(question.id, question.text); +} + +// Spreadsheet export includes selection_mode and source. +const csv = await configuration.exportQuestionsCsv({ dimension_id: "so_besoin" }); + +// Atomic, ordered draft edit. Pin the revision you read to avoid clobbering +// another editor's work. +const applied = await configuration.applyChanges({ + expected_draft_revision: draft.draft_revision ?? undefined, + changes: [ + { + entity: "question", + operation: "create", + question: { + id: "q_delivery_window", + text: "When would you like it delivered?", + type: "single_choice", + dimension_id: "so_livraison", + active: true, + choices: [ + { id: "choice_1m", label: "Within the month", maps_to_value: "dans_le_mois" }, + { id: "choice_3m", label: "Within three months", maps_to_value: "trois_mois" }, + ], + }, + }, + ], +}); + +// Publishing is asynchronous: it queues a compilation and returns 202. +const queued = await configuration.publish({ + expected_draft_revision: applied.draft_revision, +}); + +// Wait for it. Returns the terminal status — including `failed`. +const terminal = await configuration.waitForCompilation(queued.compilation_id, { + pollIntervalMs: 3_000, + timeoutMs: 900_000, +}); + +if (terminal.status === "failed") { + console.error(terminal.error?.code, terminal.error?.message); +} else { + console.log("now active:", terminal.configuration_version); +} + +// Who changed what (configuration:publish). +const audit = await configuration.listAudit({ limit: 50, resource_type: "question" }); +``` + +`waitForCompilation` raises `ZelinqaCompilationTimeoutError` only when the budget runs +out: a failed compilation is an editorial outcome, not an SDK failure, so inspect +`status.error` yourself. Pass a `signal` to cancel the wait. + +`applyChanges` and `publish` report blocking problems as +`ZelinqaConfigurationValidationError`, with every issue grouped in `error.issues` +(`code`, `message`, `entity`, `entity_id`, `change_index`) so a UI can show them +all at once. Display `message`; never assume you know every `code`. + +## Errors + +SDK HTTP, connection and compilation errors derive from `ZelinqaError`. +Invalid local arguments, choice labels and caller cancellation can instead +raise native JavaScript errors. + +| Class | When | +|---|---| +| `ZelinqaConnectionError` | network failure or per-attempt timeout, after retries | +| `ZelinqaCompilationTimeoutError` | `waitForCompilation` budget spent | +| `ZelinqaAPIError` | base of every HTTP failure: `statusCode`, `code`, `message`, `requestId`, `details`, `retryAfter` | +| `ZelinqaAuthenticationError` | `401` (no `Authorization` header) **or** `403` without a V1 envelope: key invalid, revoked, expired, or missing the scope the gateway requires for the route | +| `ZelinqaInsufficientScopeError` | `403` with `insufficient_scope`: the service's dynamic check — today only `?state=draft` without `configuration:write`. Carries `requiredScopes` / `grantedScopes` | +| `ZelinqaNotFoundError` | `404`; specialised as `ZelinqaUnknownSessionError`, `ZelinqaUnknownConfigurationError`, `ZelinqaUnknownCompilationError` | +| `ZelinqaConflictError` | `409`; specialised as `ZelinqaStateVersionConflictError` (`suppliedStateVersion`, `currentStateVersion`), `ZelinqaIdempotencyKeyReusedError`, `ZelinqaCompilationInProgressError` (`compilationId`, `compilationStatus`) | +| `ZelinqaCompiledArtifactUnavailableError` | `410`: the artifact pinned by the session is unreachable | +| `ZelinqaValidationError` | `422`; specialised as `ZelinqaInvalidPreviousTurnError`, `ZelinqaConstraintNoMatchError`, `ZelinqaInvalidChoiceError`, `ZelinqaConfigurationValidationError` (`issues`) | +| `ZelinqaRateLimitError` | `429`; retried automatically first | +| `ZelinqaIdempotencyContentionError` | `503 idempotency_contention`; retried automatically, raised only once retries are exhausted | +| `ZelinqaServerError` | any other `5xx` | + +The gateway cannot tell an invalid key from an under-scoped one — both are a bare +`403 {"message":"Forbidden"}` — so both become `ZelinqaAuthenticationError`. Read +`statusCode` to distinguish a missing header (`401`) from a refused key (`403`). + +`String(error)` renders as `": (request_id=…)"`. Quote +`error.requestId` when you open a support ticket. + +## Retries, timeouts and idempotency + +- Every mutation sends `Idempotency-Key`. If you do not supply one, the SDK + generates a UUID v4 **once per logical call and reuses it across all retries**, + so a retry can never double a turn, an outcome, a feedback or a publication. + Same key + same body replays the original response; same key + different body + is `ZelinqaIdempotencyKeyReusedError`. Server-side records are purged after 24 h. +- Retried, up to `maxRetries`: connection errors, per-attempt timeouts, `429`, + `500`, `502`, `503`, `504`. `GET` requests too. +- Never retried: `400`, `401`, `403`, `404`, `409`, `410`, `422`. +- Backoff: 0.5 s, 1 s, 2 s … capped at 10 s, with jitter. `Retry-After` (seconds + or HTTP-date) and `details.retry_after_seconds` win, capped at 30 s. +- `timeoutMs` applies **per attempt**, via an `AbortController` combined with the + `signal` you pass. + +```ts +const controller = new AbortController(); +setTimeout(() => controller.abort(), 5_000); + +await runtime.next("ses_01J8Z", { state_version: 4 }, { + idempotencyKey: "next-ses01J8Z-turn-4", // 8–128 characters + signal: controller.signal, +}); +``` + +## Custom `fetch` + +Any Fetch-compatible function works — useful for tests, tracing, proxies or a +runtime whose global `fetch` you would rather not use. + +```ts +const client = new ZelinqaClient({ + apiKey: process.env.ZELINQA_RUNTIME_KEY ?? "", + fetch: async (input, init) => { + const started = Date.now(); + const response = await fetch(input, init); + // Log the route and the status — never the headers. + console.log(new URL(String(input)).pathname, response.status, Date.now() - started); + return response; + }, +}); +``` + +## Types + +All wire types are generated from `openapi/nbq-v1.openapi.yaml` and re-exported +under friendly names: `SessionState`, `NextResponse`, `Candidate`, +`Configuration`, `ConfiguredQuestion`, `CompilationStatus`, +`ConfigurationChange`, and so on. Field names are snake_case, exactly as on the +wire. Regenerate with `pnpm generate:types`. + +## License + +Apache-2.0. See [LICENSE](https://github.com/Zelinqa/zelinqa-sdk/blob/main/LICENSE). diff --git a/typescript/tests/readme.test.ts b/typescript/tests/readme.test.ts new file mode 100644 index 0000000..a9324b3 --- /dev/null +++ b/typescript/tests/readme.test.ts @@ -0,0 +1,146 @@ +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { runInNewContext } from "node:vm"; +import ts from "typescript"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { type NextResponse, ZelinqaClient } from "../src/index.js"; +import { at, jsonResponse, parseBody, recordFetch, sharedExample } from "./helpers.js"; + +const readmes = [ + new URL("../../README.md", import.meta.url), + new URL("../README.md", import.meta.url), +]; + +function example(url: URL): string { + const source = readFileSync(url, "utf8"); + const blocks = [...source.matchAll(/```ts\n([\s\S]*?)\n```/g)]; + expect(blocks).toHaveLength(1); + const code = at(blocks, 0)[1]; + if (!code) throw new Error("Missing README example"); + return code; +} + +function decision(type: "open" | "single_choice"): NextResponse { + const response = structuredClone(sharedExample("DecisionNormale")) as unknown as NextResponse; + const question = at(response.candidates, 0); + response.candidates = [question]; + question.type = type; + if (type === "open") { + delete question.selection_mode; + } else { + question.selection_mode = "single"; + } + question.choices = type === "open" ? [] : [{ choice_id: "choice_email", label: "Email" }]; + return response; +} + +async function runExample(url: URL, reply: string, next: NextResponse) { + const recorder = recordFetch([ + () => jsonResponse(sharedExample("SessionNeuve"), { status: 201 }), + () => jsonResponse(next), + () => jsonResponse(sharedExample("DecisionNormale")), + ]); + vi.stubGlobal("fetch", recorder.fetch); + const input = { question: vi.fn(async () => reply), close: vi.fn() }; + const createInterface = vi.fn(() => input); + const log = vi.fn(); + const source = example(url); + expect(source).toContain('import { ZelinqaClient } from "@zelinqa/sdk";'); + expect([...source.matchAll(/^import .+;$/gm)]).toHaveLength(3); + const executable = source.replace(/^import .+;\n/gm, ""); + const result: unknown = runInNewContext(`(async () => { ${executable}\n})()`, { + ZelinqaClient, + createInterface, + stdin: {}, + stdout: {}, + console: { log }, + process: { env: { ZELINQA_API_KEY: "readme-test-key" } }, + }); + await result; + return { recorder, input, createInterface, log }; +} + +afterEach(() => vi.unstubAllGlobals()); + +it("keeps the npm and TypeScript quickstarts identical", () => { + expect(readFileSync(at(readmes, 0), "utf8")).toBe(readFileSync(at(readmes, 1), "utf8")); +}); + +describe.each(readmes)("README example: %s", (url) => { + it("typechecks the documented code with the SDK's public exports", () => { + const configPath = fileURLToPath(new URL("../tsconfig.json", import.meta.url)); + const config = ts.readConfigFile(configPath, ts.sys.readFile); + expect(config.error).toBeUndefined(); + const parsed = ts.parseJsonConfigFileContent( + config.config, + ts.sys, + fileURLToPath(new URL("../", import.meta.url)), + ); + const path = fileURLToPath(new URL("./readme-example.ts", import.meta.url)); + const options = { + ...parsed.options, + paths: { "@zelinqa/sdk": [fileURLToPath(new URL("../src/index.ts", import.meta.url))] }, + }; + const host = ts.createCompilerHost(options); + const originalSource = host.getSourceFile.bind(host); + host.getSourceFile = (file, languageVersion, onError, shouldCreateNewSourceFile) => + file === path + ? ts.createSourceFile(file, example(url), languageVersion, true) + : originalSource(file, languageVersion, onError, shouldCreateNewSourceFile); + const program = ts.createProgram([path], options, host); + expect( + ts + .getPreEmitDiagnostics(program) + .map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")), + ).toEqual([]); + }); + + it("submits real text with the pending identifiers and current state version", async () => { + const next = decision("open"); + const { recorder, input, log } = await runExample(url, "We need to qualify requests", next); + expect(recorder.requests).toHaveLength(3); + expect(parseBody(at(recorder.requests, 2))).toMatchObject({ + state_version: next.versions.state_version, + previous_turn: { + decision_id: next.decision_id, + question_id: at(next.candidates, 0).question_id, + user_text: "We need to qualify requests", + }, + }); + expect(input.close).toHaveBeenCalledOnce(); + expect(log).toHaveBeenLastCalledWith("ask", sharedExample("DecisionNormale").warnings); + }); + + it("resolves the displayed choice label without an extra request", async () => { + const { recorder, input } = await runExample(url, "Email", decision("single_choice")); + expect(recorder.requests).toHaveLength(3); + expect(parseBody(at(recorder.requests, 2))).toMatchObject({ + previous_turn: { structured_answer: { choice_ids: ["choice_email"] } }, + }); + expect(input.close).toHaveBeenCalledOnce(); + }); + + it("reports an empty reply as asked_no_answer", async () => { + const { recorder, input } = await runExample(url, " \t", decision("open")); + expect(recorder.requests).toHaveLength(3); + expect(parseBody(at(recorder.requests, 2))).toMatchObject({ + previous_turn: { outcome: "asked_no_answer" }, + }); + expect(input.close).toHaveBeenCalledOnce(); + }); + + it("does not prompt or submit an answer when the engine stops", async () => { + const next = sharedExample("ArretSansQuestion") as unknown as NextResponse; + const { recorder, createInterface } = await runExample(url, "unused", next); + expect(recorder.requests).toHaveLength(2); + expect(createInterface).not.toHaveBeenCalled(); + }); + + it("rejects an unknown choice locally", async () => { + const next = decision("single_choice"); + await expect(runExample(url, "Unknown", next)).rejects.toThrow( + "Unknown or ambiguous choice label", + ); + }); +});